1 use implementations::NarrowerThan;
3 /// Replacement for `as` casts going from wide integer to narrower integer.
9 /// let lo = x.truncate::<u16>();
10 /// // lo is of type u16, equivalent to `x as u16`.
12 pub(crate) trait Truncate: Sized {
13 fn truncate<To>(self) -> To
15 To: NarrowerThan<Self>,
17 NarrowerThan::truncate_from(self)
21 impl Truncate for u16 {}
22 impl Truncate for u32 {}
23 impl Truncate for u64 {}
24 impl Truncate for u128 {}
27 pub(crate) trait NarrowerThan<T> {
28 fn truncate_from(wide: T) -> Self;
31 macro_rules! impl_narrower_than {
32 ($(NarrowerThan<{$($ty:ty),*}> for $self:ty)*) => {
34 impl NarrowerThan<$ty> for $self {
35 fn truncate_from(wide: $ty) -> Self {
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