3 ms·
You can write this in safe-Rust, with a match. There are only 8 variants, and while it's a bit tedious¹, Rust will optimize it to the same code as if you had do
by deathanatos 3y ago
You can write this in safe-Rust, with a match. There are only 8 variants, and while it's a bit tedious¹, Rust will optimize it to the same code as if you had done a from_raw construction … without the possibility of UB.²
¹(but there has to be a crate for this)
²https://godbolt.org/z/W55W1GxvY https://godbolt.org/z/W55W1GxvY
- hyperman1 3y agoI wish this wasn't downvoted as for me its the right answer. unsafe in rust is a blank cheque for the compiler. Doing anything complicated in it is almost guaranteed to have UB somewhere. You decide to disable safety. If possible, write the safe but tedious code. Then measure. Only when you're sure unsafe is worth it should you take out the big cannon. Write a km of comments proving this code needs and deserves unsafe. Writing the tedious code is less time consuming than debugging the mess. I wish the video author documented why he choose unsafe here. Was it measured and worth it in an older version of rust? Or a folly of youth (which is fine, as long as you learn from it, been there done that paid the time debugging my stupidity)
- dannymi 3y ago>¹(but there has to be a crate for this) num-traits' FromPrimitive https://docs.rs/num-traits/latest/num_traits/cast/trait.FromPrimitive.html https://docs.rs/num-traits/latest/num_traits/cast/trait.From...