-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathByteReader.cs
More file actions
306 lines (261 loc) · 9.25 KB
/
ByteReader.cs
File metadata and controls
306 lines (261 loc) · 9.25 KB
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
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
using Dat.Types;
using Definitions.ObjectModels;
using System.Diagnostics.CodeAnalysis;
namespace Dat.FileParsing;
public static class ByteReader
{
[RequiresUnreferencedCode("ReadT uses reflection-based type handling and may call ReadLocoStruct which requires unreferenced code.")]
public static object ReadT(ReadOnlySpan<byte> data, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.All)] Type t, int offset, int arrLength = 0, bool isVariableLoad = false)
{
if (t == typeof(uint8_t))
{
var val = ByteReaderT.Read_uint8t(data, offset);
if (isVariableLoad && val != 0)
{
throw new InvalidDataException($"uint8_t at offset {offset} had non-zero variable-load data. Value={val}");
}
return val;
}
if (t == typeof(int8_t))
{
var val = ByteReaderT.Read_int8t(data, offset);
if (isVariableLoad && val != 0)
{
throw new InvalidDataException($"int8_t at offset {offset} had non-zero variable-load data. Value={val}");
}
return val;
}
if (t == typeof(uint16_t))
{
var val = ByteReaderT.Read_uint16t(data, offset);
if (isVariableLoad && val != 0)
{
throw new InvalidDataException($"uint16_t at offset {offset} had non-zero variable-load data. Value={val}");
}
return val;
}
if (t == typeof(int16_t))
{
var val = ByteReaderT.Read_int16t(data, offset);
if (isVariableLoad && val != 0)
{
throw new InvalidDataException($"int16_t at offset {offset} had non-zero variable-load data. Value={val}");
}
return val;
}
if (t == typeof(uint32_t))
{
var val = ByteReaderT.Read_uint32t(data, offset);
if (isVariableLoad && val != 0)
{
throw new InvalidDataException($"uint32_t at offset {offset} had non-zero variable-load data. Value={val}");
}
return val;
}
if (t == typeof(int32_t))
{
var val = ByteReaderT.Read_int32t(data, offset);
if (isVariableLoad && val != 0)
{
throw new InvalidDataException($"int32_t at offset {offset} had non-zero variable-load data. Value={val}");
}
return val;
}
if (t == typeof(string_id))
{
return ByteReaderT.Read_uint16t(data, offset);
}
if (t == typeof(bool))
{
return ByteReaderT.Read_bool(data, offset);
}
if (t.IsArray)
{
return ReadArray(data, t, offset, arrLength, isVariableLoad);
}
if (t.IsEnum) // this is so big because we need special handling for 'flags' enums
{
return ReadEnum(data, t, offset);
}
if (t.IsClass)
{
return ReadClass(data, t, offset);
}
throw new NotImplementedException(t.ToString());
}
static Array ReadArray(ReadOnlySpan<byte> data, Type t, int offset, int arrLength, bool isVariableLoad)
{
var elementType = t.GetElementType() ?? throw new ArgumentNullException(t.Name);
var size = ByteHelpers.GetObjectSize(elementType);
var arr = Array.CreateInstance(elementType, arrLength);
for (var i = 0; i < arrLength; i++)
{
arr.SetValue(ReadT(data, elementType, offset + (i * size), isVariableLoad: isVariableLoad), i); // why pass 'i' in here?
}
return arr;
}
static object ReadClass(ReadOnlySpan<byte> data, Type t, int offset)
{
if (t.Name == "ObjectHeader")
{
return ObjectHeader.Read(data[..ObjectHeader.StructLength]);
}
else if (t.Name == "S5Header")
{
return S5Header.Read(data[..S5Header.StructLength]);
}
var objectSize = ByteHelpers.GetObjectSize(t);
return ReadLocoStruct(data[offset..(offset + objectSize)], t);
}
static object ReadEnum(ReadOnlySpan<byte> data, Type t, int offset)
{
var underlyingType = t.GetEnumUnderlyingType();
var underlyingValue = ReadT(data, underlyingType, offset);
if (!t.IsDefined(typeof(FlagsAttribute), inherit: false))
{
return Enum.ToObject(t, underlyingValue);
}
var enumValues = Enum.GetValues(t);
if (underlyingType == typeof(int8_t) || underlyingType == typeof(int16_t) || underlyingType == typeof(int32_t))
{
var combinedValue = 0;
foreach (var enumValue in enumValues)
{
var parsed = Enum.Parse(t, enumValue.ToString()!);
var enumValueInt = Convert.ToInt32(parsed); // Convert to int
if ((enumValueInt & Convert.ToInt32(underlyingValue)) != 0) // Convert to int
{
combinedValue |= enumValueInt;
}
}
return Enum.ToObject(t, combinedValue);
}
else if (underlyingType == typeof(uint8_t) || underlyingType == typeof(uint16_t) || underlyingType == typeof(uint32_t))
{
var combinedValue = 0U;
foreach (var enumValue in enumValues)
{
var parsed = Enum.Parse(t, enumValue.ToString()!);
var enumValueInt = Convert.ToUInt32(parsed); // Convert to int
if ((enumValueInt & Convert.ToUInt32(underlyingValue)) != 0) // Convert to int
{
combinedValue |= enumValueInt;
}
}
return Enum.ToObject(t, combinedValue);
}
else
{
throw new ArgumentOutOfRangeException(nameof(underlyingType), underlyingType, "unrecognised type");
}
}
[RequiresUnreferencedCode("ReadLocoStruct uses reflection to read public properties and invoke constructors of the target type, which may be trimmed.")]
public static T ReadLocoStruct<T>(ReadOnlySpan<byte> data) where T : class
=> (T)ReadLocoStruct(data, typeof(T));
[RequiresUnreferencedCode("ReadLocoStruct uses reflection to read public properties and invoke constructors of the target type, which may be trimmed.")]
public static ILocoStruct ReadLocoStruct(ReadOnlySpan<byte> data, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicProperties | DynamicallyAccessedMemberTypes.PublicConstructors)] Type t)
{
var properties = t.GetProperties();
var args = new List<object>();
foreach (var p in properties)
{
// ignore non-loco properties on the records
var offsetAttr = AttributeHelper.Get<LocoStructOffsetAttribute>(p);
if (offsetAttr == null)
{
continue;
}
// ignore skipped properties (usually image ids and string ids which are only used in loco itself, not this tool
var skip = AttributeHelper.Get<LocoStructSkipReadAttribute>(p);
if (skip != null)
{
continue;
}
// special array handling
var arrLength = 0;
if (p.PropertyType.IsArray)
{
var arrLengthAttr = AttributeHelper.Get<LocoArrayLengthAttribute>(p) ?? throw new ArgumentOutOfRangeException(nameof(data), $"type {t} with property {p} didn't have LocoArrayLength attribute specified");
arrLength = arrLengthAttr.Length;
}
// ignore pointers/variable data - they'll be loaded later in Load()
var variableAttr = AttributeHelper.Get<LocoStructVariableLoadAttribute>(p);
if (variableAttr != null)
{
if (p.PropertyType.IsArray)
{
// todo: find a generic way to do this
if (p.PropertyType.GetElementType() == typeof(uint8_t))
{
args.Add(new uint8_t[arrLength]);
}
else if (p.PropertyType.GetElementType() == typeof(int8_t))
{
args.Add(new int8_t[arrLength]);
}
else if (p.PropertyType.GetElementType() == typeof(uint16_t))
{
args.Add(new uint16_t[arrLength]);
}
else if (p.PropertyType.GetElementType() == typeof(int16_t))
{
args.Add(new int16_t[arrLength]);
}
else if (p.PropertyType.GetElementType() == typeof(uint32_t))
{
args.Add(new uint32_t[arrLength]);
}
else if (p.PropertyType.GetElementType() == typeof(int32_t))
{
args.Add(new int32_t[arrLength]);
}
}
else
{
var newInstance = Activator.CreateInstance(p.PropertyType);
ArgumentNullException.ThrowIfNull(newInstance, paramName: p.PropertyType.Name);
args.Add(newInstance!);
}
continue;
}
args.Add(ReadT(data, p.PropertyType, offsetAttr.Offset, arrLength, variableAttr != null));
}
return (ILocoStruct?)Activator.CreateInstance(t, [.. args]) ?? throw new InvalidDataException("couldn't parse");
}
[RequiresUnreferencedCode("ReadLocoStructArray uses reflection to read public properties and invoke constructors of the target type, which may be trimmed.")]
public static IList<ILocoStruct> ReadLocoStructArray(ReadOnlySpan<byte> data, [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicProperties | DynamicallyAccessedMemberTypes.PublicConstructors)] Type t, int count, int structSize) // could get struct size from attribute, but easier just to pass in
{
// cannot use ReadOnlySpan with yield return :|
var list = new List<ILocoStruct>();
for (var i = 0; i < count; ++i)
{
var range = data[(i * structSize)..((i + 1) * structSize)];
list.Add(ReadLocoStruct(range, t));
}
return list;
}
//public static IList<ILocoStruct> ReadLocoStructArray(ReadOnlySpan<byte> data, Type t, int count)
//{
// // cannot use ReadOnlySpan with yield return :|
// var structSize = data.Length / count;
// var list = new List<ILocoStruct>();
// for (var i = 0; i < count; ++i)
// {
// var range = data[(i * structSize)..((i + 1) * structSize)];
// list.Add(ReadLocoStruct(range, t));
// }
// return list;
//}
[RequiresUnreferencedCode("ReadLocoStructArray uses reflection to read public properties and invoke constructors of the target type, which may be trimmed.")]
public static IList<T> ReadLocoStructArray<T>(ReadOnlySpan<byte> data, int count, int structSize) where T : class
{
// cannot use ReadOnlySpan with yield return :|
var list = new List<T>();
for (var i = 0; i < count; ++i)
{
var range = data[(i * structSize)..((i + 1) * structSize)];
list.Add(ReadLocoStruct<T>(range));
}
return list;
}
}