Skip to content

Instantly share code, notes, and snippets.

@favila
Created February 20, 2018 20:09
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 favila/81deb55d67336fc2e9d383bde812ec62 to your computer and use it in GitHub Desktop.
Save favila/81deb55d67336fc2e9d383bde812ec62 to your computer and use it in GitHub Desktop.
data readers to emit transit uuids in cljs with bits calculated at compile-time
(ns favila.transit-uuid-reader
"Use as a data reader for cljs-in-cljs or clj-for-cljs compilation to emit a
transit uuid type from a uuid string.
For clj-for-cljs compilation you must require this namespace at the top of
your cljs code somehow so that the emitted code can call
`transit-uuid-from-ints`"
#?(:clj (:import
(com.cognitect.transit types)
(goog.math Long))
:cljs (:import (java.util UUID))))
#?(:clj
(defn transit-cljs-uuid
"Data reader to return a transit-cljs UUID with its int32 parts determined
at compile time."
[^String uuid-str]
(let [juuid (UUID/fromString uuid-str)
MSB (.getMostSignificantBits juuid)
LSB (.getLeastSignificantBits juuid)
LMSB (bit-and MSB 0x00000000ffffffff)
MMSB (bit-shift-right MSB 32)
LLSB (bit-and LSB 0x00000000ffffffff)
MLSB (bit-shift-right LSB 32)]
`(transit-uuid-from-ints ~MMSB ~LMSB ~MLSB ~LLSB)))
:cljs
(defn transit-cljs-uuid
"Data reader to return a transit-cljs UUID with its int32 parts determined
at compile time."
{:jsdoc ["@param {!string} uuid-str"
"@return {!com.cognitect.transit.types.UUID}"]}
[uuid-str]
(.UUIDfromString types uuid-str)))
#?(:cljs
(defn transit-uuid-from-ints
"Create a transit uuid from 32-bit numbers, highest to lowest bits.
@param {!number} hh32
@param {!number} hl32
@param {!number} lh32
@param {!number} ll32
@return {!com.cognitect.transit.types.UUID}"
[hh32 hl32 lh32 ll32]
(new (. types -UUID) (new Long hl32 hh32) (new Long ll32 lh32))))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment