Monday, July 5, 2010

UUID version 4 for Caché ObjectScript

I had to implement UUID Version 4 generator for Intersystems Caché database in ObjectScript, since I couldn't find anyone that already done it.
UUID's are good as primary keys
So, I've decided to be the first one to share it with the world. Enjoy.
30*16
/// http://en.wikipedia.org/wiki/Universally_Unique_Identifier#Version_4_.28random.29
ClassMethod GetUUID4() As %String
{
 //xxxxxxxx-xxxx-4xxx-Yxxx-xxxxxxxxxxxxxxxx
 Set tGroupLens=$LB(8,4,3,3,12)
 
 Set tGroups=""
 for tI=1:1:$LL(tGroupLens){
  // Group len
  Set tLen=$LG(tGroupLens,tI) 
  // Create number of that hex length
  Set tNumber=$Random($ZPower(16,tLen))
  // Make it hexadecimal
  Set tNumber=$ZConvert($ZHex(tNumber),"L")
  // Pad it with zeros
  Set tNumber=$Translate($Justify(tNumber,tLen)," ","0")
  // Add to list
  Set tGroups=tGroups_$LB(tNumber)
 }
 
 // Add version number (4) to group 3
 Set $List(tGroups,3)="4"_$List(tGroups,3)
 
 // Add 8,9,a or b to group 4 (as UUID version 4 required)
 Set tRnd=$Random(4)
 Set $List(tGroups,4)=$S(
  (tRnd=0):"8",
  (tRnd=1):"9",
  (tRnd=2):"a",
  (tRnd=3):"b",
  1:"b")_$List(tGroups,4)
  
 // Join with dashes
 Quit $LTS(tGroups,"-")
}

No comments:

Post a Comment