1#![forbid(unsafe_code)]
11
12#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
14pub enum OidKind {
15 Sha1,
16 Sha256,
17}
18
19impl OidKind {
20 pub const fn digest_len(self) -> usize {
21 match self {
22 Self::Sha1 => 20,
23 Self::Sha256 => 32,
24 }
25 }
26
27 pub const fn hex_len(self) -> usize {
28 self.digest_len() * 2
29 }
30}
31
32#[derive(Clone, Copy, PartialEq, Eq, Hash)]
34pub struct Oid {
35 kind: OidKind,
36 bytes: [u8; 32],
37}
38
39impl Oid {
40 pub fn kind(self) -> OidKind {
41 self.kind
42 }
43
44 pub fn as_bytes(&self) -> &[u8] {
45 &self.bytes[..self.kind.digest_len()]
46 }
47
48 pub fn from_bytes(kind: OidKind, bytes: &[u8]) -> Result<Self, OidError> {
49 if bytes.len() != kind.digest_len() {
50 return Err(OidError::Length {
51 expected: kind.digest_len(),
52 actual: bytes.len(),
53 });
54 }
55 let mut buf = [0u8; 32];
56 buf[..kind.digest_len()].copy_from_slice(bytes);
57 Ok(Self { kind, bytes: buf })
58 }
59
60 pub fn from_hex(hex: &str) -> Result<Self, OidError> {
61 let kind = match hex.len() {
62 40 => OidKind::Sha1,
63 64 => OidKind::Sha256,
64 n => return Err(OidError::HexLength(n)),
65 };
66 if !hex.as_bytes().iter().all(u8::is_ascii_hexdigit) {
67 return Err(OidError::HexCharset);
68 }
69 let mut buf = [0u8; 32];
70 for (i, chunk) in hex.as_bytes().chunks(2).enumerate() {
71 let hi = hex_val(chunk[0])?;
72 let lo = hex_val(chunk[1])?;
73 buf[i] = (hi << 4) | lo;
74 }
75 Ok(Self { kind, bytes: buf })
76 }
77
78 pub fn to_hex(&self) -> String {
79 let mut s = String::with_capacity(self.kind.hex_len());
80 for b in self.as_bytes() {
81 s.push(HEX[(b >> 4) as usize] as char);
82 s.push(HEX[(b & 0xf) as usize] as char);
83 }
84 s
85 }
86}
87
88impl core::fmt::Debug for Oid {
89 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
90 write!(f, "Oid({})", self.to_hex())
91 }
92}
93
94impl core::fmt::Display for Oid {
95 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
96 f.write_str(&self.to_hex())
97 }
98}
99
100const HEX: &[u8; 16] = b"0123456789abcdef";
101
102fn hex_val(c: u8) -> Result<u8, OidError> {
103 match c {
104 b'0'..=b'9' => Ok(c - b'0'),
105 b'a'..=b'f' => Ok(c - b'a' + 10),
106 b'A'..=b'F' => Ok(c - b'A' + 10),
107 _ => Err(OidError::HexCharset),
108 }
109}
110
111#[derive(Debug, thiserror::Error, PartialEq, Eq)]
112pub enum OidError {
113 #[error("OID byte length mismatch: expected {expected}, got {actual}")]
114 Length { expected: usize, actual: usize },
115 #[error("OID hex length invalid: {0} (want 40 or 64)")]
116 HexLength(usize),
117 #[error("OID hex contains non-hex characters")]
118 HexCharset,
119}
120
121#[cfg(test)]
122mod tests {
123 use super::*;
124
125 #[test]
126 fn empty_blob_oid_roundtrip() {
127 let hex = "e69de29bb2d1d6434b8b29ae775ad8c2e48c5391";
128 let oid = Oid::from_hex(hex).unwrap();
129 assert_eq!(oid.kind(), OidKind::Sha1);
130 assert_eq!(oid.to_hex(), hex);
131 }
132
133 #[test]
134 fn reject_bad_hex_length() {
135 assert!(matches!(Oid::from_hex("abcd"), Err(OidError::HexLength(4))));
136 }
137
138 #[test]
139 fn hello_blob_oid_roundtrip() {
140 let hex = "b6fc4c620b67d95f953a5c1c1230aaab5db5a1b0";
141 let oid = Oid::from_hex(hex).unwrap();
142 assert_eq!(oid.kind(), OidKind::Sha1);
143 assert_eq!(oid.to_hex(), hex);
144 }
145
146 #[test]
147 fn reject_bad_hex_charset() {
148 assert!(matches!(
149 Oid::from_hex("e69de29bb2d1d6434b8b29ae775ad8c2e48c539g"),
150 Err(OidError::HexCharset)
151 ));
152 assert!(matches!(
153 Oid::from_hex("e69de29bb2d1d6434b8b29ae775ad8c2e48c539 "),
154 Err(OidError::HexCharset)
155 ));
156 }
157
158 #[test]
159 fn accept_uppercase_hex() {
160 let lower = "e69de29bb2d1d6434b8b29ae775ad8c2e48c5391";
161 let upper = "E69DE29BB2D1D6434B8B29AE775AD8C2E48C5391";
162 let oid = Oid::from_hex(upper).unwrap();
163 assert_eq!(oid.to_hex(), lower);
164 assert_eq!(oid.as_bytes(), Oid::from_hex(lower).unwrap().as_bytes());
165 }
166
167 #[test]
168 fn reject_wrong_byte_length() {
169 assert!(matches!(
170 Oid::from_bytes(OidKind::Sha1, &[0u8; 19]),
171 Err(OidError::Length {
172 expected: 20,
173 actual: 19
174 })
175 ));
176 assert!(matches!(
177 Oid::from_bytes(OidKind::Sha256, &[0u8; 20]),
178 Err(OidError::Length {
179 expected: 32,
180 actual: 20
181 })
182 ));
183 }
184
185 #[test]
186 fn display_and_debug_lowercase_hex() {
187 let hex = "e69de29bb2d1d6434b8b29ae775ad8c2e48c5391";
188 let oid = Oid::from_hex(hex).unwrap();
189 assert_eq!(oid.to_string(), hex);
190 assert_eq!(format!("{oid:?}"), format!("Oid({hex})"));
191 }
192
193 #[test]
194 fn from_bytes_roundtrip_sha1() {
195 let bytes: [u8; 20] = [
196 0xe6, 0x9d, 0xe2, 0x9b, 0xb2, 0xd1, 0xd6, 0x43, 0x4b, 0x8b, 0x29, 0xae, 0x77, 0x5a,
197 0xd8, 0xc2, 0xe4, 0x8c, 0x53, 0x91,
198 ];
199 let oid = Oid::from_bytes(OidKind::Sha1, &bytes).unwrap();
200 assert_eq!(oid.to_hex(), "e69de29bb2d1d6434b8b29ae775ad8c2e48c5391");
201 }
202
203 #[test]
204 fn sha256_hex_roundtrip() {
205 let hex = "473a0f4c3be8a93681a267e3b1e9a7dcda1185436fe141f7749120a303721813";
206 let oid = Oid::from_hex(hex).unwrap();
207 assert_eq!(oid.kind(), OidKind::Sha256);
208 assert_eq!(oid.as_bytes().len(), 32);
209 assert_eq!(oid.to_hex(), hex);
210 }
211
212 #[test]
213 fn reject_near_miss_hex_lengths() {
214 for n in [39usize, 41, 63, 65] {
215 let s = "a".repeat(n);
216 assert!(
217 matches!(Oid::from_hex(&s), Err(OidError::HexLength(got)) if got == n),
218 "len {n}"
219 );
220 }
221 }
222
223 #[test]
224 fn mixed_case_hex_normalizes_lower() {
225 let mixed = "E69de29BB2d1D6434b8B29ae775aD8c2E48c5391";
226 let oid = Oid::from_hex(mixed).unwrap();
227 assert_eq!(oid.to_hex(), "e69de29bb2d1d6434b8b29ae775ad8c2e48c5391");
228 }
229
230 #[test]
231 fn oid_kinds_expose_widths() {
232 assert_eq!(OidKind::Sha1.digest_len(), 20);
233 assert_eq!(OidKind::Sha1.hex_len(), 40);
234 assert_eq!(OidKind::Sha256.digest_len(), 32);
235 assert_eq!(OidKind::Sha256.hex_len(), 64);
236 }
237}