Class: UUIDTools::UUID

Inherits:
Object
  • Object
show all
Includes:
Comparable
Defined in:
lib/uuidtools.rb

Overview

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

Examples:

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>

Constant Summary collapse

@@last_timestamp =

This classvariable is part of a private API. You should avoid using this classvariable if possible, as it may be removed or be changed in the future.

nil
@@last_node_id =

This classvariable is part of a private API. You should avoid using this classvariable if possible, as it may be removed or be changed in the future.

nil
@@last_clock_sequence =

This classvariable is part of a private API. You should avoid using this classvariable if possible, as it may be removed or be changed in the future.

nil
@@state_file =

This classvariable is part of a private API. You should avoid using this classvariable if possible, as it may be removed or be changed in the future.

nil
@@mutex =

This classvariable is part of a private API. You should avoid using this classvariable if possible, as it may be removed or be changed in the future.

Mutex.new

Class Attribute Summary collapse

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(time_low, time_mid, time_hi_and_version, clock_seq_hi_and_reserved, clock_seq_low, nodes) ⇒ UUID

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

Creates a new UUID structure from its component values.



80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
# File 'lib/uuidtools.rb', line 80

def initialize(time_low, time_mid, time_hi_and_version,
    clock_seq_hi_and_reserved, clock_seq_low, nodes)
  unless time_low >= 0 && time_low < 4294967296
    raise ArgumentError,
      "Expected unsigned 32-bit number for time_low, got #{time_low}."
  end
  unless time_mid >= 0 && time_mid < 65536
    raise ArgumentError,
      "Expected unsigned 16-bit number for time_mid, got #{time_mid}."
  end
  unless time_hi_and_version >= 0 && time_hi_and_version < 65536
    raise ArgumentError,
      "Expected unsigned 16-bit number for time_hi_and_version, " +
      "got #{time_hi_and_version}."
  end
  unless clock_seq_hi_and_reserved >= 0 && clock_seq_hi_and_reserved < 256
    raise ArgumentError,
      "Expected unsigned 8-bit number for clock_seq_hi_and_reserved, " +
      "got #{clock_seq_hi_and_reserved}."
  end
  unless clock_seq_low >= 0 && clock_seq_low < 256
    raise ArgumentError,
      "Expected unsigned 8-bit number for clock_seq_low, " +
      "got #{clock_seq_low}."
  end
  unless nodes.kind_of?(Enumerable)
    raise TypeError,
      "Expected Enumerable, got #{nodes.class.name}."
  end
  unless nodes.size == 6
    raise ArgumentError,
      "Expected nodes to have size of 6."
  end
  for node in nodes
    unless node >= 0 && node < 256
      raise ArgumentError,
        "Expected unsigned 8-bit number for each node, " +
        "got #{node}."
    end
  end
  @time_low = time_low
  @time_mid = time_mid
  @time_hi_and_version = time_hi_and_version
  @clock_seq_hi_and_reserved = clock_seq_hi_and_reserved
  @clock_seq_low = clock_seq_low
  @nodes = nodes
end

Class Attribute Details

.ifconfig_commandObject

Returns the value of attribute ifconfig_command.



608
609
610
# File 'lib/uuidtools.rb', line 608

def ifconfig_command
  @ifconfig_command
end

.ifconfig_path_defaultObject

Returns the value of attribute ifconfig_path_default.



608
609
610
# File 'lib/uuidtools.rb', line 608

def ifconfig_path_default
  @ifconfig_path_default
end

.ip_commandObject

Returns the value of attribute ip_command.



609
610
611
# File 'lib/uuidtools.rb', line 609

def ip_command
  @ip_command
end

.ip_path_defaultObject

Returns the value of attribute ip_path_default.



609
610
611
# File 'lib/uuidtools.rb', line 609

def ip_path_default
  @ip_path_default
end

Instance Attribute Details

#clock_seq_hi_and_reservedObject

Returns the value of attribute ‘clock_seq_hi_and_reserved`



142
143
144
# File 'lib/uuidtools.rb', line 142

def clock_seq_hi_and_reserved
  @clock_seq_hi_and_reserved
end

#clock_seq_lowObject

Returns the value of attribute ‘clock_seq_low`



146
147
148
# File 'lib/uuidtools.rb', line 146

def clock_seq_low
  @clock_seq_low
end

#nodesObject

Returns the value of attribute ‘nodes`



150
151
152
# File 'lib/uuidtools.rb', line 150

def nodes
  @nodes
end

#time_hi_and_versionObject

Returns the value of attribute ‘time_hi_and_version`



138
139
140
# File 'lib/uuidtools.rb', line 138

def time_hi_and_version
  @time_hi_and_version
end

#time_lowObject

Returns the value of attribute ‘time_low`



130
131
132
# File 'lib/uuidtools.rb', line 130

def time_low
  @time_low
end

#time_midObject

Returns the value of attribute ‘time_mid`



134
135
136
# File 'lib/uuidtools.rb', line 134

def time_mid
  @time_mid
end

Class Method Details

.convert_byte_string_to_int(byte_string) ⇒ Object

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.



768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
# File 'lib/uuidtools.rb', line 768

def self.convert_byte_string_to_int(byte_string)
  if byte_string.respond_to?(:force_encoding)
    byte_string.force_encoding(Encoding::ASCII_8BIT)
  end

  integer = 0
  size = byte_string.size
  if byte_string[0].respond_to? :ord
    for i in 0...size
      integer += (byte_string[i].ord << (((size - 1) - i) * 8))
    end
  else
    for i in 0...size
      integer += (byte_string[i] << (((size - 1) - i) * 8))
    end
  end
  
  return integer
end

.convert_int_to_byte_string(integer, size) ⇒ Object

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.



755
756
757
758
759
760
761
762
763
764
# File 'lib/uuidtools.rb', line 755

def self.convert_int_to_byte_string(integer, size)
  byte_string = ""
  if byte_string.respond_to?(:force_encoding)
    byte_string.force_encoding(Encoding::ASCII_8BIT)
  end
  size.times do |i|
    byte_string << ((integer >> (((size - 1) - i) * 8)) & 0xFF)
  end
  return byte_string
end

.create_from_hash(hash_class, namespace, name) ⇒ Object

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

Creates a new UUID from a SHA1 or MD5 hash



730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
# File 'lib/uuidtools.rb', line 730

def self.create_from_hash(hash_class, namespace, name)
  if hash_class == Digest::MD5
    version = 3
  elsif hash_class == Digest::SHA1
    version = 5
  else
    raise ArgumentError,
      "Expected Digest::SHA1 or Digest::MD5, got #{hash_class.name}."
  end
  hash = hash_class.new
  hash.update(namespace.raw)
  hash.update(name)
  hash_string = hash.to_s[0..31]
  new_uuid = self.parse("#{hash_string[0..7]}-#{hash_string[8..11]}-" +
    "#{hash_string[12..15]}-#{hash_string[16..19]}-#{hash_string[20..31]}")

  new_uuid.time_hi_and_version &= 0x0FFF
  new_uuid.time_hi_and_version |= (version << 12)
  new_uuid.clock_seq_hi_and_reserved &= 0x3F
  new_uuid.clock_seq_hi_and_reserved |= 0x80
  return new_uuid
end

.first_mac(instring) ⇒ Object

Match and return the first Mac address found



649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
# File 'lib/uuidtools.rb', line 649

def self.first_mac(instring)
  mac_regexps = [
    Regexp.new("address:? (#{(["[0-9a-fA-F]{2}"] * 6).join(":")})"),
    Regexp.new("addr:? (#{(["[0-9a-fA-F]{2}"] * 6).join(":")})"),
    Regexp.new("ether:? (#{(["[0-9a-fA-F]{1,2}"] * 6).join(":")})"),
    Regexp.new("HWaddr:? (#{(["[0-9a-fA-F]{2}"] * 6).join(":")})"),
    Regexp.new("link/ether? (#{(["[0-9a-fA-F]{2}"] * 6).join(":")})"),
    Regexp.new("(#{(["[0-9a-fA-F]{2}"] * 6).join(":")})"),
    Regexp.new("(#{(["[0-9a-fA-F]{2}"] * 6).join("-")})")
  ]
  parse_mac = lambda do |output|
    (mac_regexps.map do |regexp|
       result = output[regexp, 1]
       result.downcase.gsub(/-/, ":") if result != nil
    end).compact.first
  end

  mac = parse_mac.call(instring)
  if mac
    # expand octets that were compressed (solaris)
    return (mac.split(':').map do |octet|
      (octet.length == 1 ? "0#{octet}" : octet)
    end).join(':')
  else
    return nil
  end
end

.ifconfig(all = nil) ⇒ Object

Call the ifconfig or ip command that is found



633
634
635
636
637
638
639
640
641
642
643
644
645
646
# File 'lib/uuidtools.rb', line 633

def self.ifconfig(all=nil)
  # find the path of the ifconfig command
  ifconfig_path = UUID.ifconfig_path

  # if it does not exist, try the ip command
  if ifconfig_path == nil
    ifconfig_path = "#{UUID.ip_path} addr list"
    # all makes no sense when using ip(1)
    all = nil
  end

  all_switch = all == nil ? "" : "-a"
  return `#{ifconfig_path} #{all_switch}` if not ifconfig_path == nil
end

.ifconfig_pathObject

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



615
616
617
618
619
# File 'lib/uuidtools.rb', line 615

def self.ifconfig_path
  path = `which #{UUID.ifconfig_command} 2>/dev/null`.strip
  path = UUID.ifconfig_path_default if (path == "" && File.exist?(UUID.ifconfig_path_default))
  return (path === "" ? nil : path)
end

.ip_pathObject

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



624
625
626
627
628
# File 'lib/uuidtools.rb', line 624

def self.ip_path
  path = `which #{UUID.ip_command} 2>/dev/null`.strip
  path = UUID.ip_path_default if (path == "" && File.exist?(UUID.ip_path_default))
  return (path === "" ? nil : path)
end

.mac_addressObject

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



680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
# File 'lib/uuidtools.rb', line 680

def self.mac_address
  if !defined?(@@mac_address)
    require 'rbconfig'

    os_class = UUID.os_class

    if os_class == :windows
      begin
        @@mac_address = UUID.first_mac `ipconfig /all`
      rescue
      end
    else # linux, bsd, macos, solaris
      @@mac_address = UUID.first_mac(UUID.ifconfig(:all))
    end

    if @@mac_address != nil
      if @@mac_address.respond_to?(:to_str)
        @@mac_address = @@mac_address.to_str
      else
        @@mac_address = @@mac_address.to_s
      end
      @@mac_address.downcase!
      @@mac_address.strip!
    end

    # Verify that the MAC address is in the right format.
    # Nil it out if it isn't.
    unless @@mac_address.respond_to?(:scan) &&
        @@mac_address.scan(/#{(["[0-9a-f]{2}"] * 6).join(":")}/)
      @@mac_address = nil
    end
  end
  return @@mac_address
end

.mac_address=(new_mac_address) ⇒ Object

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



718
719
720
# File 'lib/uuidtools.rb', line 718

def self.mac_address=(new_mac_address)
  @@mac_address = new_mac_address
end

.md5_create(namespace, name) ⇒ Object

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



347
348
349
# File 'lib/uuidtools.rb', line 347

def self.md5_create(namespace, name)
  return self.create_from_hash(Digest::MD5, namespace, name)
end

.os_classObject

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



585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
# File 'lib/uuidtools.rb', line 585

def self.os_class
  require 'rbconfig'
  os_platform = RbConfig::CONFIG['target_os']
  os_class = nil
  if (os_platform =~ /win/i && !(os_platform =~ /darwin/i)) ||
      os_platform =~ /w32/i
    os_class = :windows
  elsif os_platform =~ /solaris/i
    os_class = :solaris
  elsif os_platform =~ /netbsd/i
    os_class = :netbsd
  elsif os_platform =~ /openbsd/i
    os_class = :openbsd
  end
end

.parse(uuid_string) ⇒ Object

Parses a UUID from a string.

Raises:

  • (ArgumentError)


154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
# File 'lib/uuidtools.rb', line 154

def self.parse(uuid_string)
  unless uuid_string.kind_of? String
    raise TypeError,
      "Expected String, got #{uuid_string.class.name} instead."
  end
  uuid_components = uuid_string.downcase.scan(UUIDTools::UUID_REGEXP).first
  raise ArgumentError, "Invalid UUID format." if uuid_components.nil?
  time_low = uuid_components[0].to_i(16)
  time_mid = uuid_components[1].to_i(16)
  time_hi_and_version = uuid_components[2].to_i(16)
  clock_seq_hi_and_reserved = uuid_components[3].to_i(16)
  clock_seq_low = uuid_components[4].to_i(16)
  nodes = []
  6.times do |i|
    nodes << uuid_components[5][(i * 2)..(i * 2) + 1].to_i(16)
  end
  return self.new(time_low, time_mid, time_hi_and_version,
    clock_seq_hi_and_reserved, clock_seq_low, nodes)
end

.parse_hexdigest(uuid_hex) ⇒ Object

Parse a UUID from a hexdigest String.



253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
# File 'lib/uuidtools.rb', line 253

def self.parse_hexdigest(uuid_hex)
  unless uuid_hex.kind_of?(String)
    raise ArgumentError,
      "Expected String, got #{uuid_hex.class.name} instead."
  end

  time_low = uuid_hex[0...8].to_i(16)
  time_mid = uuid_hex[8...12].to_i(16)
  time_hi_and_version = uuid_hex[12...16].to_i(16)
  clock_seq_hi_and_reserved = uuid_hex[16...18].to_i(16)
  clock_seq_low = uuid_hex[18...20].to_i(16)
  nodes_string = uuid_hex[20...32]
  nodes = []
  for i in 0..5
    nodes << nodes_string[(i * 2)..(i * 2) + 1].to_i(16)
  end

  return self.new(time_low, time_mid, time_hi_and_version,
                  clock_seq_hi_and_reserved, clock_seq_low, nodes)
end

.parse_int(uuid_int) ⇒ Object

Parses a UUID from an Integer.



231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
# File 'lib/uuidtools.rb', line 231

def self.parse_int(uuid_int)
  unless uuid_int.kind_of?(Integer)
    raise ArgumentError,
      "Expected Integer, got #{uuid_int.class.name} instead."
  end

  time_low = (uuid_int >> 96) & 0xFFFFFFFF
  time_mid = (uuid_int >> 80) & 0xFFFF
  time_hi_and_version = (uuid_int >> 64) & 0xFFFF
  clock_seq_hi_and_reserved = (uuid_int >> 56) & 0xFF
  clock_seq_low = (uuid_int >> 48) & 0xFF
  nodes = []
  for i in 0..5
    nodes << ((uuid_int >> (40 - (i * 8))) & 0xFF)
  end

  return self.new(time_low, time_mid, time_hi_and_version,
                  clock_seq_hi_and_reserved, clock_seq_low, nodes)
end

.parse_raw(raw_string) ⇒ Object

Parses a UUID from a raw byte string.



176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
# File 'lib/uuidtools.rb', line 176

def self.parse_raw(raw_string)
  unless raw_string.kind_of? String
    raise TypeError,
      "Expected String, got #{raw_string.class.name} instead."
  end

  if raw_string.respond_to?(:force_encoding)
    raw_string.force_encoding(Encoding::ASCII_8BIT)
  end

  raw_length = raw_string.length
  if raw_length < 16
    # Option A: Enforce raw_string be 16 characters (More strict)
    #raise ArgumentError,
    #  "Expected 16 bytes, got #{raw_string.length} instead."

    # Option B: Pad raw_string to 16 characters (Compatible with existing behavior)
    raw_string = raw_string.rjust(16, "\0")
  elsif raw_length > 16
    # NOTE: As per "Option B" above, existing behavior would use the lower
    # 128-bits of an overly long raw_string instead of using the upper 128-bits.
    start_index = raw_length - 16
    raw_string = raw_string[start_index...raw_length]
  end

  raw_bytes = []
  if raw_string[0].respond_to? :ord
    for i in 0...raw_string.size
      raw_bytes << raw_string[i].ord
    end
  else
    raw_bytes = raw_string
  end

  time_low = ((raw_bytes[0] << 24) +
              (raw_bytes[1] << 16)  +
              (raw_bytes[2] << 8)  +
               raw_bytes[3])
  time_mid = ((raw_bytes[4] << 8) +
               raw_bytes[5])
  time_hi_and_version = ((raw_bytes[6] << 8) +
                          raw_bytes[7])
  clock_seq_hi_and_reserved = raw_bytes[8]
  clock_seq_low = raw_bytes[9]
  nodes = []
  for i in 10...16
    nodes << raw_bytes[i]
  end

  return self.new(time_low, time_mid, time_hi_and_version,
                  clock_seq_hi_and_reserved, clock_seq_low, nodes)
end

.random_createObject

Creates a UUID from a random value.



276
277
278
279
280
281
282
283
# File 'lib/uuidtools.rb', line 276

def self.random_create()
  new_uuid = self.parse_raw(SecureRandom.random_bytes(16))
  new_uuid.time_hi_and_version &= 0x0FFF
  new_uuid.time_hi_and_version |= (4 << 12)
  new_uuid.clock_seq_hi_and_reserved &= 0x3F
  new_uuid.clock_seq_hi_and_reserved |= 0x80
  return new_uuid
end

.sha1_create(namespace, name) ⇒ Object

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



353
354
355
# File 'lib/uuidtools.rb', line 353

def self.sha1_create(namespace, name)
  return self.create_from_hash(Digest::SHA1, namespace, name)
end

.timestamp_create(timestamp = nil) ⇒ Object

Creates a UUID from a timestamp.



287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
# File 'lib/uuidtools.rb', line 287

def self.timestamp_create(timestamp=nil)
  # We need a lock here to prevent two threads from ever
  # getting the same timestamp.
  @@mutex.synchronize do
    # Always use GMT to generate UUIDs.
    if timestamp.nil?
      gmt_timestamp = Time.now.gmtime
    else
      gmt_timestamp = timestamp.gmtime
    end
    # Convert to 100 nanosecond blocks
    gmt_timestamp_100_nanoseconds = (gmt_timestamp.tv_sec * 10000000) +
      (gmt_timestamp.tv_usec * 10) + 0x01B21DD213814000
    mac_address = self.mac_address
    node_id = 0
    if mac_address != nil
      nodes = mac_address.split(":").collect do |octet|
        octet.to_i(16)
      end
    else
      nodes = SecureRandom.random_bytes(6).unpack("C*")
      nodes[0] |= 0b00000001
    end
    6.times do |i|
      node_id += (nodes[i] << (40 - (i * 8)))
    end
    clock_sequence = @@last_clock_sequence
    if clock_sequence.nil?
      clock_sequence = self.convert_byte_string_to_int(
        SecureRandom.random_bytes(16)
      )
    end
    if @@last_node_id != nil && @@last_node_id != node_id
      # The node id has changed.  Change the clock id.
      clock_sequence = self.convert_byte_string_to_int(
        SecureRandom.random_bytes(16)
      )
    elsif @@last_timestamp != nil &&
        gmt_timestamp_100_nanoseconds <= @@last_timestamp
      clock_sequence = clock_sequence + 1
    end
    @@last_timestamp = gmt_timestamp_100_nanoseconds
    @@last_node_id = node_id
    @@last_clock_sequence = clock_sequence

    time_low = gmt_timestamp_100_nanoseconds & 0xFFFFFFFF
    time_mid = ((gmt_timestamp_100_nanoseconds >> 32) & 0xFFFF)
    time_hi_and_version = ((gmt_timestamp_100_nanoseconds >> 48) & 0x0FFF)
    time_hi_and_version |= (1 << 12)
    clock_seq_low = clock_sequence & 0xFF;
    clock_seq_hi_and_reserved = (clock_sequence & 0x3F00) >> 8
    clock_seq_hi_and_reserved |= 0x80

    return self.new(time_low, time_mid, time_hi_and_version,
      clock_seq_hi_and_reserved, clock_seq_low, nodes)
  end
end

Instance Method Details

#<=>(other_uuid) ⇒ Object

Compares two UUIDs lexically



453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
# File 'lib/uuidtools.rb', line 453

def <=>(other_uuid)
  return nil unless other_uuid.is_a?(UUIDTools::UUID)
  check = self.time_low <=> other_uuid.time_low
  return check if check != 0
  check = self.time_mid <=> other_uuid.time_mid
  return check if check != 0
  check = self.time_hi_and_version <=> other_uuid.time_hi_and_version
  return check if check != 0
  check = self.clock_seq_hi_and_reserved <=>
    other_uuid.clock_seq_hi_and_reserved
  return check if check != 0
  check = self.clock_seq_low <=> other_uuid.clock_seq_low
  return check if check != 0
  6.times do |i|
    if (self.nodes[i] < other_uuid.nodes[i])
      return -1
    end
    if (self.nodes[i] > other_uuid.nodes[i])
      return 1
    end
  end
  return 0
end

#eql?(other) ⇒ Boolean

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

Returns:

  • (Boolean)


578
579
580
# File 'lib/uuidtools.rb', line 578

def eql?(other)
  return self == other
end

#hashObject

Returns an integer hash value.



518
519
520
# File 'lib/uuidtools.rb', line 518

def hash
  self.frozen? ? generate_hash : (@hash ||= generate_hash)
end

#hexdigestObject

Returns the hex digest of the UUID object.



485
486
487
488
489
# File 'lib/uuidtools.rb', line 485

def hexdigest
  (self.frozen? ?
    generate_hexdigest : (@hexdigest ||= generate_hexdigest)
  ).dup
end

#inspectObject

Returns a representation of the object’s state



479
480
481
# File 'lib/uuidtools.rb', line 479

def inspect
  return "#<UUID:0x#{self.object_id.to_s(16)} UUID:#{self.to_s}>"
end

#mac_addressObject

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



430
431
432
433
434
435
436
# File 'lib/uuidtools.rb', line 430

def mac_address
  return nil if self.version != 1
  return nil if self.random_node_id?
  return (self.nodes.collect do |node|
    sprintf("%2.2x", node)
  end).join(":")
end

#nil_uuid?Boolean

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

Returns:

  • (Boolean)


372
373
374
375
376
377
378
379
380
381
382
# File 'lib/uuidtools.rb', line 372

def nil_uuid?
  return false if self.time_low != 0
  return false if self.time_mid != 0
  return false if self.time_hi_and_version != 0
  return false if self.clock_seq_hi_and_reserved != 0
  return false if self.clock_seq_low != 0
  self.nodes.each do |node|
    return false if node != 0
  end
  return true
end

#random_node_id?Boolean

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.

Returns:

  • (Boolean)


364
365
366
367
# File 'lib/uuidtools.rb', line 364

def random_node_id?
  return false if self.version != 1
  return ((self.nodes.first & 0x01) == 1)
end

#rawObject

Returns the raw bytes that represent this UUID.



493
494
495
# File 'lib/uuidtools.rb', line 493

def raw
  (self.frozen? ? generate_raw : (@raw ||= generate_raw)).dup
end

#timestampObject

Returns the timestamp used to generate this UUID



440
441
442
443
444
445
446
447
448
449
# File 'lib/uuidtools.rb', line 440

def timestamp
  return nil if self.version != 1
  gmt_timestamp_100_nanoseconds = 0
  gmt_timestamp_100_nanoseconds +=
    ((self.time_hi_and_version  & 0x0FFF) << 48)
  gmt_timestamp_100_nanoseconds += (self.time_mid << 32)
  gmt_timestamp_100_nanoseconds += self.time_low
  return Time.at(
    (gmt_timestamp_100_nanoseconds - 0x01B21DD213814000) / 10000000.0)
end

#to_iObject

Returns an integer representation for this UUID.



506
507
508
# File 'lib/uuidtools.rb', line 506

def to_i
  self.frozen? ? generate_i : (@integer ||= generate_i)
end

#to_sObject Also known as: to_str

Returns a string representation for this UUID.



499
500
501
# File 'lib/uuidtools.rb', line 499

def to_s
  (self.frozen? ? generate_s : (@string ||= generate_s)).dup
end

#to_uriObject

Returns a URI string for this UUID.



512
513
514
# File 'lib/uuidtools.rb', line 512

def to_uri
  return "urn:uuid:#{self.to_s}"
end

#valid?Boolean

Returns true if this UUID is valid.

Returns:

  • (Boolean)


418
419
420
421
422
423
424
425
# File 'lib/uuidtools.rb', line 418

def valid?
  if [0b000, 0b100, 0b110, 0b111].include?(self.variant) &&
    (1..5).include?(self.version)
    return true
  else
    return false
  end
end

#variantObject

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.



403
404
405
406
407
408
409
410
411
412
413
414
# File 'lib/uuidtools.rb', line 403

def variant
  variant_raw = (clock_seq_hi_and_reserved >> 5)
  result = nil
  if (variant_raw >> 2) == 0
    result = 0x000
  elsif (variant_raw >> 1) == 2
    result = 0x100
  else
    result = variant_raw
  end
  return (result >> 6)
end

#versionObject

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)



392
393
394
# File 'lib/uuidtools.rb', line 392

def version
  return (time_hi_and_version >> 12)
end