Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ Please check the [releases](https://github.com/mochidev/CodableDatastore/release
dependencies: [
.package(
url: "https://github.com/mochidev/CodableDatastore.git",
.upToNextMinor(from: "0.3.3")
.upToNextMinor(from: "0.3.4")
),
],
...
Expand Down
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
}