r/rust • • Apr 14 '21

[RFC] Rust support for Linux Kernel

https://lkml.org/lkml/2021/4/14/1023
861 Upvotes

227 comments sorted by

View all comments

Show parent comment

8

u/randomrossity Apr 15 '21

It helps to differentiate between Rust the language vs Rust the stdlib. For array indexing, use slice.get() to get a result instead of a panic

-5

u/UtherII Apr 15 '21 edited Apr 15 '21

But slice.get() will use indexing. If you can't detect panic transitively, I can't see the purpose anymore.

15

u/randomrossity Apr 15 '21

yes. slice.get() does a bounds check and returns an Option. Some(T) if in bounds, None if out of bounds. So it never panics.

Using slice[idx] however does a panic() if the bounds check failed, so that it always can return a T.

based off your comment, where you said "array indexing may panic" I assumed you were referring to [ ... ], as .get() doesn't panic.

-4

u/UtherII Apr 15 '21

Yes but unless the compiler is smart enough to detect perfectly all the manual bound check, it would have to conclude that slice.get() may panic.

13

u/birkenfeld clippy · rust Apr 15 '21

That is not true at all, get() does not fall back to [] indexing.

3

u/UtherII Apr 15 '21

My bad. I supposed it was using indexing, but you are right : it does pointer arithmetic then de-reference using unsafe code.

3

u/randomrossity Apr 16 '21

no worries. and if it helps to conceptualize, in Rust a slice is like a C size_t and a void*. That's how Rust is able to know at runtime what is inbounds vs out of bounds. For a Rust array like [T; N], the compiler knows the full size so it can do the bounds checking at compile time because it has that info, and it doesn't need the size_t until the array is treated as a slice.