class UUIDTools::UUID

UUIDTools was designed to be a simple library for generating any of the various types of UUIDs. It conforms to RFC 4122 whenever possible.

@example

UUID.md5_create(UUID_DNS_NAMESPACE, "www.widgets.com")
# => #<UUID:0x287576 UUID:3d813cbb-47fb-32ba-91df-831e1593ac29>
UUID.sha1_create(UUID_DNS_NAMESPACE, "www.widgets.com")
# => #<UUID:0x2a0116 UUID:21f7f8de-8051-5b89-8680-0195ef798b6a>
UUID.timestamp_create
# => #<UUID:0x2adfdc UUID:64a5189c-25b3-11da-a97b-00c04fd430c8>
UUID.random_create
# => #<UUID:0x19013a UUID:984265dc-4200-4f02-ae70-fe4f48964159>

Attributes

ifconfig_command[RW]
ifconfig_path_default[RW]
ip_command[RW]
ip_path_default[RW]
clock_seq_hi_and_reserved[RW]

Returns the value of attribute `clock_seq_hi_and_reserved`

clock_seq_low[RW]

Returns the value of attribute `clock_seq_low`

nodes[RW]

Returns the value of attribute `nodes`

time_hi_and_version[RW]

Returns the value of attribute `time_hi_and_version`

time_low[RW]

Returns the value of attribute `time_low`

time_mid[RW]

Returns the value of attribute `time_mid`

Public Class Methods

convert_byte_string_to_int(byte_string) click to toggle source

@api private

    # File lib/uuidtools.rb
710 def self.convert_byte_string_to_int(byte_string)
711   if byte_string.respond_to?(:force_encoding)
712     byte_string.force_encoding(Encoding::ASCII_8BIT)
713   end
714   integer = 0
715   size = byte_string.size
716   for i in 0..(size - 1)
717     ordinal = (byte_string[i].respond_to?(:ord) ?
718       byte_string[i].ord : byte_string[i])
719     integer += (ordinal << (((size - 1) - i) * 8))
720   end
721   return integer
722 end
convert_int_to_byte_string(integer, size) click to toggle source

@api private

    # File lib/uuidtools.rb
697 def self.convert_int_to_byte_string(integer, size)
698   byte_string = ""
699   if byte_string.respond_to?(:force_encoding)
700     byte_string.force_encoding(Encoding::ASCII_8BIT)
701   end
702   for i in 0..(size - 1)
703     byte_string << ((integer >> (((size - 1) - i) * 8)) & 0xFF)
704   end
705   return byte_string
706 end
create_from_hash(hash_class, namespace, name) click to toggle source

Creates a new UUID from a SHA1 or MD5 hash

@api private

    # File lib/uuidtools.rb
672 def self.create_from_hash(hash_class, namespace, name)
673   if hash_class == Digest::MD5
674     version = 3
675   elsif hash_class == Digest::SHA1
676     version = 5
677   else
678     raise ArgumentError,
679       "Expected Digest::SHA1 or Digest::MD5, got #{hash_class.name}."
680   end
681   hash = hash_class.new
682   hash.update(namespace.raw)
683   hash.update(name)
684   hash_string = hash.to_s[0..31]
685   new_uuid = self.parse("#{hash_string[0..7]}-#{hash_string[8..11]}-" +
686     "#{hash_string[12..15]}-#{hash_string[16..19]}-#{hash_string[20..31]}")
687 
688   new_uuid.time_hi_and_version &= 0x0FFF
689   new_uuid.time_hi_and_version |= (version << 12)
690   new_uuid.clock_seq_hi_and_reserved &= 0x3F
691   new_uuid.clock_seq_hi_and_reserved |= 0x80
692   return new_uuid
693 end
first_mac(instring) click to toggle source

Match and return the first Mac address found

    # File lib/uuidtools.rb
