Skip to main content

rand_core/
word.rs

1//! The [`Word`] trait
2
3/// A marker trait for supported "word" types.
4///
5/// This is implemented for: `u32`, `u64`.
6pub trait Word: sealed::Sealed {}
7
8impl Word for u32 {}
9impl Word for u64 {}
10
11mod sealed {
12    /// Sealed trait implemented for `u32` and `u64`.
13    pub trait Sealed: Default + Copy + TryFrom<usize> + Eq + core::hash::Hash {
14        type Bytes: Default + Sized + AsRef<[u8]> + AsMut<[u8]>;
15
16        fn from_le_bytes(bytes: Self::Bytes) -> Self;
17        fn to_le_bytes(self) -> Self::Bytes;
18
19        fn from_usize(val: usize) -> Self;
20        fn into_usize(self) -> usize;
21    }
22
23    impl Sealed for u32 {
24        type Bytes = [u8; 4];
25
26        #[inline(always)]
27        fn from_le_bytes(bytes: Self::Bytes) -> Self {
28            Self::from_le_bytes(bytes)
29        }
30        #[inline(always)]
31        fn to_le_bytes(self) -> Self::Bytes {
32            Self::to_le_bytes(self)
33        }
34
35        #[inline(always)]
36        fn from_usize(val: usize) -> Self {
37            val.try_into().unwrap()
38        }
39        #[inline(always)]
40        fn into_usize(self) -> usize {
41            self.try_into().unwrap()
42        }
43    }
44
45    impl Sealed for u64 {
46        type Bytes = [u8; 8];
47
48        #[inline(always)]
49        fn from_le_bytes(bytes: Self::Bytes) -> Self {
50            Self::from_le_bytes(bytes)
51        }
52        #[inline(always)]
53        fn to_le_bytes(self) -> Self::Bytes {
54            Self::to_le_bytes(self)
55        }
56
57        #[inline(always)]
58        fn from_usize(val: usize) -> Self {
59            val.try_into().unwrap()
60        }
61        #[inline(always)]
62        fn into_usize(self) -> usize {
63            self.try_into().unwrap()
64        }
65    }
66}