Thoughts on Rust, a few thousand lines in
rcoh.me
rcoh.me
Rust is great, and I highly recommend learning Rust if you want to become a better C++ developer. C++ introduces a lot of unnecessary headaches Rust completely solves. Rust is worth the switch if only because reading error messages from expanded templates is horrible compared to type system that actually understands type parameters.
I'm really bullish on Rust becoming even more mainstream, to the point anyone can pick it up and use it in their business without a second thought by 2020.
I wrote a large web app in scala using Futur only and it turned into a monster because of it. Even if you don’t use callback you still need to manualy unwrap them and they pollute your méthode signature.
Then more recently I wrote a pub/sub server in c# using the “await” keyword. While much better it still polute your method signature and make the debugger and stacktrace useless. Also you still have to think about trying to no make anything that could block spinlock or calling api that are not Async ex: Createfile
Compare this to Golang where project like Groupcache (1) have super clean code that replaced a thousand line of code C++ system at google.
Why do you think Golang fiber/gorotine are worse ?
One big advantage of Futures is they are decoupled from their execution environment.
For example, different types of executors can be used depending on the type of Future. For example, you may have an IOThreadPoolExecutor to handle accepting and responding to connections that should spend very little time blocking and a CPUThreadPoolExecutor for offloading heavy processing. In Go, you have no say in how goroutines are scheduled, you sacrifice control to reduce complexity.
Another big one in network programming is the polling mechanism. In Go, you have no control over your polling mechanism, whereas with a Future is decoupled from the event loop, and you can write your own event loop on any experimental kernel APIs you'd like.
Rust made the right move because in Rust, just as in C++, we want maximum control. Futures are more primitive, and it's possible to build coroutine models on top of them, but not vice versa.
My understanding is the main issue with “await” model is that you only abstract The Task model.
Running task don’t gave a real ID and stack like “Go” and “Erlang” you can list all running fiber how much memory and CPU they use ...
I believe you could write your own event loop easily in Go if they exposed the internal api used to pause and resume goroutine, you can already pause goroutine by having them wait on a mutex and resume them from your custom event loop by releasing that mutex.
You can drop to raw fd's and do whatever you like... of course this negates a lot of the niceties that go affords you.
No, fibers were removed with nothing to replace them. The futures as we know them today did not exist in the far, far past when fibers and the whole runtime thing got dropped.
You wouldn't want a Go-like M:N solution in Rust. It would be slower for no reason.
Depends on how many threads you have and what OS you’re running on.
you don’t have to pay the memory usage and context switch cost you would have if using large amounts of threads.
It’s also faster to do IO processing from a single thread in batch instead of having one OS thread per request.
Memory usage per thread is a property of the GC, not M:N threading. You can have very small stacks in a 1:1 implementation too.
You can also read data from several file descriptor in a single System Call.
This way you significantly reduce the number of System call instead of doing one blocking read() per connection. I believe context switch round trip (from user space to kernel to user space) is much more expensive than simply switching between goroutine of the same process.
Chrome manages to do async stack traces for their implementation of the similar JavaScript feature. I wonder if this would be possible for C# and Rust.
I would prefer it if this feature didn't exist at all rather than cause runtime panics.
https://play.rust-lang.org/?gist=e02ce5e9aacfee3a2b4917d5624...
It's not useful to blindly read at random offsets in UTF-8 strings. If it didn't panic, you'd get garbage. If offsets were automatically moved to skip over garbage, you wouldn't know what you're getting, and your overall algorithm would likely end up with nonsense (duplicated or skipped chars).
For algorithms that don't care about characters or UTF-8 validity, there's zero-cost `.as_bytes()`.
And in the rare cases, when it's not a bug, then one can just use `as_bytes` which would be good to do in any case, to indicate to other humans that this is not a bug.
B.t.w. I love the error message `[..3]` generates: "thread 'main' panicked at 'byte index 3 is not a char boundary; it is inside '早' (bytes 2..5) of `ab早`'" — I've never seen such easy to understand error messages in any language (except for in a few cases in Scala).
e.g. my_hashmap["foo"] will panic at runtime if the key "foo" is not present, or return the associated value if it is. But my_hashmap.get("foo") will return None if "foo" is not present and Some(value) if it is.
First of all, panics are perfectly safe. None of this has to do with safety guarantees.
Second, the [] syntax is controlled by the Index trait, which returns an &T, not an Option<&T>. It does this due to Rust's error handling philosophy. There's two kinds of errors: recoverable and unrecoverable errors. When something shouldn't fail, unless there's a bug, you shouldn't be using Option/Result, you should panic. When something may normally fail, and you want to be able to handle that explicitly, you should use Option/Result.
If [] always returned an Option, you'd be seeing tons and tons and tons of unwraps. It's not the right default here. However, that's why the .get method also exists: If you do think that this may fail, but not due to a bug, then you should use .get instead, which does give you an option.
TL;DR: everything is tradeoffs, and we picked a specific set of them, and that's how they all play out together.
Personal commentary: this is the kind of thing that's largely concerning until you actually use the language more, IMHO. Dealing with Options all the time here would feel really bad. Consider the other sub-thread about floats; it often feels like boilerplate for no good reason. That would introduce this for every single time you want to index something, which is a very common operation.
This would also free up the [] to be used for generics and avoid syntactical warts like ::<> parsin
It doesn't remove those warts, it moves them.
If you want all the data after a : character, you slice on the index of the :. The character after it is going to be the beginning of a UTF-8 character.
You do not under any circumstances guess that the colon is at position 6 in the string. That's not safe. Why are you going cowboy in a language that is so obsessed with safety?
It's like the default rule in a lexer, if it ever gets to it then it's an unrecognized character and lexing stops so error handling can proceed.
--edit--
Which I now realize was probably your point.
Granted, this is certainly incorrect but has little to do with safety, especially if the downstream code has to revalidate everything anyway.
I suppose one could have it return StrWithInvalidSurrounds, where just the first (at most) 3 and last (at most) 3 bytes might be invalid, which would then allow for O(1) revalidation to a &str, and even other operations like continuing to slice... But this is even more clunky for actual use!
I think a moderately less clunky API might have been to not use integers for byte indexing, but instead some ByteIndex wrapper type that string operations return, meaning one can't just write `s[..5]` in an attempt to get the first 5 characters of the string.
(Also, there's str::get that returns an Option: https://doc.rust-lang.org/std/primitive.str.html#method.get )
String always assumes full UTF-8. You could make an AsciiString type if you wanted, but it's not provided by the standard library.
It's exactly the opposite of what you expect. Getting the nth codepoint is often (not always) semantically incorrect since a codepoint isn't necessarily one character. Multiple codepoints might combine to form one character. (In Unicode, these are called grapheme clusters.)
Byte offsets are used a ton because you might often have the index to a position in the string from some routine, like, say, a search[1].
I've been working on text related things in both Rust and Go for several years. Both languages got this part of their strings exactly right given that their representation in memory is always a sequence of bytes.
[1] - https://doc.rust-lang.org/std/primitive.str.html#method.find
The reason being that the behavior of [] for string varies widely in different languages, and so this is something that's best made explicit, both to force the author of the code to consider whether their assumptions are valid and reasonable for what they're trying to do, and to give additional context to anyone else reading the code.
As it is, I suspect a common class of bugs for Rust will be with people assuming that [] slices codepoints, because it seems to work that way for ASCII.
There is pretty much no case where indexing by character actually makes sense because it is almost always incorrect and it is always inefficient.
Indexing by byte is rarely useful, but it does have some usefulness since it can be used correctly and efficiently since you can easily find the next or previous character by searching a maximum of four bytes for the a byte that has a MSB of 0. If you want to do something like get a &str that would fit in a n-byte buffer, then byte indices will let you do that efficiently and correctly.
> If a string is an array of characters
It is not, it is an array (technically vector) of bytes.
At the very least, shouldn't there be an O(n) method to do character-wise slicing?
You can, but it depends on what you mean by “character”, as that’s not a concept in Unicode. Every kind of thing you could mean has a method, specific to it, since they’re different things.
(char in Rust is a Unicode scalar value, and you can collect into a Vec<char> and then slice it, as an example of one of those things. And that’s still O(1) at the cost of using up to four times the memory.)
fn main() {
let a = "ab早".as_bytes();
let a = &a[..3];
println!("Hello, world!");
}This example was basically a suggestion to throw0u1t: if they want to cut in the middle of the utf-sequence for whatever reason, they can [edit:] do it without extra crates.
What I don't understand is why slices are indexed in bytes and not in objects. If String has an ability to check that we're cutting in the middle of the character sequence, why doesn't it provide an ability to take 3 fully formed characters.
If you want to find the one millionth codepoint of a UTF8-encoded string, you have to more or less (1) visit every byte of the string.
If, on the other hand, you want to find the codepoint that covers the millionth byte, on the other hand, you have to read at most four bytes (read the millionth byte, and there are three cases:
- it’s a full codepoint. If so, you‘re done.
- it is the first byte of a multi-byte codepoint. If so, read forwards in the string for up to 3 continuation characters.
- it is a continuation character. If so, search backwards in the string for the first byte, then, if necessary, read forwards to find more continuation characters.
So, that is O(1)
(1) you can skip continuation characters, but these typically are rare.
Slicing is an O(1) operation, and that would be an O(n) operation.
Also, you can get the same performance from an operation that returns a byte array instead of a string. If that kind of performance is what you want, then a Unicode string is simply not the right type to use.
You suggest just using a byte array instead, but then you'd lose the guarantee that what you're working with is valid Unicode. Contrary to your assertion, it is useful to have a type that provides that guarantee, yet which can still be operated on efficiently.
[1] https://manishearth.github.io/blog/2017/01/14/stop-ascribing...
Indexing into a UTF-8 string doesn't serve any reasonable consistent purpose anyway, because it is an abstraction of text that doesn't provide support to the notion that a "character" is more fundamental than a word or paragraph, etc. Rust's string slicing exists solely to make ASCII text easy to handle. If your text is not ASCII, then you shouldn't be slicing it at all. Thus the panic.
If that's true, isn't it the job of a type system to help avoid such nonsensical operations? If "slice" only makes sense for byte arrays and ASCII strings, it could be provided on those types without being defined on UTF-8 strings.
Panics are not unsafe. Panic exists in Rust because they are safe.
That's "safe" by a very limited definition of safety. It's one step up from undefined behavior, granted, but it's not a very high standard. In practice, in most programs, you'd want to ensure that such a panic would never happen, and personally I think the language's unhelpfulness in that regard is a wart.
It's not strictly true, because there are situations where you want to slice UTF-8. For instance, if you already know where the code point boundaries are for newlines. But if you know that, then you've run something like a regex with >O(1) behavior and you certainly wouldn't want string slicing to do redundant work.
>hat's "safe" by a very limited definition of safety
That's the definition of safe that is used. Safety in the context of Rust means memory safety. (Division can panic, btw.) If you don't see why undefined behavior is so much worse than a panic, then do some research on it. If you want programs that never fail, you need a comprehensive plan that takes into account things like hardware failure. A programming language can't do that.
Basically, string indexing is a lot harder than it seems at first glance, depending on what you want.
[1]: https://doc.rust-lang.org/std/string/struct.String.html#meth...
IIRC that's what grapheme clusters are for.
This is great for high-level code, but painful to work with from native code, because it usually needs some specific encoding to call into other libraries, and it's usually UTF-8 - so you need to re-encode all the time.
So it handles the (very) common case of needing the same encoding multiple times (e.g. for all file paths on Windows), while not introducing too much overhead in memory or speed.
I could be mistaken on exact details though, especially since I recall there being multiple implementations even within py3.x.
This was a really important learning for me. When I'm looking for crates to solve a problem and there's only a handful of them, I almost always go through every single one of them, even if some have thousands and the others only tens of downloads.
It's an incredible feeling to find those unknown diamonds..
This is often a Bad Idea, as you get unstable sorts and you are right back to the same problem.
- Explanation: How do I get the minimum or maximum value of an iterator containing floating point numbers? — https://stackoverflow.com/a/50308360/155423
- Example: https://play.integer32.com/?version=stable&mode=debug&editio...
See also:
- How to do a binary search on a Vec of floats? — https://stackoverflow.com/q/28247990/155423
Instead, use a wrapper type or raise a panic.
You could even say the reason NaN exists is so that you don't have to check for NaN constantly. Rust is being technically correct but practically really annoying, for basically no benefit.
It is not something to use by default though. It is implemented in software and thus a lot slower than the hardware comparison.
But fortunately in comparison sort algorithms that run in O(n lg n) you can get away with doing an O(n) partitioning of the array into [-, +, NaN] and then applying a fast integer comparison operator to the negative values (-) and positive values (+).
In fact the above idea ties in neatly with QuickSort, which is already based on partitioning & sorting recursively.
Is this true?
I am actually struggling to remember the last time I did a sort with a float/double as the key--especially in a performance bounded context
... <thinking> ...
Aha. Graphic engine. Octtree with coordinates.
I really had to think about that.
So, I'm a bit skeptical of float sorting happening a "lot".
Is this perhaps an ML primitive somewhere?
So since no one needs this often enough to emit the soft-float comparison code, we should emit the fast code. If folks need different behavior they should use different types. This is similar to the behavior with integer overflow, which you can opt into by using checked types or checked operations. Though in rust we have a convenience that the overflow-detecting code is emitted for debug targets.
Thanks in advance!
> it was a hassle to track down because Rust itself didn't complain and the panic message during serialization wouldn't tell me which file of the hundreds of thousands was causing it to die. For lack of a purpose-built tool, I had to manually bisect it until I narrowed it down.
> That said, definitely a footgun in the standard library to be remedied.
> My main concern here is getting rid of the footgun if at all possible. I really don't want to have to maintain a special "Never allow these types to creep into structs I'm deriving Serialize/Deserialize on, because the compiler certainly won't warn you" audit list.
If that's considered safe in Rust's standards then I rest my case.
Yes, things can still be improved, but this is nowhere near as bad as many parsing bugs.
https://github.com/rcoh/angle-grinder/blob/master/tests/stru...
You can declare structs that derive from Serde and convert to / from Json in a typesafe way.
I've seen and appreciated the use of guard clauses in many languages, as a good way to quickly check for a few conditions at the top of a function, and return early if those conditions aren't met.
Since it seems that Option<T> are recommended in Rust, there's a lot of time you want to quickly return if `Some(x)` is not here (i.e. it's `None`), and if it's here, continue through the function, without having an unnecessary indentation from an extra brackets.
There seem to be a good amount of smart discussion into handling those [1][2]. some threads are more than a year old, but it seems to be making progress.
[1] https://github.com/rust-lang/rust/issues/45978 [2] https://internals.rust-lang.org/t/pre-rfc-allow-pattern-matc...
My current understanding is that those would return an Error only? I was more describing cases where you do want to return, but not necessarily return an `Error`.
For instance in a simplified example function that returns a boolean, you could decide to return `false`. is it possible there?
// Function that returns a boolean value
fn is_equal_to_ten(n: Option<u32>) -> bool {
// some one liner that checks for None, if it's not none, gives you `x` when `n` matches content of `Some(x)` (not real code):
if let Some(x) = n else { return false; /* what to do in case it's a None*/ }
// `x` is available here:
return (x == 10);
}
Would this be considered bad practice in Rust?ok_or is a method on Option that would let you manually convert it to a Result. You could then combine it with ?, turning a None into a specific Err.
It won’t help for stuff that returns bool, it’s true.
fn is_equal_to_ten(n: Option<u32>) -> bool {
n.map(|n|n == 10).unwrap_or_default()
}Pseudocode:
if (foo is a String) {
foo.someStringMethod();
}
Flip that around a little bit: if (foo is not a String) {
return "error";
}
foo.someStringMethod();
And you've got a guard clause that's fundamentally the same kind you're asking for. I've wanted this structure in a language for a very long time. I was happy to see it pop up in Kotlin and would love to see it in Rust as well.Haskell does it too, for the same reason/purpose / with the same effect.
It's not the same as the Rust example because you're shadowing an ivar to a local, but since `self.` is implicit you're still shadowing.
You'll see the same in Rust
fn example(name: Option<String>) -> Option<usize> {
let name = name?;
Some(name.len())
}
Or fn example(name: Option<String>) {
if let Some(name) = name {
println!("{}", name.len());
}
}
A main difference is the requirement to use `Some`, which allows for the flexibility to apply to any enum.> but since `self.` is implicit
To make sure I'm following, do you mean that Rust's `self.` is implicit in Swift?
> do you mean that Rust's `self.` is implicit in Swift?
Swift's `self.` is implicit in Swift – in most contexts, to access a property the `self.` is not required. `self.name = "John"` and `name = "John"` are equivalent (assuming self is an object with a name property).
There are places where explicit `self.` is required though – when you want to differentiate between a shadowed local and a property (obviously), or when you're inside a closure (to make it clear that the closure is capturing self, not just capturing a reference to the property).
This is kind of a philosophical corner: can you shadow something that isn't there anymore? Once you've moved out of something, if you attempt to use the old name, then you'll get a compiler error different from "no such variable", so it's still there in some sense.
Pragmatically, I think you are on the money.
struct S {
var string: String
func doSomething() {
// These two lines are equivalent.
print(string)
print(self.string)
}
} let foo = "...";
let foo = parse(foo);
let foo = escaped(foo);
...
doSomethingWith(foo);
I don't see how this is helpful for avoiding the bug described. The most common bug with this type of code is mistaking which form "foo" represents at a given line of code, or that form changing as the code evolves. For example, if one programmer writes let foo = "...";
let foo = parse(foo);
...
doBarWithFoo(foo);
and another programmer comes along, doesn't notice the call to doBarWithFoo, and needs an escaped version of foo: let foo = "...";
let foo = parse(foo);
...
let foo = escaped(foo);
doBazWithFoo(foo);
...
doBarWithFoo(foo); // This still looks correct in isolation
This is a classic problem with mutable variables that frequently causes hard-to-spot bugs. Whereas if each form has a distinct meaningful name, this change wouldn't introduce a bug, and if somehow a bug were introduced, good names will make it possible to spot even considering the line in isolation: doBarWithFoo(fooEscaped); // Hey! The input to doBarWithFoo shouldn't be escaped!
If the only useful form of foo is the final one, then you can avoid having accessible names for the invalid intermediate forms like this: let foo = escaped(parsed("..."));
Or like this for more complicated logic (I'm not a Rust programmer (yet) so this may not be the right syntax): let foo = {
// Complicated logic
finalForm;
};
I feel like if I ever write a lot of code in Rust I'll find a linter rule that warns about shadowing variables and use it religiously. But maybe I'm missing a use case where it's crucial.Your type structure at no extra runtime cost is String : ParsedString : EscapedString.
This ensures you don't escape strings before parsing them too. Nice!
type A = B
but you can use the following function with a B: f :: A -> _
whereas newtype EscapedString = EscapedString String
f' :: EscapedString -> _
would prevent from using f' with the wrong data. Newtype is a zero-cost abstraction.It probably helps that the only ways to introduce new variables are all very distinctive:
let [new variables] = [expr];
if/while let [new variables] = [expr] { [new variables scoped here] }
for [new variables] in expr { [new variables scoped here] }
fn name([new_variables]) { [new variables scoped here] } let foo = "...";
let foo = parse(foo);
let foo = escaped(foo);
Is it really shadowing or mutation of foo?I would consider this shadowing (something you can do in OcaML):
let foo = "..." in
let foo = parse(foo) in
let foo = escaped(foo) in
dosomething(foo);;Although in practice I found that it's common to not indent adjacent nested let..in blocks in OCaml, either, so you'd often see something like:
let foo = "..." in
let foo = parse(foo) in
let foo = escaped(foo) in
...
And the rules are really simple - "let" always introduces a new binding.is shadowing
let foo = bar; foo = bat;
is a compilation-time error because foo isn't mutable.
let mut foo = bar; foo = bat;
is reassignment.
in working code, either foo is declared as mutable or it's not, and it's pretty obvious from the code what's happening.
The GNU C library (needed not only by C programs for C things) doesn't support static linking, so the only way this is possible is to use another library entirely, or raw inlined syscalls (where applicable).
$ rustup target add x86_64-unknown-linux-musl
$ cargo build --target x86_64-unknown-linux-musl
away.(And if you need to link against common C libraries like OpenSSL or PostgreSQL, I maintain a Docker image with the necessary C toolchains, and instructions on how to use it: https://github.com/emk/rust-musl-builder. There are a couple of similar images out there, too, I think.)
$ cargo build --target x86_64-unknown-linux-muslOf course, there's the usual issue with glibc symbol versioning, so you probably want to build your binaries on the oldest supported system (say, a centos 6 container).
This is more in line with the "bank lending model " it advocates.
I've used it in production, and subjectively it was much easier to work with than C++.