use-pin 0.0.1

Primitive electronic pin vocabulary for RustUse
Documentation
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
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
#![forbid(unsafe_code)]
#![doc = include_str!("../README.md")]

use core::{fmt, num::NonZeroU32, str::FromStr};
use std::error::Error;

use use_component::ReferenceDesignator;

/// Commonly used pin primitives.
pub mod prelude {
    pub use crate::{
        PinIdentifier, PinName, PinNameError, PinNumber, PinNumberError, PinPolarity,
        PinPolarityParseError, PinRef, PinRole, PinRoleParseError,
    };
}

/// A one-based package or component pin number.
#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
pub struct PinNumber(NonZeroU32);

impl PinNumber {
    /// Creates a non-zero pin number.
    ///
    /// # Errors
    ///
    /// Returns [`PinNumberError::Zero`] when `value` is zero.
    pub fn new(value: u32) -> Result<Self, PinNumberError> {
        NonZeroU32::new(value).map(Self).ok_or(PinNumberError::Zero)
    }

    /// Returns the pin number.
    #[must_use]
    pub const fn get(self) -> u32 {
        self.0.get()
    }
}

impl From<NonZeroU32> for PinNumber {
    fn from(value: NonZeroU32) -> Self {
        Self(value)
    }
}

impl TryFrom<u32> for PinNumber {
    type Error = PinNumberError;

    fn try_from(value: u32) -> Result<Self, Self::Error> {
        Self::new(value)
    }
}

impl fmt::Display for PinNumber {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        self.get().fmt(formatter)
    }
}

/// Errors returned while constructing pin numbers.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum PinNumberError {
    /// Pin number zero is not accepted.
    Zero,
}

impl fmt::Display for PinNumberError {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Zero => formatter.write_str("pin number must be non-zero"),
        }
    }
}

impl Error for PinNumberError {}

/// A descriptive pin name such as `VCC`, `GND`, `SDA`, or `RESET`.
#[derive(Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
pub struct PinName(String);

impl PinName {
    /// Creates a pin name from non-empty text.
    ///
    /// # Errors
    ///
    /// Returns [`PinNameError::Empty`] when the trimmed value is empty.
    pub fn new(value: impl AsRef<str>) -> Result<Self, PinNameError> {
        let trimmed = value.as_ref().trim();
        if trimmed.is_empty() {
            Err(PinNameError::Empty)
        } else {
            Ok(Self(trimmed.to_string()))
        }
    }

    /// Returns the pin name text.
    #[must_use]
    pub fn as_str(&self) -> &str {
        &self.0
    }

    /// Consumes the pin name and returns the owned string.
    #[must_use]
    pub fn into_string(self) -> String {
        self.0
    }
}

impl AsRef<str> for PinName {
    fn as_ref(&self) -> &str {
        self.as_str()
    }
}

impl fmt::Display for PinName {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter.write_str(self.as_str())
    }
}

impl FromStr for PinName {
    type Err = PinNameError;

    fn from_str(value: &str) -> Result<Self, Self::Err> {
        Self::new(value)
    }
}

/// Errors returned while constructing pin names.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum PinNameError {
    /// The pin name was empty after trimming whitespace.
    Empty,
}

impl fmt::Display for PinNameError {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Empty => formatter.write_str("pin name cannot be empty"),
        }
    }
}

impl Error for PinNameError {}

/// Descriptive electronic pin roles.
#[derive(Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
pub enum PinRole {
    Input,
    Output,
    Bidirectional,
    Power,
    Ground,
    Clock,
    Reset,
    Enable,
    NoConnect,
    Unknown,
    Custom(String),
}

impl fmt::Display for PinRole {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter.write_str(match self {
            Self::Input => "input",
            Self::Output => "output",
            Self::Bidirectional => "bidirectional",
            Self::Power => "power",
            Self::Ground => "ground",
            Self::Clock => "clock",
            Self::Reset => "reset",
            Self::Enable => "enable",
            Self::NoConnect => "no-connect",
            Self::Unknown => "unknown",
            Self::Custom(value) => value.as_str(),
        })
    }
}

impl FromStr for PinRole {
    type Err = PinRoleParseError;

    fn from_str(value: &str) -> Result<Self, Self::Err> {
        let trimmed = value.trim();
        if trimmed.is_empty() {
            return Err(PinRoleParseError::Empty);
        }

        match normalized_token(trimmed).as_str() {
            "input" | "in" => Ok(Self::Input),
            "output" | "out" => Ok(Self::Output),
            "bidirectional" | "bidirectional-io" | "io" => Ok(Self::Bidirectional),
            "power" => Ok(Self::Power),
            "ground" | "gnd" => Ok(Self::Ground),
            "clock" | "clk" => Ok(Self::Clock),
            "reset" => Ok(Self::Reset),
            "enable" => Ok(Self::Enable),
            "no-connect" | "nc" => Ok(Self::NoConnect),
            "unknown" => Ok(Self::Unknown),
            _ => Ok(Self::Custom(trimmed.to_string())),
        }
    }
}

/// Errors returned while parsing pin roles.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum PinRoleParseError {
    /// The role was empty after trimming whitespace.
    Empty,
}

impl fmt::Display for PinRoleParseError {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Empty => formatter.write_str("pin role cannot be empty"),
        }
    }
}

