assert_into/
lib.rs

1#![no_std]
2
3use core::{any::type_name, convert::TryFrom, fmt::Debug};
4
5pub trait AssertInto<T>: Sized {
6    fn assert_into(self) -> T;
7}
8
9impl<T, U> AssertInto<U> for T
10where
11    U: TryFrom<T>,
12    T: Debug,
13    T: Copy,
14    <U as TryFrom<T>>::Error: Debug,
15{
16    #[inline]
17    #[track_caller]
18    fn assert_into(self) -> U {
19        let v = U::try_from(self);
20
21        match v {
22            Ok(v) => v,
23            Err(e) => {
24                panic!(
25                    "{:?} is out of range for type {}: {:?}",
26                    self,
27                    type_name::<U>(),
28                    e
29                );
30            }
31        }
32    }
33}