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
17 def write_vuint(port, x):
19 bytes_from_uint = compat.bytes_from_uint
21 raise Exception("vuints must not be negative")
23 write(bytes_from_uint(0))
29 write(bytes_from_uint(0x80 | seven_bits))
31 write(bytes_from_uint(seven_bits))
38 raise EOFError('encountered EOF while reading vuint')
46 result |= ((b & 0x7f) << offset)
50 raise EOFError('encountered EOF while reading vuint')
52 result |= (b << offset)
57 def write_vint(port, x):
58 # Sign is handled with the second bit of the first byte. All else
61 bytes_from_uint = compat.bytes_from_uint
63 write(bytes_from_uint(0))
67 sign_and_six_bits = (x & 0x3f) | 0x40
69 sign_and_six_bits = x & 0x3f
72 write(bytes_from_uint(0x80 | sign_and_six_bits))
75 write(bytes_from_uint(sign_and_six_bits))
81 raise EOFError('encountered EOF while reading vint')
85 # Handle first byte with sign bit specially.
101 result |= ((b & 0x7f) << offset)
105 raise EOFError('encountered EOF while reading vint')
107 result |= (b << offset)
115 def write_bvec(port, x):
116 write_vuint(port, len(x))
126 port.read(read_vuint(port))
128 def send(port, types, *args):
129 if len(types) != len(args):
130 raise Exception('number of arguments does not match format string')
131 for (type, value) in zip(types, args):
133 write_vuint(port, value)
135 write_vint(port, value)
137 write_bvec(port, value)
139 raise Exception('unknown xpack format string item "' + type + '"')
141 def recv(port, types):
145 result.append(read_vuint(port))
147 result.append(read_vint(port))
149 result.append(read_bvec(port))
151 raise Exception('unknown xunpack format string item "' + type + '"')
154 def pack(types, *args):
156 send(port, types, *args)
157 return port.getvalue()
159 def unpack(types, data):
161 return recv(port, types)