Skip to content

Commit

Permalink
Added a raw UUID comparison thats always available
Browse files Browse the repository at this point in the history
  • Loading branch information
dimitribouniol committed Jun 19, 2024
1 parent f49a7f1 commit c63db6e
Showing 1 changed file with 23 additions and 25 deletions.
48 changes: 23 additions & 25 deletions Sources/CodableDatastore/Indexes/UUID+Comparable.swift
Original file line number Diff line number Diff line change
Expand Up @@ -15,44 +15,42 @@ extension UUID: @retroactive Comparable {
@inlinable
@_disfavoredOverload
public static func < (lhs: UUID, rhs: UUID) -> Bool {
lhs.isLessThan(rhs: rhs)
lhs.uuid < rhs.uuid
}
}
#else
extension UUID: Comparable {
@inlinable
@_disfavoredOverload
public static func < (lhs: UUID, rhs: UUID) -> Bool {
lhs.isLessThan(rhs: rhs)
lhs.uuid < rhs.uuid
}
}
#endif
#endif

extension UUID {
/// Make UUIDs comparable, so that they can be used transparently as an index.
///
/// - SeeAlso: https://github.com/apple/swift-foundation/blob/5388acf1d929865d4df97d3c50e4d08bc4c6bdf0/Sources/FoundationEssentials/UUID.swift#L135-L156
@usableFromInline
func isLessThan(rhs: UUID) -> Bool {
var leftUUID = self.uuid
var rightUUID = rhs.uuid
var result: Int = 0
var diff: Int = 0
withUnsafeBytes(of: &leftUUID) { leftPtr in
withUnsafeBytes(of: &rightUUID) { rightPtr in
for offset in (0 ..< MemoryLayout<uuid_t>.size).reversed() {
diff = Int(leftPtr.load(fromByteOffset: offset, as: UInt8.self)) -
Int(rightPtr.load(fromByteOffset: offset, as: UInt8.self))
// Constant time, no branching equivalent of
// if (diff != 0) {
// result = diff;
// }
result = (result & (((diff - 1) & ~diff) >> 8)) | diff
}
/// Make UUIDs comparable, so that they can be used transparently as an index.
///
/// - SeeAlso: https://github.com/apple/swift-foundation/blob/5388acf1d929865d4df97d3c50e4d08bc4c6bdf0/Sources/FoundationEssentials/UUID.swift#L135-L156
@inlinable
public func < (lhs: uuid_t, rhs: uuid_t) -> Bool {
var lhs = lhs
var rhs = rhs
var result: Int = 0
var diff: Int = 0
withUnsafeBytes(of: &lhs) { leftPtr in
withUnsafeBytes(of: &rhs) { rightPtr in
for offset in (0 ..< MemoryLayout<uuid_t>.size).reversed() {
diff = Int(leftPtr.load(fromByteOffset: offset, as: UInt8.self)) -
Int(rightPtr.load(fromByteOffset: offset, as: UInt8.self))
// Constant time, no branching equivalent of
// if (diff != 0) {
// result = diff;
// }
result = (result & (((diff - 1) & ~diff) >> 8)) | diff
}
}

return result < 0
}

return result < 0
}

0 comments on commit c63db6e

Please sign in to comment.