-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathutil.zig
313 lines (247 loc) · 9.29 KB
/
util.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
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
307
308
309
310
311
312
313
const std = @import("std");
const slab = @import("slab.zig");
const Glyph = @import("font").Glyph;
const log = std.log.scoped(.util);
//
pub const Base = enum {
binary,
decimal,
};
pub fn NumberPrefix(comptime T: type, comptime base: Base) type {
return struct {
num: T,
pub const Self = @This();
pub fn new(num: T) Self {
return Self{
.num = num,
};
}
// format(actual_fmt, options, writer);
pub fn format(self: Self, comptime _: []const u8, opts: std.fmt.FormatOptions, writer: anytype) !void {
var num = self.num;
const prec = opts.precision orelse 1;
switch (base) {
.binary => {
const table: [10][]const u8 = .{ "", "Ki", "Mi", "Gi", "Ti", "Pi", "Ei", "Zi", "Yi", "Ri" };
for (table) |scale| {
if (num < 1024 * prec) {
return std.fmt.format(writer, "{d} {s}", .{ num, scale });
}
num /= 1024;
}
return std.fmt.format(writer, "{d} Qi", .{num});
},
.decimal => {
const table: [10][]const u8 = .{ "", "K", "M", "G", "T", "P", "E", "Z", "Y", "R" };
for (table) |scale| {
if (num < 1000 * prec) {
return std.fmt.format(writer, "{d} {s}", .{ num, scale });
}
num /= 1000;
}
return std.fmt.format(writer, "{d} Q", .{num});
},
}
}
};
}
/// print the offset of each field in hex
pub fn debugFieldOffsets(comptime T: type) void {
const s = @typeInfo(T).Struct;
const v: T = undefined;
log.info("struct {any} field offsets:", .{T});
inline for (s.fields) |field| {
const offs = @intFromPtr(&@field(&v, field.name)) - @intFromPtr(&v);
log.info(" - 0x{x}: {s}", .{ offs, field.name });
}
}
// less effort than spamming align(1) on every field,
// since zig packed structs are not like in every other language
pub fn pack(comptime T: type) type {
var s = comptime @typeInfo(T).Struct;
const n_fields = comptime s.fields.len;
var fields: [n_fields]std.builtin.Type.StructField = undefined;
inline for (0..n_fields) |i| {
fields[i] = s.fields[i];
fields[i].alignment = 1;
}
s.fields = fields[0..];
return @Type(std.builtin.Type{ .Struct = s });
}
pub const Parser = struct {
bytes: []const u8,
pub fn init(bytes: []const u8) Parser {
return .{ .bytes = bytes };
}
pub fn read(self: *Parser, comptime T: type) !T {
switch (@typeInfo(T)) {
.Int => return try self.readInt(T),
.Array => return try self.readArray(T),
.Struct => return try self.readStruct(T),
else => @compileError("unsupported type"),
}
}
pub fn readInt(self: *Parser, comptime T: type) !T {
const size = @sizeOf(T);
if (self.bytes.len <= size) {
return error.UnexpectedEof;
}
const value: *align(1) const T = @ptrCast(self.bytes);
self.bytes = self.bytes[size..];
return value.*;
}
pub fn readArray(self: *Parser, comptime T: type) !T {
if (self.bytes.len <= @sizeOf(T)) {
return error.UnexpectedEof;
}
const array = @typeInfo(T).Array;
var instance: [array.len]array.child = undefined;
inline for (0..array.len) |i| {
instance[i] = try self.read(array.child);
}
return instance;
}
pub fn readStruct(self: *Parser, comptime T: type) !T {
if (self.bytes.len <= @sizeOf(T)) {
return error.UnexpectedEof;
}
const fields = @typeInfo(T).Struct.fields;
var instance: T = undefined;
inline for (fields) |field| {
@field(instance, field.name) = try self.read(field.type);
}
return instance;
}
pub fn bytesLeft(self: *const Parser) []const u8 {
return self.bytes;
}
};
pub fn Image(storage: type) type {
return struct {
width: u32,
height: u32,
pitch: u32,
bits_per_pixel: u16,
pixel_array: storage,
const Self = @This();
pub fn debug(self: *const Self) void {
std.log.debug("addr: {*}, size: {d}", .{ self.pixel_array, self.height * self.pitch });
}
pub fn subimage(self: *const Self, x: u32, y: u32, w: u32, h: u32) error{OutOfBounds}!Image(@TypeOf(self.pixel_array[0..])) {
if (self.width < x + w or self.height < y + h) {
return error.OutOfBounds;
}
const offs = x * self.bits_per_pixel / 8 + y * self.pitch;
return .{
.width = w,
.height = h,
.pitch = self.pitch,
.bits_per_pixel = self.bits_per_pixel,
.pixel_array = @ptrCast(self.pixel_array[offs..]),
};
}
pub fn fill(self: *const Self, r: u8, g: u8, b: u8) void {
const pixel = [4]u8{ r, g, b, 0 }; // 4 becomes a u32
const pixel_size = self.bits_per_pixel / 8;
for (0..self.height) |y| {
for (0..self.width) |x| {
const dst: *[4]u8 = @ptrCast(&self.pixel_array[x * pixel_size + y * self.pitch]);
dst.* = pixel;
}
}
}
pub fn fillGlyph(self: *const Self, glyph: *const Glyph) void {
// if (self.width != 16) {
// return
// }
const pixel_size = self.bits_per_pixel / 8;
for (0..self.height) |y| {
for (0..self.width) |x| {
const bit: u8 = @truncate((glyph.img[y] >> @intCast(x)) & 1);
const is_white: u8 = bit * 255;
const dst: *volatile [4]u8 = @ptrCast(&self.pixel_array[x * pixel_size + y * self.pitch]);
dst.* = [4]u8{ is_white, is_white, is_white, 0 };
}
}
}
pub fn copyTo(from: *const Self, to: anytype) error{ SizeMismatch, BppMismatch }!void {
if (from.width != to.width or from.height != to.height) {
return error.SizeMismatch;
}
if (from.bits_per_pixel != to.bits_per_pixel) {
return error.BppMismatch;
}
const from_row_width = from.width * from.bits_per_pixel / 8;
const to_row_width = to.width * to.bits_per_pixel / 8;
for (0..to.height) |y| {
const from_row = y * from.pitch;
const to_row = y * to.pitch;
const from_row_slice = from.pixel_array[from_row .. from_row + from_row_width];
const to_row_slice = to.pixel_array[to_row .. to_row + to_row_width];
std.mem.copyForwards(u8, to_row_slice, from_row_slice);
}
}
pub fn copyPixelsTo(from: *const Self, to: anytype) error{SizeMismatch}!void {
if (from.width != to.width or from.height != to.height) {
return error.SizeMismatch;
}
if (from.bits_per_pixel == to.bits_per_pixel) {
return copyTo(from, to) catch unreachable;
}
const from_pixel_size = from.bits_per_pixel / 8;
const to_pixel_size = to.bits_per_pixel / 8;
for (0..to.height) |y| {
for (0..to.width) |x| {
const from_idx = x * from_pixel_size + y * from.pitch;
const from_pixel: *const Pixel = @ptrCast(&from.pixel_array[from_idx]);
const to_idx = x * to_pixel_size + y * to.pitch;
const to_pixel: *Pixel = @ptrCast(&to.pixel_array[to_idx]);
// print("loc: {d},{d}", .{ x, y });
// print("from: {*} to: {*}", .{ from_pixel, to_pixel });
to_pixel.* = from_pixel.*;
}
}
}
};
}
const Pixel = struct {
red: u8,
green: u8,
blue: u8,
};
//
pub fn Arc(comptime T: type) type {
return struct {
val: *Inner,
const Inner = struct {
val: T,
count: std.atomic.Value(usize),
};
const Self = @This();
pub fn init(val: T) std.mem.Allocator.Error!Self {
const new = try slab.global_allocator.allocator().create(Inner);
new.val = val;
new.count = .{ .raw = 0 };
return .{ .val = new };
}
pub fn clone(self: Self) !Self {
const old = self.val.count.fetchAdd(1, .monotonic);
if (old >= (std.math.maxInt(usize) >> 1)) {
@setCold(true);
return error.TooManyRefs;
}
return .{ .val = self.val };
}
pub fn deinit(self: Self) void {
const cnt = self.val.count.fetchSub(1, .release);
if (cnt >= 2) {
return;
}
@setCold(true);
slab.global_allocator.allocator().destroy(self.val);
}
pub fn get(self: Self) *T {
return &self.val.val;
}
};
}