]> git.lizzy.rs Git - rust.git/blob - src/tools/miri/src/helpers/convert.rs
Rollup merge of #102115 - Alfriadox:master, r=thomcc
[rust.git] / src / tools / miri / src / helpers / convert.rs
1 use implementations::NarrowerThan;
2
3 /// Replacement for `as` casts going from wide integer to narrower integer.
4 ///
5 /// # Example
6 ///
7 /// ```ignore
8 /// let x = 99_u64;
9 /// let lo = x.truncate::<u16>();
10 /// // lo is of type u16, equivalent to `x as u16`.
11 /// ```
12 pub(crate) trait Truncate: Sized {
13     fn truncate<To>(self) -> To
14     where
15         To: NarrowerThan<Self>,
16     {
17         NarrowerThan::truncate_from(self)
18     }
19 }
20
21 impl Truncate for u16 {}
22 impl Truncate for u32 {}
23 impl Truncate for u64 {}
24 impl Truncate for u128 {}
25
26 mod implementations {
27     pub(crate) trait NarrowerThan<T> {
28         fn truncate_from(wide: T) -> Self;
29     }
30
31     macro_rules! impl_narrower_than {
32         ($(NarrowerThan<{$($ty:ty),*}> for $self:ty)*) => {
33             $($(
34                 impl NarrowerThan<$ty> for $self {
35                     fn truncate_from(wide: $ty) -> Self {
36                         wide as Self
37                     }
38                 }
39             )*)*
40         };
41     }
42
43     impl_narrower_than! {
44         NarrowerThan<{u128, u64, u32, u16}> for u8
45         NarrowerThan<{u128, u64, u32}> for u16
46         NarrowerThan<{u128, u64}> for u32
47         NarrowerThan<{u128}> for u64
48     }
49 }