Created
November 21, 2020 06:07
-
-
Save valerauko/138978741ef9477104eac5796195e61e to your computer and use it in GitHub Desktop.
Nano squids
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
;; for comparison, have the squid generator from the clojure cookbook that uses seconds | |
;; from https://github.com/clojure-cookbook/clojure-cookbook/blob/master/01_primitive-data/1-24_uuids.asciidoc | |
(defn squuid-secs [] | |
(let [uuid (java.util.UUID/randomUUID) | |
time (System/currentTimeMillis) | |
secs (quot time 1000) | |
lsb (.getLeastSignificantBits uuid) | |
msb (.getMostSignificantBits uuid) | |
timed-msb (bit-or (bit-shift-left secs 32) | |
(bit-and 0x00000000ffffffff msb))] | |
(java.util.UUID. timed-msb lsb))) | |
;; let's see if it's okay | |
(let [squids (take 10 (repeatedly squuid-secs))] | |
(assert (= squids (sort squids)))) | |
;; how about using nanoseconds instead? | |
(defn squuid-nanos [] | |
(let [uuid (java.util.UUID/randomUUID) | |
time (System/nanoTime) | |
lsb (.getLeastSignificantBits uuid) | |
msb (.getMostSignificantBits uuid) | |
timed-msb (bit-or (bit-shift-left time 32) | |
(bit-and 0x00000000ffffffff msb))] | |
(java.util.UUID. timed-msb lsb))) | |
;; let's see if it's okay | |
(let [squids (take 10 (repeatedly squuid-nanos))] | |
(assert (= squids (sort squids)))) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment