Class: CBOR

Inherits:
Object show all
Defined in:
lib/cbor-pure.rb,
lib/cbor-pretty.rb

Defined Under Namespace

Modules: Streaming Classes: Break, Simple, Tagged

Constant Summary collapse

BREAK =
Break.new.freeze
TAG_BIGNUM_BASE =
2
HALF_NAN_BYTES =
("\xf9".force_encoding(Encoding::BINARY) + Half::NAN_BYTES).freeze
MT_TO_ENCODING =
{2 => Encoding::BINARY, 3 => Encoding::UTF_8}
MT_NAMES =
["unsigned", "negative", "bytes", "text", "array", "map", "tag", "primitive"]

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(s = String.new) ⇒ CBOR

Returns a new instance of CBOR.



54
55
56
57
# File 'lib/cbor-pure.rb', line 54

def initialize(s = String.new)
  @buffer = s
  @pos = 0
end

Instance Attribute Details

#bufferObject (readonly)

Returns the value of attribute buffer.



53
54
55
# File 'lib/cbor-pure.rb', line 53

def buffer
  @buffer
end

Class Method Details

.decode(s) ⇒ Object



49
50
51
# File 'lib/cbor-pure.rb', line 49

def self.decode(s)
  new(s).decode_item_final
end

.encode(d) ⇒ Object



46
47
48
# File 'lib/cbor-pure.rb', line 46

def self.encode(d)
  new.add(d).buffer
end

.pretty(s, indent = 0, max_target = 40) ⇒ Object



16
17
18
# File 'lib/cbor-pretty.rb', line 16

def self.pretty(s, indent = 0, max_target = 40)
  new(s).pretty_item_final(indent, max_target)
end

Instance Method Details

#add(d) ⇒ Object



105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
# File 'lib/cbor-pure.rb', line 105

def add(d)
  case d
  when Integer
    ib = if d < 0
           d = -1-d
           0x20
         else
           0x00
         end
    head(ib, d) {             # block is called if things do not fit
      s = bignum_to_bytes(d)
      head(0xc0, TAG_BIGNUM_BASE + (ib >> 5))
      head(0x40, s.bytesize)
      s
    }
  when Numeric; addfloat(d)
  when Symbol; add(d.to_s)    # hack: this should really be tagged
  when Simple; head(0xe0, d.value)
  when false; head(0xe0, 20)
  when true; head(0xe0, 21)
  when nil; head(0xe0, 22)
  when Tagged                 # we don't handle :simple here
    head(0xc0, d.tag)
    add(d.data)
  when String
    lengths = d.cbor_stream?
    e = d
    ib = if d.encoding == Encoding::BINARY
           0x40
         else
           d = d.encode(Encoding::UTF_8).force_encoding(Encoding::BINARY)
           0x60
         end
    if lengths
      @buffer << (ib + 31)
      pos = 0
      lengths.each do |r|
        add(e[pos, r])
        pos += r
      end
      @buffer << 0xff
    else
      head(ib, d.bytesize)
      @buffer << d
    end
  when Array
    if d.cbor_stream?
      @buffer << 0x9f
      d.each {|di| add(di)}
      @buffer << 0xff
    else
      head(0x80, d.size)
      d.each {|di| add(di)}
    end
  when Hash
    if d.cbor_stream?
      @buffer << 0xbf
      d.each {|k, v| add(k); add(v)}
      @buffer << 0xff
    else
      head(0xa0, d.size)
      d.each {|k, v| add(k); add(v)}
    end
  else
    raise("Don't know how to encode #{d.inspect}")
  end
  self
end

#addfloat(fv) ⇒ Object



79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
# File 'lib/cbor-pure.rb', line 79

def addfloat(fv)
  if fv.nan?
    @buffer << HALF_NAN_BYTES
  else
    ss = [fv].pack("g")         # single-precision
    if ss.unpack("g").first == fv
      if hs = Half.encode_from_single(fv, ss)
        @buffer << 0xf9 << hs
      else
        @buffer << 0xfa << ss
      end
    else
      @buffer << [0xfb, fv].pack("CG") # double-precision
    end
  end
end

#bignum_to_bytes(d) ⇒ Object



96
97
98
99
100
101
102
103
# File 'lib/cbor-pure.rb', line 96

def bignum_to_bytes(d)
  s = String.new
  while (d != 0)
    s << (d & 0xFF)
    d >>= 8
  end
  s.reverse!
end

#decode_item(breakable = false) ⇒ Object



213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
# File 'lib/cbor-pure.rb', line 213

def decode_item(breakable = false)
  ib = take(1).ord
  ai = ib & 0x1F
  val = case ai
        when 0...24; ai
        when 24; take(1).ord
        when 25; take(2).unpack("n").first
        when 26; (s = take(4)).unpack("N").first
        when 27; (s = take(8)).unpack("Q>").first
        when 31; return decode_item_streaming(ib, breakable)
        else raise "unknown additional information #{ai} in ib #{ib}"
        end
  case ib >>= 5
  when 0; val
  when 1; -1-val
  when 7
    case ai
    when 20; false
    when 21; true
    when 22; nil
    # when 27; Simple.new(27)   # Ruby does not have Undefined
    when 25; Half.decode(val)
    when 26; s.unpack("g").first # cannot go directly from val
    when 27; s.unpack("G").first #   in Ruby
    else
      Simple.new(val)
    end
  when 6
    di = decode_item
    if String === di && (val & ~1) == TAG_BIGNUM_BASE
      (TAG_BIGNUM_BASE - val) ^ di.bytes.inject(0) {|sum, b| sum <<= 8; sum += b }
    else
      Tagged.new(val, di)
    end
  when 2; take(val).force_encoding(Encoding::BINARY)
  when 3; take(val).force_encoding(Encoding::UTF_8)
  when 4; Array.new(val) { decode_item }
  when 5; Hash[Array.new(val) {[decode_item, decode_item]}]
  end
