stak_native/
arithmetic.rs1use stak_vm::{Error, Heap, Memory, PrimitiveSet};
2use winter_maybe_async::maybe_async;
3
4pub enum ArithmeticPrimitive {
6 Quotient,
8}
9
10impl ArithmeticPrimitive {
11 const QUOTIENT: usize = Self::Quotient as _;
12}
13
14#[derive(Debug, Default)]
16pub struct ArithmeticPrimitiveSet {}
17
18impl ArithmeticPrimitiveSet {
19 pub fn new() -> Self {
21 Self::default()
22 }
23}
24
25impl<H: Heap> PrimitiveSet<H> for ArithmeticPrimitiveSet {
26 type Error = Error;
27
28 #[maybe_async]
29 fn operate(&mut self, memory: &mut Memory<H>, primitive: usize) -> Result<(), Self::Error> {
30 match primitive {
31 ArithmeticPrimitive::QUOTIENT => {
32 let [x, y] = memory.pop_many()?;
33 let x = x.assume_number();
34 let y = y.assume_number();
35
36 memory.push((x - x.remainder(y)?).divide(y)?.into())?;
37 }
38 _ => return Err(Error::IllegalPrimitive),
39 }
40
41 Ok(())
42 }
43}
44
45#[cfg(test)]
46mod tests {
47 use super::*;
48 use stak_util::block_on;
49 use stak_vm::{Number, Value};
50
51 const HEAP_SIZE: usize = 1 << 8;
52
53 fn quotient(x: i64, y: i64) -> Result<i64, Error> {
54 let mut memory = Memory::new([Value::default(); HEAP_SIZE]).unwrap();
55 memory.set_stack(memory.null().unwrap());
56 memory.push(Number::from_i64(x).into()).unwrap();
57 memory.push(Number::from_i64(y).into()).unwrap();
58
59 let mut set = ArithmeticPrimitiveSet::new();
60 block_on!(set.operate(&mut memory, ArithmeticPrimitive::QUOTIENT))?;
61
62 Ok(memory.pop().unwrap().assume_number().to_i64())
63 }
64
65 #[test]
66 fn calculate_quotient() {
67 assert_eq!(quotient(7, 2), Ok(3));
68 assert_eq!(quotient(6, 3), Ok(2));
69 assert_eq!(quotient(-7, 2), Ok(-3));
70 }
71
72 #[test]
73 fn calculate_quotient_by_zero() {
74 assert!(matches!(quotient(1, 0), Ok(_) | Err(Error::DivisionByZero)));
75 }
76}