Skip to content

Commit baf4506

Browse files
committed
Add Equatable and Hashable conformance to GUID.
On Windows, `GUID` is a currency type and (along with its various typedefs) is used pervasively Windows offers `IsEqualGUID()` and `UuidHash()` for comparing and hashing them, respectively, but `IsEqualGUID()` is a macro in C mode and `UuidHash()` only provides a 16-bit hash. We should provide conformance to these protocols in the WinSDK overlay to provide equivalent functionality in Swift.
1 parent 0cbcd56 commit baf4506

File tree

2 files changed

+33
-1
lines changed

2 files changed

+33
-1
lines changed

stdlib/public/Windows/WinSDK.swift

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -319,3 +319,24 @@ func _convertWindowsBoolToBool(_ b: WindowsBool) -> Bool {
319319
return b.boolValue
320320
}
321321

322+
// GUID
323+
324+
extension GUID: Equatable, Hashable {
325+
@usableFromInline @_transparent
326+
private var uint128Value: UInt128 {
327+
unsafe withUnsafeBytes(of: self) { buffer in
328+
// GUID is 32-bit-aligned only, so use loadUnaligned().
329+
unsafe buffer.baseAddress!.loadUnaligned(as: UInt128.self)
330+
}
331+
}
332+
333+
@_transparent
334+
public static func ==(lhs: Self, rhs: Self) -> Bool {
335+
lhs.uint128Value == rhs.uint128Value
336+
}
337+
338+
@_transparent
339+
public func hash(into: inout Hasher) {
340+
hasher.combine(uint128Value)
341+
}
342+
}

test/stdlib/WinSDK_GUID.swift

Lines changed: 12 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
1-
// RUN: %target-build-swift %s
1+
// RUN: %target-swift-frontend -typecheck -swift-version 6 %s -verify
2+
// REQUIRES: executable_test
23
// REQUIRES: OS=windows-msvc
34

45
// Make sure that importing WinSDK brings in the GUID type, which is declared in
@@ -7,3 +8,13 @@
78
import WinSDK
89

910
public func usesGUID(_ x: GUID) {}
11+
12+
// Make sure equating and hashing GUIDs works.
13+
14+
let guid: GUID = GUID_NULL
15+
assert(guid == guid)
16+
assert(guid.hashValue == guid.hashValue)
17+
18+
let guid2: GUID = IID_IUnknown
19+
assert(guid != guid2)
20+
assert(guid.hashValue != guid2.hashValue) // well, probably

0 commit comments

Comments
 (0)