Class: Cabriolet::Binary::ENCINTWriter

Inherits:
Object
  • Object
show all
Defined in:
lib/cabriolet/binary/chm_structures.rb

Overview

Helper class for writing ENCINT (variable-length integers)

Class Method Summary collapse

Class Method Details

.encode(value) ⇒ String

Encode an integer as ENCINT bytes

Parameters:

  • value (Integer)

    Value to encode (must be non-negative)

Returns:

  • (String)

    Encoded bytes



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
# File 'lib/cabriolet/binary/chm_structures.rb', line 186

def self.encode(value)
  if value.negative?
    raise ArgumentError,
          "ENCINT value must be non-negative"
  end

  # Special case: zero
  return "\x00".b if value.zero?

  bytes = []

  # Encode 7 bits at a time
  while value.positive?
    byte = value & 0x7F
    value >>= 7
    bytes.unshift(byte)
  end

  # Set high bit on all but last byte
  (0...(bytes.length - 1)).each do |i|
    bytes[i] |= 0x80
  end

  bytes.pack("C*")
end

.write(io, value) ⇒ Integer

Write an ENCINT to an IO stream

Parameters:

  • io (IO)

    IO object to write to

  • value (Integer)

    Value to encode

Returns:

  • (Integer)

    Number of bytes written



177
178
179
180
181
# File 'lib/cabriolet/binary/chm_structures.rb', line 177

def self.write(io, value)
  bytes = encode(value)
  io.write(bytes)
  bytes.bytesize
end