1.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000
1.2 +++ b/iixr/data.py Tue Sep 15 00:15:11 2009 +0200
1.3 @@ -0,0 +1,64 @@
1.4 +#!/usr/bin/env python
1.5 +
1.6 +"""
1.7 +Variable-length integer functions.
1.8 +
1.9 +Copyright (C) 2009 Paul Boddie <paul@boddie.org.uk>
1.10 +
1.11 +This program is free software; you can redistribute it and/or modify it under
1.12 +the terms of the GNU General Public License as published by the Free Software
1.13 +Foundation; either version 3 of the License, or (at your option) any later
1.14 +version.
1.15 +
1.16 +This program is distributed in the hope that it will be useful, but WITHOUT ANY
1.17 +WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
1.18 +PARTICULAR PURPOSE. See the GNU General Public License for more details.
1.19 +
1.20 +You should have received a copy of the GNU General Public License along
1.21 +with this program. If not, see <http://www.gnu.org/licenses/>.
1.22 +"""
1.23 +
1.24 +try:
1.25 + from vint import vint as _vint
1.26 +
1.27 + def vint(number):
1.28 +
1.29 + "Write 'number' as a variable-length integer."
1.30 +
1.31 + if number >= 0:
1.32 + return _vint(number)
1.33 + else:
1.34 + raise ValueError, "Number %r is negative." % number
1.35 +
1.36 +except ImportError:
1.37 +
1.38 + def vint(number):
1.39 +
1.40 + "Write 'number' as a variable-length integer."
1.41 +
1.42 + if number >= 0:
1.43 +
1.44 + # Special case: one byte containing a 7-bit number.
1.45 +
1.46 + if number < 128:
1.47 + return chr(number)
1.48 +
1.49 + # Write the number from least to most significant digits.
1.50 +
1.51 + bytes = []
1.52 +
1.53 + while number != 0:
1.54 + lsd = number & 127
1.55 + number = number >> 7
1.56 + if number != 0:
1.57 + lsd |= 128
1.58 + bytes.append(chr(lsd))
1.59 +
1.60 + return "".join(bytes)
1.61 +
1.62 + # Negative numbers are not supported.
1.63 +
1.64 + else:
1.65 + raise ValueError, "Number %r is negative." % number
1.66 +
1.67 +# vim: tabstop=4 expandtab shiftwidth=4