Skip to main content

zinc_utils/
from_ref.rs

1use crypto_primitives::{boolean::Boolean, crypto_bigint_int::Int, crypto_bigint_uint::Uint};
2
3//
4// FromRef
5//
6
7/// This trait is essentially equivalent to `From<&T>`, other than it allows us
8/// to implement it for external types that don't implement it out of the box,
9/// most notably primitive types.
10pub trait FromRef<T> {
11    fn from_ref(value: &T) -> Self;
12}
13
14impl<T> FromRef<Boolean> for T
15where
16    T: From<bool>,
17{
18    fn from_ref(value: &Boolean) -> Self {
19        T::from(**value)
20    }
21}
22
23macro_rules! impl_from_ref_for_primitive {
24    ($dst:ty, [$($src:ty),+]) => {
25        $(
26            impl FromRef<$src> for $dst {
27                fn from_ref(value: &$src) -> Self {
28                    <$dst>::from(*value)
29                }
30            }
31        )+
32    };
33}
34
35impl_from_ref_for_primitive!(i128, [i128, i64, i32, i16, i8]);
36impl_from_ref_for_primitive!(i64, [i64, i32, i16, i8]);
37impl_from_ref_for_primitive!(i32, [i32, i16, i8]);
38impl_from_ref_for_primitive!(i16, [i16, i8]);
39impl_from_ref_for_primitive!(i8, [i8]);
40
41macro_rules! impl_int_from_primitive_ref {
42    ($($t:ty),+) => {
43        $(
44            impl<const LIMBS: usize> FromRef<$t> for Int<LIMBS> {
45                #[inline(always)]
46                fn from_ref(value: &$t) -> Self {
47                    Self::from(*value)
48                }
49            }
50        )+
51    };
52}
53
54impl_int_from_primitive_ref!(i8, i16, i32, i64, i128);
55
56impl<const LIMBS: usize, const LIMBS2: usize> FromRef<Int<LIMBS2>> for Int<LIMBS> {
57    #[inline]
58    fn from_ref(value: &Int<LIMBS2>) -> Self {
59        Self::try_from(value.inner()).expect("Destination Int type is too small")
60    }
61}
62
63impl<const LIMBS: usize, const LIMBS2: usize> FromRef<Uint<LIMBS2>> for Uint<LIMBS> {
64    #[inline]
65    fn from_ref(value: &Uint<LIMBS2>) -> Self {
66        Self::try_from(value.inner()).expect("Destination Uint type is too small")
67    }
68}