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