Skip to main content

yevm_base/
int.rs

1use yevm_misc::hex::{Hex, parse};
2
3pub type Int = Hex<32>;
4
5pub const fn int(s: &str) -> Int {
6    Int::new(parse(s))
7}
8
9pub mod math {
10    use ruint::Uint;
11
12    use crate::Int;
13
14    pub type U256 = Uint<256, 4>;
15
16    pub struct Val(U256);
17
18    pub const ONE: U256 = U256::ONE;
19    pub const ZERO: U256 = U256::ZERO;
20
21    impl From<Int> for Val {
22        fn from(int: Int) -> Self {
23            Val(U256::from_be_slice(int.as_ref()))
24        }
25    }
26
27    impl From<Val> for Int {
28        fn from(val: Val) -> Self {
29            let buffer: [u8; 32] = val.0.to_be_bytes();
30            Int::from(&buffer[..])
31        }
32    }
33
34    pub fn lift<const N: usize>(f: impl Fn([U256; N]) -> U256) -> impl Fn([Int; N]) -> Int {
35        move |xs: [Int; N]| {
36            let mut ys = [U256::ZERO; N];
37            for i in 0..N {
38                let v: Val = xs[i].into();
39                ys[i] = v.0;
40            }
41            let r = f(ys);
42            Val(r).into()
43        }
44    }
45
46    #[cfg(test)]
47    mod tests {
48        use super::*;
49
50        #[test]
51        fn test_add() {
52            let f = lift(|[a, b]| a + b);
53            let a = Int::from(41u32);
54            let b = Int::ONE;
55            let c = Int::from(42u32);
56            assert_eq!(f([a, b]), c);
57        }
58    }
59}