Create time UUID from timestamp.
authorMathieu <mbaudier@argeo.org>
Mon, 14 Nov 2022 05:30:36 +0000 (06:30 +0100)
committerMathieu <mbaudier@argeo.org>
Mon, 14 Nov 2022 05:30:36 +0000 (06:30 +0100)
org.argeo.api.uuid/src/org/argeo/api/uuid/ConcurrentTimeUuidState.java
org.argeo.api.uuid/src/org/argeo/api/uuid/TimeUuid.java

index 6dbd403dd506468341c42b09f13e419619740413..fd158fb8315db647b8d0b07e7790d1ec57aa2b3f 100644 (file)
@@ -143,9 +143,7 @@ public class ConcurrentTimeUuidState implements UuidFactory.TimeUuidState {
        @Override
        public long getMostSignificantBits() {
                long timestamp = useTimestamp();
-               long mostSig = UuidFactory.MOST_SIG_VERSION1 | ((timestamp & 0xFFFFFFFFL) << 32) // time_low
-                               | (((timestamp >> 32) & 0xFFFFL) << 16) // time_mid
-                               | ((timestamp >> 48) & 0x0FFFL);// time_hi_and_version
+               long mostSig = TimeUuid.toMostSignificantBits(timestamp);
                return mostSig;
        }
 
index 2276cd26831976344acb80e53b708aca902da854..2e0587d12748128445ee3b81b64439fa8b6a59f2 100644 (file)
@@ -76,4 +76,23 @@ public class TimeUuid extends TypedUuid {
                Duration duration = Duration.between(TimeUuid.TIMESTAMP_ZERO, instant);
                return durationToTimestamp(duration);
        }
+
+       /**
+        * Crate a time UUID with this instant as timestamp and clock and node id set to
+        * zero.
+        */
+       public static UUID fromInstant(Instant instant) {
+               long timestamp = instantToTimestamp(instant);
+               long mostSig = toMostSignificantBits(timestamp);
+               UUID uuid = new UUID(mostSig, UuidFactory.LEAST_SIG_RFC4122_VARIANT);
+               return uuid;
+       }
+
+       /** Convert timestamp in UUID format to most significant bits of a time UUID. */
+       static long toMostSignificantBits(long timestamp) {
+               long mostSig = UuidFactory.MOST_SIG_VERSION1 | ((timestamp & 0xFFFFFFFFL) << 32) // time_low
+                               | (((timestamp >> 32) & 0xFFFFL) << 16) // time_mid
+                               | ((timestamp >> 48) & 0x0FFFL);// time_hi_and_version
+               return mostSig;
+       }
 }