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
Returns the value of attribute ‘clock_seq_hi_and_reserved`
Returns the value of attribute ‘clock_seq_low`
Returns the value of attribute ‘nodes`
Returns the value of attribute ‘time_hi_and_version`
Returns the value of attribute ‘time_low`
Returns the value of attribute ‘time_mid`
Public Class Methods
@api private
# File lib/uuidtools.rb 768 def self.convert_byte_string_to_int(byte_string) 769 if byte_string.respond_to?(:force_encoding) 770 byte_string.force_encoding(Encoding::ASCII_8BIT) 771 end 772 773 integer = 0 774 size = byte_string.size 775 if byte_string[0].respond_to? :ord 776 for i in 0...size 777 integer += (byte_string[i].ord << (((size - 1) - i) * 8)) 778 end 779 else 780 for i in 0...size 781 integer += (byte_string[i] << (((size - 1) - i) * 8)) 782 end 783 end 784 785 return integer 786 end
@api private
# File lib/uuidtools.rb 755 def self.convert_int_to_byte_string(integer, size) 756 byte_string = "" 757 if byte_string.respond_to?(:force_encoding) 758 byte_string.force_encoding(Encoding::ASCII_8BIT) 759 end 760 size.times do |i| 761 byte_string << ((integer >> (((size - 1) - i) * 8)) & 0xFF) 762 end 763 return byte_string 764 end
Creates a new UUID
from a SHA1 or MD5 hash
@api private
# File lib/uuidtools.rb 730 def self.create_from_hash(hash_class, namespace, name) 731 if hash_class == Digest::MD5 732 version = 3 733 elsif hash_class == Digest::SHA1 734 version = 5 735 else 736 raise ArgumentError, 737 "Expected Digest::SHA1 or Digest::MD5, got #{hash_class.name}." 738 end 739 hash = hash_class.new 740 hash.update(namespace.raw) 741 hash.update(name) 742 hash_string = hash.to_s[0..31] 743 new_uuid = self.parse("#{hash_string[0..7]}-#{hash_string[8..11]}-" + 744 "#{hash_string[12..15]}-#{hash_string[16..19]}-#{hash_string[20..31]}") 745 746 new_uuid.time_hi_and_version &= 0x0FFF 747 new_uuid.time_hi_and_version |= (version << 12) 748 new_uuid.clock_seq_hi_and_reserved &= 0x3F 749 new_uuid.clock_seq_hi_and_reserved |= 0x80 750 return new_uuid 751 end
Match and return the first Mac address found
# File lib/uuidtools.rb 649 def self.first_mac(instring) 650 mac_regexps = [ 651 Regexp.new("address:? (#{(["[0-9a-fA-F]{2}"] * 6).join(":")})"), 652 Regexp.new("addr:? (#{(["[0-9a-fA-F]{2}"] * 6).join(":")})"), 653 Regexp.new("ether:? (#{(["[0-9a-fA-F]{1,2}"] * 6).join(":")})"), 654 Regexp.new("HWaddr:? (#{(["[0-9a-fA-F]{2}"] * 6).join(":")})"), 655 Regexp.new("link/ether? (#{(["[0-9a-fA-F]{2}"] * 6).join(":")})"), 656 Regexp.new("(#{(["[0-9a-fA-F]{2}"] * 6).join(":")})"), 657 Regexp.new("(#{(["[0-9a-fA-F]{2}"] * 6).join("-")})") 658 ] 659 parse_mac = lambda do |output| 660 (mac_regexps.map do |regexp| 661 result = output[regexp, 1] 662 result.downcase.gsub(/-/, ":") if result != nil 663 end).compact.first 664 end 665 666 mac = parse_mac.call(instring) 667 if mac 668 # expand octets that were compressed (solaris) 669 return (mac.split(':').map do |octet| 670 (octet.length == 1 ? "0#{octet}" : octet) 671 end).join(':') 672 else 673 return nil 674 end 675 end
Call the ifconfig or ip command that is found
# File lib/uuidtools.rb 633 def self.ifconfig(all=nil) 634 # find the path of the ifconfig command 635 ifconfig_path = UUID.ifconfig_path 636 637 # if it does not exist, try the ip command 638 if ifconfig_path == nil 639 ifconfig_path = "#{UUID.ip_path} addr list" 640 # all makes no sense when using ip(1) 641 all = nil 642 end 643 644 all_switch = all == nil ? "" : "-a" 645 return `#{ifconfig_path} #{all_switch}` if not ifconfig_path == nil 646 end
Find the path of the ifconfig(8) command if it is present
# File lib/uuidtools.rb 615 def self.ifconfig_path 616 path = `which #{UUID.ifconfig_command} 2>/dev/null`.strip 617 path = UUID.ifconfig_path_default if (path == "" && File.exist?(UUID.ifconfig_path_default)) 618 return (path === "" ? nil : path) 619 end
Find the path of the ip(8) command if it is present
# File lib/uuidtools.rb 624 def self.ip_path 625 path = `which #{UUID.ip_command} 2>/dev/null`.strip 626 path = UUID.ip_path_default if (path == "" && File.exist?(UUID.ip_path_default)) 627 return (path === "" ? nil : path) 628 end
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 680 def self.mac_address 681 if !defined?(@@mac_address) 682 require 'rbconfig' 683 684 os_class = UUID.os_class 685 686 if os_class == :windows 687 begin 688 @@mac_address = UUID.first_mac `ipconfig /all` 689 rescue 690 end 691 else # linux, bsd, macos, solaris 692 @@mac_address = UUID.first_mac(UUID.ifconfig(:all)) 693 end 694 695 if @@mac_address != nil 696 if @@mac_address.respond_to?(:to_str) 697 @@mac_address = @@mac_address.to_str 698 else 699 @@mac_address = @@mac_address.to_s 700 end 701 @@mac_address.downcase! 702 @@mac_address.strip! 703 end 704 705 # Verify that the MAC address is in the right format. 706 # Nil it out if it isn't. 707 unless @@mac_address.respond_to?(:scan) && 708 @@mac_address.scan(/#{(["[0-9a-f]{2}"] * 6).join(":")}/) 709 @@mac_address = nil 710 end 711 end 712 return @@mac_address 713 end
Allows users to set the MAC address manually in cases where the MAC address cannot be obtained programatically.
# File lib/uuidtools.rb 718 def self.mac_address=(new_mac_address) 719 @@mac_address = new_mac_address 720 end
Creates a UUID
using the MD5 hash. (Version 3)
# File lib/uuidtools.rb 347 def self.md5_create(namespace, name) 348 return self.create_from_hash(Digest::MD5, namespace, name) 349 end
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
Determine what OS we’re running on. Helps decide how to find the MAC
# File lib/uuidtools.rb 585 def self.os_class 586 require 'rbconfig' 587 os_platform = RbConfig::CONFIG['target_os'] 588 os_class = nil 589 if (os_platform =~ /win/i && !(os_platform =~ /darwin/i)) || 590 os_platform =~ /w32/i 591 os_class = :windows 592 elsif os_platform =~ /solaris/i 593 os_class = :solaris 594 elsif os_platform =~ /netbsd/i 595 os_class = :netbsd 596 elsif os_platform =~ /openbsd/i 597 os_class = :openbsd 598 end 599 end
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 6.times do |i| 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 a UUID
from a hexdigest String.
# File lib/uuidtools.rb 253 def self.parse_hexdigest(uuid_hex) 254 unless uuid_hex.kind_of?(String) 255 raise ArgumentError, 256 "Expected String, got #{uuid_hex.class.name} instead." 257 end 258 259 time_low = uuid_hex[0...8].to_i(16) 260 time_mid = uuid_hex[8...12].to_i(16) 261 time_hi_and_version = uuid_hex[12...16].to_i(16) 262 clock_seq_hi_and_reserved = uuid_hex[16...18].to_i(16) 263 clock_seq_low = uuid_hex[18...20].to_i(16) 264 nodes_string = uuid_hex[20...32] 265 nodes = [] 266 for i in 0..5 267 nodes << nodes_string[(i * 2)..(i * 2) + 1].to_i(16) 268 end 269 270 return self.new(time_low, time_mid, time_hi_and_version, 271 clock_seq_hi_and_reserved, clock_seq_low, nodes) 272 end
Parses a UUID
from an Integer.
# File lib/uuidtools.rb 231 def self.parse_int(uuid_int) 232 unless uuid_int.kind_of?(Integer) 233 raise ArgumentError, 234 "Expected Integer, got #{uuid_int.class.name} instead." 235 end 236 237 time_low = (uuid_int >> 96) & 0xFFFFFFFF 238 time_mid = (uuid_int >> 80) & 0xFFFF 239 time_hi_and_version = (uuid_int >> 64) & 0xFFFF 240 clock_seq_hi_and_reserved = (uuid_int >> 56) & 0xFF 241 clock_seq_low = (uuid_int >> 48) & 0xFF 242 nodes = [] 243 for i in 0..5 244 nodes << ((uuid_int >> (40 - (i * 8))) & 0xFF) 245 end 246 247 return self.new(time_low, time_mid, time_hi_and_version, 248 clock_seq_hi_and_reserved, clock_seq_low, nodes) 249 end
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 182 if raw_string.respond_to?(:force_encoding) 183 raw_string.force_encoding(Encoding::ASCII_8BIT) 184 end 185 186 raw_length = raw_string.length 187 if raw_length < 16 188 # Option A: Enforce raw_string be 16 characters (More strict) 189 #raise ArgumentError, 190 # "Expected 16 bytes, got #{raw_string.length} instead." 191 192 # Option B: Pad raw_string to 16 characters (Compatible with existing behavior) 193 raw_string = raw_string.rjust(16, "\0") 194 elsif raw_length > 16 195 # NOTE: As per "Option B" above, existing behavior would use the lower 196 # 128-bits of an overly long raw_string instead of using the upper 128-bits. 197 start_index = raw_length - 16 198 raw_string = raw_string[start_index...raw_length] 199 end 200 201 raw_bytes = [] 202 if raw_string[0].respond_to? :ord 203 for i in 0...raw_string.size 204 raw_bytes << raw_string[i].ord 205 end 206 else 207 raw_bytes = raw_string 208 end 209 210 time_low = ((raw_bytes[0] << 24) + 211 (raw_bytes[1] << 16) + 212 (raw_bytes[2] << 8) + 213 raw_bytes[3]) 214 time_mid = ((raw_bytes[4] << 8) + 215 raw_bytes[5]) 216 time_hi_and_version = ((raw_bytes[6] << 8) + 217 raw_bytes[7]) 218 clock_seq_hi_and_reserved = raw_bytes[8] 219 clock_seq_low = raw_bytes[9] 220 nodes = [] 221 for i in 10...16 222 nodes << raw_bytes[i] 223 end 224 225 return self.new(time_low, time_mid, time_hi_and_version, 226 clock_seq_hi_and_reserved, clock_seq_low, nodes) 227 end
Creates a UUID
from a random value.
# File lib/uuidtools.rb 276 def self.random_create() 277 new_uuid = self.parse_raw(SecureRandom.random_bytes(16)) 278 new_uuid.time_hi_and_version &= 0x0FFF 279 new_uuid.time_hi_and_version |= (4 << 12) 280 new_uuid.clock_seq_hi_and_reserved &= 0x3F 281 new_uuid.clock_seq_hi_and_reserved |= 0x80 282 return new_uuid 283 end
Creates a UUID
using the SHA1 hash. (Version 5)
# File lib/uuidtools.rb 353 def self.sha1_create(namespace, name) 354 return self.create_from_hash(Digest::SHA1, namespace, name) 355 end
Creates a UUID
from a timestamp.
# File lib/uuidtools.rb 287 def self.timestamp_create(timestamp=nil) 288 # We need a lock here to prevent two threads from ever 289 # getting the same timestamp. 290 @@mutex.synchronize do 291 # Always use GMT to generate UUIDs. 292 if timestamp.nil? 293 gmt_timestamp = Time.now.gmtime 294 else 295 gmt_timestamp = timestamp.gmtime 296 end 297 # Convert to 100 nanosecond blocks 298 gmt_timestamp_100_nanoseconds = (gmt_timestamp.tv_sec * 10000000) + 299 (gmt_timestamp.tv_usec * 10) + 0x01B21DD213814000 300 mac_address = self.mac_address 301 node_id = 0 302 if mac_address != nil 303 nodes = mac_address.split(":").collect do |octet| 304 octet.to_i(16) 305 end 306 else 307 nodes = SecureRandom.random_bytes(6).unpack("C*") 308 nodes[0] |= 0b00000001 309 end 310 6.times do |i| 311 node_id += (nodes[i] << (40 - (i * 8))) 312 end 313 clock_sequence = @@last_clock_sequence 314 if clock_sequence.nil? 315 clock_sequence = self.convert_byte_string_to_int( 316 SecureRandom.random_bytes(16) 317 ) 318 end 319 if @@last_node_id != nil && @@last_node_id != node_id 320 # The node id has changed. Change the clock id. 321 clock_sequence = self.convert_byte_string_to_int( 322 SecureRandom.random_bytes(16) 323 ) 324 elsif @@last_timestamp != nil && 325 gmt_timestamp_100_nanoseconds <= @@last_timestamp 326 clock_sequence = clock_sequence + 1 327 end 328 @@last_timestamp = gmt_timestamp_100_nanoseconds 329 @@last_node_id = node_id 330 @@last_clock_sequence = clock_sequence 331 332 time_low = gmt_timestamp_100_nanoseconds & 0xFFFFFFFF 333 time_mid = ((gmt_timestamp_100_nanoseconds >> 32) & 0xFFFF) 334 time_hi_and_version = ((gmt_timestamp_100_nanoseconds >> 48) & 0x0FFF) 335 time_hi_and_version |= (1 << 12) 336 clock_seq_low = clock_sequence & 0xFF; 337 clock_seq_hi_and_reserved = (clock_sequence & 0x3F00) >> 8 338 clock_seq_hi_and_reserved |= 0x80 339 340 return self.new(time_low, time_mid, time_hi_and_version, 341 clock_seq_hi_and_reserved, clock_seq_low, nodes) 342 end 343 end
Public Instance Methods
Compares two UUIDs lexically
# File lib/uuidtools.rb 453 def <=>(other_uuid) 454 return nil unless other_uuid.is_a?(UUIDTools::UUID) 455 check = self.time_low <=> other_uuid.time_low 456 return check if check != 0 457 check = self.time_mid <=> other_uuid.time_mid 458 return check if check != 0 459 check = self.time_hi_and_version <=> other_uuid.time_hi_and_version 460 return check if check != 0 461 check = self.clock_seq_hi_and_reserved <=> 462 other_uuid.clock_seq_hi_and_reserved 463 return check if check != 0 464 check = self.clock_seq_low <=> other_uuid.clock_seq_low 465 return check if check != 0 466 6.times do |i| 467 if (self.nodes[i] < other_uuid.nodes[i]) 468 return -1 469 end 470 if (self.nodes[i] > other_uuid.nodes[i]) 471 return 1 472 end 473 end 474 return 0 475 end
Returns an integer hash value.
# File lib/uuidtools.rb 518 def hash 519 self.frozen? ? generate_hash : (@hash ||= generate_hash) 520 end
Returns the hex digest of the UUID
object.
# File lib/uuidtools.rb 485 def hexdigest 486 (self.frozen? ? 487 generate_hexdigest : (@hexdigest ||= generate_hexdigest) 488 ).dup 489 end
Returns a representation of the object’s state
# File lib/uuidtools.rb 479 def inspect 480 return "#<UUID:0x#{self.object_id.to_s(16)} UUID:#{self.to_s}>" 481 end
Returns the IEEE 802 address used to generate this UUID
or nil if a MAC address was not used.
# File lib/uuidtools.rb 430 def mac_address 431 return nil if self.version != 1 432 return nil if self.random_node_id? 433 return (self.nodes.collect do |node| 434 sprintf("%2.2x", node) 435 end).join(":") 436 end
Returns true if this UUID
is the nil UUID
(00000000-0000-0000-0000-000000000000).
# File lib/uuidtools.rb 372 def nil_uuid? 373 return false if self.time_low != 0 374 return false if self.time_mid != 0 375 return false if self.time_hi_and_version != 0 376 return false if self.clock_seq_hi_and_reserved != 0 377 return false if self.clock_seq_low != 0 378 self.nodes.each do |node| 379 return false if node != 0 380 end 381 return true 382 end
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 364 def random_node_id? 365 return false if self.version != 1 366 return ((self.nodes.first & 0x01) == 1) 367 end
Returns the raw bytes that represent this UUID
.
# File lib/uuidtools.rb 493 def raw 494 (self.frozen? ? generate_raw : (@raw ||= generate_raw)).dup 495 end
Returns the timestamp used to generate this UUID
# File lib/uuidtools.rb 440 def timestamp 441 return nil if self.version != 1 442 gmt_timestamp_100_nanoseconds = 0 443 gmt_timestamp_100_nanoseconds += 444 ((self.time_hi_and_version & 0x0FFF) << 48) 445 gmt_timestamp_100_nanoseconds += (self.time_mid << 32) 446 gmt_timestamp_100_nanoseconds += self.time_low 447 return Time.at( 448 (gmt_timestamp_100_nanoseconds - 0x01B21DD213814000) / 10000000.0) 449 end
Returns an integer representation for this UUID
.
# File lib/uuidtools.rb 506 def to_i 507 self.frozen? ? generate_i : (@integer ||= generate_i) 508 end
Returns a string representation for this UUID
.
# File lib/uuidtools.rb 499 def to_s 500 (self.frozen? ? generate_s : (@string ||= generate_s)).dup 501 end
Returns a URI string for this UUID
.
# File lib/uuidtools.rb 512 def to_uri 513 return "urn:uuid:#{self.to_s}" 514 end
Returns true if this UUID
is valid.
# File lib/uuidtools.rb 418 def valid? 419 if [0b000, 0b100, 0b110, 0b111].include?(self.variant) && 420 (1..5).include?(self.version) 421 return true 422 else 423 return false 424 end 425 end
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 403 def variant 404 variant_raw = (clock_seq_hi_and_reserved >> 5) 405 result = nil 406 if (variant_raw >> 2) == 0 407 result = 0x000 408 elsif (variant_raw >> 1) == 2 409 result = 0x100 410 else 411 result = variant_raw 412 end 413 return (result >> 6) 414 end
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 392 def version 393 return (time_hi_and_version >> 12) 394 end
Protected Instance Methods
Generates an integer hash value.
@api private
# File lib/uuidtools.rb 534 def generate_hash 535 return self.to_i % 0x3fffffff 536 end
Generates the hex digest of the UUID
object.
@api private
# File lib/uuidtools.rb 527 def generate_hexdigest 528 return self.to_i.to_s(16).rjust(32, "0") 529 end
Generates an integer representation for this UUID
.
@api private
# File lib/uuidtools.rb 542 def generate_i 543 return (begin 544 bytes = (time_low << 96) + (time_mid << 80) + 545 (time_hi_and_version << 64) + (clock_seq_hi_and_reserved << 56) + 546 (clock_seq_low << 48) 547 6.times do |i| 548 bytes += (nodes[i] << (40 - (i * 8))) 549 end 550 bytes 551 end) 552 end
Generates the raw bytes that represent this UUID
.
@api private
# File lib/uuidtools.rb 571 def generate_raw 572 return self.class.convert_int_to_byte_string(self.to_i, 16) 573 end
Generates a string representation for this UUID
.
@api private
# File lib/uuidtools.rb 558 def generate_s 559 result = sprintf("%8.8x-%4.4x-%4.4x-%2.2x%2.2x-", @time_low, @time_mid, 560 @time_hi_and_version, @clock_seq_hi_and_reserved, @clock_seq_low); 561 6.times do |i| 562 result << sprintf("%2.2x", @nodes[i]) 563 end 564 return result.downcase 565 end