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 | # Write the number from least to most significant digits. |
paul@44 | 33 | |
paul@44 | 34 | bytes = [] |
paul@44 | 35 | |
paul@54 | 36 | while number > 127: |
paul@54 | 37 | lsd = number & 127 | 128 |
paul@54 | 38 | bytes.append(chr(lsd)) |
paul@44 | 39 | number = number >> 7 |
paul@54 | 40 | else: |
paul@54 | 41 | bytes.append(chr(number)) |
paul@44 | 42 | |
paul@44 | 43 | return "".join(bytes) |
paul@44 | 44 | |
paul@44 | 45 | # Negative numbers are not supported. |
paul@44 | 46 | |
paul@44 | 47 | else: |
paul@44 | 48 | raise ValueError, "Number %r is negative." % number |
paul@44 | 49 | |
paul@51 | 50 | for i in xrange(0, 1024): |
paul@51 | 51 | vint_cache[i] = vint(i) |
paul@51 | 52 | |
paul@44 | 53 | # vim: tabstop=4 expandtab shiftwidth=4 |