Class: CBOR::Loader

Inherits:
Object
  • Object
show all
Includes:
Consts
Defined in:
lib/cbor/loader.rb

Constant Summary collapse

@@registered_tags =
{}

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(io, local_tags) ⇒ Loader

Returns a new instance of Loader.



10
11
12
13
# File 'lib/cbor/loader.rb', line 10

def initialize(io, local_tags)
  @io = io
  @local_tags = local_tags
end

Class Method Details

.register_tag(tag, &block) ⇒ Object



6
7
8
# File 'lib/cbor/loader.rb', line 6

def self.register_tag(tag, &block)
  @@registered_tags[tag] = block
end

Instance Method Details

#loadObject



15
16
17
18
19
20
21
22
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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
# File 'lib/cbor/loader.rb', line 15

def load
  typeInt = get_bytes(1, "C")
  major = (typeInt >> 5)

  case major
  when Major::UINT
    get_uint(typeInt)
  when Major::NEGINT
    -get_uint(typeInt)-1
  when Major::BYTESTRING
    count = get_uint(typeInt)
    get_bytes(count, "a*")
  when Major::TEXTSTRING
    count = get_uint(typeInt)
    s = get_bytes(count, "a*").force_encoding(Encoding::UTF_8)
    unless s.valid_encoding?
      raise CBOR::CborError.new("Received non-utf8 string when expecting utf8")
    end
    s
  when Major::ARRAY
    count = get_uint(typeInt)
    count.times.map { load }
  when Major::MAP
    count = get_uint(typeInt)
    Hash[count.times.map { [load, load] }]
  when Major::TAG
    tag = get_uint(typeInt)
    if block = @@registered_tags[tag]
      block.call(load)
    elsif block = @local_tags[tag]
      block.call(load)
    else
      raise CBOR::CborError.new("Unknown tag #{tag}")
    end
  when Major::SIMPLE
    case typeInt & 0x1F
    when Simple::FALSE
      false
    when Simple::TRUE
      true
    when Simple::NULL
      nil
    when Simple::FLOAT32
      get_bytes(4, "g")
    when Simple::FLOAT64
      get_bytes(8, "G")
    else
      raise CBOR::CborError.new("Unknown simple type #{simple}")
    end
  else
    raise CBOR::CborError.new("Unknown major type #{major}")
  end
end