ichen_openprotocol/
operator.rs

1use super::{TextName, ID};
2use serde::{Deserialize, Serialize};
3use std::convert::TryInto;
4
5/// A data structure containing information on a single user on the system.
6///
7#[derive(Debug, Eq, PartialEq, Hash, Clone, Serialize, Deserialize)]
8#[serde(rename_all = "camelCase")]
9pub struct Operator<'a> {
10    /// Unique user ID, which cannot be zero.
11    operator_id: ID,
12    //
13    /// Name of the user.
14    #[serde(borrow)]
15    operator_name: Option<TextName<'a>>,
16}
17
18impl<'a> Operator<'a> {
19    /// Get the operator ID.
20    ///
21    /// # Examples
22    ///
23    /// ~~~
24    /// # use ichen_openprotocol::*;
25    /// let opr = Operator::new(ID::from_u32(12345));
26    /// assert_eq!(12345, opr.id());
27    /// ~~~
28    pub fn id(&self) -> ID {
29        self.operator_id
30    }
31
32    // Get the operator's name, if any.
33    ///
34    /// # Examples
35    ///
36    /// ~~~
37    /// # use ichen_openprotocol::*;
38    /// # fn main() -> std::result::Result<(), String> {
39    /// let opr = Operator::try_new_with_name(ID::from_u32(12345), "John")?;
40    /// assert_eq!(Some("John"), opr.name());
41    /// # Ok(())
42    /// # }
43    /// ~~~
44    pub fn name(&self) -> Option<&str> {
45        self.operator_name.as_ref().map(|name| name.as_ref())
46    }
47
48    /// Create an `Operator` with just an ID and no name.
49    ///
50    /// # Examples
51    ///
52    /// ~~~
53    /// # use ichen_openprotocol::*;
54    /// let opr = Operator::new(ID::from_u32(12345));
55    /// assert_eq!(12345, opr.id());
56    /// assert_eq!(None, opr.name());
57    /// ~~~
58    pub fn new(id: ID) -> Self {
59        Self { operator_id: id, operator_name: None }
60    }
61
62    /// Create an `Operator` with ID and name.
63    ///
64    ///
65    /// # Errors
66    ///
67    /// Returns `Err(`[`OpenProtocolError::EmptyField`]`)` if the `operator_name` field is
68    /// set to an empty string or is all whitespace.
69    ///
70    /// ## Error Examples
71    ///
72    /// ~~~
73    /// # use ichen_openprotocol::*;
74    /// let result = Operator::try_new_with_name(ID::from_u32(12345), "");
75    /// assert_eq!(Err("invalid value: a non-empty, non-whitespace string required for operator name".into()), result);
76    /// ~~~
77    ///
78    /// # Examples
79    ///
80    /// ~~~
81    /// # use ichen_openprotocol::*;
82    /// # fn main() -> std::result::Result<(), String> {
83    /// let opr = Operator::try_new_with_name(ID::from_u32(12345), "John")?;
84    /// assert_eq!(12345, opr.id());
85    /// assert_eq!(Some("John"), opr.name());
86    /// # Ok(())
87    /// # }
88    /// ~~~
89    pub fn try_new_with_name(id: ID, name: &'a str) -> std::result::Result<Self, String> {
90        Ok(Self {
91            operator_name: Some(name.try_into().map_err(|e| format!("{} for operator name", e))?),
92            ..Self::new(id)
93        })
94    }
95}