Skip to content

Instantly share code, notes, and snippets.

@ytyubox
Created April 23, 2022 07:15
Show Gist options
  • Save ytyubox/4028fe494e744583016e431495ed2c7d to your computer and use it in GitHub Desktop.
Save ytyubox/4028fe494e744583016e431495ed2c7d to your computer and use it in GitHub Desktop.
import XCTest
import struct Foundation.UUID
extension UUID {
internal init(_ uint8s: UInt8...) {
var list:[UInt8] = Array(repeating: 0, count: 16)
for (index, value) in uint8s.enumerated() where index < 16 {
list[15-index] = value
}
self.init(list: list)
}
public init(n: Int) {
self.init(u: n > 0 ? UInt(n) : 0)
}
public init(u: UInt) {
var u = u
var list:[UInt8] = Array(repeating: 0, count: 16)
let u8Max = UInt(UInt8.max)
var i = 15
while u > 0 {
list[i] = UInt8(u&u8Max)
u >>= UInt8.bitWidth
i -= 1
}
self.init(list: list)
}
private init(list: [uint8]) {
let uuidT = (list[0],
list[01], list[02], list[03], list[04], list[05],
list[06], list[07], list[08], list[09], list[10],
list[11], list[12], list[13], list[14], list[15])
self.init(uuid: uuidT)
}
}
extension UUID: ExpressibleByIntegerLiteral {
public init(integerLiteral value: Int) {
self.init(n: value)
}
}
final class UUIDsTests: XCTestCase {
func testInitByInt_UInt() throws {
XCTAssertEqual(UUID(n: 0).uuidString, "00000000-0000-0000-0000-000000000000")
XCTAssertEqual(UUID(n: 1).uuidString, "00000000-0000-0000-0000-000000000001")
XCTAssertEqual(UUID(n: 2).uuidString, "00000000-0000-0000-0000-000000000002")
XCTAssertEqual(UUID(n: 3).uuidString, "00000000-0000-0000-0000-000000000003")
XCTAssertEqual(UUID(n: 255).uuidString, "00000000-0000-0000-0000-0000000000FF")
XCTAssertEqual(UUID(n: 256).uuidString, "00000000-0000-0000-0000-000000000100")
XCTAssertEqual(UUID(n: .max).uuidString, "00000000-0000-0000-7FFF-FFFFFFFFFFFF")
XCTAssertEqual(UUID(n: -1).uuidString, "00000000-0000-0000-0000-000000000000")
XCTAssertEqual(UUID(u: .max).uuidString, "00000000-0000-0000-FFFF-FFFFFFFFFFFF")
}
func testNumberLiteral() throws {
let expect = "00000000-0000-0000-0000-000000000011"
assertUUID(17, expect)
assertUUID(0_1_7, expect)
assertUUID(0b10001, expect)
assertUUID(0o21, expect)
assertUUID(0x11, expect)
}
func testHelper() throws {
XCTAssertEqual(UUID(1,1).uuidString, "00000000-0000-0000-0000-000000000101")
XCTAssertEqual(UUID(1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1).uuidString, "01010101-0101-0101-0101-010101010101")
XCTAssertEqual(UUID(1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1).uuidString, "01010101-0101-0101-0101-010101010101")
}
private func assertUUID(_ uuid: UUID, _ expect: String, message: String = "", file: StaticString = #filePath, line: UInt = #line) {
XCTAssertEqual(uuid.uuidString, expect, message, file: file, line: line)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment