1use std::fmt;
30
31#[repr(C)]
37#[derive(Clone, Copy, PartialEq, Eq, Hash, Default)]
38pub struct Guid {
39 pub data1: u32,
40 pub data2: u16,
41 pub data3: u16,
42 pub data4: [u8; 8],
43}
44
45impl Guid {
46 pub const fn parse(s: &str) -> Self {
53 let b = s.as_bytes();
54 assert!(b.len() == 36, "a GUID is 36 characters");
55 assert!(
56 b[8] == b'-' && b[13] == b'-' && b[18] == b'-' && b[23] == b'-',
57 "GUID separators are misplaced"
58 );
59
60 const fn hex(c: u8) -> u32 {
61 match c {
62 b'0'..=b'9' => (c - b'0') as u32,
63 b'a'..=b'f' => (c - b'a' + 10) as u32,
64 b'A'..=b'F' => (c - b'A' + 10) as u32,
65 _ => panic!("not a hex digit in a GUID"),
66 }
67 }
68 const fn u32_at(b: &[u8], i: usize) -> u32 {
69 let mut v = 0u32;
70 let mut k = 0;
71 while k < 8 {
72 v = (v << 4) | hex(b[i + k]);
73 k += 1;
74 }
75 v
76 }
77 const fn u16_at(b: &[u8], i: usize) -> u16 {
78 ((hex(b[i]) << 12) | (hex(b[i + 1]) << 8) | (hex(b[i + 2]) << 4) | hex(b[i + 3])) as u16
79 }
80 const fn u8_at(b: &[u8], i: usize) -> u8 {
81 ((hex(b[i]) << 4) | hex(b[i + 1])) as u8
82 }
83
84 Self {
85 data1: u32_at(b, 0),
86 data2: u16_at(b, 9),
87 data3: u16_at(b, 14),
88 data4: [
89 u8_at(b, 19),
90 u8_at(b, 21),
91 u8_at(b, 24),
92 u8_at(b, 26),
93 u8_at(b, 28),
94 u8_at(b, 30),
95 u8_at(b, 32),
96 u8_at(b, 34),
97 ],
98 }
99 }
100
101 pub fn to_be_bytes(self) -> [u8; 16] {
103 let mut out = [0u8; 16];
104 out[0..4].copy_from_slice(&self.data1.to_be_bytes());
105 out[4..6].copy_from_slice(&self.data2.to_be_bytes());
106 out[6..8].copy_from_slice(&self.data3.to_be_bytes());
107 out[8..16].copy_from_slice(&self.data4);
108 out
109 }
110
111 fn from_be_bytes(b: [u8; 16]) -> Self {
112 Self {
113 data1: u32::from_be_bytes([b[0], b[1], b[2], b[3]]),
114 data2: u16::from_be_bytes([b[4], b[5]]),
115 data3: u16::from_be_bytes([b[6], b[7]]),
116 data4: [b[8], b[9], b[10], b[11], b[12], b[13], b[14], b[15]],
117 }
118 }
119
120 pub fn signature(&self) -> String {
122 format!("{{{self}}}")
123 }
124}
125
126impl fmt::Display for Guid {
127 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
128 write!(
129 f,
130 "{:08x}-{:04x}-{:04x}-{:02x}{:02x}-{:02x}{:02x}{:02x}{:02x}{:02x}{:02x}",
131 self.data1,
132 self.data2,
133 self.data3,
134 self.data4[0],
135 self.data4[1],
136 self.data4[2],
137 self.data4[3],
138 self.data4[4],
139 self.data4[5],
140 self.data4[6],
141 self.data4[7]
142 )
143 }
144}
145
146impl fmt::Debug for Guid {
147 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
148 write!(f, "{self}")
149 }
150}
151
152#[derive(Debug, Clone)]
154pub enum Signature {
155 Primitive(&'static str),
157 Interface(Guid),
159 Class {
161 name: &'static str,
162 default_interface: Guid,
163 },
164 Enum { name: &'static str, signed: bool },
166 Struct {
168 name: &'static str,
169 fields: Vec<Signature>,
170 },
171 Delegate(Guid),
173 Parameterized {
175 generic: Guid,
176 arguments: Vec<Signature>,
177 },
178}
179
180impl Signature {
181 pub const BOOL: Self = Self::Primitive("b1");
182 pub const U8: Self = Self::Primitive("u1");
183 pub const I16: Self = Self::Primitive("i2");
184 pub const U16: Self = Self::Primitive("u2");
185 pub const I32: Self = Self::Primitive("i4");
186 pub const U32: Self = Self::Primitive("u4");
187 pub const I64: Self = Self::Primitive("i8");
188 pub const U64: Self = Self::Primitive("u8");
189 pub const STRING: Self = Self::Primitive("string");
190 pub const GUID: Self = Self::Primitive("g16");
191 pub const OBJECT: Self = Self::Primitive("cinterface(IInspectable)");
193
194 pub fn text(&self) -> String {
196 match self {
197 Self::Primitive(code) => (*code).to_string(),
198 Self::Interface(iid) => iid.signature(),
199 Self::Class {
200 name,
201 default_interface,
202 } => {
203 format!("rc({name};{})", default_interface.signature())
204 }
205 Self::Enum { name, signed } => {
206 format!("enum({name};{})", if *signed { "i4" } else { "u4" })
207 }
208 Self::Struct { name, fields } => {
209 let inner: Vec<String> = fields.iter().map(Self::text).collect();
210 format!("struct({name};{})", inner.join(";"))
211 }
212 Self::Delegate(iid) => format!("delegate({})", iid.signature()),
213 Self::Parameterized { generic, arguments } => {
214 let inner: Vec<String> = arguments.iter().map(Self::text).collect();
215 format!("pinterface({};{})", generic.signature(), inner.join(";"))
216 }
217 }
218 }
219
220 pub fn iid(&self) -> Option<Guid> {
225 match self {
226 Self::Interface(iid) | Self::Delegate(iid) => Some(*iid),
227 Self::Parameterized { .. } => {
228 Some(uuid_v5(WINRT_PIID_NAMESPACE, self.text().as_bytes()))
229 }
230 _ => None,
231 }
232 }
233}
234
235pub const WINRT_PIID_NAMESPACE: Guid = Guid::parse("11f47ad5-7b73-42c0-abae-878b1e16adee");
237
238pub fn uuid_v5(namespace: Guid, name: &[u8]) -> Guid {
240 let mut input = Vec::with_capacity(16 + name.len());
241 input.extend_from_slice(&namespace.to_be_bytes());
242 input.extend_from_slice(name);
243
244 let hash = sha1(&input);
245 let mut bytes = [0u8; 16];
246 bytes.copy_from_slice(&hash[..16]);
247 bytes[6] = (bytes[6] & 0x0F) | 0x50;
249 bytes[8] = (bytes[8] & 0x3F) | 0x80;
250 Guid::from_be_bytes(bytes)
251}
252
253fn sha1(data: &[u8]) -> [u8; 20] {
256 let mut h: [u32; 5] = [
257 0x6745_2301,
258 0xEFCD_AB89,
259 0x98BA_DCFE,
260 0x1032_5476,
261 0xC3D2_E1F0,
262 ];
263
264 let mut message = data.to_vec();
265 let bit_length = (data.len() as u64) * 8;
266 message.push(0x80);
267 while message.len() % 64 != 56 {
268 message.push(0);
269 }
270 message.extend_from_slice(&bit_length.to_be_bytes());
271
272 for chunk in message.chunks_exact(64) {
273 let mut w = [0u32; 80];
274 for (i, word) in chunk.chunks_exact(4).enumerate() {
275 w[i] = u32::from_be_bytes([word[0], word[1], word[2], word[3]]);
276 }
277 for i in 16..80 {
278 w[i] = (w[i - 3] ^ w[i - 8] ^ w[i - 14] ^ w[i - 16]).rotate_left(1);
279 }
280 let (mut a, mut b, mut c, mut d, mut e) = (h[0], h[1], h[2], h[3], h[4]);
281 for (i, word) in w.iter().enumerate() {
282 let (f, k) = match i {
283 0..=19 => ((b & c) | (!b & d), 0x5A82_7999),
284 20..=39 => (b ^ c ^ d, 0x6ED9_EBA1),
285 40..=59 => ((b & c) | (b & d) | (c & d), 0x8F1B_BCDC),
286 _ => (b ^ c ^ d, 0xCA62_C1D6),
287 };
288 let temp = a
289 .rotate_left(5)
290 .wrapping_add(f)
291 .wrapping_add(e)
292 .wrapping_add(k)
293 .wrapping_add(*word);
294 e = d;
295 d = c;
296 c = b.rotate_left(30);
297 b = a;
298 a = temp;
299 }
300 h[0] = h[0].wrapping_add(a);
301 h[1] = h[1].wrapping_add(b);
302 h[2] = h[2].wrapping_add(c);
303 h[3] = h[3].wrapping_add(d);
304 h[4] = h[4].wrapping_add(e);
305 }
306
307 let mut out = [0u8; 20];
308 for (i, word) in h.iter().enumerate() {
309 out[i * 4..i * 4 + 4].copy_from_slice(&word.to_be_bytes());
310 }
311 out
312}
313
314#[cfg(test)]
315mod tests {
316 use super::*;
317 use crate::iids::generics;
318
319 #[test]
320 fn guids_round_trip_through_their_text_form() {
321 for text in [
322 "9fc2b0bb-e446-44e2-aa61-9cab8f636af2",
323 "00000000-0000-0000-0000-000000000000",
324 "ffffffff-ffff-ffff-ffff-ffffffffffff",
325 "11f47ad5-7b73-42c0-abae-878b1e16adee",
326 ] {
327 assert_eq!(Guid::parse(text).to_string(), text);
328 }
329 }
330
331 #[test]
337 fn a_class_with_a_parameterised_default_interface_gets_an_iid() {
338 use crate::iids::classes;
339
340 let element = Signature::Parameterized {
341 generic: generics::I_VECTOR_VIEW,
342 arguments: vec![Signature::Class {
343 name: classes::DEVICE_INFORMATION.0,
344 default_interface: classes::DEVICE_INFORMATION.1,
345 }],
346 };
347 let iid = element.iid().expect("a parameterised signature has an IID");
348
349 assert_ne!(iid, generics::I_VECTOR_VIEW);
353 assert_ne!(iid, classes::DEVICE_INFORMATION.1);
354
355 let again = Signature::Parameterized {
358 generic: generics::I_VECTOR_VIEW,
359 arguments: vec![Signature::Class {
360 name: classes::DEVICE_INFORMATION.0,
361 default_interface: classes::DEVICE_INFORMATION.1,
362 }],
363 }
364 .iid()
365 .unwrap();
366 assert_eq!(iid, again);
367
368 let other = Signature::Parameterized {
371 generic: generics::I_VECTOR_VIEW,
372 arguments: vec![Signature::Primitive("string")],
373 }
374 .iid()
375 .unwrap();
376 assert_ne!(iid, other);
377 }
378
379 #[test]
380 fn the_abi_layout_is_what_com_expects() {
381 assert_eq!(std::mem::size_of::<Guid>(), 16);
382 assert_eq!(std::mem::align_of::<Guid>(), 4);
383 }
384
385 #[test]
386 fn only_the_first_three_fields_are_byte_swapped() {
387 let g = Guid::parse("01020304-0506-0708-090a-0b0c0d0e0f10");
390 assert_eq!(g.data1, 0x0102_0304);
391 assert_eq!(g.data2, 0x0506);
392 assert_eq!(g.data3, 0x0708);
393 assert_eq!(g.data4, [0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10]);
394 assert_eq!(
395 g.to_be_bytes(),
396 [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16]
397 );
398 }
399
400 #[test]
401 fn sha1_matches_known_vectors() {
402 assert_eq!(
403 sha1(b"abc"),
404 [
405 0xA9, 0x99, 0x3E, 0x36, 0x47, 0x06, 0x81, 0x6A, 0xBA, 0x3E, 0x25, 0x71, 0x78, 0x50,
406 0xC2, 0x6C, 0x9C, 0xD0, 0xD8, 0x9D
407 ]
408 );
409 assert_eq!(
410 sha1(b""),
411 [
412 0xDA, 0x39, 0xA3, 0xEE, 0x5E, 0x6B, 0x4B, 0x0D, 0x32, 0x55, 0xBF, 0xEF, 0x95, 0x60,
413 0x18, 0x90, 0xAF, 0xD8, 0x07, 0x09
414 ]
415 );
416 }
417
418 #[test]
419 fn uuid_v5_matches_the_published_vector() {
420 let dns = Guid::parse("6ba7b810-9dad-11d1-80b4-00c04fd430c8");
424 assert_eq!(
425 uuid_v5(dns, b"python.org").to_string(),
426 "886313e1-3b8a-5372-9b90-0c9aee199e5d"
427 );
428 }
429
430 #[test]
431 fn version_and_variant_bits_are_set() {
432 let id = uuid_v5(WINRT_PIID_NAMESPACE, b"anything at all");
433 assert_eq!(id.data3 >> 12, 5, "version must be 5");
434 assert_eq!(id.data4[0] >> 6, 0b10, "variant must be RFC 4122");
435 }
436
437 #[test]
438 fn signature_strings_match_the_official_bindings() {
439 let handler = Signature::Parameterized {
443 generic: generics::TYPED_EVENT_HANDLER,
444 arguments: vec![Signature::OBJECT, Signature::OBJECT],
445 };
446 assert!(
447 handler
448 .text()
449 .starts_with("pinterface({9de1c534-6ae1-11e0-84e1-18a905bcc53f};"),
450 "got {}",
451 handler.text()
452 );
453
454 let operation = Signature::Parameterized {
455 generic: generics::I_ASYNC_OPERATION,
456 arguments: vec![Signature::BOOL],
457 };
458 assert_eq!(
459 operation.text(),
460 "pinterface({9fc2b0bb-e446-44e2-aa61-9cab8f636af2};b1)"
461 );
462 }
463
464 #[test]
465 fn nested_signatures_compose() {
466 let class = Signature::Class {
469 name: "Windows.Devices.Bluetooth.BluetoothLEDevice",
470 default_interface: Guid::parse("b5ee2f7b-4ad8-4642-ac48-80a0b500e887"),
471 };
472 let operation = Signature::Parameterized {
473 generic: generics::I_ASYNC_OPERATION,
474 arguments: vec![class],
475 };
476 let handler = Signature::Parameterized {
477 generic: generics::ASYNC_OPERATION_COMPLETED_HANDLER,
478 arguments: vec![operation.clone()],
479 };
480
481 assert_eq!(
482 operation.text(),
483 "pinterface({9fc2b0bb-e446-44e2-aa61-9cab8f636af2};\
484 rc(Windows.Devices.Bluetooth.BluetoothLEDevice;\
485 {b5ee2f7b-4ad8-4642-ac48-80a0b500e887}))"
486 .replace(char::is_whitespace, "")
487 );
488 assert!(handler.text().contains(&operation.text()));
489 assert_ne!(operation.iid(), handler.iid());
491 }
492
493 #[test]
494 fn a_parameterised_iid_is_stable_and_argument_dependent() {
495 let of = |arg: Signature| {
496 Signature::Parameterized {
497 generic: generics::I_ASYNC_OPERATION,
498 arguments: vec![arg],
499 }
500 .iid()
501 .unwrap()
502 };
503 assert_eq!(
504 of(Signature::BOOL),
505 of(Signature::BOOL),
506 "must be deterministic"
507 );
508 assert_ne!(
509 of(Signature::BOOL),
510 of(Signature::I32),
511 "must depend on the argument"
512 );
513 }
514
515 #[test]
516 fn non_parameterised_types_have_no_computed_iid() {
517 assert!(Signature::BOOL.iid().is_none());
518 assert!(Signature::Class {
519 name: "X.Y",
520 default_interface: Guid::default()
521 }
522 .iid()
523 .is_none());
524 let iid = Guid::parse("59cb50c1-5934-4f68-a198-eb864fa44e6b");
525 assert_eq!(Signature::Interface(iid).iid(), Some(iid));
526 }
527}