1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
#![allow(non_upper_case_globals)]

use bitflags::*;
use serde::{Deserialize, Deserializer, Serialize, Serializer};
use std::fmt::{Display, Formatter};
use std::ops::{Add, AddAssign};
use std::str::FromStr;

bitflags! {
    /// General authorizations to access the iChen System via Open Protocol.
    ///
    /// See [this document] for details.
    ///
    /// [this document]: https://github.com/chenhsong/OpenProtocol/blob/master/doc/enums.md#filters
    ///
    pub struct Filters: u32 {
        /// No rights.
        const None = 0;
        //
        /// Controller status update messages.
        const Status = 0b_0000_0001;
        /// Cycle data messages.
        const Cycle = 0b_0000_0010;
        /// Mold data messages.
        const Mold = 0b_0000_0100;
        /// Controller action messages.
        const Actions = 0b_0000_1000;
        /// Controller alarm messages.
        const Alarms = 0b_0001_0000;
        /// Controller audit trail of setting changes
        const Audit = 0b_0010_0000;
        /// Administrator rights.
        ///
        /// `All` implies `Status` + `Cycle` + `Mold` + `Actions` + `Alarms` + `Audit`
        const All = 0b_1111_1111;
        //
        /// MIS/MES integration: Job scheduling messages.
        const JobCards = 0b_0001_0000_0000_0000;
        /// MIS/MES integration: User authorization messages.
        const Operators = 0b_0010_0000_0000_0000;
        //
        /// Industrial bus integration: Connect via OPC UA.
        const OPCUA = 0b_0001_0000_0000_0000_0000_0000_0000_0000;
    }
}

static ALL: &str = "Status | Cycle | Mold | Actions | Alarms | Audit | All";

impl Filters {
    /// Is a particular set of filters set?
    ///
    /// # Examples
    ///
    /// ~~~
    /// # use ichen_openprotocol::*;
    /// let f = Filters::Status + Filters::Audit + Filters::JobCards;
    /// assert!(f.has(Filters::Status));
    /// assert!(f.has(Filters::JobCards));
    /// assert!(!f.has(Filters::All));
    /// assert!(!f.has(Filters::OPCUA));
    /// assert!(!f.has(Filters::Mold));
    /// ~~~
    pub fn has(self, other: Self) -> bool {
        self.contains(other)
    }
}

impl FromStr for Filters {
    type Err = String;

    /// Parse a comma-delimited `String` into a `Filters` values.
    ///
    /// **`Filters::from_str` never fails.**
    /// Unmatched tokens will simply be discarded.
    /// If nothing matches, `Filters::None` will be returned.
    ///
    /// # Examples
    ///
    /// ~~~
    /// # use std::str::FromStr;
    /// # use ichen_openprotocol::*;
    /// let f = Filters::from_str("Hello, World, Cycle, Mold,Operators|Foo+BarXYZYXYZ=123").unwrap();
    /// assert_eq!(Filters::Cycle + Filters::Mold, f);
    ///
    /// let f = Filters::from_str("All, OPCUA").unwrap();
    /// assert_eq!(Filters::All + Filters::OPCUA, f);
    /// assert!(f.has(Filters::All));
    /// assert!(f.has(Filters::OPCUA));
    /// assert!(!f.has(Filters::Operators));
    /// assert!(!f.has(Filters::JobCards));
    /// assert!(f.has(Filters::Cycle));
    /// assert!(f.has(Filters::Status));
    /// assert!(f.has(Filters::Mold));
    /// assert!(f.has(Filters::Audit));
    /// assert!(f.has(Filters::Alarms));
    /// ~~~
    fn from_str(text: &str) -> Result<Self, Self::Err> {
        let text = text.trim();

        Ok(if text == "None" || text.is_empty() {
            Filters::None
        } else {
            text.split(',')
                .map(|t| match t.trim() {
                    "Status" => Filters::Status,
                    "Cycle" => Filters::Cycle,
                    "Mold" => Filters::Mold,
                    "Actions" => Filters::Actions,
                    "Alarms" => Filters::Alarms,
                    "Audit" => Filters::Audit,
                    "All" => Filters::All,
                    "JobCards" => Filters::JobCards,
                    "Operators" => Filters::Operators,
                    "OPCUA" => Filters::OPCUA,
                    _ => Filters::None,
                })
                .fold(Filters::None, |f, x| f | x)
        })
    }
}

impl<T: AsRef<str>> From<T> for Filters {
    /// Call `Filters::from_str` to parse a filters value from a comma-delimited string.
    fn from(s: T) -> Self {
        // `Filters::from_str` does not fail.
        Self::from_str(s.as_ref()).unwrap()
    }
}

impl From<Filters> for String {
    /// Convert filters value into a comma-delimited list.
    fn from(f: Filters) -> Self {
        f.to_string()
    }
}

impl Add for Filters {
    type Output = Self;

    /// Turn on a particular filter.
    ///
    /// # Example
    ///
    /// ~~~
    /// # use ichen_openprotocol::*;
    /// let mut f = Filters::Cycle + Filters::OPCUA;
    /// f = f + Filters::All;
    /// assert_eq!(Filters::All + Filters::OPCUA, f);
    /// ~~~
    #[allow(clippy::suspicious_arithmetic_impl)]
    fn add(self, rhs: Self) -> Self::Output {
        self | rhs
    }
}

impl AddAssign for Filters {
    /// Turn on a particular filter.
    ///
    /// # Example
    ///
    /// ~~~
    /// # use ichen_openprotocol::*;
    /// let mut f = Filters::Cycle + Filters::OPCUA;
    /// f += Filters::All;
    /// assert_eq!(Filters::All + Filters::OPCUA, f);
    /// ~~~
    fn add_assign(&mut self, other: Self) {
        *self |= other;
    }
}

/// Serialize `Filters` as comma-separated list.
///
/// # Examples
///
/// ~~~
/// # use ichen_openprotocol::*;
/// let f = Filters::All + Filters::Cycle + Filters::OPCUA;
/// assert_eq!("All, OPCUA", f.to_string());
/// ~~~
impl Display for Filters {
    /// Display filters value as comma-delimited list.
    fn fmt(&self, f: &mut Formatter) -> std::fmt::Result {
        let text = format!("{:?}", self);
        let mut text = text.trim();

        // Remove redundant flags when All is present
        if text.starts_with(ALL) {
            text = text[ALL.len() - 3..].trim();
        }

        if text.is_empty() {
            write!(f, "None")
        } else {
            write!(f, "{}", text.replace(" | ", ", "))
        }
    }
}

impl Serialize for Filters {
    fn serialize<S: Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
        s.serialize_str(&self.to_string())
    }
}

impl<'de> Deserialize<'de> for Filters {
    fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
        let s = Deserialize::deserialize(d).map_err(serde::de::Error::custom)?;
        Filters::from_str(s).map_err(serde::de::Error::custom)
    }
}