tasm_lib/arithmetic/u64/
incr.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
use std::collections::HashMap;

use triton_vm::prelude::*;

use crate::prelude::*;
use crate::traits::basic_snippet::Reviewer;
use crate::traits::basic_snippet::SignOffFingerprint;

/// Increment a `u64` by 1.
///
/// Crashes the VM if the input is [`u64::MAX`].
///
/// ### Behavior
///
/// ```text
/// BEFORE: _ v
/// AFTER:  _ (v+1)
/// ```
///
/// ### Preconditions
///
/// - all input arguments are properly [`BFieldCodec`] encoded
///
/// ### Postconditions
///
/// - the output is properly [`BFieldCodec`] encoded
#[derive(Debug, Default, Copy, Clone, Eq, PartialEq, Hash)]
pub struct Incr;

impl Incr {
    pub const OVERFLOW_ERROR_ID: i128 = 440;
}

impl BasicSnippet for Incr {
    fn inputs(&self) -> Vec<(DataType, String)> {
        vec![(DataType::U64, "value".to_string())]
    }

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

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

    fn code(&self, _: &mut Library) -> Vec<LabelledInstruction> {
        let entrypoint = self.entrypoint();
        let carry = format!("{entrypoint}_carry");
        triton_asm!(
            // BEFORE: _ [value: u64]
            // AFTER:  _ [value + 1: u64]
            {entrypoint}:
                addi 1
                dup 0
                push {1_u64 << 32}
                eq
                skiz
                    call {carry}
                return

            {carry}:
                pop 1
                addi 1
                dup 0
                push {1_u64 << 32}
                eq
                push 0
                eq
                assert error_id {Self::OVERFLOW_ERROR_ID}
                push 0
                return
        )
    }

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

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

    impl Closure for Incr {
        type Args = u64;

        fn rust_shadow(&self, stack: &mut Vec<BFieldElement>) {
            let v = pop_encodable::<Self::Args>(stack);
            let incr = v.checked_add(1).unwrap();
            push_encodable(stack, &incr);
        }

        fn pseudorandom_args(
            &self,
            seed: [u8; 32],
            bench_case: Option<BenchmarkCase>,
        ) -> Self::Args {
            match bench_case {
                Some(BenchmarkCase::CommonCase) => (1000 << 32) + 7, // no carry
                Some(BenchmarkCase::WorstCase) => (1000 << 32) + u64::from(u32::MAX), // carry
                None => StdRng::from_seed(seed).random(),
            }
        }

        fn corner_case_args(&self) -> Vec<Self::Args> {
            vec![0, u32::MAX.into(), u64::MAX - 1]
        }
    }

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

    #[test]
    fn u64_max_crashes_vm() {
        test_assertion_failure(
            &ShadowedClosure::new(Incr),
            InitVmState::with_stack(Incr.set_up_test_stack(u64::MAX)),
            &[Incr::OVERFLOW_ERROR_ID],
        );
    }
}

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

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