crowdstrike_cloudproto/framing/
hdr_version.rs

1use strum_macros::{Display, EnumCount, FromRepr};
2
3#[repr(u16)]
4#[derive(Eq, PartialEq, Copy, Clone, Debug, Display, EnumCount, FromRepr)]
5pub enum CloudProtoVersion {
6    /// All packets that don't fall in other categories
7    Normal,
8    /// Used for the first packets sent
9    Connect,
10    /// I haven't seen other values used yet
11    Other(u16),
12}
13
14impl From<u16> for CloudProtoVersion {
15    fn from(value: u16) -> Self {
16        match value {
17            x if x == Self::Normal.into() => Self::Normal,
18            x if x == Self::Connect.into() => Self::Connect,
19            x => Self::Other(x),
20        }
21    }
22}
23
24impl From<CloudProtoVersion> for u16 {
25    fn from(kind: CloudProtoVersion) -> Self {
26        match kind {
27            CloudProtoVersion::Normal => 1,
28            CloudProtoVersion::Connect => 2,
29            CloudProtoVersion::Other(x) => x,
30        }
31    }
32}
33
34impl From<&CloudProtoVersion> for u16 {
35    fn from(v: &CloudProtoVersion) -> Self {
36        u16::from(*v)
37    }
38}
39
40impl std::fmt::LowerHex for CloudProtoVersion {
41    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
42        let val: u16 = self.into();
43        std::fmt::LowerHex::fmt(&val, f)
44    }
45}
46
47impl std::fmt::UpperHex for CloudProtoVersion {
48    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
49        let val: u16 = self.into();
50        std::fmt::UpperHex::fmt(&val, f)
51    }
52}
53
54#[cfg(test)]
55mod test {
56    use crate::framing::CloudProtoVersion;
57    use std::collections::HashSet;
58    use strum::EnumCount;
59
60    #[test]
61    fn cloud_proto_magic_roundtrip() {
62        let mut seen = HashSet::new();
63        for v in 0..=u16::MAX {
64            let m = CloudProtoVersion::from(v);
65            seen.insert(std::mem::discriminant(&m));
66            assert_eq!(u16::from(m), v);
67        }
68        // If this fails, you may have forgotten to update From<u16>
69        assert_eq!(seen.len(), CloudProtoVersion::COUNT)
70    }
71}