tasm_lib/arithmetic/u32/
shift_right.rs1use 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#[derive(Debug, Default, Copy, Clone, Eq, PartialEq, Hash)]
31pub struct ShiftRight;
32
33impl ShiftRight {
34 pub const SHIFT_AMOUNT_TOO_BIG_ERROR_ID: i128 = 490;
35}
36
37impl BasicSnippet for ShiftRight {
38 fn inputs(&self) -> Vec<(DataType, String)> {
39 let arg = (DataType::U32, "arg".to_string());
40 let shift_amount = (DataType::U32, "shift_amount".to_string());
41
42 vec![arg, shift_amount]
43 }
44
45 fn outputs(&self) -> Vec<(DataType, String)> {
46 vec![(DataType::U32, "shifted_arg".to_string())]
47 }
48
49 fn entrypoint(&self) -> String {
50 "tasmlib_arithmetic_u32_shift_right".to_string()
51 }
52
53 fn code(&self, _: &mut Library) -> Vec<LabelledInstruction> {
54 triton_asm!(
55 {self.entrypoint()}:
58 push 32
60 dup 1
61 lt
62 assert error_id {Self::SHIFT_AMOUNT_TOO_BIG_ERROR_ID}
63
64 push -1
66 mul
67 addi 32
68 push 2
69 pow
70 mul
73 split
76 pop 1
77 return
80 )
81 }
82
83 fn sign_offs(&self) -> HashMap<Reviewer, SignOffFingerprint> {
84 let mut sign_offs = HashMap::new();
85 sign_offs.insert(Reviewer("ferdinand"), 0xf07f7ed3f3fe8e49.into());
86 sign_offs
87 }
88}
89
90#[cfg(test)]
91mod tests {
92 use super::*;
93 use crate::test_prelude::*;
94
95 impl Closure for ShiftRight {
96 type Args = (u32, u32);
97
98 fn rust_shadow(&self, stack: &mut Vec<BFieldElement>) {
99 let (arg, shift_amount) = pop_encodable::<Self::Args>(stack);
100 assert!(shift_amount < 32);
101 push_encodable(stack, &(arg >> shift_amount));
102 }
103
104 fn pseudorandom_args(
105 &self,
106 seed: [u8; 32],
107 bench_case: Option<BenchmarkCase>,
108 ) -> Self::Args {
109 let mut rng = StdRng::from_seed(seed);
110 match bench_case {
111 Some(BenchmarkCase::CommonCase) => ((1 << 16) - 1, 16),
112 Some(BenchmarkCase::WorstCase) => (u32::MAX, 1),
113 None => (rng.random(), rng.random_range(0..32)),
114 }
115 }
116
117 fn corner_case_args(&self) -> Vec<Self::Args> {
118 (0..32).map(|i| (u32::MAX, i)).collect()
119 }
120 }
121
122 #[test]
123 fn rust_shadow() {
124 ShadowedClosure::new(ShiftRight).test();
125 }
126
127 #[proptest]
128 fn too_big_shift_amount_crashes_vm(arg: u32, #[strategy(32_u32..)] shift_amount: u32) {
129 test_assertion_failure(
130 &ShadowedClosure::new(ShiftRight),
131 InitVmState::with_stack(ShiftRight.set_up_test_stack((arg, shift_amount))),
132 &[ShiftRight::SHIFT_AMOUNT_TOO_BIG_ERROR_ID],
133 )
134 }
135}
136
137#[cfg(test)]
138mod benches {
139 use super::*;
140 use crate::test_prelude::*;
141
142 #[test]
143 fn benchmark() {
144 ShadowedClosure::new(ShiftRight).bench();
145 }
146}