Why is x86::_bswap unsafe?

The core::arch::x86::_bswap intrinsic is marked unsafe: https://doc.rust-lang.org/beta/core/arch/x86/fn._bswap.html

Can anyone explain why? It seems like there is no way to violate any kind of safety just swapping some bytes around. Some of the other intrinsics are only safe to call if a particular feature is supported on the processor, so I understand why those would be unsafe, but that is not the case for bswap.

I use bswap as an example, but there are other functions in the same situation. For example: https://doc.rust-lang.org/beta/core/arch/x86/fn.__cpuid_count.html

Thanks!

My default answer was going to be "because it uses target_feature." But it doesn't actually. My guess is that it's an oversight, or more likely, everything in std::arch was assigned an unsafe label in order to be conservative.

I'd say probably submitting a PR to std removing the unsafe would be appropriate.

2 Likes

Ok, thank you.

I think it's because of an expectation that you'd only use it if you're using other unsafe intrinsics anyway, perhaps because you're porting over C code that used said intrinsics.

If you just want to swap bytes in an i32, then you want https://doc.rust-lang.org/std/primitive.i32.html#method.swap_bytes which is safe and cross-platform and just as fast.

3 Likes

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.