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
13 from bup import compat
14 from bup import _helpers
17 def write_vuint(port, x):
18 port.write(encode_vuint(x))
23 return _helpers.vuint_encode(x)
26 bytes_from_uint = compat.bytes_from_uint
28 raise Exception("vuints must not be negative")
29 assert x, "the C version should have picked this up"
35 ret += bytes_from_uint(0x80 | seven_bits)
37 ret += bytes_from_uint(seven_bits)
44 raise EOFError('encountered EOF while reading vuint')
45 assert isinstance(c, bytes)
53 result |= ((b & 0x7f) << offset)
57 raise EOFError('encountered EOF while reading vuint')
59 result |= (b << offset)
64 def write_vint(port, x):
65 # Sign is handled with the second bit of the first byte. All else
67 port.write(encode_vint(x))
72 return _helpers.vint_encode(x)
74 bytes_from_uint = compat.bytes_from_uint
75 assert x != 0, "the C version should have picked this up"
78 sign_and_six_bits = (x & 0x3f) | 0x40
80 sign_and_six_bits = x & 0x3f
82 assert x, "the C version should have picked this up"
83 return bytes_from_uint(0x80 | sign_and_six_bits) + encode_vuint(x)
89 raise EOFError('encountered EOF while reading vint')
90 assert isinstance(c, bytes)
94 # Handle first byte with sign bit specially.
109 result |= ((b & 0x7f) << offset)
113 raise EOFError('encountered EOF while reading vint')
115 result |= (b << offset)
123 def write_bvec(port, x):
124 write_vuint(port, len(x))
134 return _helpers.vuint_encode(len(x)) + x
138 port.read(read_vuint(port))
140 def send(port, types, *args):
141 if len(types) != len(args):
142 raise Exception('number of arguments does not match format string')
143 for (type, value) in zip(types, args):
145 write_vuint(port, value)
147 write_vint(port, value)
149 write_bvec(port, value)
151 raise Exception('unknown xpack format string item "' + type + '"')
153 def recv(port, types):
157 result.append(read_vuint(port))
159 result.append(read_vint(port))
161 result.append(read_bvec(port))
163 raise Exception('unknown xunpack format string item "' + type + '"')
166 def pack(types, *args):
168 return _helpers.limited_vint_pack(types, args)
169 except OverflowError:
170 assert len(types) == len(args)
172 for typ, value in zip(types, args):
174 ret.append(encode_vuint(value))
176 ret.append(encode_vint(value))
178 ret.append(encode_bvec(value))
183 def unpack(types, data):
185 return recv(port, types)