591 def self.first_mac(instring)
592   mac_regexps = [
593     Regexp.new("address:? (#{(["[0-9a-fA-F]{2}"] * 6).join(":")})"),
594     Regexp.new("addr:? (#{(["[0-9a-fA-F]{2}"] * 6).join(":")})"),
595     Regexp.new("ether:? (#{(["[0-9a-fA-F]{1,2}"] * 6).join(":")})"),
596     Regexp.new("HWaddr:? (#{(["[0-9a-fA-F]{2}"] * 6).join(":")})"),
597     Regexp.new("link/ether? (#{(["[0-9a-fA-F]{2}"] * 6).join(":")})"),
598     Regexp.new("(#{(["[0-9a-fA-F]{2}"] * 6).join(":")})"),
599     Regexp.new("(#{(["[0-9a-fA-F]{2}"] * 6).join("-")})")
600   ]
601   parse_mac = lambda do |output|
602     (mac_regexps.map do |regexp|
603        result = output[regexp, 1]
604        result.downcase.gsub(/-/, ":") if result != nil
605     end).compact.first
606   end
607 
608   mac = parse_mac.call(instring)
609   if mac
610     # expand octets that were compressed (solaris)
611     return (mac.split(':').map do |octet|
612       (octet.length == 1 ? "0#{octet}" : octet)
613     end).join(':')
614   else
615     return nil
616   end
617 end
ifconfig(all=nil) click to toggle source

Call the ifconfig or ip command that is found

    # File lib/uuidtools.rb
575 def self.ifconfig(all=nil)
576   # find the path of the ifconfig command
577   ifconfig_path = UUID.ifconfig_path
578 
579   # if it does not exist, try the ip command
580   if ifconfig_path == nil
581     ifconfig_path = "#{UUID.ip_path} addr list"
582     # all makes no sense when using ip(1)
583     all = nil
584   end
585 
586   all_switch = all == nil ? "" : "-a"
587   return `#{ifconfig_path} #{all_switch}` if not ifconfig_path == nil
588 end
ifconfig_path() click to toggle source

Find the path of the ifconfig(8) command if it is present

    # File lib/uuidtools.rb
557 def self.ifconfig_path
558   path = `which #{UUID.ifconfig_command} 2>/dev/null`.strip
559   path = UUID.ifconfig_path_default if (path == "" && File.exist?(UUID.ifconfig_path_default))
560   return (path === "" ? nil : path)
561 end
ip_path() click to toggle source

Find the path of the ip(8) command if it is present

    # File lib/uuidtools.rb
566 def self.ip_path
567   path = `which #{UUID.ip_command} 2>/dev/null`.strip
568   path = UUID.ip_path_default if (path == "" && File.exist?(UUID.ip_path_default))
569   return (path === "" ? nil : path)
570 end
mac_address() click to toggle source

Returns the MAC address of the current computer's network card. Returns nil if a MAC address could not be found.

    # File lib/uuidtools.rb
