Skip to content

Commit

Permalink
Add GUID::to_u128 (#1756)
Browse files Browse the repository at this point in the history
* 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
  • Loading branch information
GamePad64 authored May 13, 2022
1 parent 8281cc9 commit 68576f3
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 0 deletions.
17 changes: 17 additions & 0 deletions crates/libs/windows/src/core/guid.rs
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,11 @@ impl GUID {
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() }
}

/// Converts a `GUID` to a `u128` value.
pub const fn to_u128(&self) -> u128 {
((self.data1 as u128) << 96) + ((self.data2 as u128) << 80) + ((self.data3 as u128) << 64) + u64::from_be_bytes(self.data4) as u128
}

/// Creates a `GUID` for a "generic" WinRT type.
pub const fn from_signature(signature: ConstBuffer) -> Self {
let data = ConstBuffer::from_slice(&[0x11, 0xf4, 0x7a, 0xd5, 0x7b, 0x73, 0x42, 0xc0, 0xab, 0xae, 0x87, 0x8b, 0x1e, 0x16, 0xad, 0xee]);
Expand Down Expand Up @@ -98,6 +103,18 @@ impl core::convert::From<&str> for GUID {
}
}

impl core::convert::From<u128> for GUID {
fn from(value: u128) -> Self {
Self::from_u128(value)
}
}

impl core::convert::From<GUID> for u128 {
fn from(value: GUID) -> Self {
value.to_u128()
}
}

trait HexReader {
fn next_u8(&mut self) -> u8;
fn next_u16(&mut self) -> u16;
Expand Down
8 changes: 8 additions & 0 deletions crates/tests/core/tests/guid.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,3 +16,11 @@ fn from_u128() {
assert!(a == b);
assert!(a == c);
}

#[test]
fn to_u128() {
let num: u128 = 0x1fd63fef_c0d2_42fe_823a_53a4052b8c8f;
let guid: GUID = "1FD63FEF-C0D2-42FE-823A-53A4052B8C8F".into();

assert_eq!(u128::from(guid), num); // From<GUID>
}

0 comments on commit 68576f3

Please sign in to comment.