Crate safe_transmute
source ·Expand description
This crate contains checked implementations of transmute()
.
The base functions in this crate are not inherently safe, but just guarded against common simple mistakes (like trying to create an 8-byte type from 7 bytes). These functions are exactly as safe as the data passed to them - creating a null pointer, for example, is not unsafe in and of itself, but dereferencing it certainly is, but they don’t do that (see here for extended discussion).
Other functions in this crate, on the other hand, provide enough safety measures to ensure safety in
all circumstances. This is the case for those found in the pod
and bool
modules.
Take note, however, that alignment is unaccounted for: you may, in the course of using this crate, invoke unaligned access, which some CPUs may trap on; that did not, however, happen in any of our tests on MIPS64 (BE), x86_64 (LE), nor armv6l (LE).
This crate can be used in a no-std
environment by disabling the std
feature through specifying
default-features = false
on import.
Examples
View bytes as a series of u16
s:
assert_eq!(guarded_transmute_many::<u16>(&[0x00, 0x01,
0x12, 0x34,
// Spare byte, unused
0x00])?,
&[0x0100, 0x3412]);
View all bytes as a series of u16
s:
assert_eq!(guarded_transmute_many_pedantic::<u16>(&[0x00, 0x01,
0x12, 0x34])?,
&[0x0100, 0x3412]);
View bytes as an f64
:
assert_eq!(guarded_transmute::<f64>(&[0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x40])?,
2.0);
View a series of u16
s as bytes:
assert_eq!(guarded_transmute_to_bytes_pod_many(&[0x0001u16,
0x1234u16]),
&[0x01, 0x00, 0x34, 0x12].le_to_native::<u16>());
Modules
guard
module exposes an API for memory boundary checking.Structs
Guard
.Enums
Traits
unsafe
ly transmuted intoFunctions
Copy
able type.Copy
able type.