6 ms·
Pitfalls of Safe Rust
- woah 2y agoIs "as" an uneccesary footgun?
- whytevuhuni 2y agoThat was my first impression as well. So much of Rust’s language and standard library enforces correctness, that gaps start to feel way more visible. “as” is a good example. Floats are pretty much the only reason PartialEq exists, so why can’t we have a guaranteed-not-NaN-nor-inf type in std and use that everywhere? Why not make wrapping integers a panic even in release mode? Why not have proper dependent types (e.g. to remove bound checks), and proper linear types (to enforce that object destructors always run)? It’s easy to forget that Rust is not an ideal language, but rather a very pragmatic one, and sometimes correctness loses in favour of some other goals.
- bombela 2y agoI have been following rust very closely since 2013. As Rust is both evolving and spreading wide, we; the programmers, users of Rust; are also leveling up in how we approach correctness and design with it. Maybe the next evolution will be something like Haskell but fast like Rust is fast like C without the pain of C++. But it takes a while for the world to catch up, and for everybody to explore and find ways to work with or around the abstractions that helps with correctness. It's a bit like the evolution from a pointer to some malloc memory, then the shared/unique pointer of C++, to the fully safe box/(a)rc of Rust. It might be obvious today how much more efficient it is programming with those abstractions. I see some similarities with functional programming that still seems so niche. Even though the enlighteneds swears by it. And now we actually seem to be slowly merging the best parts of functional and imperative together somehow. So maybe we are actually evolving programming as a species. And Rust happens to be one of the best scaffold at this point in history. Thank you for reading my essay.
- pjmlp 2y agoThere is hardly any evolution from pointer to malloc, C is one of the few systems languages, including those that predated it, where one needs math to allocate heap memory. I do agree that the evolution is most likely a language that combines automatic resource management with affine/linear/effects/dependent/proofs. Or AIs improve to the point to render all existing programming languages a thing from the past, replaced by regular natural languages and regular math.
- bombela 2y agoSorry, my wording was not great. You got it right. I was saying that the evolution started with (a pointer from) malloc, then uniqueptr, then box.
- hansvm 2y ago> guaranteed-not-NaN-nor-inf Nor negative zero
- adgjlsfhk1 2y agoThe other option would be to change how floating point works. IEEE specifies operations, not names, so it would be totally valid to have <= on floats be a total order (using integer cpu instructions), and make a function called IEEEAreIdiotsWhoThinkThisIsFloatingPointLessThan which is the partial order that sucks.
- wongarsu 2y agoFor purposes of sorting, Rust does offer a non-IEEE order as f64::total_cmp. You can easily build a wrapper type that uses that for all comparisons, or use a crate that does it for you https://doc.rust-lang.org/std/primitive.f64.html#method.total_cmp https://doc.rust-lang.org/std/primitive.f64.html#method.tota...
- zozbot234 2y agototal_cmp is precisely IEEE's separately specified total order for floats. It's just that the more common operators do something different, and that's perhaps better for most uses where NaN are inherently unexpected and generally indicate that some kind of error condition has occurred.
- deleted 2y ago[deleted]
- thayne 2y agoThere is some movement towards deprecating "as", and lints that will recommend using alternatives when possible, but there are a couple of cases, such as intentional truncation, where there isn't a stable alternative yet.
- int_19h 2y agoSome of these don't strike me as particularly pragmatic. E.g. are overflow checks really that expensive, given that it's a well-known footgun that is often exploitable? Sure, you don't want, say, 10% overhead in your number-crunching codec or whatever, but surely it's better to have those cases opt in for better perf as needed, as opposed to a default behavior that silently produces invalid results?
- mustache_kimono 2y ago> Some of these don't strike me as particularly pragmatic. E.g. are overflow checks really that expensive Did you read the article? Rust includes overflow checks in debug builds, and then about a dozen methods (checked_mul, checked_add, etc.) which explicitly provide for checks in release builds. Pragmatism, for me, is this help when you need it approach. TBF Rust forces certain choices on one in other instances, like SipHash as the default Hasher for HashMap. But again opting out, like opting in, isn't hard.
- bobbylarrybobby 2y agoI'd prefer for Rust to opt for correctness/bug-freeness over performance, even in release builds. If you are doing number crunching you should have to opt out of these checks.
- mustache_kimono 2y ago> I'd prefer for Rust to opt for correctness/bug-freeness over performance, even in release builds. If you are doing number crunching you should have to opt out of these checks. You can turn those checks on, in release mode, of course: https://doc.rust-lang.org/rustc/codegen-options/index.html#overflow-checks https://doc.rust-lang.org/rustc/codegen-options/index.html#o... But I think the behavior on overflow is to "panic!()" (terminate immediately)? So -- I guess from my POV I wouldn't in release mode. I just think that tradeoff isn't generally worth it, but again, you can turn that behavior on.
- 2y ago
- FreezyLemon 2y agoRegarding the not-NAN float type, there was actually a proposal for it which was shot down: https://github.com/rust-lang/libs-team/issues/238 https://github.com/rust-lang/libs-team/issues/238. I don't remember every argument in there but it seemed that there are good reasons not to add it unlike a NonZero integer type which seems to have no real downsides.
- eptcyka 2y agoWhen fitting larger types into smaller ones? Yes.
- bombela 2y agoCompared to C/C++ "as" feels so much safe r. Now that Rust and we the programmers have evolved with it, I too feel that "as" for narrowing conversion is a small foot gun.
- bigstrat2003 2y agoI'm struggling to see how you would implement narrowing conversion in a way that is harder for programmers to misuse when they aren't being mindful, while also being pleasant to use when you really do want to just drop higher bits. Like, you could conceivably have something like a "try_narrow" trait which wraps the truncated value inside an Err when it doesn't fit, and it would probably be harder to accidentally misuse, but that's also really cumbersome to use when you are trying to truncate things.
- woah 2y agolet foo: u8 = bar<u64>.truncate_to()?
- recursivecaveat 2y agoI don't really want narrowing conversion to be harder, I just want checked conversion to be at least nearly as convenient. `x as usize` vs `x.try_into().unwrap()` becomes `x tiu usize` or something even. I'm not picky. It's kindof funny that this is the exact mistake C++ made, where the safe version of every container operation is the verbose one: `vector[]` vs `vector.at()` or `*optional` vs `optional.value()`, which results in tons and tons of memory problems for code that has absolutely no performance need for unchecked operations.
- bigstrat2003 2y agoI wouldn't say so. I quite like "as". It can have sharp edges but I think the language would be significantly worse off without it.
- zozbot234 2y agoThe question is not whether the language should include such a facility, but whether 'as' should be the syntax for it. 'as' is better than the auto conversions of C but it's still extremely obscure. It would be better to have some kind of explicit operator marking this kind of possibly unintended modulo conversion. Rust will gain safe transmute operations in the near future so that will perhaps be a chance to revise this whole area as well.
- wongarsu 2y agoIt's useful to have something that does the job of "as", but I dislike how the most dangerous tool for type conversions has the nicest syntax. Most of the time I want the behavior of ".try_into().unwrap()" (with the compiler optimizing the checks away if it's always safe) or would even prefer a version that only works if the conversion is safe and lossless (something I can reason about right now, but want to ensure even after refactorings). The latter is really hard to achieve, and ".try_into.unwrap()" is 20 characters where "as" is 2. Not a big deal to type with autocomplete, but a lot of visual clutter.
- nerdile 2y agoTitle is slightly misleading but the content is good. It's the "Safe Rust" in the title that's weird to me. These apply to Rust altogether, you don't avoid them by writing unsafe Rust code. They also aren't unique to Rust. A less baity title might be "Rust pitfalls: Runtime correctness beyond memory safety."
- burakemir 2y agoIt is consistent with the way the Rust community uses "safe": as "passes static checks and thus protects from many runtime errors." This regularly drives C++ programmers mad: the statement "C++ is all unsafe" is taken as some kind of hyperbole, attack or dogma, while the intent may well be to factually point out the lack of statically checked guarantees. It is subtle but not inconsistent that strong static checks ("safe Rust") may still leave the possibility of runtime errors. So there is a legitimate, useful broader notion of "safety" where Rust's static checking is not enough. That's a bit hard to express in a title - "correctness" is not bad, but maybe a bit too strong.
- whytevuhuni 2y agoNo, the Rust community almost universally understands "safe" as referring to memory safety, as per Rust's documentation, and especially the unsafe book, aka Rustonomicon [1]. In that regard, Safe Rust is safe, Unsafe Rust is unsafe, and C++ is also unsafe. I don't think anyone is saying "C++ is all unsafe." You might be talking about "correct", and that's true, Rust generally favors correctness more than most other languages (e.g. Rust being obstinate about turning a byte array into a file path, because not all file paths are made of byte arrays, or e.g. the myriad string types to denote their semantics). [1] https://doc.rust-lang.org/nomicon/meet-safe-and-unsafe.html https://doc.rust-lang.org/nomicon/meet-safe-and-unsafe.html
- pjmlp 2y agoMostly, there is a sub culture that promotes to taint everything as unsafe that could be used incorrectly, instead of memory safety related operations.
- IshKebab 2y agoFor integer overflows and array out of bounds I'm quite optimistic about Flux https://github.com/flux-rs/flux https://github.com/flux-rs/flux I haven't actually used it but I do have experience of refinement types / liquid types (don't ask me about the nomenclature) and IMO they occupy a very nice space just before you get to "proper" formal verification and having to deal with loop invariants and all of that complexity.
- 0rzech 2y ago> refinement types / liquid types (don't ask me about the nomenclature) There's a nice FOSDEM presentation "Understanding liquid types, contracts and formal verification with Ada/SPARK" by Fernando Oleo Blanco (Irvise): https://fosdem.org/2025/schedule/event/fosdem-2025-4879-understanding-liquid-types-contracts-and-formal-verification-with-ada-spark/ https://fosdem.org/2025/schedule/event/fosdem-2025-4879-unde.... One of the slides says: Liquid types! Logically Qualified Types, aka, Types with Logic! Aka dependent types, etc...
- quotemstr 2y agoSome of this advice is wrongheaded. Consider array indexing: usually, an out of bounds access indicates a logic error and should fail fast to abort the problem so it doesn't go further off the rails. Encouraging people to use try-things everywhere just encourage them to paper over logic bugs and leads to less reliable software in the end. Every generation has to learn this lesson anew through pain.
- bombela 2y agoI think what you are saying is that there must be an informed decision betwen crashing the program vs returning an error. Instead of returning an error for everything that happens to be a logic error at a given level of abstraction.
- hansvm 2y agoTry-things have the benefit of accurately representing the thing you're describing. Leave it to the caller to decide whether to panic or resize the data structure or whatever. That's also not the only choice in the design space for correct array accesses. Instead of indices being raw integers, you can use tagged types (in Rust, probably using lifetimes as the mechanism if you had to piggy back on existing features, but that's an implementation detail) and generate safe, tagged indices which allow safe access without having to bounds check on access. However you do it, the point is to not lie about what you're actually doing and invoke a panic-handler-something as a cludgy way of working around the language.
- sgt 2y agoGolang might be better for writing robust software, if that is the goal. Robust services that don't go down.
- NoTeslaThrow 2y agoHell, just go full erlang at that point and you get loads of services for "free".
- efnx 2y agoAnd why is that? I already don’t agree, but I’d love to hear your take.
- surajrmal 2y agoMentioning golang is a rust article comment section is just bait. People just live comparing the two even though it's somewhat boring comparison
- pjmlp 2y agoFirst they have to improve the memory model due to possible races when sharing slices due to their fat pointers implementation.
- neillyons 2y agoGolang will panic with a runtime error index out of range if you index out of bounds. There doesn't seem to be a nice built in way to do `arr.get(3)` like in Rust. slice := []int{1, 2, 3} i := slice[3] fmt.Println(i)
- IshKebab 2y agoI don't think so. Rust has much stronger typing than Go which allows you to prevent more classes of bugs than just memory errors. The coolest one I've heard is that Fuchsia's network stack managed to eliminate deadlocks. But even on a basic level Rust has that "if it compiles it works" experience which Go definitely doesn't.
- 2y ago
- meta_ai_x 2y ago[flagged]
- forrestthewoods 2y ago> Overflow errors can happen pretty easily No they can’t. Overflows aren’t a real problem. Do not add checked_mul to all your maths. Thankfully Rust changed overflow behavior from “undefined” to “well defined twos-complement”.
- LiamPowell 2y agoWhat makes you think this is the case? Having done a bunch of formal verification I can say that overflows are probably the most common type of bug by far.
- imtringued 2y agoYeah, they're so common they've become a part of our culture when it comes to interacting with computers. Arithmetic overflows have become the punchline of video game exploits. Unsigned underflow is also one of the most dangerous types. You go from one of the smallest values to one of the biggest values.
- forrestthewoods 2y agoUnsigned integers were largely a mistake. Use i64 and called it a day. (Rusts refusal to allow indexing with i64 or isize is a huge mistake.) Don’t do arithmetic with u8 or probably even u16.
- throwaway17_17 2y agoCan you expand on your thoughts here? What is the root issue with unsigned integers? Is your complaint primarily based on the implications/consequences of overflow or underflow? I’m genuinely curious as I very often prefer u32 for most numeric computations (although in a more ‘mathematics’ domain signed ints will often be the correct choice).
- forrestthewoods 2y ago> What is the root issue with unsigned integers? If I play "Appeal to Authority" you can read some thoughts on this from Alexandrescu, Stroustrup, and Carruth here: https://stackoverflow.com/questions/18795453/why-prefer-signed-over-unsigned-in-c https://stackoverflow.com/questions/18795453/why-prefer-sign... Unsigned integers are appealing because they make a range of invalid values impossible to represent. That's good! Indices can't be negative so simply do not allow negative values. The issues are numerous, and benefits are marginal. First and foremost it is extremely common to do offset math on indices whereby negative values are perfectly valid. Given two indices idxA and idxB if you have unsigned indices then one of (idxB - idxA) or (idxA - idxB) will underflow and cause catastrophe. (Unless they're the same, of course). The benefits are marginal because even though unsigned cannot represent a value below the valid range it can represent a value above container.size() so you still need to bounds check the upper range. If you can't go branchless then who cares about eliminating one branch that can always be treated as cold. On a modern 64-bit machine doing math on smaller integers isn't any faster and may in fact be slower! Now it can be valuable to store smaller integers. Especially for things like index lists. But in this case you're probably not doing any math so the overflow/underflow issue is somewhat moot. Anyhow. Use unsigned when doing bitmasking or bitmanipulation. Otherwise default to signed integer. And default to i64/int64_t. You can use smaller integer types and even unsigned. Just use i64 by default and only use something else if you have a particular reason. I'm kinda rambling and those thoughts are scattered. Hope it was helpful.
- thrance 2y agoI'd add memory leaks to the list. Sometimes you feel compelled to wrap your data in an Rc or Arc (reference counted pointers for those unfamiliar) to appease the borrow checker. With capture semantics of closures and futures and such it's quite easy to fall into a referential cycle, which won't be freed when dropped.
- sieabahlpark 2y ago[dead]
- pornel 2y agoI don't think it's a common concern in Rust. It used to be a problem in Internet Explorer. It's a footgun in Swift, but Rust's exclusive ownership and immutability make cycles very difficult to create by accident. If you wrap a Future in Arc, you won't be able to use it. Polling requires exclusive access, which Arc disables. Most combinators and spawn() require exclusive ownership of the bare Future type. This is verified at compile time. Making a cycle with `Arc` is impossible unless two other criteria are met: 1. You have to have a recursive type. `Arc<Data>` can't be recursive unless `Data` already contains `Arc<Data>` inside it, or some abstract type that could contain `Arc<Data>` in it. Rust doesn't use dynamic types by default, and most data types can be easily shown to never allow such cycle. It's difficult to make a cycle with a closure too, because you need to have an instance of the closure before you can create an Arc, but your closure can't capture the Arc before it's created. It's a catch-22 that needs extra tricks to work around, which is not something that you can just do by accident. 2. Even if a type can be recursive, it's still not enough, because the default immutability of Arc allows only trees. To make a cycle you need the recursive part of the type to also be in a wrapper type allowing interior mutability, so you can modify it later to form a cycle (or use `Arc::new_cycle` helper, which is an obvious red flag, but you still need to upgrade the reference to a strong one after construction). It's common to have Arc-wrapped Mutex. It's possible to have recursive types, but having both together at the same time are less common, and then still you need to make a cycle yourself, and dodge all the ownership and borrow checking issues required to poll a future in such type.
- Sharlin 2y ago> Surprising Behavior of Path::join With Absolute Paths > I was not the only one who was confused by this behavior. Here’s a thread on the topic, which also includes an answer by Johannes Dahlström: > > The behavior is useful because a caller […] can choose whether it wants to use a relative or absolute path, and the callee can then simply absolutize it by adding its own prefix and the absolute path is unaffected which is probably what the caller wanted. The callee doesn’t have to separately check whether the path is absolute or not. > And yet, I still think it’s a footgun. It’s easy to overlook this behavior when you use user-provided paths. Perhaps join should return a Result instead? In any case, be aware of this behavior. Oh, hey, that's me! I agree that it's a footgun, for what it's worth, and there should probably get a dedicated "absolutize" method for getting the "prefix this if relative, leave as is if already absolute" semantics. (link to the thread: https://users.rust-lang.org/t/rationale-behind-replacing-paths-while-joining/104288 https://users.rust-lang.org/t/rationale-behind-replacing-pat...)
- glandium 2y agoIt's the same in at least Python, so it's not a Rust idiosyncratic behavior. The "absolutize" method you're asking for exists since 1.79. https://doc.rust-lang.org/stable/std/path/fn.absolute.html https://doc.rust-lang.org/stable/std/path/fn.absolute.html
- Sharlin 2y agoYeah, but I meant a method that would take a custom prefix, like join does now. (In the hypothetical situation where join had different semantics.)
- conaclos 2y agoI find it strange that the article doesn't talk about the alternative to checked arithmetic: explicit Wrapping [0] and Saturating [1] types, also provided as methods on numeric types (e.g. `usize::MAX.saturating_add(1)`). Regarding `as` casting, I completely agree. I am trying to use safe `From::from` instead. However, this is a bit noisy: `usize::from(n)` vs `n as usize`. [0] https://doc.rust-lang.org/std/num/struct.Wrapping.html https://doc.rust-lang.org/std/num/struct.Wrapping.html [1] https://doc.rust-lang.org/std/num/struct.Saturating.html https://doc.rust-lang.org/std/num/struct.Saturating.html
- kelnos 2y ago> I am trying to use safe `From::from` instead. However, this is a bit noisy: `usize::from(n)` vs `n as usize`. If there's enough information in the surrounding code for type inference to do its thing, you can shorten it to `n.into()`.
- conaclos 2y agoAnother limitation I face is the impossibility of using `usize::from(n)` in `const` context.
- mre 2y agoTrue, I should add the wrapping types. They are actually quite useful if you know that you have a fixed range of values and you can't go above the min/max. Like a volume dial that just would stay at "max" if you turn up the volume; it wouldn't wrap around.
- bennettnate5 2y agoHere's an important one: never use `mem::size_of_val(&T)`. Rust as a language strongly steers you towards ignoring double (or even triple)-referenced types because they're implicitly auto-dereferenced in most places, but the moment you try to throw one of those into this API it returns the size of the referenced reference `&T` which is very much not the same as `T`. I've been burned by this before, particularly in unsafe contexts; I only use `size_of::<T>()` now.
- zk4x 2y agoThis is very nice article, objectively lists possible pitfalls. It's however not quite that simple. I am in favor of removing as, but then try_from needs to work with more types, for example try converting u64 into f32 without using as. It turns out to be very hard. TryInto does not work in single step. Important aspect is performance. HPC code needs to be able to opt out of math checks. Also Results and Options are very costly, as they introduce lot of branching. Panic is just faster. Hopefully one day rust will use something like IEX by default https://docs.rs/iex/latest/iex/ https://docs.rs/iex/latest/iex/ It has the same benefits as Results, but if error is returned in less than 15% of function calls, then IEX is much faster. Btw. allocation failure in std returning Result anytime soon?
- nurettin 2y ago> price.checked_mul(quantity) nope, I won't do that. I'd rather waste away at a bank using early 2000s oracle forms . Make it a compiler flag, detect it statically or gtfo.