impl Error for PinRoleParseError {}

/// Descriptive pin polarity vocabulary.
#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
pub enum PinPolarity {
    ActiveHigh,
    ActiveLow,
    NonInverting,
    Inverting,
    Unknown,
}

impl fmt::Display for PinPolarity {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter.write_str(match self {
            Self::ActiveHigh => "active-high",
            Self::ActiveLow => "active-low",
            Self::NonInverting => "non-inverting",
            Self::Inverting => "inverting",
            Self::Unknown => "unknown",
        })
    }
}

impl FromStr for PinPolarity {
    type Err = PinPolarityParseError;

    fn from_str(value: &str) -> Result<Self, Self::Err> {
        let trimmed = value.trim();
        if trimmed.is_empty() {
            return Err(PinPolarityParseError::Empty);
        }

        match normalized_token(trimmed).as_str() {
            "active-high" => Ok(Self::ActiveHigh),
            "active-low" => Ok(Self::ActiveLow),
            "non-inverting" => Ok(Self::NonInverting),
            "inverting" => Ok(Self::Inverting),
            "unknown" => Ok(Self::Unknown),
            _ => Err(PinPolarityParseError::Unknown),
        }
    }
}

/// Errors returned while parsing pin polarity.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum PinPolarityParseError {
    /// The polarity text was empty after trimming whitespace.
    Empty,
    /// The polarity was not part of the fixed vocabulary.
    Unknown,
}

impl fmt::Display for PinPolarityParseError {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Empty => formatter.write_str("pin polarity cannot be empty"),
            Self::Unknown => formatter.write_str("unknown pin polarity"),
        }
    }
}

impl Error for PinPolarityParseError {}

/// A pin identified by number or name.
#[derive(Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
pub enum PinIdentifier {
    Number(PinNumber),
    Name(PinName),
}

impl From<PinNumber> for PinIdentifier {
    fn from(value: PinNumber) -> Self {
        Self::Number(value)
    }
}

impl From<PinName> for PinIdentifier {
    fn from(value: PinName) -> Self {
        Self::Name(value)
    }
}

impl fmt::Display for PinIdentifier {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Number(number) => number.fmt(formatter),
            Self::Name(name) => name.fmt(formatter),
        }
    }
}

/// A reference to a component pin, such as `U2:VCC` or `R1:1`.
#[derive(Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
pub struct PinRef {
    component: ReferenceDesignator,
    pin: PinIdentifier,
}

impl PinRef {
    /// Creates a pin reference from a component designator and pin identifier.
    #[must_use]
    pub const fn new(component: ReferenceDesignator, pin: PinIdentifier) -> Self {
        Self { component, pin }
    }

    /// Creates a pin reference from a numeric pin.
    #[must_use]
    pub const fn numbered(component: ReferenceDesignator, pin: PinNumber) -> Self {
        Self::new(component, PinIdentifier::Number(pin))
    }

    /// Creates a pin reference from a named pin.
    #[must_use]
    pub const fn named(component: ReferenceDesignator, pin: PinName) -> Self {
        Self::new(component, PinIdentifier::Name(pin))
    }

    /// Returns the component reference designator.
    #[must_use]
    pub const fn component(&self) -> &ReferenceDesignator {
        &self.component
    }

    /// Returns the pin identifier.
    #[must_use]
    pub const fn pin(&self) -> &PinIdentifier {
        &self.pin
    }
}

impl fmt::Display for PinRef {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(formatter, "{}:{}", self.component, self.pin)
    }
}

fn normalized_token(value: &str) -> String {
    value.trim().to_ascii_lowercase().replace(['_', ' '], "-")
}

#[cfg(test)]
mod tests {
    use super::{
        PinName, PinNameError, PinNumber, PinNumberError, PinPolarity, PinRole, PinRoleParseError,
    };

    #[test]
    fn accepts_valid_pin_numbers() -> Result<(), PinNumberError> {
        let number = PinNumber::new(1)?;

        assert_eq!(number.get(), 1);
        assert_eq!(number.to_string(), "1");
        Ok(())
    }

    #[test]
    fn rejects_zero_pin_numbers() {
        assert_eq!(PinNumber::new(0), Err(PinNumberError::Zero));
    }

    #[test]
    fn accepts_valid_pin_names() -> Result<(), PinNameError> {
        let name = PinName::new("RESET")?;

        assert_eq!(name.as_str(), "RESET");
        assert_eq!(name.to_string(), "RESET");
        Ok(())
    }

    #[test]
    fn rejects_empty_pin_names() {
        assert_eq!(PinName::new(" "), Err(PinNameError::Empty));
    }

    #[test]
    fn displays_and_parses_pin_roles() -> Result<(), PinRoleParseError> {
        assert_eq!("input".parse::<PinRole>()?, PinRole::Input);
        assert_eq!("NC".parse::<PinRole>()?, PinRole::NoConnect);
        assert_eq!(PinRole::Power.to_string(), "power");
        Ok(())
    }

    #[test]
    fn displays_and_parses_pin_polarity() -> Result<(), Box<dyn std::error::Error>> {
        assert_eq!("active low".parse::<PinPolarity>()?, PinPolarity::ActiveLow);
        assert_eq!(PinPolarity::NonInverting.to_string(), "non-inverting");
        Ok(())
    }
}