use serde::{Deserialize, Serialize};
use super::{Operand, Operator};
#[derive(Clone, Debug, Eq, PartialEq, Deserialize, Serialize)]
pub struct NarrowTuple(Operator, Operand);
impl NarrowTuple {
pub const fn new() -> Self {
Self(Operator::new(), Operand::new())
}
pub const fn create(operator: Operator, operand: Operand) -> Self {
Self(operator, operand)
}
pub const fn operator(&self) -> &Operator {
&self.0
}
pub fn set_operator(&mut self, val: Operator) {
self.0 = val;
}
pub fn with_operator(self, val: Operator) -> Self {
Self(val, self.1)
}
pub const fn operand(&self) -> &Operand {
&self.1
}
pub fn set_operand(&mut self, val: Operand) {
self.1 = val;
}
pub fn with_operand(self, val: Operand) -> Self {
Self(self.0, val)
}
}
impl Default for NarrowTuple {
fn default() -> Self {
Self::new()
}
}
impl std::fmt::Display for NarrowTuple {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
serde_json::to_string(self)
.map_err(|_| std::fmt::Error)
.and_then(|s| write!(f, "{s}"))
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_narrow_tuple() {
[
(Operator::Channel, Operand::from(1)),
(Operator::Channel, Operand::from("general")),
(Operator::Channels, Operand::from([1, 2])),
(Operator::Channels, Operand::from(["general", "test"])),
(Operator::Dm, Operand::from(1)),
(Operator::Dm, Operand::from("test_user")),
(Operator::Is, Operand::from(1)),
(Operator::NotIs, Operand::from(["general", "test"])),
(Operator::Near, Operand::from(1)),
]
.into_iter()
.for_each(|(opor, opand)| {
let opor_json = serde_json::to_string(&opor).unwrap();
let opand_json = serde_json::to_string(&opand).unwrap();
let narrow = NarrowTuple::create(opor, opand.clone());
let narrow_json = format!(r#"[{opor_json},{opand_json}]"#);
assert_eq!(narrow.operator(), &opor);
assert_eq!(narrow.operand(), &opand);
assert_eq!(serde_json::to_string(&narrow).unwrap(), narrow_json);
assert_eq!(
serde_json::from_str::<NarrowTuple>(&narrow_json).unwrap(),
narrow
);
});
}
}