summaryrefslogtreecommitdiffstats
path: root/crawl-ref/source/python/binfile.py
blob: 2ebb986539b31631b664a8f09b13bcf7b5d6940a (plain) (blame)
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
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
import struct

class reader(object):
    """Wrapper around a read-only binary file"""
    def __init__(self, fileorname):
        """fileorname may be a file-like object or a filename"""
        self.byteorder = '='    # can also be '<' or '>'
        if hasattr(fileorname, 'read'):
            self.file = fileorname
        else:
            self.file = file(fileorname, 'rb')

    def read(self,len): return self.file.read(len)

    def stream(self, fmt, len=0):
        """Unpack fmt from f and return results."""
        fmt = self.byteorder + fmt                 # don't enforce alignment!
        if len == 0: len = struct.calcsize(fmt)
        data = self.file.read(len)
        return struct.unpack(fmt, data)

    def stream1(self, fmt, len=0):
        """Unpack fmt from f and return just one result."""
        (data,) = self.stream(fmt,len)
        return data

    def _streamStringLow(self, len):
        if len <= 0: return ''
        str = self.file.read(len-1)
        char = self.file.read(1)
        if ord(char)==0: return str
        else: return str+char

    def streamCooky(self):
        l = list(self.stream("4c"))
        l.reverse()
        return ''.join(l)
        
    def streamString4(self):
        """Stream string prefixed with 4 bytes of length"""
        (strlen,) = self.stream("I",4)
        if strlen >= 2048:
            print "Bad string len: %#x" % strlen
            assert strlen < 2048
        return self._streamStringLow(strlen)

    def streamString2(self):
        """Stream string prefixed with 2 bytes of length"""
        (strlen,) = self.stream("H",2)
        assert strlen < 2048
        return self._streamStringLow(strlen)

    def streamString1(self):
        """Stream string prefixed with 1 byte of length"""
        (strlen,) = self.stream("B",1)
        assert strlen < 2048
        return self._streamStringLow(strlen)
    
class writer(object):
    """Wrapper around a write-only binary file"""
    def __init__(self, fileorname):
        """fileorname may be a file-like object or a filename"""
        if hasattr(fileorname, 'write'):
            self.file = fileorname
        else:
            self.file = file(fileorname, 'wb')

    def write(self,data): return self.file.write(data)
    def stream(self, fmt, *args):
        fmt = '='+fmt                   # add the "no alignment" flag to the fmt
        self.file.write(struct.pack(fmt, *args))
    # for symmetry with reader
    def stream1(self, fmt, *args):
        fmt = '='+fmt                   # add the "no alignment" flag to the fmt
        self.file.write(struct.pack(fmt, *args))

    def streamCooky(self, cooky):
        assert len(cooky)==4
        l = list(cooky)
        l.reverse()
        self.stream("4c", *l)
        
    def streamString1(self, str):
        """Stream string prefixed with 1 byte of length"""
        #print "writing %s" % str
        # Game doesn't handle 0-length null strings
        self.file.write(struct.pack("B",len(str)+1))
        self.file.write(str)
        self.file.write("\0")

    def streamString2(self, str):
        """Stream string prefixed with 2 bytes of length"""
        #print "writing %s" % str
        # Game doesn't handle 0-length null strings
        self.file.write(struct.pack("H",len(str)+1))
        self.file.write(str)
        self.file.write("\0")

    def streamString4(self, str):
        """Stream string prefixed with 4 bytes of length"""
        if str=='':
            self.file.write(struct.pack("I",0))
        else:
            #print "writing %s" % str
            self.file.write(struct.pack("I",len(str)+1))
            self.file.write(str)
            self.file.write("\0")