comparison pytouhou/utils/bitstream.pyx @ 367:2674c789e0c3

Various optimizations
author Thibaut Girka <thib@sitedethib.com>
date Tue, 10 Jul 2012 00:25:08 +0200
parents b5c7369abd7c
children efae61ad6efe
comparison
equal deleted inserted replaced
366:7dc012f631dc 367:2674c789e0c3
11 ## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 11 ## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 ## GNU General Public License for more details. 12 ## GNU General Public License for more details.
13 ## 13 ##
14 14
15 cdef class BitStream: 15 cdef class BitStream:
16 cdef public io 16 cdef public object io
17 cdef public int bits 17 cdef unsigned int bits
18 cdef public unsigned char byte 18 cdef unsigned char byte
19 cdef bytes bytes
19 20
20 21
21 def __init__(BitStream self, io): 22 def __init__(BitStream self, io):
22 self.io = io 23 self.io = io
23 self.bits = 0 24 self.bits = 0
46 return self.io.tell(), self.bits 47 return self.io.tell(), self.bits
47 48
48 49
49 cpdef unsigned char read_bit(BitStream self): 50 cpdef unsigned char read_bit(BitStream self):
50 if not self.bits: 51 if not self.bits:
51 self.byte = ord(self.io.read(1)) 52 self.bytes = self.io.read(1)
53 self.byte = (<unsigned char*> self.bytes)[0]
52 self.bits = 8 54 self.bits = 8
53 self.bits -= 1 55 self.bits -= 1
54 return (self.byte >> self.bits) & 0x01 56 return (self.byte >> self.bits) & 0x01
55 57
56 58
57 cpdef unsigned int read(BitStream self, int nb_bits): 59 cpdef unsigned int read(BitStream self, unsigned int nb_bits):
58 cdef unsigned int value = 0 60 cdef unsigned int value = 0, read = 0
59 cdef int i 61 cdef unsigned int nb_bits2 = nb_bits
60 62
61 for i in range(nb_bits - 1, -1, -1): 63 while nb_bits2:
62 value |= self.read_bit() << i 64 if not self.bits:
63 return value 65 self.bytes = self.io.read(1)
66 self.byte = (<unsigned char*> self.bytes)[0]
67 self.bits = 8
68 read = self.bits if nb_bits2 > self.bits else nb_bits2
69 nb_bits2 -= read
70 self.bits -= read
71 value |= (self.byte >> self.bits) << nb_bits2
72 return value & ((1 << nb_bits) - 1)
64 73
65 74
66 cpdef write_bit(BitStream self, bit): 75 cpdef write_bit(BitStream self, bit):
67 if self.bits == 8: 76 if self.bits == 8:
68 self.io.write(chr(self.byte)) 77 self.io.write(chr(self.byte))