zulip-api 0.0.8

Client library for interacting with the Zulip API
Documentation
use serde::{Deserialize, Serialize};

use super::{Operand, Operator};

mod tuple;

pub use tuple::NarrowTuple;

/// Represents the narrow filter used to restrict results.
#[derive(Clone, Debug, Eq, PartialEq, Deserialize, Serialize)]
pub struct Narrow {
    operator: Operator,
    operand: Operand,
}

impl Narrow {
    /// Creates a new [Narrow].
    pub const fn new() -> Self {
        Self {
            operator: Operator::new(),
            operand: Operand::new(),
        }
    }

    /// Creates a new [Narrow] from the provide parameters.
    pub const fn create(operator: Operator, operand: Operand) -> Self {
        Self { operator, operand }
    }

    /// Gets the [Narrow] operator.
    pub const fn operator(&self) -> &Operator {
        &self.operator
    }

    /// Sets the [Narrow] operator.
    pub fn set_operator(&mut self, val: Operator) {
        self.operator = val;
    }

    /// Builder function that sets the [Narrow] operator.
    pub fn with_operator(self, val: Operator) -> Self {
        Self {
            operator: val,
            ..self
        }
    }

    /// Gets the [Narrow] operand.
    pub const fn operand(&self) -> &Operand {
        &self.operand
    }

    /// Sets the [Narrow] operand.
    pub fn set_operand(&mut self, val: Operand) {
        self.operand = val;
    }

    /// Builder function that sets the [Narrow] operand.
    pub fn with_operand(self, val: Operand) -> Self {
        Self {
            operand: val,
            ..self
        }
    }
}

impl Default for Narrow {
    fn default() -> Self {
        Self::new()
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_narrow() {
        [
            (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 = Narrow::create(opor, opand.clone());
            let narrow_json = format!(r#"{{"operator":{opor_json},"operand":{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::<Narrow>(&narrow_json).unwrap(),
                narrow
            );
        });
    }
}