|
| 1 | +mod sealed { |
| 2 | + pub trait Sealed {} |
| 3 | +} |
| 4 | +use sealed::Sealed; |
| 5 | + |
| 6 | +/// Supporting trait for byte conversion functions. |
| 7 | +pub trait ToBytes: Sealed { |
| 8 | + /// The bytes representation of this type. |
| 9 | + type Bytes; |
| 10 | + |
| 11 | + #[doc(hidden)] |
| 12 | + fn to_bytes_impl(self) -> Self::Bytes; |
| 13 | + |
| 14 | + #[doc(hidden)] |
| 15 | + fn from_bytes_impl(bytes: Self::Bytes) -> Self; |
| 16 | +} |
| 17 | + |
| 18 | +macro_rules! impl_to_bytes { |
| 19 | + { $name:ident, $($int_width:literal -> $byte_width:literal),* } => { |
| 20 | + $( |
| 21 | + impl Sealed for crate::$name<$int_width> where Self: crate::LanesAtMost32 {} |
| 22 | + impl ToBytes for crate::$name<$int_width> |
| 23 | + where |
| 24 | + Self: crate::LanesAtMost32, |
| 25 | + crate::SimdU8<$byte_width>: crate::LanesAtMost32, |
| 26 | + { |
| 27 | + type Bytes = crate::SimdU8<$byte_width>; |
| 28 | + fn to_bytes_impl(self) -> Self::Bytes { |
| 29 | + unsafe { core::mem::transmute(self) } |
| 30 | + } |
| 31 | + fn from_bytes_impl(bytes: Self::Bytes) -> Self { |
| 32 | + unsafe { core::mem::transmute(bytes) } |
| 33 | + } |
| 34 | + } |
| 35 | + )* |
| 36 | + |
| 37 | + impl<const LANES: usize> crate::$name<LANES> |
| 38 | + where |
| 39 | + Self: ToBytes + crate::LanesAtMost32, |
| 40 | + { |
| 41 | + /// Return the memory representation of this integer as a byte array in native byte |
| 42 | + /// order. |
| 43 | + pub fn to_ne_bytes(self) -> <Self as ToBytes>::Bytes { self.to_bytes_impl() } |
| 44 | + |
| 45 | + /// Create a native endian integer value from its memory representation as a byte array |
| 46 | + /// in native endianness. |
| 47 | + pub fn from_ne_bytes(bytes: <Self as ToBytes>::Bytes) -> Self { Self::from_bytes_impl(bytes) } |
| 48 | + } |
| 49 | + } |
| 50 | +} |
| 51 | + |
| 52 | +impl_to_bytes! { SimdU8, 1 -> 1, 2 -> 2, 4 -> 4, 8 -> 8, 16 -> 16, 32 -> 32 } |
| 53 | +impl_to_bytes! { SimdU16, 1 -> 2, 2 -> 4, 4 -> 8, 8 -> 16, 16 -> 32 } |
| 54 | +impl_to_bytes! { SimdU32, 1 -> 4, 2 -> 8, 4 -> 16, 8 -> 32 } |
| 55 | +impl_to_bytes! { SimdU64, 1 -> 8, 2 -> 16, 4 -> 32 } |
| 56 | +#[cfg(target_pointer_width = "32")] |
| 57 | +impl_to_bytes! { SimdUsize, 1 -> 4, 2 -> 8, 4 -> 16, 8 -> 32 } |
| 58 | +#[cfg(target_pointer_width = "64")] |
| 59 | +impl_to_bytes! { SimdUsize, 1 -> 8, 2 -> 16, 4 -> 32 } |
| 60 | + |
| 61 | +impl_to_bytes! { SimdI8, 1 -> 1, 2 -> 2, 4 -> 4, 8 -> 8, 16 -> 16, 32 -> 32 } |
| 62 | +impl_to_bytes! { SimdI16, 1 -> 2, 2 -> 4, 4 -> 8, 8 -> 16, 16 -> 32 } |
| 63 | +impl_to_bytes! { SimdI32, 1 -> 4, 2 -> 8, 4 -> 16, 8 -> 32 } |
| 64 | +impl_to_bytes! { SimdI64, 1 -> 8, 2 -> 16, 4 -> 32 } |
| 65 | +#[cfg(target_pointer_width = "32")] |
| 66 | +impl_to_bytes! { SimdIsize, 1 -> 4, 2 -> 8, 4 -> 16, 8 -> 32 } |
| 67 | +#[cfg(target_pointer_width = "64")] |
| 68 | +impl_to_bytes! { SimdIsize, 1 -> 8, 2 -> 16, 4 -> 32 } |
0 commit comments