-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathchunks.py
executable file
·57 lines (41 loc) · 1.39 KB
/
chunks.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
from struct import Struct
from struct import error as struct_error
from .namedstruct import NamedStruct
chunk = Struct('<4si')
def chunks(data, overrides = {}):
"""
generator giving all off the IFF chunks in a buffer
does not handle bad input :(
"""
counter, filesize = 0, len(data)
last = None
while counter < filesize:
try:
magic, size = chunk.unpack_from(data, counter)
except struct_error as e:
print('failed loading chunk from', data[:counter])
print('last chunk:', last)
raise e
counter += chunk.size
contents = data[counter:counter+size]
if magic[3] != 0x4D:
raise Exception('bad magic', magic, 'last chunk:', last)
if magic in overrides:
size = overrides[magic]
yield magic, size, contents
counter += size
last = (magic, size, contents)
def parse(data, cnkformat):
result = {}
for id, size, data in chunks(data):
magic_as_str = id[::-1].decode()
if not magic_as_str in cnkformat:
print(f'format for {magic_as_str} not specified')
continue
format_decl = cnkformat[magic_as_str]
result[magic_as_str] = format_decl.unpack(data)
return result
def makechunk(cc, data):
assert type(cc) == str
assert type(data) == str
return cc + str( len(data) ) + data