-
-
Notifications
You must be signed in to change notification settings - Fork 23
/
bitmap.py
87 lines (65 loc) · 2.26 KB
/
bitmap.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
"""
The BitMap library provides tools to interact with a highly efficient datastructure
that stores boolean values with minimal overhead (1 bit per bool)
"""
BitMap = bytes
BYTE_SIZE = 8
POWS = [2**i for i in range(BYTE_SIZE)]
def init_bitmap(size: int) -> BitMap:
"""Creates an empty bitmap with size bits"""
return b"\x00" * ((size + BYTE_SIZE - 1) // BYTE_SIZE)
def test_bitmap(bmp: BitMap, i: int) -> bool:
"""Tests if bit at position i has been set to 1"""
byte = bmp[i // BYTE_SIZE]
bit = (byte // POWS[(BYTE_SIZE - 1) - (i % BYTE_SIZE)]) % 2
return bit == 1
def _set_bitmap(bmp: BitMap, i: int, v: bool) -> BitMap:
"""
Sets a bit in the bitmap to the specified value
i: index of the value to set
v: value of the bit to be set (0 or 1)
"""
scaled_i = i // BYTE_SIZE
byte = bmp[scaled_i]
powi = POWS[(BYTE_SIZE - 1) - (i % BYTE_SIZE)]
bit = (byte // powi) % 2
if bit == v:
new_byte = byte
elif not v:
# v == 0
new_byte = byte - powi
else:
# v == 1
new_byte = byte + powi
return bmp[:scaled_i] + bytes([new_byte]) + bmp[scaled_i + 1 :]
def set_bitmap(bmp: BitMap, i: int) -> BitMap:
"""Sets a bit in the bitmap to 1"""
return _set_bitmap(bmp, i, True)
def reset_bitmap(bmp: BitMap, i: int) -> BitMap:
"""Sets a bit in the bitmap to 0"""
return _set_bitmap(bmp, i, False)
def flip_bitmap(bmp: BitMap, i: int) -> BitMap:
"""Flips a bit in the bitmap"""
scaled_i = i // BYTE_SIZE
byte = bmp[scaled_i]
powi = POWS[(BYTE_SIZE - 1) - (i % BYTE_SIZE)]
bit = (byte // powi) % 2
if bit == 1:
# v == 0
new_byte = byte - powi
else:
# v == 1
new_byte = byte + powi
return bmp[:scaled_i] + bytes([new_byte]) + bmp[scaled_i + 1 :]
def size_bitmap(bmp: BitMap) -> int:
"""Returns the size of the bitmap in bits"""
return len(bmp) * BYTE_SIZE
def any_bitmap(b: BitMap) -> bool:
"""Returns whether any bit was set to 1"""
return b != (b"\x00" * len(b))
def all_bitmap(b: BitMap) -> bool:
"""Returns whether all bits were set to 1"""
return b == (b"\xFF" * len(b))
def none_bitmap(b: BitMap) -> bool:
"""Returns whether no bits were set to 1"""
return b == (b"\x00" * len(b))