tasm_lib/arithmetic/u64/
sub.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
use std::collections::HashMap;

use triton_vm::prelude::*;

use crate::arithmetic::u64::overflowing_sub::OverflowingSub;
use crate::prelude::*;
use crate::traits::basic_snippet::Reviewer;
use crate::traits::basic_snippet::SignOffFingerprint;

/// [Subtraction][sub] for unsigned 64-bit integers.
///
/// # Behavior
///
/// ```text
/// BEFORE: _ [subtrahend: u64] [minuend: u64]
/// AFTER:  _ [difference: u64]
/// ```
///
/// # Preconditions
///
/// - the `minuend` is greater than or equal to the `subtrahend`
/// - all input arguments are properly [`BFieldCodec`] encoded
///
/// # Postconditions
///
/// - the output is the `minuend` minus the `subtrahend`
/// - the output is properly [`BFieldCodec`] encoded
///
/// [sub]: core::ops::Sub
#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash)]
pub struct Sub;

impl Sub {
    pub const OVERFLOW_ERROR_ID: i128 = 340;
}

impl BasicSnippet for Sub {
    fn inputs(&self) -> Vec<(DataType, String)> {
        OverflowingSub.inputs()
    }

    fn outputs(&self) -> Vec<(DataType, String)> {
        vec![(DataType::U64, "difference".to_string())]
    }

    fn entrypoint(&self) -> String {
        "tasmlib_arithmetic_u64_sub".to_string()
    }

    fn code(&self, _: &mut Library) -> Vec<LabelledInstruction> {
        triton_asm!(
            // BEFORE: _ subtrahend_hi subtrahend_lo minuend_hi minuend_lo
            // AFTER:  _ difference_hi difference_lo
            {self.entrypoint()}:
                {&OverflowingSub::common_subtraction_code()}
                // _ difference_lo (minuend_hi - subtrahend_hi - carry)

                split
                place 2
                // _ difference_hi difference_lo only_0_if_no_overflow

                push 0
                eq
                assert error_id {Self::OVERFLOW_ERROR_ID}
                // _ difference_hi difference_lo

                return
        )
    }

    fn sign_offs(&self) -> HashMap<Reviewer, SignOffFingerprint> {
        let mut sign_offs = HashMap::new();
        sign_offs.insert(Reviewer("ferdinand"), 0x7d887e69af21cab6.into());
        sign_offs
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::test_prelude::*;

    impl Sub {
        pub fn assert_expected_behavior(&self, subtrahend: u64, minuend: u64) {
            let mut expected_stack = self.set_up_test_stack((subtrahend, minuend));
            self.rust_shadow(&mut expected_stack);

            test_rust_equivalence_given_complete_state(
                &ShadowedClosure::new(Self),
                &self.set_up_test_stack((subtrahend, minuend)),
                &[],
                &NonDeterminism::default(),
                &None,
                Some(&expected_stack),
            );
        }
    }

    impl Closure for Sub {
        type Args = <OverflowingSub as Closure>::Args;

        fn rust_shadow(&self, stack: &mut Vec<BFieldElement>) {
            let (subtrahend, minuend) = pop_encodable::<Self::Args>(stack);
            push_encodable(stack, &(minuend - subtrahend));
        }

        fn pseudorandom_args(
            &self,
            seed: [u8; 32],
            bench_case: Option<BenchmarkCase>,
        ) -> Self::Args {
            let Some(bench_case) = bench_case else {
                let mut rng = StdRng::from_seed(seed);
                let subtrahend = rng.random();
                let minuend = rng.random_range(subtrahend..=u64::MAX);
                return (subtrahend, minuend);
            };

            match bench_case {
                BenchmarkCase::CommonCase => (0x3ff, 0x7fff_ffff),
                BenchmarkCase::WorstCase => (0x1_7fff_ffff, 0x64_0000_03ff),
            }
        }

        fn corner_case_args(&self) -> Vec<Self::Args> {
            let edge_case_values = OverflowingSub::edge_case_values();

            edge_case_values
                .iter()
                .cartesian_product(&edge_case_values)
                .filter(|(&subtrahend, &minuend)| minuend.checked_sub(subtrahend).is_some())
                .map(|(&subtrahend, &minuend)| (subtrahend, minuend))
                .collect()
        }
    }

    #[test]
    fn rust_shadow() {
        ShadowedClosure::new(Sub).test();
    }

    #[test]
    fn unit_test() {
        Sub.assert_expected_behavior(129, 256);
        Sub.assert_expected_behavior(1, 1 << 32);
    }

    #[proptest]
    fn property_test(subtrahend: u64, #[strategy(#subtrahend..)] minuend: u64) {
        Sub.assert_expected_behavior(subtrahend, minuend);
    }

    #[proptest]
    fn negative_property_test(
        #[strategy(1_u64..)] subtrahend: u64,
        #[strategy(..#subtrahend)] minuend: u64,
    ) {
        test_assertion_failure(
            &ShadowedClosure::new(Sub),
            InitVmState::with_stack(Sub.set_up_test_stack((subtrahend, minuend))),
            &[Sub::OVERFLOW_ERROR_ID],
        );
    }
}

#[cfg(test)]
mod benches {
    use super::*;
    use crate::test_prelude::*;

    #[test]
    fn benchmark() {
        ShadowedClosure::new(Sub).bench();
    }
}