const_oid/arcs.rs
1//! Arcs are integer values which exist within an OID's hierarchy.
2
3use crate::{Error, Result};
4
5#[cfg(doc)]
6use crate::ObjectIdentifier;
7
8/// Type alias used to represent an "arc", i.e. integer identifier value, where an OID comprises a
9/// sequence of arcs.
10///
11/// X.660 does not define a maximum size of an arc. We instead follow Mozilla* conventions for
12/// maximum values of an arc, with a maximum value of 2^32-1 (4294967295), a.k.a. [`u32::MAX`]
13/// with [`Arc`] being a type alias for [`u32`].
14///
15/// Note that this means we deliberately do *NOT* support UUIDs used as OIDs.
16///
17/// *NOTE: please see this study for a survey of how various OID libraries handle maximum arcs:
18/// <https://misc.daniel-marschall.de/asn.1/oid_facts.html>
19pub type Arc = u32;
20
21/// Maximum value of the first arc in an OID.
22pub(crate) const ARC_MAX_FIRST: Arc = 2;
23
24/// Maximum value of the second arc in an OID.
25pub(crate) const ARC_MAX_SECOND: Arc = 39;
26
27/// [`Iterator`] over [`Arc`] values (a.k.a. nodes) in an [`ObjectIdentifier`].
28///
29/// This iterates over all arcs in an OID, including the root.
30pub struct Arcs<'a> {
31 /// OID bytes we're iterating over.
32 bytes: &'a [u8],
33
34 /// Current position within the serialized BER bytes of this OID.
35 cursor: Option<usize>,
36}
37
38impl<'a> Arcs<'a> {
39 /// Create a new iterator over an OID encoded as BER bytes.
40 pub(crate) fn new(bytes: &'a [u8]) -> Self {
41 Self {
42 bytes,
43 cursor: None,
44 }
45 }
46
47 /// Try to parse the next arc in this OID.
48 ///
49 /// This method is fallible so it can be used as a first pass to determine
50 /// that the arcs in the OID are well-formed.
51 pub(crate) fn try_next(&mut self) -> Result<Option<Arc>> {
52 match self.cursor {
53 // Indicates we're on the root arc
54 None => {
55 let root_byte = *self.bytes.first().ok_or(Error::Empty)?;
56 let root = RootArcs::try_from(root_byte)?;
57 self.cursor = Some(0);
58 Ok(Some(root.first_arc()))
59 }
60 Some(0) => {
61 let root = RootArcs::try_from(self.bytes[0])?;
62 self.cursor = Some(1);
63 Ok(Some(root.second_arc()))
64 }
65 Some(offset) => {
66 let mut result: Arc = 0;
67 let mut arc_bytes = 0;
68
69 loop {
70 let len = checked_add!(offset, arc_bytes);
71
72 match self.bytes.get(len).cloned() {
73 Some(byte) => {
74 arc_bytes = checked_add!(arc_bytes, 1);
75
76 // A five byte arc can still exceed `Arc`, so the digits are
77 // accumulated with overflow checking rather than by counting
78 // bytes.
79 result = match result
80 .checked_mul(0x80)
81 .and_then(|result| result.checked_add((byte & 0b0111_1111) as Arc))
82 {
83 Some(result) => result,
84 None => return Err(Error::ArcTooBig),
85 };
86
87 if byte & 0b1000_0000 == 0 {
88 self.cursor = Some(checked_add!(offset, arc_bytes));
89 return Ok(Some(result));
90 }
91 }
92 None => {
93 if arc_bytes == 0 {
94 return Ok(None);
95 } else {
96 return Err(Error::Base128);
97 }
98 }
99 }
100 }
101 }
102 }
103 }
104}
105
106impl Iterator for Arcs<'_> {
107 type Item = Arc;
108
109 fn next(&mut self) -> Option<Arc> {
110 // ObjectIdentifier constructors should ensure the OID is well-formed
111 self.try_next().expect("OID malformed")
112 }
113}
114
115/// Byte containing the first and second arcs of an OID.
116///
117/// This is represented this way in order to reduce the overall size of the
118/// [`ObjectIdentifier`] struct.
119#[derive(Copy, Clone, Debug, Eq, PartialEq)]
120struct RootArcs(u8);
121
122impl RootArcs {
123 /// Create [`RootArcs`] from the first and second arc values represented
124 /// as `Arc` integers.
125 pub(crate) const fn new(first_arc: Arc, second_arc: Arc) -> Result<Self> {
126 if first_arc > ARC_MAX_FIRST {
127 return Err(Error::ArcInvalid { arc: first_arc });
128 }
129
130 if second_arc > ARC_MAX_SECOND {
131 return Err(Error::ArcInvalid { arc: second_arc });
132 }
133
134 // The checks above ensure this operation will not overflow
135 #[allow(clippy::arithmetic_side_effects)]
136 let byte = (first_arc * (ARC_MAX_SECOND + 1)) as u8 + second_arc as u8;
137
138 Ok(Self(byte))
139 }
140
141 /// Get the value of the first arc
142 #[allow(clippy::arithmetic_side_effects)]
143 pub(crate) const fn first_arc(self) -> Arc {
144 self.0 as Arc / (ARC_MAX_SECOND + 1)
145 }
146
147 /// Get the value of the second arc
148 #[allow(clippy::arithmetic_side_effects)]
149 pub(crate) const fn second_arc(self) -> Arc {
150 self.0 as Arc % (ARC_MAX_SECOND + 1)
151 }
152}
153
154impl TryFrom<u8> for RootArcs {
155 type Error = Error;
156
157 // Ensured not to overflow by constructor invariants
158 #[allow(clippy::arithmetic_side_effects)]
159 fn try_from(octet: u8) -> Result<Self> {
160 let first = octet as Arc / (ARC_MAX_SECOND + 1);
161 let second = octet as Arc % (ARC_MAX_SECOND + 1);
162 let result = Self::new(first, second)?;
163 debug_assert_eq!(octet, result.0);
164 Ok(result)
165 }
166}
167
168impl From<RootArcs> for u8 {
169 fn from(root_arcs: RootArcs) -> u8 {
170 root_arcs.0
171 }
172}