Class: Cabriolet::Binary::ENCINTWriter
- Inherits:
-
Object
- Object
- Cabriolet::Binary::ENCINTWriter
- Defined in:
- lib/cabriolet/binary/chm_structures.rb
Overview
Helper class for writing ENCINT (variable-length integers)
Class Method Summary collapse
-
.encode(value) ⇒ String
Encode an integer as ENCINT bytes.
-
.write(io, value) ⇒ Integer
Write an ENCINT to an IO stream.
Class Method Details
.encode(value) ⇒ String
Encode an integer as ENCINT 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
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 |