1 #!/usr/bin/env python 2 3 """ 4 Variable-length integer functions. 5 6 Copyright (C) 2009 Paul Boddie <paul@boddie.org.uk> 7 8 This program is free software; you can redistribute it and/or modify it under 9 the terms of the GNU General Public License as published by the Free Software 10 Foundation; either version 3 of the License, or (at your option) any later 11 version. 12 13 This program is distributed in the hope that it will be useful, but WITHOUT ANY 14 WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A 15 PARTICULAR PURPOSE. See the GNU General Public License for more details. 16 17 You should have received a copy of the GNU General Public License along 18 with this program. If not, see <http://www.gnu.org/licenses/>. 19 """ 20 21 vint_cache = {} 22 23 def vint(number): 24 25 "Write 'number' as a variable-length integer." 26 27 try: 28 return vint_cache[number] 29 except KeyError: 30 if number >= 0: 31 32 # Write the number from least to most significant digits. 33 34 bytes = [] 35 36 while number > 127: 37 lsd = number & 127 | 128 38 bytes.append(chr(lsd)) 39 number = number >> 7 40 else: 41 bytes.append(chr(number)) 42 43 return "".join(bytes) 44 45 # Negative numbers are not supported. 46 47 else: 48 raise ValueError, "Number %r is negative." % number 49 50 for i in xrange(0, 1024): 51 vint_cache[i] = vint(i) 52 53 # vim: tabstop=4 expandtab shiftwidth=4