3 ms·
I listed two things Rust doesn't handle well without unsafe code, doubly linked lists and multidimensional arrays. Here are examples of both from popular reposi
by Animats 10y ago
I listed two things Rust doesn't handle well without unsafe code, doubly linked lists and multidimensional arrays. Here are examples of both from popular repositories with high download numbers:
- https://github.com/andelf/rust-adivon/blob/master/src/deque.rs https://github.com/andelf/rust-adivon/blob/master/src/deque....
- https://github.com/andelf/rust-adivon/blob/master/src/queue.rs https://github.com/andelf/rust-adivon/blob/master/src/queue....
These are all the doubly-linked list problem:
struct Node<T> {
item: T,
next: Option<Box<Node<T>>>,
prev: Rawlink<Node<T>>
}
Since this is templated code, it might be possible to break it by instantiating it on a type with unusual semantics.
- https://github.com/BurntSushi/aho-corasick/blob/master/src/full.rs https://github.com/BurntSushi/aho-corasick/blob/master/src/f...
Looks like unsafe code for "performance reasons". But there are no comments near "unsafe", so it's hard to tell.
- https://github.com/SiegeLord/RustAlgebloat/blob/master/algebloat/src/index.rs https://github.com/SiegeLord/RustAlgebloat/blob/master/algeb...
Matrix math. "Unsafe" all over the place, and unsafeness is exported, allowing the caller to do unsafe things. This is an example of why I occasionally stress the need for multidimensional array support at the language level. If the compiler knew about multidimensional arrays, it could optimize the subscript checks for them, avoiding code such as this.
The unsafe version. The caller can store anywhere in memory.
fn unsafe_set_idx(&self, $mat: &T, v: f64)
{
let $self_ = self;
let (r, c) = $rc_expr;
unsafe
{ $mat.raw_set(r, c, v) }
}
Safe, but inefficient version. The compiler can't hoist those checks out of loops.
fn set_idx(&self, $mat: &T, v: f64)
{ let $self_ = self;
let (r, c) = $rc_expr;
assert!(r < $mat.nrow());
assert!(c < $mat.ncol());
unsafe
{ $mat.raw_set(r, c, v) }
}
This is the sort of thing that leads to exploits in code that reads things like JPEG files. Yet you can't do much better in Rust. That's why doing multidimensional arrays in macros and templates isn't good enough.
- dbaupp 10y agoWhy do you still think the compiler can't host those out of loops? LLVM is perfectly capable of doing so in many cases and you've been told as much previously, could you make your claim more specific?
- Animats 10y agoWhere does LLVM do that? LLVM does hoist of invariant code out of loops in the Loop Invariant Code Motion and Loop Strength Reduction phases.[1] But that's not enough. This isn't an invariant situation. Consider a matrix multiply, the most common operation in number-crunching. You're indexing through three 2D matrices along both axes. The indices are usually controlled by FOR statements, so the compiler knows the range the indices can take. If the compiler knows about multidimensional arrays, it's easy to make those checks once at FOR loop entry. But if those checks are in asserts, it's tougher. Is LLVM allowed to fail an assert early? If the array is 0..999, and the index is 0..1000, a subscript out of range condition will occur on iteration 1001. For best performance, you want to detect the subscript out of range condition at the point it becomes inevitable, rather than checking on every iteration and failing on iteration 1001. (Although technically you could generate a special case.) But that requires special treatment of "assert". In Rust, "assert!" is just a macro. The compiler can't optimize it that aggressively and fail early. Especially since you can now catch assertion failures during unwinding. If all those optimizations really exist, why is there code like this (at https://github.com/SiegeLord/RustAlgebloat/blob/master/algebloat/src/matrix_mul.rs https://github.com/SiegeLord/RustAlgebloat/blob/master/algeb...)? MatrixMul<LHS, RHS> { unsafe fn raw_get(&self, r: usize, c: usize) -> f64 { let mut ret = 0.0; for z in 0..self.lhs.ncol() { ret += self.lhs.raw_get(r, z) * self.rhs.raw_get(z, c); } ret } } If what you say is true, all that unsafe stuff is unnecessary. [1] http://llvm.org/docs/Passes.html http://llvm.org/docs/Passes.html
- Manishearth 10y ago> If the compiler knows about multidimensional arrays, it's easy to make those checks once at FOR loop entry. Or you could just use a little unsafe code to implement iterators and matrix multiplication on top of the array, and then never use unsafe with the matrices anyway. This is what gets done with regular arrays and vectors. Directly indexing these types is pretty rare. You would do the same with matrices. "Put it in the language" is not a solution for everything, especially when the tools are there to build it with almost the same level of ergonomics. Requiring unsafe for designing some kinds of abstractions is not a bad thing. There's no need to shove everything into the language if it can be implemented as a library with a smattering of unsafe code. It's almost equivalent, really. Making a mistake when writing this unsafe code and making a mistake in the builtin optimization are mostly equivalent risks. There's nothing inherently worse about doing it as a library, aside from the minor issue that the indexing syntax isn't so great.
- Manishearth 10y agoThe multidimensional array thing has nothing to do with "Rust not handling multidimensional arrays without unsafe code". It's a mistake in the library to export that as safe, yes (filed an issue). But that unsafe code being unsafe has nothing to do with multidimensional arrays. It has to do with arrays in general. Implementing multidimensional arrays in the language would not change the fact that they would have `get_unchecked()` and `set_unchecked()` methods. The only thing that would change would be that you might have slightly nicer syntax for them, and "one way to do it". It doesn't change the scope for optimizations, either. Subscript checks do get optimized out in 1D arrays and they should get optimized out in this case too. The way indexing works for 1D arrays is basically exactly the same; there's a pair of methods for checked and unchecked; the subscript operator is specified to do checked indexing via an Index impl, and the optimizer usually gets rid of the checks. This would not change if indexing for the 1D array type was not implemented by the language itself. Sometimes when the invariants aren't easily seen by the optimizer it won't get optimized out, and that's when folks use unchecked indexing. Now, there is a problem here, and that is that unchecked indexing is an unsafe operation in Rust, whether with 1-D or 2-D arrays. Could be fixed with dependent types, but that's a lot of complexity and 99% of the cases where dependent types would work would have been optimized anyway. But this has nothing whatsoever to do with multidimensional arrays, and would not be helped at all by multidimensional arrays being in the language. The compiler already knows enough about multidimensional arrays to be able to optimize things. Rust supports multidimensional arrays in the language. It just doesn't have syntax sugar for it; and syntax sugar can't really affect optimization. > it might be possible to break it by instantiating it on a type with unusual semantics. Can you give an example? A lot of the semantics are well-encoded in the marker traits, so as long as you correctly specify the right Sized/Copy/Send/Sync bounds these problems should go away. (Panic safety could be an issue if you were calling methods on T, but you're not)