tasm_lib/arithmetic/u32/
safe_add.rs

1use std::collections::HashMap;
2
3use triton_vm::prelude::*;
4
5use crate::prelude::*;
6use crate::traits::basic_snippet::Reviewer;
7use crate::traits::basic_snippet::SignOffFingerprint;
8
9/// Add two `u32`s and crash on overflow.
10///
11/// ### Behavior
12///
13/// ```text
14/// BEFORE: _ [right: 32] [left: u32]
15/// AFTER:  _ [left + right: u32]
16/// ```
17///
18/// ### Preconditions
19///
20/// - all input arguments are properly [`BFieldCodec`] encoded
21/// - the sum of `left` and `right` is less than or equal to [`u32::MAX`]
22///
23/// ### Postconditions
24///
25/// - the output is the sum of the input
26/// - the output is properly [`BFieldCodec`] encoded
27#[derive(Debug, Default, Copy, Clone, Eq, PartialEq, Hash)]
28pub struct SafeAdd;
29
30impl SafeAdd {
31    pub const OVERFLOW_ERROR_ID: i128 = 450;
32}
33
34impl BasicSnippet for SafeAdd {
35    fn inputs(&self) -> Vec<(DataType, String)> {
36        ["right", "left"]
37            .map(|s| (DataType::U32, s.to_string()))
38            .to_vec()
39    }
40
41    fn outputs(&self) -> Vec<(DataType, String)> {
42        vec![(DataType::U32, "left + right".to_string())]
43    }
44
45    fn entrypoint(&self) -> String {
46        "tasmlib_arithmetic_u32_safe_add".to_string()
47    }
48
49    fn code(&self, _: &mut Library) -> Vec<LabelledInstruction> {
50        triton_asm!(
51            {self.entrypoint()}:
52                add    // _ sum
53                dup 0  // _ sum sum
54                split  // _ sum hi lo
55                pop 1  // _ sum hi
56                push 0 // _ sum hi 0
57                eq     // _ sum (hi == 0)
58                assert error_id {Self::OVERFLOW_ERROR_ID}
59                return
60        )
61    }
62
63    fn sign_offs(&self) -> HashMap<Reviewer, SignOffFingerprint> {
64        let mut sign_offs = HashMap::new();
65        sign_offs.insert(Reviewer("ferdinand"), 0x92d8f083ca55e1d.into());
66        sign_offs
67    }
68}
69
70#[cfg(test)]
71mod tests {
72    use super::*;
73    use crate::test_prelude::*;
74
75    impl Closure for SafeAdd {
76        type Args = (u32, u32);
77
78        fn rust_shadow(&self, stack: &mut Vec<BFieldElement>) {
79            let (right, left) = pop_encodable::<Self::Args>(stack);
80            let sum = left.checked_add(right).unwrap();
81            push_encodable(stack, &sum);
82        }
83
84        fn pseudorandom_args(
85            &self,
86            seed: [u8; 32],
87            bench_case: Option<BenchmarkCase>,
88        ) -> Self::Args {
89            let Some(bench_case) = bench_case else {
90                let mut rng = StdRng::from_seed(seed);
91                let left = rng.random();
92                let right = rng.random_range(0..=u32::MAX - left);
93
94                return (right, left);
95            };
96
97            match bench_case {
98                BenchmarkCase::CommonCase => (1 << 16, 1 << 15),
99                BenchmarkCase::WorstCase => (u32::MAX >> 1, u32::MAX >> 2),
100            }
101        }
102
103        fn corner_case_args(&self) -> Vec<Self::Args> {
104            vec![(0, u32::MAX)]
105        }
106    }
107
108    #[test]
109    fn rust_shadow() {
110        ShadowedClosure::new(SafeAdd).test();
111    }
112
113    #[proptest]
114    fn overflow_crashes_vm(
115        #[filter(#left != 0)] left: u32,
116        #[strategy(u32::MAX - #left + 1..)] right: u32,
117    ) {
118        debug_assert!(left.checked_add(right).is_none());
119        test_assertion_failure(
120            &ShadowedClosure::new(SafeAdd),
121            InitVmState::with_stack(SafeAdd.set_up_test_stack((left, right))),
122            &[SafeAdd::OVERFLOW_ERROR_ID],
123        )
124    }
125}
126
127#[cfg(test)]
128mod benches {
129    use super::*;
130    use crate::test_prelude::*;
131
132    #[test]
133    fn safe_add_benchmark() {
134        ShadowedClosure::new(SafeAdd).bench();
135    }
136}