paul@37 | 1 | #!/usr/bin/env python |
paul@37 | 2 | |
paul@48 | 3 | """ |
paul@48 | 4 | A variable-length integer encoding implementation in Pyrex. |
paul@48 | 5 | |
paul@48 | 6 | Copyright (C) 2009 Paul Boddie <paul@boddie.org.uk> |
paul@48 | 7 | |
paul@48 | 8 | This program is free software; you can redistribute it and/or modify it under |
paul@48 | 9 | the terms of the GNU General Public License as published by the Free Software |
paul@48 | 10 | Foundation; either version 3 of the License, or (at your option) any later |
paul@48 | 11 | version. |
paul@48 | 12 | |
paul@48 | 13 | This program is distributed in the hope that it will be useful, but WITHOUT ANY |
paul@48 | 14 | WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A |
paul@48 | 15 | PARTICULAR PURPOSE. See the GNU General Public License for more details. |
paul@48 | 16 | |
paul@48 | 17 | You should have received a copy of the GNU General Public License along |
paul@48 | 18 | with this program. If not, see <http://www.gnu.org/licenses/>. |
paul@48 | 19 | """ |
paul@48 | 20 | |
paul@37 | 21 | cdef extern from "Python.h": |
paul@37 | 22 | object PyString_FromStringAndSize(char *, int) |
paul@37 | 23 | |
paul@37 | 24 | def vint(int number): |
paul@37 | 25 | |
paul@37 | 26 | cdef char bytes[40] # NOTE: Arbitrary limit. |
paul@37 | 27 | cdef int lsd, i |
paul@37 | 28 | |
paul@38 | 29 | if number < 128: |
paul@38 | 30 | bytes[0] = number |
paul@38 | 31 | s = PyString_FromStringAndSize(bytes, 1) |
paul@38 | 32 | return s |
paul@38 | 33 | |
paul@37 | 34 | i = 0 |
paul@37 | 35 | while number != 0: |
paul@37 | 36 | lsd = number & 127 |
paul@37 | 37 | number = number >> 7 |
paul@37 | 38 | if number != 0: |
paul@37 | 39 | lsd = lsd | 128 |
paul@37 | 40 | bytes[i] = lsd |
paul@37 | 41 | i = i + 1 |
paul@37 | 42 | |
paul@37 | 43 | s = PyString_FromStringAndSize(bytes, i) |
paul@37 | 44 | return s |
paul@37 | 45 | |
paul@37 | 46 | # vim: tabstop=4 expandtab shiftwidth=4 |