Last active
July 3, 2024 02:09
-
-
Save espeed/5687774 to your computer and use it in GitHub Desktop.
Random UUID compressed into a Binary 16 byte array 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
;; Random UUID compressed into a Binary 16 byte array in Clojure. | |
;; by James Thornton, http://jamesthornton.com | |
(ns espeed.uuid | |
(require [clojure.data.codec.base64 :as b64])) | |
(defn uuid4 [] (java.util.UUID/randomUUID)) | |
(defn uuid-as-byte-array [] | |
(let [u (uuid4) ; uuid4 | |
^long lo (.getLeastSignificantBits u) ; least significant bits | |
^long hi (.getMostSignificantBits u)] ; most significant bits (left-most bits) | |
(-> (java.nio.ByteBuffer/allocate 16) ; http://docs.oracle.com/javase/6/docs/api/java/util/UUID.html | |
(.putLong hi) | |
(.putLong lo) | |
(.array)))) | |
(defn bytes-to-base64-bytes | |
[bytes] | |
(b64/encode bytes)) | |
(defn bytes-to-base64-str | |
[bytes] | |
(-> bytes b64/encode (String. "UTF-8"))) | |
;; originally derived from... | |
;; http://corfield.org/blog/post.cfm/to-uuid-or-not-to-uuid | |
(comment defn uuid2 [] (com.eaio.uuid.UUID.)) | |
(comment defn uuid-as-byte-array [] | |
(let [u (uuid2) | |
^long lo (.getClockSeqAndNode u) | |
^long hi (.getTime u)] | |
(-> (java.nio.ByteBuffer/allocate 16) | |
(.putLong hi) | |
(.putLong lo) | |
(.array)))) | |
;; Notes... | |
;; http://www.thebinaryidiot.com/archives/2011/06/25/jpa-and-uuid-primary-keys/ | |
;; http://www.mysqlperformanceblog.com/2007/03/13/to-uuid-or-not-to-uuid/ | |
;; https://bugzilla.mozilla.org/show_bug.cgi?id=843013 | |
;; https://news.ycombinator.com/item?id=2339120 | |
;; http://stackoverflow.com/questions/11825444/clojure-base64-encoding |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment