oscar6echo / rust-c-go-speed

12 stars 4 forks source link

Unsafe rust test #1

Closed anuradhawick closed 6 months ago

anuradhawick commented 6 months ago

The unsafe part of rust was not quite clear. Could you explain what was different compared to rust safe and unsafe executions?

Thanks, Anuradha

oscar6echo commented 6 months ago

The unsafe code is here: https://github.com/oscar6echo/rust-c-go-speed/blob/main/rust/src/key_gen_face_five.rs

In short accessing an element in a vec by an index requires a bound check.
If it is certain that the index is not outside bounds one can .get_unchecked(index) to access the value in an unsafe block.

Now if the index is written in such a way that the compiler knows that it is not out of bounds, then no unsafe block is necessary.
Example: valid = (0..c - 1).all(|i| !sums[i + 1..c].contains(&sums[i])); (from file)

In general it is not advised to use unsafe blocks, and in this case there is a faster safe version anyway.

Also, it is worth reading the related rust forum conversation: https://users.rust-lang.org/t/rust-vs-c-vs-go-runtime-speed-comparison/104107

Hope this clarifies a bit.

anuradhawick commented 6 months ago

Thanks for the clarification. Makes sense now. :)