Avatar ·

Is it possible to implement the fast inverse square root from Quake in Rust?

Hi everyone! I'm learning Rust and came across the legendary InvSqrt() function from Quake III Arena, which computes 1/sqrt(x) incredibly fast using bit hacks. In C/C++ it looks like this:\n\n```c\nfloat Q_rsqrt(float number) {\n long i;\n float x2, y;\n const float threehalfs = 1.5F;\n\n x2 = number * 0.5F;\n y = number;\n i = * ( long * ) &y; // evil cast (type punning)\n i = 0x5f3759df - ( i >> 1 ); // magic constant\n y = * ( float * ) &i;\n y = y * ( threehalfs - ( x2 * y * y ) ); // one Newton iteration\n return y;\n}\n```\n\nThe problem is that in Rust such direct pointer casting (`*(long*)&y`) is considered undefined behavior (UB) and is forbidden. I tried doing it through `transmute`:\n\n```rust\nfn inv_sqrt(x: f32) -> f32 {