forked from retreev/io_scene_mpet
-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathioutil.py
55 lines (38 loc) · 1.36 KB
/
ioutil.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
# ioutil.py - Just some simple utilities for reading/writing C-style data.
# Every project has to have it's own little utility functions. It sucks but
# it's better than repeating yourself ad nauseum.
import struct
def wraptext(s, w):
return [s[i:i + w] for i in range(0, len(s), w)]
# read_struct reads struct data from a file-like object
def read_struct(file, fmt):
size = struct.calcsize(fmt)
data = file.read(size)
if len(data) < size:
print('warning: short struct read (%i < %i)' % (len(data), size))
return struct.unpack(fmt, data)
# write_struct writes struct data to a file-like object
def write_struct(file, fmt, *args):
file.write(struct.pack(fmt, *args))
# read_cstr reads a C-style string (and returns a `bytes` object.)
def read_cstr(file):
buf = bytearray()
while True:
b = file.read(1)
if b == '' or b == b'\x00':
return bytes(buf)
else:
buf.append(ord(b))
# write_cstr writes a C-style string
def write_cstr(file, buf):
file.write(buf + '\x00')
def read_fixed_string(file):
length, = read_struct(file, '<I')
if length <= 0:
return b''
return read_struct(file, "<{}s".format(length))[0].split(b'\x00')[0]
def write_fixed_string(file, buff):
length = len(buff)
write_struct(file, '<I', length)
if length > 0:
file.write(buff)