end

#decode_item_finalObject



254
255
256
257
258
# File 'lib/cbor-pure.rb', line 254

def decode_item_final
  val = decode_item
  raise "extra bytes follow after a deserialized object" if @pos != @buffer.size
  val
end

#decode_item_streaming(ib, breakable) ⇒ Object



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
# File 'lib/cbor-pure.rb', line 183

def decode_item_streaming(ib, breakable)
  case ib >>= 5
  when 2, 3
    want_encoding = MT_TO_ENCODING[ib]
    subs = []
    while (element = decode_item(true)) != BREAK
      raise "non-string (#{element.inspect}) in streaming string" unless String === element
      raise "bytes/text mismatch (#{element.encoding} != #{want_encoding}) in streaming string" unless element.encoding == want_encoding
      subs << element
    end
    result = subs.join.cbor_stream!(subs.map(&:length)).force_encoding(want_encoding)
  when 4
    result = Array.new;
    while (element = decode_item(true)) != BREAK
      result << element
    end
    result
  when 5
    result = Hash.new
    while (key = decode_item(true)) != BREAK
      result[key] = decode_item
    end
    result
  when 7
    raise "break stop code outside indefinite length item" unless breakable
    BREAK
  else raise "unknown ib #{ib} for additional information 31"
  end
end

#head(ib, n) ⇒ Object



59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
# File 'lib/cbor-pure.rb', line 59

def head(ib, n)
  @buffer <<
    case n
    when 0...24
      [ib + n].pack("C")
    when 0...256
      [ib + 24, n].pack("CC")
    when 0...65536
      [ib + 25, n].pack("Cn")
    when 0...4294967296
      [ib + 26, n].pack("CN")
    when 0...18446744073709551616
      [ib + 27, n].pack("CQ>")
    else
      yield                   # throw back to caller
    end
end

#pretty_itemObject



44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
# File 'lib/cbor-pretty.rb', line 44

def pretty_item
  ib = take_and_print(1, '   ' * @indent).ord
  ai = ib & 0x1F
  val = case ai
        when 0...24; ai
        when 24; take_and_print(1, ' ').ord
        when 25; take_and_print(2, ' ').unpack("n").first
        when 26; (s = take_and_print(4, ' ')).unpack("N").first
        when 27; (s = take_and_print(8, ' ')).unpack("Q>").first
        when 31; return pretty_item_streaming(ib)
        else raise "unknown additional information #{ai} in ib #{ib}"
        end
  @out << " # #{MT_NAMES[ib >> 5]}(#{val})\n"
  @indent += 1
  case ib >>= 5
  when 6
    pretty_item
  when 2, 3
    @out << '   ' * (@indent)
    s = take_and_print(val)
    @out << " # #{s.inspect}"
    @out << "\n"
  when 4; val.times { pretty_item }
  when 5; val.times { pretty_item; pretty_item}
  end
  @indent -= 1
  nil
end

#pretty_item_final(indent = 0, max_target = 40) ⇒ Object



73
74
75
76
77
78
79
80
81
82
83
84
85
86
# File 'lib/cbor-pretty.rb', line 73

def pretty_item_final(indent = 0, max_target = 40)
  @out = ''
  @indent = indent
  pretty_item
  raise if @pos != @buffer.size
  target = [@out.each_line.map {|ln| ln =~ /#/ || 0}.max, max_target].min
  @out.each_line.map {|ln|
    col = ln =~ /#/
    if col && col < target
      ln[col, 0] = ' ' * (target - col)
    end
    ln
  }.join
end

#pretty_item_streaming(ib) ⇒ Object



27
28
29
30
31
32
33
34
35
36
37
38
39
40
# File 'lib/cbor-pretty.rb', line 27

def pretty_item_streaming(ib)
  res = nil
  @out << " # #{MT_NAMES[ib >> 5]}(*)\n"
  @indent += 1
  case ib >>= 5
  when 2, 3, 4, 5
    while (element = pretty_item) != BREAK
    end
  when 7; res = BREAK
  else raise "unknown ib #{ib} for additional information 31"
  end
  @indent -= 1
  res
end

#take(n) ⇒ Object



174
175
176
177
178
179
# File 'lib/cbor-pure.rb', line 174

def take(n)
  opos = @pos
  @pos += n
  raise "Out of bytes to decode: #{opos} + #{n} > #{@buffer.bytesize}" if @pos > @buffer.bytesize
  @buffer[opos, n]
end

#take_and_print(n, prefix = '') ⇒ Object



20
21
22
23
24
25
# File 'lib/cbor-pretty.rb', line 20

def take_and_print(n, prefix = '')
  s = take(n)
  @out << prefix
  @out << s.hexbytes
  s
end