forked from zigimg/zigimg
/
utils.zig
74 lines (63 loc) · 2.33 KB
/
utils.zig
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
const builtin = std.builtin;
const std = @import("std");
const io = std.io;
const meta = std.meta;
const image = @import("image.zig");
pub fn toMagicNumberNative(magic: []const u8) u32 {
var result: u32 = 0;
for (magic) |character, index| {
result |= (@as(u32, character) << @intCast(u5, (index * 8)));
}
return result;
}
pub fn toMagicNumberForeign(magic: []const u8) u32 {
var result: u32 = 0;
for (magic) |character, index| {
result |= (@as(u32, character) << @intCast(u5, (magic.len - 1 - index) * 8));
}
return result;
}
pub const toMagicNumberBig = switch (builtin.endian) {
builtin.Endian.Little => toMagicNumberForeign,
builtin.Endian.Big => toMagicNumberNative,
};
pub const toMagicNumberLittle = switch (builtin.endian) {
builtin.Endian.Little => toMagicNumberNative,
builtin.Endian.Big => toMagicNumberForeign,
};
pub fn readStructNative(reader: image.ImageReader, comptime T: type) !T {
return try reader.readStruct(T);
}
pub fn readStructForeign(reader: image.ImageReader, comptime T: type) !T {
comptime std.debug.assert(@typeInfo(T).Struct.layout != builtin.TypeInfo.ContainerLayout.Auto);
var result: T = undefined;
inline for (meta.fields(T)) |entry| {
switch (@typeInfo(entry.field_type)) {
.ComptimeInt, .Int => {
@field(result, entry.name) = try reader.readIntForeign(entry.field_type);
},
.Struct => {
@field(result, entry.name) = try readStructForeign(reader, entry.field_type);
},
.Enum => {
@field(result, entry.name) = try reader.readEnum(entry.field_type, switch (builtin.endian) {
builtin.Endian.Little => builtin.Endian.Big,
builtin.Endian.Big => builtin.Endian.Little,
});
},
else => {
unreachable;
//@panic("Add support for type {} in readStructForeign");//, .{@typeName(entry.field_type)});
},
}
}
return result;
}
pub const readStructLittle = switch (builtin.endian) {
builtin.Endian.Little => readStructNative,
builtin.Endian.Big => readStructForeign,
};
pub const readStructBig = switch (builtin.endian) {
builtin.Endian.Little => readStructForeign,
builtin.Endian.Big => readStructNative,
};