622 def self.mac_address
623   if !defined?(@@mac_address)
624     require 'rbconfig'
625 
626     os_class = UUID.os_class
627 
628     if os_class == :windows
629       begin
630         @@mac_address = UUID.first_mac `ipconfig /all`
631       rescue
632       end
633     else # linux, bsd, macos, solaris
634       @@mac_address = UUID.first_mac(UUID.ifconfig(:all))
635     end
636 
637     if @@mac_address != nil
638       if @@mac_address.respond_to?(:to_str)
639         @@mac_address = @@mac_address.to_str
640       else
641         @@mac_address = @@mac_address.to_s
642       end
643       @@mac_address.downcase!
644       @@mac_address.strip!
645     end
646 
647     # Verify that the MAC address is in the right format.
648     # Nil it out if it isn't.
649     unless @@mac_address.respond_to?(:scan) &&
650         @@mac_address.scan(/#{(["[0-9a-f]{2}"] * 6).join(":")}/)
651       @@mac_address = nil
652     end
653   end
654   return @@mac_address
655 end
mac_address=(new_mac_address) click to toggle source

Allows users to set the MAC address manually in cases where the MAC address cannot be obtained programatically.

    # File lib/uuidtools.rb
660 def self.mac_address=(new_mac_address)
661   @@mac_address = new_mac_address
662 end
md5_create(namespace, name) click to toggle source

Creates a UUID using the MD5 hash. (Version 3)

    # File lib/uuidtools.rb
289 def self.md5_create(namespace, name)
290   return self.create_from_hash(Digest::MD5, namespace, name)
291 end
new(time_low, time_mid, time_hi_and_version, clock_seq_hi_and_reserved, clock_seq_low, nodes) click to toggle source

Creates a new UUID structure from its component values. @see UUID.md5_create @see UUID.sha1_create @see UUID.timestamp_create @see UUID.random_create @api private

    # File lib/uuidtools.rb
 80 def initialize(time_low, time_mid, time_hi_and_version,
 81     clock_seq_hi_and_reserved, clock_seq_low, nodes)
 82   unless time_low >= 0 && time_low < 4294967296
 83     raise ArgumentError,
 84       "Expected unsigned 32-bit number for time_low, got #{time_low}."
 85   end
 86   unless time_mid >= 0 && time_mid < 65536
 87     raise ArgumentError,
 88       "Expected unsigned 16-bit number for time_mid, got #{time_mid}."
 89   end
 90   unless time_hi_and_version >= 0 && time_hi_and_version < 65536
 91     raise ArgumentError,
 92       "Expected unsigned 16-bit number for time_hi_and_version, " +
 93       "got #{time_hi_and_version}."
 94   end
 95   unless clock_seq_hi_and_reserved >= 0 && clock_seq_hi_and_reserved < 256
 96     raise ArgumentError,
 97       "Expected unsigned 8-bit number for clock_seq_hi_and_reserved, " +
 98       "got #{clock_seq_hi_and_reserved}."
 99   end
100   unless clock_seq_low >= 0 && clock_seq_low < 256
101     raise ArgumentError,
102       "Expected unsigned 8-bit number for clock_seq_low, " +
103       "got #{clock_seq_low}."
104   end
105   unless nodes.kind_of?(Enumerable)
106     raise TypeError,
107       "Expected Enumerable, got #{nodes.class.name}."
108   end
109   unless nodes.size == 6
110     raise ArgumentError,
111       "Expected nodes to have size of 6."
112   end
113   for node in nodes
114     unless node >= 0 && node < 256
115       raise ArgumentError,
116         "Expected unsigned 8-bit number for each node, " +
117         "got #{node}."
118     end
119   end
120   @time_low = time_low
121   @time_mid = time_mid
122   @time_hi_and_version = time_hi_and_version
123   @clock_seq_hi_and_reserved = clock_seq_hi_and_reserved
124   @clock_seq_low = clock_seq_low
125   @nodes = nodes
126 end
os_class() click to toggle source

Determine what OS we're running on. Helps decide how to find the MAC

    # File lib/uuidtools.rb
527 def self.os_class
528   require 'rbconfig'
529   os_platform = RbConfig::CONFIG['target_os']
530   os_class = nil
531   if (os_platform =~ /win/i && !(os_platform =~ /darwin/i)) ||
532       os_platform =~ /w32/i
533     os_class = :windows
534   elsif os_platform =~ /solaris/i
535     os_class = :solaris
536   elsif os_platform =~ /netbsd/i
537     os_class = :netbsd
538   elsif os_platform =~ /openbsd/i
539     os_class = :openbsd
540   end
541 end
parse(uuid_string) click to toggle source

Parses a UUID from a string.

    # File lib/uuidtools.rb
154 def self.parse(uuid_string)
155   unless uuid_string.kind_of? String
156     raise TypeError,
157       "Expected String, got #{uuid_string.class.name} instead."
158   end
159   uuid_components = uuid_string.downcase.scan(UUIDTools::UUID_REGEXP).first
160   raise ArgumentError, "Invalid UUID format." if uuid_components.nil?
161   time_low = uuid_components[0].to_i(16)
162   time_mid = uuid_components[1].to_i(16)
163   time_hi_and_version = uuid_components[2].to_i(16)
164   clock_seq_hi_and_reserved = uuid_components[3].to_i(16)
165   clock_seq_low = uuid_components[4].to_i(16)
166   nodes = []
167   for i in 0..5
168     nodes << uuid_components[5][(i * 2)..(i * 2) + 1].to_i(16)
169   end
170   return self.new(time_low, time_mid, time_hi_and_version,
171     clock_seq_hi_and_reserved, clock_seq_low, nodes)
172 end
parse_hexdigest(uuid_hexdigest) click to toggle source

Parse a UUID from a hexdigest String.

    # File lib/uuidtools.rb
208 def self.parse_hexdigest(uuid_hexdigest)
209   unless uuid_hexdigest.kind_of?(String)
210     raise ArgumentError,
211       "Expected String, got #{uuid_hexdigest.class.name} instead."
212   end
213   return self.parse_int(uuid_hexdigest.to_i(16))
214 end
parse_int(uuid_int) click to toggle source

Parses a UUID from an Integer.

    # File lib/uuidtools.rb
198 def self.parse_int(uuid_int)
199   unless uuid_int.kind_of?(Integer)
200     raise ArgumentError,
201       "Expected Integer, got #{uuid_int.class.name} instead."
202   end
203   return self.parse_raw(self.convert_int_to_byte_string(uuid_int, 16))
204 end
parse_raw(raw_string) click to toggle source

Parses a UUID from a raw byte string.

    # File lib/uuidtools.rb
176 def self.parse_raw(raw_string)
177   unless raw_string.kind_of? String
178     raise TypeError,
179       "Expected String, got #{raw_string.class.name} instead."
180   end
181   integer = self.convert_byte_string_to_int(raw_string)
182 
183   time_low = (integer >> 96) & 0xFFFFFFFF
184   time_mid = (integer >> 80) & 0xFFFF
185   time_hi_and_version = (integer >> 64) & 0xFFFF
186   clock_seq_hi_and_reserved = (integer >> 56) & 0xFF
187   clock_seq_low = (integer >> 48) & 0xFF
188   nodes = []
189   for i in 0..5
190     nodes << ((integer >> (40 - (i * 8))) & 0xFF)
191   end
192   return self.new(time_low, time_mid, time_hi_and_version,
193     clock_seq_hi_and_reserved, clock_seq_low, nodes)
194 end
random_create() click to toggle source

Creates a UUID from a random value.

    # File lib/uuidtools.rb
218 def self.random_create()
219   new_uuid = self.parse_raw(SecureRandom.random_bytes(16))
220   new_uuid.time_hi_and_version &= 0x0FFF
221   new_uuid.time_hi_and_version |= (4 << 12)
222   new_uuid.clock_seq_hi_and_reserved &= 0x3F
223   new_uuid.clock_seq_hi_and_reserved |= 0x80
224   return new_uuid
225 end
sha1_create(namespace, name) click to toggle source

Creates a UUID using the SHA1 hash. (Version 5)

    # File lib/uuidtools.rb
295 def self.sha1_create(namespace, name)
296   return self.create_from_hash(Digest::SHA1, namespace, name)
297 end
timestamp_create(timestamp=nil) click to toggle source

Creates a UUID from a timestamp.

    # File lib/uuidtools.rb
229 def self.timestamp_create(timestamp=nil)
230   # We need a lock here to prevent two threads from ever
231   # getting the same timestamp.
232   @@mutex.synchronize do
233     # Always use GMT to generate UUIDs.
234     if timestamp.nil?
235       gmt_timestamp = Time.now.gmtime
236     else
237       gmt_timestamp = timestamp.gmtime
238     end
239     # Convert to 100 nanosecond blocks
240     gmt_timestamp_100_nanoseconds = (gmt_timestamp.tv_sec * 10000000) +
241       (gmt_timestamp.tv_usec * 10) + 0x01B21DD213814000
242     mac_address = self.mac_address
243     node_id = 0
244     if mac_address != nil
245       nodes = mac_address.split(":").collect do |octet|
246         octet.to_i(16)
247       end
248     else
249       nodes = SecureRandom.random_bytes(6).unpack("C*")
250       nodes[0] |= 0b00000001
251     end
252     for i in 0..5
253       node_id += (nodes[i] << (40 - (i * 8)))
254     end
255     clock_sequence = @@last_clock_sequence
256     if clock_sequence.nil?
257       clock_sequence = self.convert_byte_string_to_int(
258         SecureRandom.random_bytes(16)
259       )
260     end
261     if @@last_node_id != nil && @@last_node_id != node_id
262       # The node id has changed.  Change the clock id.
263       clock_sequence = self.convert_byte_string_to_int(
264         SecureRandom.random_bytes(16)
265       )
266     elsif @@last_timestamp != nil &&
267         gmt_timestamp_100_nanoseconds <= @@last_timestamp
268       clock_sequence = clock_sequence + 1
269     end
270     @@last_timestamp = gmt_timestamp_100_nanoseconds
271     @@last_node_id = node_id
272     @@last_clock_sequence = clock_sequence
273 
274     time_low = gmt_timestamp_100_nanoseconds & 0xFFFFFFFF
275     time_mid = ((gmt_timestamp_100_nanoseconds >> 32) & 0xFFFF)
276     time_hi_and_version = ((gmt_timestamp_100_nanoseconds >> 48) & 0x0FFF)
277     time_hi_and_version |= (1 << 12)
278     clock_seq_low = clock_sequence & 0xFF;
279     clock_seq_hi_and_reserved = (clock_sequence & 0x3F00) >> 8
280     clock_seq_hi_and_reserved |= 0x80
281 
282     return self.new(time_low, time_mid, time_hi_and_version,
283       clock_seq_hi_and_reserved, clock_seq_low, nodes)
284   end
285 end

Public Instance Methods

<=>(other_uuid) click to toggle source

Compares two UUIDs lexically

    # File lib/uuidtools.rb
395 def <=>(other_uuid)
396   return nil unless other_uuid.is_a?(UUIDTools::UUID)
397   check = self.time_low <=> other_uuid.time_low
398   return check if check != 0
399   check = self.time_mid <=> other_uuid.time_mid
400   return check if check != 0
401   check = self.time_hi_and_version <=> other_uuid.time_hi_and_version
402   return check if check != 0
403   check = self.clock_seq_hi_and_reserved <=>
404     other_uuid.clock_seq_hi_and_reserved
405   return check if check != 0
406   check = self.clock_seq_low <=> other_uuid.clock_seq_low
407   return check if check != 0
408   for i in 0..5
409     if (self.nodes[i] < other_uuid.nodes[i])
410       return -1
411     end
412     if (self.nodes[i] > other_uuid.nodes[i])
413       return 1
414     end
415   end
416   return 0
417 end
eql?(other) click to toggle source

Returns true if this UUID is exactly equal to the other UUID.

    # File lib/uuidtools.rb
520 def eql?(other)
521   return self == other
522 end
hash() click to toggle source

Returns an integer hash value.

    # File lib/uuidtools.rb
460 def hash
461   self.frozen? ? generate_hash : (@hash ||= generate_hash)
462 end
hexdigest() click to toggle source

Returns the hex digest of the UUID object.

    # File lib/uuidtools.rb
427 def hexdigest
428   (self.frozen? ?
429     generate_hexdigest : (@hexdigest ||= generate_hexdigest)
430   ).dup
431 end
inspect() click to toggle source

Returns a representation of the object's state

    # File lib/uuidtools.rb
421 def inspect
422   return "#<UUID:0x#{self.object_id.to_s(16)} UUID:#{self.to_s}>"
423 end
mac_address() click to toggle source

Returns the IEEE 802 address used to generate this UUID or nil if a MAC address was not used.

    # File lib/uuidtools.rb
372 def mac_address
373   return nil if self.version != 1
374   return nil if self.random_node_id?
375   return (self.nodes.collect do |node|
376     sprintf("%2.2x", node)
377   end).join(":")
378 end
nil_uuid?() click to toggle source

Returns true if this UUID is the nil UUID (00000000-0000-0000-0000-000000000000).

    # File lib/uuidtools.rb
314 def nil_uuid?
315   return false if self.time_low != 0
316   return false if self.time_mid != 0
317   return false if self.time_hi_and_version != 0
318   return false if self.clock_seq_hi_and_reserved != 0
319   return false if self.clock_seq_low != 0
320   self.nodes.each do |node|
321     return false if node != 0
322   end
323   return true
324 end
random_node_id?() click to toggle source

This method applies only to version 1 UUIDs. Checks if the node ID was generated from a random number or from an IEEE 802 address (MAC address). Always returns false for UUIDs that aren't version 1. This should not be confused with version 4 UUIDs where more than just the node id is random.

    # File lib/uuidtools.rb
306 def random_node_id?
307   return false if self.version != 1
308   return ((self.nodes.first & 0x01) == 1)
309 end
raw() click to toggle source

Returns the raw bytes that represent this UUID.

    # File lib/uuidtools.rb
435 def raw
436   (self.frozen? ? generate_raw : (@raw ||= generate_raw)).dup
437 end
timestamp() click to toggle source

Returns the timestamp used to generate this UUID

    # File lib/uuidtools.rb
382 def timestamp
383   return nil if self.version != 1
384   gmt_timestamp_100_nanoseconds = 0
385   gmt_timestamp_100_nanoseconds +=
386     ((self.time_hi_and_version  & 0x0FFF) << 48)
387   gmt_timestamp_100_nanoseconds += (self.time_mid << 32)
388   gmt_timestamp_100_nanoseconds += self.time_low
389   return Time.at(
390     (gmt_timestamp_100_nanoseconds - 0x01B21DD213814000) / 10000000.0)
391 end
to_i() click to toggle source

Returns an integer representation for this UUID.

    # File lib/uuidtools.rb
448 def to_i
449   self.frozen? ? generate_i : (@integer ||= generate_i)
450 end
to_s() click to toggle source

Returns a string representation for this UUID.

    # File lib/uuidtools.rb
441 def to_s
442   (self.frozen? ? generate_s : (@string ||= generate_s)).dup
443 end
Also aliased as: to_str
to_str()
Alias for: to_s
to_uri() click to toggle source

Returns a URI string for this UUID.

    # File lib/uuidtools.rb
454 def to_uri
455   return "urn:uuid:#{self.to_s}"
456 end
valid?() click to toggle source

Returns true if this UUID is valid.

    # File lib/uuidtools.rb
360 def valid?
361   if [0b000, 0b100, 0b110, 0b111].include?(self.variant) &&
362     (1..5).include?(self.version)
363     return true
364   else
365     return false
366   end
367 end
variant() click to toggle source

Returns the UUID variant. Possible values: 0b000 - Reserved, NCS backward compatibility. 0b100 - The variant specified in this document. 0b110 - Reserved, Microsoft Corporation backward compatibility. 0b111 - Reserved for future definition.

    # File lib/uuidtools.rb
345 def variant
346   variant_raw = (clock_seq_hi_and_reserved >> 5)
347   result = nil
348   if (variant_raw >> 2) == 0
349     result = 0x000
350   elsif (variant_raw >> 1) == 2
351     result = 0x100
352   else
353     result = variant_raw
354   end
355   return (result >> 6)
356 end
version() click to toggle source

Returns the UUID version type. Possible values: 1 - Time-based with unique or random host identifier 2 - DCE Security version (with POSIX UIDs) 3 - Name-based (MD5 hash) 4 - Random 5 - Name-based (SHA-1 hash)

    # File lib/uuidtools.rb
334 def version
335   return (time_hi_and_version >> 12)
336 end

Protected Instance Methods

generate_hash() click to toggle source

Generates an integer hash value.

@api private

    # File lib/uuidtools.rb
476 def generate_hash
477   return self.to_i % 0x3fffffff
478 end
generate_hexdigest() click to toggle source

Generates the hex digest of the UUID object.

@api private

    # File lib/uuidtools.rb
469 def generate_hexdigest
470   return self.to_i.to_s(16).rjust(32, "0")
471 end
generate_i() click to toggle source

Generates an integer representation for this UUID.

@api private

    # File lib/uuidtools.rb
484 def generate_i
485   return (begin
486     bytes = (time_low << 96) + (time_mid << 80) +
487       (time_hi_and_version << 64) + (clock_seq_hi_and_reserved << 56) +
488       (clock_seq_low << 48)
489     for i in 0..5
490       bytes += (nodes[i] << (40 - (i * 8)))
491     end
492     bytes
493   end)
494 end
generate_raw() click to toggle source

Generates the raw bytes that represent this UUID.

@api private

    # File lib/uuidtools.rb
513 def generate_raw
514   return self.class.convert_int_to_byte_string(self.to_i, 16)
515 end
generate_s() click to toggle source

Generates a string representation for this UUID.

@api private

    # File lib/uuidtools.rb
500 def generate_s
501   result = sprintf("%8.8x-%4.4x-%4.4x-%2.2x%2.2x-", @time_low, @time_mid,
502     @time_hi_and_version, @clock_seq_hi_and_reserved, @clock_seq_low);
503   for i in 0..5
504     result << sprintf("%2.2x", @nodes[i])
505   end
506   return result.downcase
507 end