| 1 | cdef extern from "stdlib.h": |
|---|
| 2 | cdef void *malloc(int size) |
|---|
| 3 | |
|---|
| 4 | def encode_int(long n): |
|---|
| 5 | if <unsigned long>n > 0x40000000: |
|---|
| 6 | raise ValueError, "Out of range" |
|---|
| 7 | |
|---|
| 8 | cdef char *bytes = NULL |
|---|
| 9 | cdef long real_value = n |
|---|
| 10 | cdef char changed = 0 |
|---|
| 11 | cdef unsigned char count = 0 |
|---|
| 12 | |
|---|
| 13 | if n > 0x1fffff: |
|---|
| 14 | bytes = <char *>malloc(5 * sizeof(char)) |
|---|
| 15 | real_value = n |
|---|
| 16 | changed = 1 |
|---|
| 17 | n = n >> 1 |
|---|
| 18 | bytes[count] = 0x80 | ((n >> 21) & 0xff) |
|---|
| 19 | count += 1 |
|---|
| 20 | |
|---|
| 21 | if n > 0x3fff: |
|---|
| 22 | if bytes == NULL: |
|---|
| 23 | bytes = <char *>malloc(4) |
|---|
| 24 | |
|---|
| 25 | bytes[count] = 0x80 | ((n >> 14) & 0xff) |
|---|
| 26 | count += 1 |
|---|
| 27 | |
|---|
| 28 | if n > 0x7f: |
|---|
| 29 | if bytes == NULL: |
|---|
| 30 | bytes = <char *>malloc(3) |
|---|
| 31 | |
|---|
| 32 | bytes[count] = 0x80 | ((n >> 7) & 0xff) |
|---|
| 33 | count += 1 |
|---|
| 34 | |
|---|
| 35 | if changed == 1: |
|---|
| 36 | n = real_value |
|---|
| 37 | |
|---|
| 38 | if bytes == NULL: |
|---|
| 39 | bytes = <char *>malloc(2) |
|---|
| 40 | |
|---|
| 41 | if n > 0x1fffff: |
|---|
| 42 | bytes[count] = n & 0xff |
|---|
| 43 | else: |
|---|
| 44 | bytes[count] = n & 0x7f |
|---|
| 45 | |
|---|
| 46 | bytes[count + 1] = 0 |
|---|
| 47 | |
|---|
| 48 | return bytes |
|---|