-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathdatafile.d
135 lines (127 loc) · 2.43 KB
/
datafile.d
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
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
import std.file;
import std.stdio;
final class DataFile
{
string filename;
private:
immutable(ubyte)[] data;
size_t pos;
public:
this(string filename)
{
this.filename = filename;
this.data = cast(immutable(ubyte)[]).read(filename);
}
this(DataFile other, size_t start)
{
this.filename = other.filename;
this.data = other.data[start..$];
}
ubyte peekByte()
{
return data[pos];
}
ubyte readByte()
{
return data[pos++];
}
ushort readWordLE()
{
auto d = data[pos..pos+2];
pos += 2;
return getWordLE(d);
}
uint readDwordLE()
{
auto d = data[pos..pos+4];
pos += 4;
return getDwordLE(d);
}
uint readDwordBE()
{
auto d = data[pos..pos+4];
pos += 4;
return getDwordBE(d);
}
T read(T)()
{
auto d = data[pos..pos+T.sizeof];
pos += T.sizeof;
return (cast(T[])d)[0];
}
T peek(T)()
{
auto d = data[pos..pos+T.sizeof];
return (cast(T[])d)[0];
}
bool empty()
{
return pos == data.length;
}
void seek(size_t pos)
{
this.pos = pos;
}
size_t tell()
{
return pos;
}
void alignto(size_t num)
{
pos += num-1;
pos &= ~(num-1);
}
immutable(ubyte)[] readBytes(size_t n)
{
auto d = data[pos..pos+n];
pos += n;
return d;
}
immutable(ubyte)[] readPreString()
{
return readBytes(read!ubyte());
}
immutable(ubyte)[] readZString()
{
auto save = pos;
while(data[pos])
pos++;
return data[save..pos++];
}
}
ubyte getByte(ref immutable(ubyte)[] d)
{
ubyte r = d[0];
d = d[1..$];
return r;
}
ushort getWordLE(ref immutable(ubyte)[] d)
{
ushort r = d[0] | (d[1] << 8);
d = d[2..$];
return r;
}
ushort getWordBE(ref immutable(ubyte)[] d)
{
ushort r = d[1] | (d[0] << 8);
d = d[2..$];
return r;
}
uint getDwordLE(ref immutable(ubyte)[] d)
{
uint r = d[0] | (d[1] << 8) | (d[2] << 16) | (d[3] << 24);
d = d[4..$];
return r;
}
uint getDwordBE(ref immutable(ubyte)[] d)
{
uint r = d[3] | (d[2] << 8) | (d[1] << 16) | (d[0] << 24);
d = d[4..$];
return r;
}
immutable(ubyte)[] getBytes(ref immutable(ubyte)[] d, size_t n)
{
immutable(ubyte)[] r = d[0..n];
d = d[n..$];
return r;
}