Mercurial > touhou
comparison pytouhou/utils/bitstream.pyx @ 131:fab7ad2f0d8b
Use Cython, improve performances!
author | Thibaut Girka <thib@sitedethib.com> |
---|---|
date | Sun, 11 Sep 2011 02:02:59 +0200 |
parents | pytouhou/utils/bitstream.py@ac2e5e1c2c3c |
children | b5c7369abd7c |
comparison
equal
deleted
inserted
replaced
130:11ab06f4c4c6 | 131:fab7ad2f0d8b |
---|---|
1 # -*- encoding: utf-8 -*- | |
2 ## | |
3 ## Copyright (C) 2011 Thibaut Girka <thib@sitedethib.com> | |
4 ## | |
5 ## This program is free software; you can redistribute it and/or modify | |
6 ## it under the terms of the GNU General Public License as published | |
7 ## by the Free Software Foundation; version 3 only. | |
8 ## | |
9 ## This program is distributed in the hope that it will be useful, | |
10 ## but WITHOUT ANY WARRANTY; without even the implied warranty of | |
11 ## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the | |
12 ## GNU General Public License for more details. | |
13 ## | |
14 | |
15 cdef class BitStream: | |
16 cdef public io | |
17 cdef public int bits | |
18 cdef public int byte | |
19 | |
20 def __init__(BitStream self, io): | |
21 self.io = io | |
22 self.bits = 0 | |
23 self.byte = 0 | |
24 | |
25 | |
26 def __enter__(self): | |
27 return self | |
28 | |
29 | |
30 def __exit__(self, type, value, traceback): | |
31 return self.io.__exit__(type, value, traceback) | |
32 | |
33 | |
34 def seek(BitStream self, offset, whence=0): | |
35 self.io.seek(offset, whence) | |
36 self.byte = 0 | |
37 self.bits = 0 | |
38 | |
39 | |
40 def tell(BitStream self): | |
41 return self.io.tell() | |
42 | |
43 | |
44 def tell2(BitStream self): | |
45 return self.io.tell(), self.bits | |
46 | |
47 | |
48 cpdef unsigned char read_bit(BitStream self): | |
49 if not self.bits: | |
50 self.byte = ord(self.io.read(1)) | |
51 self.bits = 8 | |
52 self.bits -= 1 | |
53 return (self.byte >> self.bits) & 0x01 | |
54 | |
55 | |
56 def read(BitStream self, nb_bits): | |
57 cdef unsigned int value | |
58 value = 0 | |
59 for i in range(nb_bits - 1, -1, -1): | |
60 value |= self.read_bit() << i | |
61 return value | |
62 | |
63 | |
64 cpdef write_bit(BitStream self, bit): | |
65 if self.bits == 8: | |
66 self.io.write(chr(self.byte)) | |
67 self.bits = 0 | |
68 self.byte = 0 | |
69 self.byte &= ~(1 << (7 - self.bits)) | |
70 self.byte |= bit << (7 - self.bits) | |
71 self.bits += 1 | |
72 | |
73 | |
74 def write(BitStream self, bits, nb_bits): | |
75 for i in range(nb_bits): | |
76 self.write_bit(bits >> (nb_bits - 1 - i) & 0x01) | |
77 | |
78 | |
79 def flush(BitStream self): | |
80 self.io.write(chr(self.byte)) | |
81 self.bits = 0 | |
82 self.byte = 0 | |
83 self.io.flush() | |
84 |