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
use derive::FromValue;
use netidx_derive::Pack;
use serde::{Deserialize, Serialize};
use std::{error::Error as StdError, fmt, str::FromStr};

/// Components within an Architect installation are uniquely identified by a 16-bit integer
/// in the range `1..<0xFFFF`.
///
/// The integers 0 and 0xFFFF are reserved as special values and MUST NOT be used as component IDs.
///
/// Canonical meanings of special values:
///
/// * `0x0` -- None/executor/broadcast
/// * `0xFFFF` -- Self/loopback
#[derive(
    Debug,
    Clone,
    Copy,
    PartialEq,
    Eq,
    PartialOrd,
    Ord,
    Hash,
    Pack,
    FromValue,
    Serialize,
    Deserialize,
)]
#[pack(unwrapped)]
#[repr(transparent)]
pub struct ComponentId(pub(crate) u16);

impl ComponentId {
    pub fn new(id: u16) -> Result<Self, ComponentIdError> {
        if id <= 1 {
            Err(ComponentIdError::InvalidId)
        } else {
            Ok(Self(id))
        }
    }

    #[inline(always)]
    pub fn none() -> Self {
        Self(0)
    }

    #[inline(always)]
    pub fn is_none(&self) -> bool {
        self.0 == 0
    }

    #[inline(always)]
    pub fn loopback() -> Self {
        Self(u16::MAX)
    }

    #[inline(always)]
    pub fn is_loopback(&self) -> bool {
        self.0 == u16::MAX
    }

    pub fn filename(&self) -> String {
        format!("{}", self.0)
    }
}

impl fmt::Display for ComponentId {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        if self.is_none() {
            write!(f, "#none")
        } else if self.is_loopback() {
            write!(f, "#loopback")
        } else {
            write!(f, "#{}", self.0)
        }
    }
}

impl FromStr for ComponentId {
    type Err = ComponentIdError;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        if s.starts_with('#') {
            let id = s[1..].parse::<u16>().map_err(|_| ComponentIdError::ParseError)?;
            Self::new(id)
        } else {
            Err(ComponentIdError::ParseError)
        }
    }
}

#[derive(Debug, Clone)]
pub enum ComponentIdError {
    InvalidId,
    ParseError,
}

impl fmt::Display for ComponentIdError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::InvalidId => {
                write!(f, "invalid component id; must not be 0 or 0xFFFF")
            }
            Self::ParseError => {
                write!(f, "invalid component id format; must be of the form #<id>")
            }
        }
    }
}

impl StdError for ComponentIdError {}