UUID v7

Tom Glod tom at makeshyft.com
Fri Sep 1 13:20:04 EDT 2023


Hi Folks,

Sharing this because its useful, and also, more eyeballs on the code makes
sense.
I implemented this with the help of chatGPT.

This is a handler that can generate v7 UUIDs.
v7 UUIDs work better in databases, because they are not so random,
improving performance.
And they are sequential.
They also match the format of uuid v4
Also the specs for v7 have not yet been finalized.

Here it is:

function CreateUUID pVersion
   // This Handler returns a
   if pVersion is not 7 then
      //Return V4 Random UUID
      return uuid("random")

   else if pVersion = 7 then
      // return V7 Random yet sequenced UUID

      local tUnixTsMs, tVer, tRandA, tTVar, tRandB, tTheID
      -- Get the current timestamp in milliseconds

      put baseConvert(the milliseconds, 10, 16) into tUnixTsMs
      put format("%012s", tUnixTsMs) into tUnixTsMs

      // Set the version field to 0b0111 (7)
      put "7" into tVer

      // Generate 12 bits of pseudo-random data for RAND A
      put random(4095) into tRandA -- 4095 is the maximum value for 12 bits
      put baseConvert(tRandA, 10, 16) into tRandA
      put format("%03s", tRandA) into tRandA

      // Set the variant field to 0b10
      put "8" into tTVar -- 0b10 in hexadecimal

      // Generate 62 bits of pseudo-random data for RAND B
      repeat 16 times
         put baseConvert(random(15), 10, 16) after tRandB -- generate one
hex digit at a time
      end repeat

      // Combine all the bits to form the UUID
      put tUnixTsMs & tVer & tRandA & tTVar & tRandB into tTheID

      // Insert dashes to form the UUID in 8-4-4-4-12 format
      put char 1 to 8 of tTheID & "-" & char 9 to 12 of tTheID & "-" & char
13 to 16 of tTheID & "-" & char 17 to 20 of tTheID & "-" & char 21 to 32 of
tTheID into tTheID

      return tTheID
   end if
end CreateUUID tVersion

Cheers,

Tom


More information about the use-livecode mailing list