Skip to content

Commit bfb5bf5

Browse files
committed
Add try_transmute!, try_transmute_{ref,mut}!
TODO: Commit message body TODO: - Update try_transmute! docs to mention the size equality constraint? Add an example of this failing? - In `try_transmute!`, should the argument be dropped or forgotten (ie, `mem::forget`) when the transmute fails? Makes progress on #5
1 parent d1921e2 commit bfb5bf5

File tree

3 files changed

+243
-2
lines changed

3 files changed

+243
-2
lines changed

src/lib.rs

Lines changed: 197 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1939,14 +1939,16 @@ mod simd {
19391939
simd_arch_mod!(arm, int8x4_t, uint8x4_t);
19401940
}
19411941

1942-
// Used in `transmute!` below.
1942+
// Used in macros below.
19431943
#[doc(hidden)]
19441944
pub use core::mem::transmute as __real_transmute;
1945+
#[doc(hidden)]
1946+
pub use core::mem::ManuallyDrop as __RealManuallyDrop;
19451947

19461948
/// Safely transmutes a value of one type to a value of another type of the same
19471949
/// size.
19481950
///
1949-
/// The expression `$e` must have a concrete type, `T`, which implements
1951+
/// The expression, `$e`, must have a concrete type, `T`, which implements
19501952
/// `AsBytes`. The `transmute!` expression must also have a concrete type, `U`
19511953
/// (`U` is inferred from the calling context), and `U` must implement
19521954
/// `FromBytes`.
@@ -1989,6 +1991,168 @@ macro_rules! transmute {
19891991
}}
19901992
}
19911993

