jaq_syn/
ops.rs

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