Last active
February 19, 2024 23:35
-
-
Save thinkier/17a32312992d0580b56cc3ef157f99b3 to your computer and use it in GitHub Desktop.
Swift script to generate UUID version 7 in accordance with draft-ietf-uuidrev-rfc4122bis-14. Can generate about 4k/ms on a Release profile on my A16 Bionic.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/// License: Public Domain, or MIT License where Public Domain is not available | |
import Foundation | |
extension UUID { | |
/// Implementation of UUIDv7 generator based on the specifications in draft-ietf-uuidrev-rfc4122bis-14 | |
/// | |
/// UUIDv7 is generated without using any additional methods of Monotonicity Guarantees. (Section 6.2) As such, the UUID is accurate to the millisecond only. | |
/// | |
// Field and Bit Layout: | |
// 0 1 2 3 | |
// 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 | |
// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | |
// | unix_ts_ms | | |
// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | |
// | unix_ts_ms | ver | rand_a | | |
// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | |
// |var| rand_b | | |
// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | |
// | rand_b | | |
// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | |
public static func init_v7(timeAtGeneration: Date = Date()) -> UUID? { | |
let unix_ts_ms = withUnsafeBytes(of: UInt64(timeAtGeneration.timeIntervalSince1970 * 1000).bigEndian, Array.init) | |
var rand = [UInt8](repeating: 0, count: 10) | |
guard errSecSuccess == SecRandomCopyBytes(kSecRandomDefault, rand.count, &rand) else { | |
return nil | |
} | |
// ver | |
rand[0] &= 0b00001111 | |
rand[0] |= 0b01110000 | |
// var | |
rand[2] &= 0b00111111 | |
rand[2] |= 0b10000000 | |
let bytes = ( | |
unix_ts_ms[2], unix_ts_ms[3], unix_ts_ms[4], unix_ts_ms[5], | |
unix_ts_ms[6], unix_ts_ms[7], rand[0], rand[1], | |
rand[2], rand[3], rand[4], rand[5], | |
rand[6], rand[7], rand[8], rand[9] | |
) | |
return UUID(uuid: bytes) | |
} | |
} |
Author
thinkier
commented
Feb 19, 2024
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment