Last active
March 17, 2023 21:15
-
-
Save favila/51437232ae486d5dd49d571dbb638dd0 to your computer and use it in GitHub Desktop.
Utilities to construct or decompose datomic entity ids on on-prem systems using bit arithmetic
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
(ns favila.eid-utils | |
"Utilities to construct or decompose entity ids on on-prem systems. | |
Many of these utilities replicate datomic.api functions because the peer api | |
lacks them. | |
The entity id format is: | |
sign-bit, reserved-bit, 20-partition-bits, 42-t-bits | |
1. The sign-bit is on for tempids, off otherwise. | |
2. Reserved-bit must be 0. | |
3. The 20 partition bits are the t-bits of the partition eid this eid | |
belongs in. | |
4. The lowest 42 bits are \"t\" or \"idx\" bits. These bits are unique | |
across all entity ids.") | |
(def ^:const ^long MASK-20 | |
2r000000000000000000000000000000000000000000011111111111111111111) | |
(def ^:const ^long MASK-42 | |
2r000000000000000000000111111111111111111111111111111111111111111) | |
(def ^:const ^long MASK-PART | |
2r011111111111111111111000000000000000000000000000000000000000000) | |
(def ^:const ^long TX-PART-BITS | |
2r000000000000000000011000000000000000000000000000000000000000000) | |
(defn make-eid ^long [^long partition-eid ^long t] | |
(bit-or | |
(bit-shift-left partition-eid 42) | |
(bit-and MASK-42 t))) | |
(defn part ^long [^long eid] | |
(bit-shift-right (bit-and eid MASK-PART) 42)) | |
(defn tx->t ^long [^long t] | |
(bit-and MASK-42 t)) | |
(defn t->tx ^long [^long t] | |
(bit-or TX-PART-BITS (bit-and MASK-42 t))) | |
(defn entid-at ^long [^long part-eid ^long t] | |
{:pre [(== (bit-and part-eid MASK-20) part-eid)]} | |
(make-eid part-eid t)) | |
(defn partition-start ^long [^long part-eid] | |
(entid-at part-eid 0)) | |
(defn partition-end ^long [^long part-eid] | |
(entid-at part-eid MASK-42)) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment