jaq_core/
ops.rs

1//! Binary operations.
2
3use core::ops::{Add, Div, Mul, Rem, Sub};
4
5/// Arithmetic operation, such as `+`, `-`, `*`, `/`, `%`.
6#[derive(Copy, Clone, Debug, PartialEq, Eq)]
7pub enum Math {
8    /// Addition
9    Add,
10    /// Subtraction
11    Sub,
12    /// Multiplication
13    Mul,
14    /// Division
15    Div,
16    /// Remainder
17    Rem,
18}
19
20impl Math {
21    /// Perform the arithmetic operation on the given inputs.
22    pub fn run<I, O>(&self, l: I, r: I) -> O
23    where
24        I: Add<Output = O> + Sub<Output = O> + Mul<Output = O> + Div<Output = O> + Rem<Output = O>,
25    {
26        match self {
27            Self::Add => l + r,
28            Self::Sub => l - r,
29            Self::Mul => l * r,
30            Self::Div => l / r,
31            Self::Rem => l % r,
32        }
33    }
34}
35
36impl Math {
37    /// String representation of an arithmetic operation.
38    pub fn as_str(&self) -> &'static str {
39        match self {
40            Self::Add => "+",
41            Self::Sub => "-",
42            Self::Mul => "*",
43            Self::Div => "/",
44            Self::Rem => "%",
45        }
46    }
47}
48
49/// An operation that orders two values, such as `<`, `<=`, `>`, `>=`, `==`, `!=`.
50#[derive(Copy, Clone, Debug, PartialEq, Eq)]
51pub enum Cmp {
52    /// Less-than (<).
53    Lt,
54    /// Less-than or equal (<=).
55    Le,
56    /// Greater-than (>).
57    Gt,
58    /// Greater-than or equal (>=).
59    Ge,
60    /// Equals (=).
61    Eq,
62    /// Not equals (!=).
63    Ne,
64}
65
66impl Cmp {
67    /// Perform the ordering operation on the given inputs.
68    pub fn run<I: PartialOrd + PartialEq>(&self, l: &I, r: &I) -> bool {
69        match self {
70            Self::Gt => l > r,
71            Self::Ge => l >= r,
72            Self::Lt => l < r,
73            Self::Le => l <= r,
74            Self::Eq => l == r,
75            Self::Ne => l != r,
76        }
77    }
78}
79
80impl Cmp {
81    /// String representation of a comparison operation.
82    pub fn as_str(&self) -> &'static str {
83        match self {
84            Self::Lt => "<",
85            Self::Gt => ">",
86            Self::Le => "<=",
87            Self::Ge => ">=",
88            Self::Eq => "==",
89            Self::Ne => "!=",
90        }
91    }
92}