Last active
June 19, 2024 17:14
-
-
Save saidone75/28611d131821fb2c2eb507fe19e4c299 to your computer and use it in GitHub Desktop.
UUIDv7 in Clojure
This file contains hidden or 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
(ns uuidv7 | |
(:require [clojure.string :as str]) | |
(:import (java.security SecureRandom))) | |
(defn gen-uuid-v7 | |
"Returns an UUIDv7 as a byte seq." | |
[] | |
(let [rand-array (byte-array 10)] | |
(.nextBytes (SecureRandom.) rand-array) | |
(concat | |
;; timestamp | |
(map byte (.toByteArray (biginteger (System/currentTimeMillis)))) | |
;; version | |
[(bit-or (bit-and (first rand-array) 0x0F) 0x70)] | |
[(nth rand-array 1)] | |
;; variant | |
[(bit-or (bit-and (nth rand-array 2) 0x3F) 0x80)] | |
(drop 3 rand-array)))) | |
(defn uuid-to-string | |
"Formats a byte seq UUIDv7 to lowercase hex string with dashes." | |
[uuid-bytes] | |
(str/join "-" | |
(map #(apply str %) | |
(let [indices (reductions + 0 [4 2 2 2 6])] | |
(map #(subvec (vec (map (partial format "%02x") uuid-bytes)) %1 %2) | |
(butlast indices) | |
(rest indices)))))) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment