Class: Keybox::UUID

Inherits:
Object
  • Object
show all
Defined in:
lib/keybox/uuid.rb

Overview

A quick implementation of a UUID class using the internal randomizer for byte generation

Constant Summary collapse

XF =
"%0.2x"
FORMAT =
sprintf("%s-%s-%s-%s-%s", XF * 4, XF * 2, XF * 2, XF * 2, XF * 6)
REGEX =
%r|^[0-9a-f]{8}(-[0-9a-f]{4}){3}-[0-9a-f]{12}$|

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(bytes = nil) ⇒ UUID

the UUID can be initialized with:

- nothing ( default case ) in this case the UUID is generated
- a string in the standarde uuid format, in this case it is
  decoded and converted to the internal format
- a string of bytes, in this case they are considered to be
  the bytes used internally so 16 of them are taken


23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
# File 'lib/keybox/uuid.rb', line 23

def initialize(bytes = nil)

    if bytes.nil? then
        @bytes = Keybox::RandomDevice.random_bytes(16)
    elsif bytes.size == 36 and bytes.split("-").size == 5 then
        if bytes =~ REGEX then
            # remove the dashes and make sure that we're all
            # lowercase
            b = bytes.gsub(/-/,'').downcase

            # convert to an array of hex strings
            b = b.unpack("a2"*16)

            # convert the hex strings to integers
            b.collect! { |x| x.to_i(16) }

            # and pack those integers into a string
            @bytes = b.pack("C*")

            # of course this could all be done in one line with
            # @bytes = bytes.gsub(/-/,'').downcase.unpack("a2"*16").collect {|x| x.to_i(16) }.pack("C*")
        else
            raise ArgumentError, "[#{bytes}] is not a hex encoded UUID"
        end
    elsif bytes.kind_of?(String) and bytes.length >= 16
        @bytes = bytes[0..16]
    else
        raise ArgumentError, "[#{bytes}] cannot be converted to a UUID"
    end
end

Instance Attribute Details

#bytesObject (readonly)

Returns the value of attribute bytes.



10
11
12
# File 'lib/keybox/uuid.rb', line 10

def bytes
  @bytes
end

Instance Method Details

#==(other) ⇒ Object



66
67
68
# File 'lib/keybox/uuid.rb', line 66

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

#eql?(other) ⇒ Boolean

Returns:

  • (Boolean)


70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
# File 'lib/keybox/uuid.rb', line 70

def eql?(other)
    case other
    when Keybox::UUID
        self.bytes == other.bytes
    when String
        begin
            o = Keybox::UUID.new(other)
            self == o
        rescue 
            false
        end
    else
        false
    end
end

#to_aObject



62
63
64
# File 'lib/keybox/uuid.rb', line 62

def to_a
    @bytes.unpack("C*")
end

#to_sObject

convert the bytes to the hex encoded string format of XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX



58
59
60
# File 'lib/keybox/uuid.rb', line 58

def to_s
    sprintf(FORMAT,*to_a)
end