by Animats · 2y ago · 0 comments
Rust does need a better way to do backlinks. You can do it with Rc, RefCell, and Weak, but it involves run-time borrow checks that should never fail. Those should be checked at compile time. Detecting a double borrow is the same problem as detecting a double lock of a mutex by one thread, which is being worked on.
Because it’s impossible to implement any non-trivial data structures in safe Rust. Even Vec has unsafe code in the implementation to allocate heap memory. When you need efficient trees or graphs (I doubt any non-trivial software doesn’t need at least one of them), unsafe code is the only reasonable choice.
C++ does pretty much the same under the hood, but that’s OK because the entire language is unsafe.
C# has an unsafe subset of the language with more features, just like Rust. However, it runs inside a memory-safe garbage collected runtime. Even List and Dictionary data structures from the standard library are implemented with safe subset of the language. Efficient trees and graphs are also trivial to implement in safe C#, thanks to the GC.
To name one example, the AnimationGraph in Bevy is implemented with petgraph, which is built using adjacency lists, and doesn't use any unsafe code in any of the parts that we use. It is very high-performance, as animation evaluation has to be.
Are you sure evaluating these animations is performance critical? I doubt games have enough data to saturate a CPU core doing that. Screens only have 2-8 megapixels; animated objects need to be much larger than 1 pixel.
If you animate bones for skeletal animation that’s still not much data to compute because real life people have less than 256 bones. You don’t need much more than that even if your models have fancy manually-animated clothes.
Isn't this obviously true? A key part of UI work is avoiding "jank", which commonly refers to skipped frames.
> I doubt games have enough data to saturate a CPU core doing that.
Got a bit lost here: games?
> Screens only have 2-8 megapixels.
4 bytes per pixel, 32 MB/frame. 120 frames / sec = 8 ms/frame. 3.84 GB/second.
> animated objects need to be much larger than 1 pixel.
Got lost again here.
In general, I'm lost.
First, there's a weak claim that all performant data structures in Rust must use unsafe code.
I don't think the author meant all performant data structures must use unsafe code.
I assume they meant "a Rust data structure with unsafe code will outperform an equivalent Rust data structure with only safe code"
Then, someone mentions a 3D renderer, written in Rust, is using a data structure with only safe code.
I don't understand how questioning if its truly performant, then arguing rendering 3D isn't that hard, is relevant.
Beyond that, you only need unsafe code for specific kinds of data structures. At least in my experience.
This might be fine for code which consumes data structures implemented by other people. The approach is not good when you actually need to implement data structures in your program.
In modern world this is especially bad for a low-level language (marketed as high performance, BTW) because the gap between memory latency and compute performance is now huge. You do need efficient data structures, which often implies developing custom ones for specific use cases. This is required to saturate CPU cores as opposed to stalling on RAM latency while chasing pointers, or on cache coherency protocol while incrementing/decrementing reference counters from multiple CPU cores.
Interestingly, neither C++ nor C# has that boundary, for different reasons: C++ is completely unsafe, and safe C# supports almost all data structures (except really weird ones like XOR linked lists) because GC.
You are assuming you can't do this with those vecs/maps. But you can! That's what the "additional semantics" are.
They will be slightly slower due to often using indexes instead of raw pointer, which requires a bound check and an addition to get the pointer, and sometimes a reallocation, but they won't be that slow. Surely they will be faster than C#, which you claim can implement those same data structures efficiently. You also often get the benefit of better cache locality due to packing everything together, meaning it could even be faster.
If you need an array for your custom data structure, a standard library vector is almost always good enough. Associative arrays are a bit more tricky, but you should be able to find a handful of map implementations that cover most of your needs. And when you need a custom one, you can often implement it on top of the standard library vector.
>Because it’s impossible to implement any non-trivial data structures in safe Rust. Even Vec has unsafe code
Hmm.. wasn't memory safety the main selling point for rust? If not the only. Now mix of two languages looks even worst than one complex. Especially taking into account that it can be paired with safe language from long list. Don't know what rust fans are thinking, but from outside it doesn't look very attractive. Definitely not enough to make a switch. Julia looked better at first, but turned out to be just a graveyard of abandoned academic projects.
The point is that the vast majority of code doesn't have to be unsafe. Empirically, Rust code has far fewer memory safety problems than non-memory-safe languages.
The vast majority of Rust programmers aren't spending their time re-implementing core data structures like Vec, so memory safety (and the fact that library authors can build safe abstractions on top of unsafe code, which is impossible in C or C++) still benefits them.
The fundamental / syntactic promise of Rust is providing mechanisms to handle and encapsulate unsafety such that it is possible to construct a set of libraries that handle the unsafety in designated places. Therefore the rest of the program can be mathematically proven to be safe. Only the unsafe parts can be unsafe.
Coming from Java or Go or Js or Python angle wouldn't be the same. Those languages don't come with mechanisms to let you to make system calls directly or handle the precise memory structure of the data which is necessary when one is communicating with hardware or the OS or just wants to have an acceptable amount of performance.
In C++, the compiler can literally remove your code if you sum or multiply integers wrong or assume the char is signed/unsigned. There is no designated syntax that limits the places possible memory overflow error happen. The design of the language is such that some most trivial oversight can break your program silently and significantly. It is too broad so it is not possible to create a safe and mathematically proven and performant subset with the C and C++ syntax. It is possible with Rust. It is like the difference of chips that didn't have a hardware mechanism to switch between user and kernel mode so everything was simply "all programs should behave well and no writes to other programs' memory pinky promise".
Rust doesn't leave this just as a possibility. Its standard library is mostly safe and one can already write completely safe and useful utilities with the standard library. The purpose of the standard library is provide you ways to avoid unsafe as much as possible.
Of course more hardware access or extremely efficient implementations would require unsafe. However again, only the unsafe parts can cause safety bugs. They are much easier to find and debug compared to C++. People write libraries for encapsulating unsafe so there are even less places that use unsafe. If people are out of their C++ habit, reaching for the big unsafe stick way too often, then they are using Rust wrong.
Whatever you do, there will be always a need for people and software that enables a certain hardware mode, multiply matrices fast, allocates a part of display for rendering a window etc. We can encapsulate the critical parts of those operations with unsafe and the rest of the business logic can be safe.
Here’s a C# library for Linux where I’m doing all these things https://github.com/Const-me/Vrmac/blob/master/VrmacVideo/Rea... As you see from that readme, the performance is pretty good too.
Here is an interesting case of an optimization-triggered bug in Rust code I've heard of: https://www.youtube.com/watch?v=hBjQ3HqCfxs
Eh? You can of course do all of that in python. https://docs.python.org/3/library/struct.html
This is why I think rust is great for application programmers. Honestly high performance web servers, games, anything in that realm it's pretty good for.
Low level systems and high performance data structures are better implemented with direct memory management, but the consumers of those libraries shouldn't have that same burden (as much as possible).
Granted, I haven't worked with rust enough to run into issues with other people's unsafe code.
I agree. I rarely ever use unsafe, and only as a last resort. Unsafe code is really not needed to achieve high performance.
> Rust does need a better way to do backlinks. You can do it with Rc, RefCell, and Weak, but it involves run-time borrow checks that should never fail.
I think this will basically turn into provably-correct data structures. Which is possible to do, and I've long thought there should be systems built on top of Rust to allow for proving these correct. But we should be clear that something like Idris is what we're signing up for. Whatever it is, it is assuredly going to be far more complex than the borrow check. We should basically only use such systems for the implementations of core data structures.
That's kind of what I'm thinking. The basic idea is to prove that .upgrade().unwrap() and .borrow() never panic. This isn't all that much harder than what the borrow checker does. If you have the rule that the return value from those functions must stay within the scope where they are created, then what has to be proven is that no two such scopes for the same RefCell overlap. Sometimes this will be easy; sometimes it will be hard. A reasonable first cut would be to check that no such scopes overlap for a specific type, anywhere. That's rather conservative. If you can prove that, you don't need the checking. So it's an optimization.
I hear cargo-geiger is useful identifying such crates.
> I just do not see why people seem to use "unsafe" so much.
Because it's:
A) fast (branchless access)
B) fast (calling C libs or assembly)
C) fast (SIMD)
D) people think unsafe Rust is easier
Want to write a JSON parser that will gobble up gigabytes per second? Your only way is removing as many branches and use assembly as much as possible. Doubly so on stable! I guess the same goes for making a "blazingly fast"™ graphical stack.
People that think unsafe is easier, shouldn't be writing unsafe code. Writing unsafe code correctly is like juggling burning chainsaws. Saying that's easier than using chainsaws is moronic at best.
EDIT: Consider following, if each of your unsafe {} blocks doesn't contain a
// SAFETY:
// Detailed explanation of invariants
One of the chainsaws just cut off your leg.If that's their line of thought, I don't know why they simply don't use C/++. Or even C# with unsafe blocks. I know you said the same, but I wanted to reiterate that.
But yes, I can see a few very specific cases where unsafe access is needed. Emphasis on "few". I think anything past some fundamentals should be at best a late optimizing step after an MVP is established.
I also think, if it's not already there, that crates should be able to identify if it's "safe" or "unsafe". Same mentality where I'd probably want to rely on safe crates until I need to optimize a sector and then look into blazing fast but unsafe crates.
It's not clear to me how rustc could detect a dangling backlink in a tree structure at compile time. Seems impossible short of adding proofs to the type system.
Unfortunately it only thinks about are unique, an opinionated form of borrowed ownership, and a little bit about shared (weak I think is punted entirely to the library?), and not all other ownership policies can effectively be implemented on top of them.
The usual thing approach would be:
given two types, P and C (which may be the same type in case of homogeneous trees, but this), with at least the following fields:
class P:
child1: ChildPointer[C]
class C:
parent: ParentPointer[P]
Then `p.child1 = c` will transparently be transformed into something like: p.child1?.parent = null
c?.parent?.child1 = null # only needed if splice-to-steal is permitted; may need iteration if multiple children
p.child1 = c
p.child1?.parent = p
Note that ChildPointer might be come in unique-like or shared-like implementations. ParentPointer[T] is basically Optional[UnopinionatedlyBorrowed[T]].A have a list of several other ownership policies that people actually want: https://gist.github.com/o11c/dee52f11428b3d70914c4ed5652d43f...
I think that Rust having unsafe is fine as there will be edge cases where the compiler can't quite work out whether some code will work fine or not and where the programmer can vouch for it. That's no problem.
The issue I have with it is that the unsafe block then gets kinda swallowed by the supposedly safe wrappers around it. And there's no clear auditable trail back to it. I find that a bit surprising as I'd expect it obvious to have some kind of 'uses unsafe' declaration (annotation? I don't know what Rust calls those statements with a number sign and square brackets in front of a subroutine) which would then propagate upwards. A bit like how in Java (the most elegant and refined of all programming languages) you can use an annotation to state that a function 'throws XYZException' which then needs to be propagated up to a point where it can get handled.
Not having such a mechanism feels a bit icky to me. It's like if there's spiders crawling out of your ears it's useful to know that they're coming out of your ears so you don't have to wonder 'are those spiders creeping out of my ears? Or out of my nose? Or out of my eyelids?', which would be a bit inconvenient.
[1] https://doc.rust-lang.org/std/slice/fn.from_raw_parts.html
SIMD seems to be a big one.
Backlinks would be "nice" but they break fundamental assumptions that the borrow checker does.
> Detecting a double borrow is the same problem as detecting a double lock of a mutex by one thread, which is being worked on.
Is it being worked on using heuristics or formal methods?
I don’t know what fancy things you’re doing with unsafe that you’re seeing it on a daily basis… maybe it’s a you problem