1 """Binary encodings for bup."""
3 # Copyright (C) 2010 Rob Browning
5 # This code is covered under the terms of the GNU Library General
6 # Public License as described in the bup LICENSE file.
8 # Variable length integers are encoded as vints -- see lucene.
10 from __future__ import absolute_import
11 from io import BytesIO
14 from bup import compat
15 from bup import _helpers
18 def write_vuint(port, x):
19 port.write(encode_vuint(x))
24 return _helpers.vuint_encode(x)
27 bytes_from_uint = compat.bytes_from_uint
29 raise Exception("vuints must not be negative")
30 assert x, "the C version should have picked this up"
36 ret += bytes_from_uint(0x80 | seven_bits)
38 ret += bytes_from_uint(seven_bits)
45 raise EOFError('encountered EOF while reading vuint')
46 assert isinstance(c, bytes)
54 result |= ((b & 0x7f) << offset)
58 raise EOFError('encountered EOF while reading vuint')
60 result |= (b << offset)
65 def write_vint(port, x):
66 # Sign is handled with the second bit of the first byte. All else
68 port.write(encode_vint(x))
73 return _helpers.vint_encode(x)
75 bytes_from_uint = compat.bytes_from_uint
76 assert x != 0, "the C version should have picked this up"
79 sign_and_six_bits = (x & 0x3f) | 0x40
81 sign_and_six_bits = x & 0x3f
83 assert x, "the C version should have picked this up"
84 return bytes_from_uint(0x80 | sign_and_six_bits) + encode_vuint(x)
90 raise EOFError('encountered EOF while reading vint')
91 assert isinstance(c, bytes)
95 # Handle first byte with sign bit specially.
110 result |= ((b & 0x7f) << offset)
114 raise EOFError('encountered EOF while reading vint')
116 result |= (b << offset)
124 def write_bvec(port, x):
125 write_vuint(port, len(x))
135 return _helpers.vuint_encode(len(x)) + x
139 port.read(read_vuint(port))
141 def send(port, types, *args):
142 if len(types) != len(args):
143 raise Exception('number of arguments does not match format string')
144 for (type, value) in zip(types, args):
146 write_vuint(port, value)
148 write_vint(port, value)
150 write_bvec(port, value)
152 raise Exception('unknown xpack format string item "' + type + '"')
154 def recv(port, types):
158 result.append(read_vuint(port))
160 result.append(read_vint(port))
162 result.append(read_bvec(port))
164 raise Exception('unknown xunpack format string item "' + type + '"')
167 def pack(types, *args):
169 return _helpers.limited_vint_pack(types, args)
170 except OverflowError:
171 assert len(types) == len(args)
173 for typ, value in zip(types, args):
175 ret.append(encode_vuint(value))
177 ret.append(encode_vint(value))
179 ret.append(encode_bvec(value))
184 def unpack(types, data):
186 return recv(port, types)