Skip to content

Instantly share code, notes, and snippets.

@valerauko
Created November 21, 2020 06:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save valerauko/138978741ef9477104eac5796195e61e to your computer and use it in GitHub Desktop.
Save valerauko/138978741ef9477104eac5796195e61e to your computer and use it in GitHub Desktop.
Nano squids
;; 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