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))
31 raise EOFError('encountered EOF while reading vuint');
37 result |= ((b & 0x7f) << offset)
41 result |= (b << offset)
46 def write_vint(port, x):
47 # Sign is handled with the second bit of the first byte. All else
54 sign_and_six_bits = (x & 0x3f) | 0x40
56 sign_and_six_bits = x & 0x3f
59 port.write(chr(0x80 | sign_and_six_bits))
62 port.write(chr(sign_and_six_bits))
68 raise EOFError('encountered EOF while reading vint');
72 # Handle first byte with sign bit specially.
88 result |= ((b & 0x7f) << offset)
92 result |= (b << offset)
100 def write_bvec(port, x):
101 write_vuint(port, len(x))
111 port.read(read_vuint(port))
114 def pack(types, *args):
115 if len(types) != len(args):
116 raise Exception('number of arguments does not match format string')
118 for (type, value) in zip(types, args):
120 write_vuint(port, value)
122 write_vint(port, value)
124 write_bvec(port, value)
126 raise Exception('unknown xpack format string item "' + type + '"')
127 return port.getvalue()
130 def unpack(types, data):
135 result.append(read_vuint(port))
137 result.append(read_vint(port))
139 result.append(read_bvec(port))
141 raise Exception('unknown xunpack format string item "' + type + '"')