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
21 changes: 20 additions & 1 deletion Sources/Dependencies/DependencyValues/UUID.swift
Original file line number Diff line number Diff line change
Expand Up @@ -113,8 +113,27 @@ public struct UUIDGenerator: Sendable {
}

extension UUID {
/// Initializes a UUID from an integer by converting it to hex and padding it with 0's.
///
/// For example:
///
/// ```swift
/// UUID(16) == UUID(uuidString: "00000000-0000-0000-0000000000F0")
/// ```
///
/// If a negative number is passed to this function then it is inverted and the negative sign
/// is encoded into the 16th bit of the UUID:
///
/// ```swift
/// UUID(-16) == UUID(uuidString: "00000000-0001-0000-0000000000F0")
/// 👆
/// ```
public init(_ intValue: Int) {
self.init(uuidString: "00000000-0000-0000-0000-\(String(format: "%012x", intValue))")!
let isNegative = intValue < 0
let intValue = isNegative ? -intValue : intValue
var hexString = String(format: "%016llx", intValue)
hexString.insert("-", at: hexString.index(hexString.startIndex, offsetBy: 4))
self.init(uuidString: "00000000-0000-000\(isNegative ? "1" : "0")-\(hexString)")!
}
}

Expand Down
4 changes: 4 additions & 0 deletions Tests/DependenciesTests/UUIDTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -18,5 +18,9 @@ final class UUIDDependencyTests: XCTestCase {
XCTAssertEqual(UUID(1), UUID(uuidString: "00000000-0000-0000-0000-000000000001"))
XCTAssertEqual(UUID(15), UUID(uuidString: "00000000-0000-0000-0000-00000000000F"))
XCTAssertEqual(UUID(256), UUID(uuidString: "00000000-0000-0000-0000-000000000100"))

XCTAssertEqual(UUID(Int.max), UUID(uuidString: "00000000-0000-0000-7FFF-FFFFFFFFFFFF"))
XCTAssertEqual(UUID(-1), UUID(uuidString: "00000000-0000-0001-0000-000000000001"))
XCTAssertEqual(UUID(-Int.max), UUID(uuidString: "00000000-0000-0001-7FFF-FFFFFFFFFFFF"))
}
}