Skip to content

Commit 68576f3

Browse files
authored
Add GUID::to_u128 (#1756)
* Add GUID::to_u128 * Add From trait implementation for GUID and u128 * Add test for From<GUID> for u128 * Test both From<GUID> and From<&GUID> * Remove From<&GUID>, as GUID is Copy
1 parent 8281cc9 commit 68576f3

File tree

2 files changed

+25
-0
lines changed

2 files changed

+25
-0
lines changed

crates/libs/windows/src/core/guid.rs

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -36,6 +36,11 @@ impl GUID {
3636
Self { data1: (uuid >> 96) as u32, data2: (uuid >> 80 & 0xffff) as u16, data3: (uuid >> 64 & 0xffff) as u16, data4: (uuid as u64).to_be_bytes() }
3737
}
3838

39+
/// Converts a `GUID` to a `u128` value.
40+
pub const fn to_u128(&self) -> u128 {
41+
((self.data1 as u128) << 96) + ((self.data2 as u128) << 80) + ((self.data3 as u128) << 64) + u64::from_be_bytes(self.data4) as u128
42+
}
43+
3944
/// Creates a `GUID` for a "generic" WinRT type.
4045
pub const fn from_signature(signature: ConstBuffer) -> Self {
4146
let data = ConstBuffer::from_slice(&[0x11, 0xf4, 0x7a, 0xd5, 0x7b, 0x73, 0x42, 0xc0, 0xab, 0xae, 0x87, 0x8b, 0x1e, 0x16, 0xad, 0xee]);
@@ -98,6 +103,18 @@ impl core::convert::From<&str> for GUID {
98103
}
99104
}
100105

106+
impl core::convert::From<u128> for GUID {
107+
fn from(value: u128) -> Self {
108+
Self::from_u128(value)
109+
}
110+
}
111+
112+
impl core::convert::From<GUID> for u128 {
113+
fn from(value: GUID) -> Self {
114+
value.to_u128()
115+
}
116+
}
117+
101118
trait HexReader {
102119
fn next_u8(&mut self) -> u8;
103120
fn next_u16(&mut self) -> u16;

crates/tests/core/tests/guid.rs

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,3 +16,11 @@ fn from_u128() {
1616
assert!(a == b);
1717
assert!(a == c);
1818
}
19+
20+
#[test]
21+
fn to_u128() {
22+
let num: u128 = 0x1fd63fef_c0d2_42fe_823a_53a4052b8c8f;
23+
let guid: GUID = "1FD63FEF-C0D2-42FE-823A-53A4052B8C8F".into();
24+
25+
assert_eq!(u128::from(guid), num); // From<GUID>
26+
}

0 commit comments

Comments
 (0)