Skip to content

Instantly share code, notes, and snippets.

@jcoglan

jcoglan/numbers.rb

Created Dec 13, 2018
Embed
What would you like to do?
module Pack
module Numbers
module VarIntLE
def self.write(size, shift)
bytes = []
mask = 2 ** shift - 1
until size <= mask
bytes << (0x80 | size & mask)
size >>= shift
mask, shift = 0x7f, 7
end
bytes + [size]
end
def self.read(input, shift)
first = input.readbyte
size = first & (2 ** shift - 1)
byte = first
until byte < 0x80
byte = input.readbyte
size |= (byte & 0x7f) << shift
shift += 7
end
[first, size]
end
end
module PackedInt56LE
def self.write(value)
bytes = (0 .. 6).map { |i| (value >> (8 * i)) & 0xff }
flags = bytes.map.with_index { |b, i| b == 0 ? 0 : 1 << i }
header = flags.reduce { |a, b| a | b }
[header] + bytes.reject { |b| b == 0 }
end
def self.read(input, header)
flags = (0 .. 6).reject { |i| header & (1 << i) == 0 }
bytes = flags.map { |i| input.readbyte << (8 * i) }
bytes.reduce { |a, b| a | b }
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment