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 from __future__ import absolute_import
11 # Variable length integers are encoded as vints -- see jakarta lucene.
13 def write_vuint(port, x):
15 raise Exception("vuints must not be negative")
23 port.write(chr(0x80 | seven_bits))
25 port.write(chr(seven_bits))
32 raise EOFError('encountered EOF while reading vuint')
40 result |= ((b & 0x7f) << offset)
44 raise EOFError('encountered EOF while reading vuint')
46 result |= (b << offset)
51 def write_vint(port, x):
52 # Sign is handled with the second bit of the first byte. All else
59 sign_and_six_bits = (x & 0x3f) | 0x40
61 sign_and_six_bits = x & 0x3f
64 port.write(chr(0x80 | sign_and_six_bits))
67 port.write(chr(sign_and_six_bits))
73 raise EOFError('encountered EOF while reading vint')
77 # Handle first byte with sign bit specially.
93 result |= ((b & 0x7f) << offset)
97 raise EOFError('encountered EOF while reading vint')
99 result |= (b << offset)
107 def write_bvec(port, x):
108 write_vuint(port, len(x))
118 port.read(read_vuint(port))
120 def send(port, types, *args):
121 if len(types) != len(args):
122 raise Exception('number of arguments does not match format string')
123 for (type, value) in zip(types, args):
125 write_vuint(port, value)
127 write_vint(port, value)
129 write_bvec(port, value)
131 raise Exception('unknown xpack format string item "' + type + '"')
133 def recv(port, types):
137 result.append(read_vuint(port))
139 result.append(read_vint(port))
141 result.append(read_bvec(port))
143 raise Exception('unknown xunpack format string item "' + type + '"')
146 def pack(types, *args):
148 send(port, types, *args)
149 return port.getvalue()
151 def unpack(types, data):
153 return recv(port, types)