1994+
/// Safely attempts to transmute a value of one type to a value of another type
1995+
/// of the same size, failing if the transmute would be unsound.
1996+
///
1997+
/// The expression, `$e`, must have a concrete type, `T`, which implements
1998+
/// `AsBytes`. The `try_transmute!` expression must also have a concrete type,
1999+
/// `Option<U>` (`U` is inferred from the calling context), and `U` must
2000+
/// implement `TryFromBytes`.
2001+
///
2002+
/// [`TryFromBytes::try_read_from`] is used to attempt to convert `$e` to the
2003+
/// output type `U`. This will fail if the bytes of `$e` do not correspond to a
2004+
/// valid instance of `U`.
2005+
///
2006+
/// Note that the `T` produced by the expression `$e` will *not* be dropped.
2007+
/// Semantically, its bits will be copied into a new value of type `U`, the
2008+
/// original `T` will be forgotten, and the value of type `U` will be returned.
2009+
///
2010+
/// # Examples
2011+
///
2012+
/// ```rust
2013+
/// # use zerocopy::try_transmute;
2014+
/// assert_eq!(try_transmute!(1u8), Some(true));
2015+
/// assert_eq!(try_transmute!(2u8), None::<bool>);
2016+
///
2017+
/// assert_eq!(try_transmute!(108u32), Some('l'));
2018+
/// assert_eq!(try_transmute!(0xD800u32), None::<char>);
2019+
/// ```
2020+
#[macro_export]
2021+
macro_rules! try_transmute {
2022+
($e:expr) => {{
2023+
// NOTE: This must be a macro (rather than a function with trait bounds)
2024+
// because there's no way, in a generic context, to enforce that two
2025+
// types have the same size. `core::mem::transmute` uses compiler magic
2026+
// to enforce this so long as the types are concrete.
2027+
2028+
let e = $e;
2029+
if false {
2030+
// This branch, though never taken, ensures that the type of `e` is
2031+
// `AsBytes` and that the type of this macro invocation expression
2032+
// is `TryFromBytes`.
2033+
const fn transmute<T: $crate::AsBytes, U: $crate::TryFromBytes>(_t: T) -> U {
2034+
unreachable!()
2035+
}
2036+
Some(transmute(e))
2037+
} else if false {
2038+
// Though never executed, this ensures that the source and
2039+
// destination types have the same size. This isn't strictly
2040+
// necessary for soundness, but it turns what would otherwise be
2041+
// runtime errors into compile-time errors.
2042+
//
2043+
// SAFETY: This branch never executes.
2044+
Some(unsafe { $crate::__real_transmute(e) })
2045+
} else {
2046+
// TODO: What's the correct drop behavior on `None`? Does this just
2047+
// behave like `mem::forget` in that case?
2048+
let m = $crate::__RealManuallyDrop::new(e);
2049+
$crate::TryFromBytes::try_read_from($crate::AsBytes::as_bytes(&m))
2050+
}
2051+
}}
2052+
}
2053+
2054+
/// Safely attempts to transmute a reference of one type to a reference of
2055+
/// another type, failing if the transmute would be unsound.
2056+
///
2057+
/// The expression, `$e`, must have a concrete type, `&T`, where `T: AsBytes`.
2058+
/// The `try_transmute_ref!` expression must also have a concrete type,
2059+
/// `Option<&U>` (`U` is inferred from the calling context), and `U` must
2060+
/// implement `TryFromBytes`.
2061+
///
2062+
/// [`TryFromBytes::try_from_ref`] is used to attempt to convert `$e` to the
2063+
/// output reference type `&U`. This will fail if `$e` is not the right size, is
2064+
/// not properly aligned, or if the bytes of `$e` do not correspond to a valid
2065+
/// instance of `U`.
2066+
///
2067+
/// Note that, if `U` is an unsized type, there will be multiple sizes for `$e`
2068+
/// which correspond to valid values of `U`.
2069+
///
2070+
/// # Examples
2071+
///
2072+
/// ```rust
2073+
/// # use zerocopy::try_transmute_ref;
2074+
/// # use zerocopy::AsBytes as _;
2075+
/// let s: Option<&str> = try_transmute_ref!(&[104u8, 101, 108, 108, 111]);
2076+
/// assert_eq!(s, Some("hello"));
2077+
///
2078+
/// // Invalid UTF-8
2079+
/// assert_eq!(try_transmute_ref!(&0xFFFFFFFFu32), None::<&str>);
2080+
///
2081+
/// // Not enough bytes for a `u8`
2082+
/// assert_eq!(try_transmute_ref!(&()), None::<&u8>);
2083+
///
2084+
/// // Valid `&[[u8; 2]]` slices could be 2 or 4 bytes long,
2085+
/// // but not 3.
2086+
/// assert_eq!(try_transmute_ref!(&[0u8, 1, 2]), None::<&[[u8; 2]]>);
2087+
///
2088+
/// // Guaranteed to be invalidly-aligned so long as
2089+
/// // `align_of::<u16>() == 2` and `align_of::<u32>() >= 2`
2090+
/// // (this is true on most targets, but it isn't guaranteed).
2091+
/// assert_eq!(try_transmute_ref!(&0u32.as_bytes()[1..]), None::<&u16>);
2092+
/// ```
2093+
#[macro_export]
2094+
macro_rules! try_transmute_ref {
2095+
($e:expr) => {
2096+
$crate::TryFromBytes::try_from_ref($crate::AsBytes::as_bytes($e))
2097+
};
2098+
}
2099+
2100+
/// Safely attempts to transmute a mutable reference of one type to a mutable
2101+
/// reference of another type, failing if the transmute would be unsound.
2102+
///
2103+
/// The expression, `$e`, must have a concrete type, `&mut T`, where `T:
2104+
/// FromBytes + AsBytes`. The `try_transmute_ref!` expression must also have a
2105+
/// concrete type, `Option<&mut U>` (`U` is inferred from the calling context),
2106+
/// and `U` must implement `TryFromBytes`.
2107+
///
2108+
/// [`TryFromBytes::try_from_mut`] is used to attempt to convert `$e` to the
2109+
/// output reference type, `&mut U`. This will fail if `$e` is not the right
2110+
/// size, is not properly aligned, or if the bytes of `$e` do not correspond to
2111+
/// a valid instance of `U`.
2112+
///
2113+
/// Note that, if `U` is an unsized type, there will be multiple sizes for `$e`
2114+
/// which correspond to valid values of `U`.
2115+
///
2116+
/// # Examples
2117+
///
2118+
/// ```rust
2119+
/// # use zerocopy::try_transmute_mut;
2120+
/// # use zerocopy::AsBytes as _;
2121+
/// let bytes = &mut [104u8, 101, 108, 108, 111];
2122+
/// let mut s = try_transmute_mut!(bytes);
2123+
/// assert_eq!(s, Some(String::from("hello").as_mut_str()));
2124+
///
2125+
/// // Mutations to the transmuted reference are reflected
2126+
/// // in the original reference.
2127+
/// s.as_mut().unwrap().make_ascii_uppercase();
2128+
/// assert_eq!(bytes, &[72, 69, 76, 76, 79]);
2129+
///
2130+
/// // Invalid UTF-8
2131+
/// let mut u = 0xFFFFFFFFu32;
2132+
/// assert_eq!(try_transmute_mut!(&mut u), None::<&mut str>);
2133+
///
2134+
/// // Not enough bytes for a `u8`
2135+
/// let mut tuple = ();
2136+
/// assert_eq!(try_transmute_mut!(&mut tuple), None::<&mut u8>);
2137+
///
2138+
/// // Valid `&mut [[u8; 2]]` slices could be 2 or 4 bytes
2139+
/// // long, but not 3.
2140+
/// let bytes = &mut [0u8, 1, 2];
2141+
/// assert_eq!(try_transmute_mut!(bytes), None::<&mut [[u8; 2]]>);
2142+
///
2143+
/// // Guaranteed to be invalidly-aligned so long as
2144+
/// // `align_of::<u16>() == 2` and `align_of::<u32>() >= 2`
2145+
/// // (this is true on most targets, but it isn't guaranteed).
2146+
/// let mut u = 0u32;
2147+
/// assert_eq!(try_transmute_mut!(&mut u.as_bytes_mut()[1..]), None::<&mut u16>);
2148+
/// ```
2149+
#[macro_export]
2150+
macro_rules! try_transmute_mut {
2151+
($e:expr) => {
2152+
$crate::TryFromBytes::try_from_mut($crate::AsBytes::as_bytes_mut($e))
2153+
};
2154+
}
2155+
19922156
/// A typed reference derived from a byte slice.
19932157
///
19942158
/// A `Ref<B, T>` is a reference to a `T` which is stored in a byte slice, `B`.
@@ -3599,10 +3763,16 @@ mod tests {
35993763
// Test that memory is transmuted as expected.
36003764
let array_of_u8s = [0u8, 1, 2, 3, 4, 5, 6, 7];
36013765
let array_of_arrays = [[0, 1], [2, 3], [4, 5], [6, 7]];
3766+
36023767
let x: [[u8; 2]; 4] = transmute!(array_of_u8s);
36033768
assert_eq!(x, array_of_arrays);
3769+
let x: Option<[[u8; 2]; 4]> = try_transmute!(array_of_u8s);
3770+
assert_eq!(x, Some(array_of_arrays));
3771+
36043772
let x: [u8; 8] = transmute!(array_of_arrays);
36053773
assert_eq!(x, array_of_u8s);
3774+
let x: Option<[u8; 8]> = try_transmute!(array_of_arrays);
3775+
assert_eq!(x, Some(array_of_u8s));
36063776

36073777
// Test that the source expression's value is forgotten rather than
36083778
// dropped.
@@ -3615,12 +3785,37 @@ mod tests {
36153785
}
36163786
}
36173787
let _: () = transmute!(PanicOnDrop(()));
3788+
let _: Option<()> = try_transmute!(PanicOnDrop(()));
36183789

36193790
// Test that `transmute!` is legal in a const context.
36203791
const ARRAY_OF_U8S: [u8; 8] = [0u8, 1, 2, 3, 4, 5, 6, 7];
36213792
const ARRAY_OF_ARRAYS: [[u8; 2]; 4] = [[0, 1], [2, 3], [4, 5], [6, 7]];
36223793
const X: [[u8; 2]; 4] = transmute!(ARRAY_OF_U8S);
36233794
assert_eq!(X, ARRAY_OF_ARRAYS);
3795+
3796+
// Test fallible transmutations with `try_transmute!`.
3797+
let mut b: Option<bool> = try_transmute!(0u8);
3798+
assert_eq!(b, Some(false));
3799+
b = try_transmute!(1u8);
3800+
assert_eq!(b, Some(true));
3801+
b = try_transmute!(2u8);
3802+
assert_eq!(b, None);
3803+
}
3804+
3805+
#[test]
3806+
fn test_try_transmute_ref_mut() {
3807+
// These macros are dead-simple thin wrappers which delegate to other
3808+
// traits. We only have this test to ensure that the macros are uesd
3809+
// somewhere so our tests will break if the paths to various items
3810+
// break.
3811+
let x: Option<&[u8; 2]> = try_transmute_ref!(&0xFFFFu16);
3812+
assert_eq!(x, Some(&[255, 255]));
3813+
3814+
let mut u = 0xFFFFu16;
3815+
let x: Option<&mut [u8; 2]> = try_transmute_mut!(&mut u);
3816+
assert_eq!(x, Some(&mut [255, 255]));
3817+
*x.unwrap() = [0, 0];
3818+
assert_eq!(u, 0);
36243819
}
36253820

36263821
#[test]

tests/ui-nightly/transmute-illegal.rs

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,3 +8,9 @@ fn main() {}
88

99
// It is unsound to inspect the usize value of a pointer during const eval.
1010
const POINTER_VALUE: usize = zerocopy::transmute!(&0usize as *const usize);
11+
12+
// `transmute!` and `try_transmute!` enforce size equality.
13+
const TOO_LARGE: u64 = zerocopy::transmute!(0u8);
14+
const TRY_TOO_LARGE: Option<u64> = zerocopy::try_transmute!(0u8);
15+
const TOO_SMALL: u8 = zerocopy::transmute!(0u64);
16+
const TRY_TOO_SMALL: Option<u8> = zerocopy::try_transmute!(0u64);

tests/ui-nightly/transmute-illegal.stderr

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,3 +14,43 @@ note: required by a bound in `POINTER_VALUE::transmute`
1414
10 | const POINTER_VALUE: usize = zerocopy::transmute!(&0usize as *const usize);
1515
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ required by this bound in `transmute`
1616
= note: this error originates in the macro `zerocopy::transmute` (in Nightly builds, run with -Z macro-backtrace for more info)
17+
18+
error[E0512]: cannot transmute between types of different sizes, or dependently-sized types
19+
--> tests/ui-nightly/transmute-illegal.rs:13:24
20+
|
21+
13 | const TOO_LARGE: u64 = zerocopy::transmute!(0u8);
22+
| ^^^^^^^^^^^^^^^^^^^^^^^^^
23+
|
24+
= note: source type: `u8` (8 bits)
25+
= note: target type: `u64` (64 bits)
26+
= note: this error originates in the macro `zerocopy::transmute` (in Nightly builds, run with -Z macro-backtrace for more info)
27+
28+
error[E0512]: cannot transmute between types of different sizes, or dependently-sized types
29+
--> tests/ui-nightly/transmute-illegal.rs:14:36
30+
|
31+
14 | const TRY_TOO_LARGE: Option<u64> = zerocopy::try_transmute!(0u8);
32+
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
33+
|
34+
= note: source type: `u8` (8 bits)
35+
= note: target type: `u64` (64 bits)
36+
= note: this error originates in the macro `zerocopy::try_transmute` (in Nightly builds, run with -Z macro-backtrace for more info)
37+
38+
error[E0512]: cannot transmute between types of different sizes, or dependently-sized types
39+
--> tests/ui-nightly/transmute-illegal.rs:15:23
40+
|
41+
15 | const TOO_SMALL: u8 = zerocopy::transmute!(0u64);
42+
| ^^^^^^^^^^^^^^^^^^^^^^^^^^
43+
|
44+
= note: source type: `u64` (64 bits)
45+
= note: target type: `u8` (8 bits)
46+
= note: this error originates in the macro `zerocopy::transmute` (in Nightly builds, run with -Z macro-backtrace for more info)
47+
48+
error[E0512]: cannot transmute between types of different sizes, or dependently-sized types
49+
--> tests/ui-nightly/transmute-illegal.rs:16:35
50+
|
51+
16 | const TRY_TOO_SMALL: Option<u8> = zerocopy::try_transmute!(0u64);
52+
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
53+
|
54+
= note: source type: `u64` (64 bits)
55+
= note: target type: `u8` (8 bits)
56+
= note: this error originates in the macro `zerocopy::try_transmute` (in Nightly builds, run with -Z macro-backtrace for more info)

0 commit comments

Comments
 (0)