Debian Codegraph @

debian/rust-vendor/codspeed/instrument-hooks/src/bincode.zig

raw
1 // Taken from here: https://github.com/qbradley/bincode-zig/blob/main/bincode.zig
2
3 const std = @import("std");
4 const utils = @import("./utils.zig");
5
6 pub fn deserializeAlloc(stream: anytype, allocator: std.mem.Allocator, comptime T: type) !T {
7 return switch (@typeInfo(T)) {
8 .void => {},
9 .bool => try deserializeBool(stream),
10 .float => try deserializeFloat(stream, T),
11 .int => try deserializeInt(stream, T),
12 .optional => |info| try deserializeOptionalAlloc(stream, allocator, info.child),
13 .pointer => |info| try deserializePointerAlloc(stream, info, allocator),
14 .array => |info| try deserializeArrayAlloc(stream, info, allocator),
15 .@"struct" => |info| try deserializeStructAlloc(stream, info, allocator, T),
16 .@"enum" => try deserializeEnum(stream, T),
17 .@"union" => |info| try deserializeUnionAlloc(stream, info, allocator, T),
18 else => unsupportedType(T),
19 };
20 }
21
22 pub fn deserialize(stream: anytype, comptime T: type) !T {
23 return switch (@typeInfo(T)) {
24 .void => {},
25 .bool => try deserializeBool(stream),
26 .float => try deserializeFloat(stream, T),
27 .int => try deserializeInt(stream, T),
28 .optional => |info| try deserializeOptional(stream, info.child),
29 .array => |info| try deserializeArray(stream, info),
30 .@"struct" => |info| try deserializeStruct(stream, info, T),
31 .@"enum" => try deserializeEnum(stream, T),
32 .@"union" => |info| try deserializeUnion(stream, info, T),
33 else => unsupportedType(T),
34 };
35 }
36
37 pub fn deserializeBuffer(comptime T: type, source: *[]const u8) T {
38 return switch (@typeInfo(T)) {
39 .void => {},
40 .bool => deserializeBufferBool(source),
41 .float => deserializeBufferFloat(T, source),
42 .int => deserializeBufferInt(T, source),
43 .optional => |info| deserializeBufferOptional(info.child, source),
44 .pointer => |info| deserializeBufferPointer(info, source),
45 .array => |info| deserializeBufferArray(info, source),
46 .@"struct" => |info| deserializeBufferStruct(T, info, source),
47 .@"enum" => deserializeBufferEnum(T, source),
48 .@"union" => |info| deserializeBufferUnion(T, info, source),
49 else => unsupportedType(T),
50 };
51 }
52
53 pub fn serialize(stream: anytype, value: anytype) @TypeOf(stream).Error!void {
54 const T = @TypeOf(value);
55 return switch (@typeInfo(T)) {
56 .void => {},
57 .bool => try serializeBool(stream, value),
58 .float => try serializeFloat(stream, T, value),
59 .int => try serializeInt(stream, T, value),
60 .optional => |info| try serializeOptional(stream, info.child, value),
61 .pointer => |info| try serializePointer(stream, info, T, value),
62 .array => |info| try serializeArray(stream, info, T, value),
63 .@"struct" => |info| try serializeStruct(stream, info, T, value),
64 .@"enum" => try serializeEnum(stream, T, value),
65 .@"union" => |info| try serializeUnion(stream, info, T, value),
66 else => unsupportedType(T),
67 };
68 }
69
70 pub fn deserializeSliceIterator(comptime T: type, source: []const u8) DeserializeSliceIterator(T) {
71 return DeserializeSliceIterator(T){
72 .source = source,
73 };
74 }
75
76 pub fn DeserializeSliceIterator(comptime T: type) type {
77 return struct {
78 source: []const u8,
79
80 pub fn next(self: *@This()) ?T {
81 if (self.source.len > 0) {
82 return deserializeBuffer(T, &self.source);
83 } else {
84 return null;
85 }
86 }
87 };
88 }
89
90 fn deserializeBufferInt(comptime T: type, source_ptr: *[]const u8) T {
91 const bytesRequired = @sizeOf(T);
92 const source = source_ptr.*;
93 if (bytesRequired <= source.len) {
94 var tmp: [bytesRequired]u8 = undefined;
95 std.mem.copy(u8, &tmp, source[0..bytesRequired]);
96 source_ptr.* = source[bytesRequired..];
97 return std.mem.readIntLittle(T, &tmp);
98 } else {
99 invalidProtocol("Buffer ran out of bytes too soon.");
100 }
101 }
102
103 fn deserializeBufferBool(source: *[]const u8) bool {
104 return switch (deserializeBufferInt(u8, source)) {
105 0 => return false,
106 1 => return true,
107 else => invalidProtocol("Boolean values should be encoded as a single byte with value 0 or 1 only."),
108 };
109 }
110
111 fn deserializeBufferOptional(comptime T: type, source: *[]const u8) ?T {
112 if (deserializeBufferBool(source)) {
113 return deserializeBuffer(T, source);
114 } else {
115 return null;
116 }
117 }
118
119 fn deserializeBufferFloat(comptime T: type, source: *[]const u8) T {
120 switch (T) {
121 f32 => return @as(T, @bitCast(deserializeBufferInt(u32, source))),
122 f64 => return @as(T, @bitCast(deserializeBufferInt(u64, source))),
123 else => unsupportedType(T),
124 }
125 }
126
127 fn deserializeBufferEnum(comptime T: type, source: *[]const u8) T {
128 const raw_tag = deserializeBufferInt(u32, source);
129 return @enumFromInt(raw_tag);
130 }
131
132 fn deserializeBufferStruct(comptime T: type, comptime info: std.builtin.Type.Struct, source: *[]const u8) T {
133 var value: T = undefined;
134 inline for (info.fields) |field| {
135 @field(value, field.name) = deserializeBuffer(field.type, source);
136 }
137 return value;
138 }
139
140 fn deserializeBufferUnion(comptime T: type, comptime info: std.builtin.Type.Union, source: *[]const u8) T {
141 if (info.tag_type) |Tag| {
142 const raw_tag = deserializeBufferInt(u32, source);
143 const tag = @as(T, @enumFromInt(raw_tag));
144
145 inline for (info.fields) |field| {
146 if (tag == @field(Tag, field.name)) {
147 const inner = deserializeBuffer(field.type, source);
148 return @unionInit(T, field.name, inner);
149 }
150 }
151 unreachable;
152 } else {
153 unsupportedType(T);
154 }
155 }
156
157 fn deserializeBufferArray(comptime info: std.builtin.Type.Array, source_ptr: *[]const u8) [info.len]info.child {
158 const T = @Type(.{ .array = info });
159 if (info.sentinel_ptr != null) unsupportedType(T);
160 var value: T = undefined;
161 if (info.child == u8) {
162 const source = source_ptr.*;
163 if (info.len <= source.len) {
164 std.mem.copy(u8, &value, source[0..info.len]);
165 source_ptr.* = source[info.len..];
166 } else {
167 invalidProtocol("The stream end was found before all required bytes were read.");
168 }
169 } else {
170 for (0..info.len) |idx| {
171 value[idx] = deserializeBuffer(info.child, source_ptr);
172 }
173 }
174 return value;
175 }
176
177 fn deserializeBufferPointer(comptime info: std.builtin.Type.Pointer, source_ptr: *[]const u8) []const info.child {
178 const T = @Type(.{ .pointer = info });
179 if (info.sentinel_ptr != null) unsupportedType(T);
180 switch (info.size) {
181 .one => unsupportedType(T),
182 .slice => {
183 const len = @as(usize, @intCast(deserializeBufferInt(u64, source_ptr)));
184 if (info.child == u8) {
185 const source = source_ptr.*;
186 if (len <= source.len) {
187 source_ptr.* = source[len..];
188 return source[0..len];
189 } else {
190 invalidProtocol("The stream end was found before all required bytes were read.");
191 }
192 } else {
193 // we can't support a variable slice of types where the stream format
194 // differs from in-memory format without allocating.
195 unsupportedType(T);
196 }
197 },
198 .c => unsupportedType(T),
199 .many => unsupportedType(T),
200 }
201 }
202
203 fn deserializeBool(stream: anytype) !bool {
204 switch (try stream.readInt(u8, .little)) {
205 0 => return false,
206 1 => return true,
207 else => invalidProtocol("Boolean values should be encoded as a single byte with value 0 or 1 only."),
208 }
209 }
210
211 fn deserializeFloat(stream: anytype, comptime T: type) !T {
212 switch (T) {
213 f32 => return @as(T, @bitCast(try stream.readInt(u32, .little))),
214 f64 => return @as(T, @bitCast(try stream.readInt(u64, .little))),
215 else => unsupportedType(T),
216 }
217 }
218
219 fn deserializeInt(stream: anytype, comptime T: type) !T {
220 switch (T) {
221 i8 => return try stream.readInt(i8, .little),
222 i16 => return try stream.readInt(i16, .little),
223 i32 => return try stream.readInt(i32, .little),
224 i64 => return try stream.readInt(i64, .little),
225 i128 => return try stream.readInt(i128, .little),
226 u8 => return try stream.readInt(u8, .little),
227 u16 => return try stream.readInt(u16, .little),
228 u32 => return try stream.readInt(u32, .little),
229 u64 => return try stream.readInt(u64, .little),
230 u128 => return try stream.readInt(u128, .little),
231 else => unsupportedType(T),
232 }
233 }
234
235 fn deserializeOptionalAlloc(stream: anytype, allocator: std.mem.Allocator, comptime T: type) !?T {
236 switch (try stream.readInt(u8, .little)) {
237 // None
238 0 => return null,
239 // Some
240 1 => return try deserializeAlloc(stream, allocator, T),
241 else => invalidProtocol("Optional is encoded as a single 0 valued byte for null, or a single 1 valued byte followed by the encoding of the contained value."),
242 }
243 }
244
245 fn deserializeOptional(stream: anytype, comptime T: type) !?T {
246 switch (try stream.readInt(u8, .little)) {
247 // None
248 0 => return null,
249 // Some
250 1 => return try deserialize(stream, T),
251 else => invalidProtocol("Optional is encoded as a single 0 valued byte for null, or a single 1 valued byte followed by the encoding of the contained value."),
252 }
253 }
254
255 fn deserializePointerAlloc(stream: anytype, comptime info: std.builtin.Type.Pointer, allocator: std.mem.Allocator) ![]info.child {
256 const T = @Type(.{ .pointer = info });
257 if (info.sentinel_ptr != null) unsupportedType(T);
258 switch (info.size) {
259 .one => unsupportedType(T),
260 .slice => {
261 const len = @as(usize, @intCast(try stream.readInt(u64, .little)));
262 var memory = try allocator.alloc(info.child, len);
263 if (info.child == u8) {
264 const amount = try stream.readAll(memory);
265 if (amount != len) {
266 invalidProtocol("The stream end was found before all required bytes were read.");
267 }
268 } else {
269 for (0..len) |idx| {
270 memory[idx] = try deserializeAlloc(stream, allocator, info.child);
271 }
272 }
273 return memory;
274 },
275 .c => unsupportedType(T),
276 .many => unsupportedType(T),
277 }
278 }
279
280 fn deserializeArrayAlloc(stream: anytype, comptime info: std.builtin.Type.Array, allocator: std.mem.Allocator) ![info.len]info.child {
281 const T = @Type(.{ .array = info });
282 if (info.sentinel_ptr != null) unsupportedType(T);
283 var value: T = undefined;
284 if (info.child == u8) {
285 const amount = try stream.readAll(value[0..]);
286 if (amount != info.len) {
287 invalidProtocol("The stream end was found before all required bytes were read.");
288 }
289 } else {
290 for (0..info.len) |idx| {
291 value[idx] = try deserializeAlloc(stream, allocator, info.child);
292 }
293 }
294 return value;
295 }
296
297 fn deserializeArray(stream: anytype, comptime info: std.builtin.Type.Array) ![info.len]info.child {
298 const T = @Type(.{ .array = info });
299 if (info.sentinel_ptr != null) unsupportedType(T);
300 var value: T = undefined;
301 if (info.child == u8) {
302 const amount = try stream.readAll(value[0..]);
303 if (amount != info.len) {
304 invalidProtocol("The stream end was found before all required bytes were read.");
305 }
306 } else {
307 for (0..info.len) |idx| {
308 value[idx] = try deserialize(stream, info.child);
309 }
310 }
311 return value;
312 }
313
314 fn deserializeStructAlloc(stream: anytype, comptime info: std.builtin.Type.Struct, allocator: std.mem.Allocator, comptime T: type) !T {
315 var value: T = undefined;
316 inline for (info.fields) |field| {
317 @field(value, field.name) = try deserializeAlloc(stream, allocator, field.type);
318 }
319 return value;
320 }
321
322 fn deserializeStruct(stream: anytype, comptime info: std.builtin.Type.Struct, comptime T: type) !T {
323 var value: T = undefined;
324 inline for (info.fields) |field| {
325 @field(value, field.name) = try deserialize(stream, field.type);
326 }
327 return value;
328 }
329
330 fn deserializeEnum(stream: anytype, comptime T: type) !T {
331 const raw_tag = try deserializeInt(stream, u32);
332 return @as(T, @enumFromInt(raw_tag));
333 }
334
335 fn deserializeUnionAlloc(stream: anytype, comptime info: std.builtin.Type.Union, allocator: std.mem.Allocator, comptime T: type) !T {
336 if (info.tag_type) |Tag| {
337 const raw_tag = try deserializeAlloc(stream, allocator, u32);
338 const tag = @as(Tag, @enumFromInt(raw_tag));
339
340 inline for (info.fields) |field| {
341 if (tag == @field(Tag, field.name)) {
342 const inner = try deserializeAlloc(stream, allocator, field.type);
343 return @unionInit(T, field.name, inner);
344 }
345 }
346 unreachable;
347 } else {
348 unsupportedType(T);
349 }
350 }
351
352 fn deserializeUnion(stream: anytype, comptime info: std.builtin.Type.Union, comptime T: type) !T {
353 if (info.tag_type) |Tag| {
354 const raw_tag = try deserialize(stream, u32);
355 const tag = @as(Tag, @enumFromInt(raw_tag));
356
357 inline for (info.fields) |field| {
358 if (tag == @field(Tag, field.name)) {
359 const inner = try deserialize(stream, field.type);
360 return @unionInit(T, field.name, inner);
361 }
362 }
363 unreachable;
364 } else {
365 unsupportedType(T);
366 }
367 }
368
369 pub fn serializeBool(stream: anytype, value: bool) @TypeOf(stream).Error!void {
370 const code: u8 = if (value) @as(u8, 1) else @as(u8, 0);
371 return stream.writeIntLittle(u8, code);
372 }
373
374 pub fn serializeFloat(stream: anytype, comptime T: type, value: T) @TypeOf(stream).Error!void {
375 switch (T) {
376 f32 => try stream.writeIntLittle(u32, @as(u32, @bitCast(value))),
377 f64 => try stream.writeIntLittle(u64, @as(u64, @bitCast(value))),
378 else => unsupportedType(T),
379 }
380 }
381
382 pub fn serializeInt(stream: anytype, comptime T: type, value: T) @TypeOf(stream).Error!void {
383 switch (T) {
384 i8 => try stream.writeInt(i8, value, .little),
385 i16 => try stream.writeInt(i16, value, .little),
386 i32 => try stream.writeInt(i32, value, .little),
387 i64 => try stream.writeInt(i64, value, .little),
388 i128 => try stream.writeInt(i128, value, .little),
389 u8 => try stream.writeInt(u8, value, .little),
390 u16 => try stream.writeInt(u16, value, .little),
391 u32 => try stream.writeInt(u32, value, .little),
392 u64 => try stream.writeInt(u64, value, .little),
393 u128 => try stream.writeInt(u128, value, .little),
394 else => unsupportedType(T),
395 }
396 }
397
398 pub fn serializeOptional(stream: anytype, comptime T: type, value: ?T) @TypeOf(stream).Error!void {
399 if (value) |actual| {
400 try stream.writeInt(u8, 1, .little);
401 try serialize(stream, actual);
402 } else {
403 // None
404 try stream.writeInt(u8, 0, .little);
405 }
406 }
407
408 pub fn serializePointer(stream: anytype, comptime info: std.builtin.Type.Pointer, comptime T: type, value: T) @TypeOf(stream).Error!void {
409 if (info.sentinel_ptr != null) unsupportedType(T);
410 switch (info.size) {
411 .one => unsupportedType(T),
412 .slice => {
413 try stream.writeInt(u64, value.len, .little);
414 if (info.child == u8) {
415 try stream.writeAll(value);
416 } else {
417 for (value) |item| {
418 try serialize(stream, item);
419 }
420 }
421 },
422 .c => unsupportedType(T),
423 .many => unsupportedType(T),
424 }
425 }
426
427 pub fn serializeArray(stream: anytype, comptime info: std.builtin.Type.Array, comptime T: type, value: T) @TypeOf(stream).Error!void {
428 if (info.sentinel_ptr != null) unsupportedType(T);
429 if (info.child == u8) {
430 try stream.writeAll(value);
431 } else {
432 for (value) |item| {
433 try serialize(stream, item);
434 }
435 }
436 }
437
438 pub fn serializeStruct(stream: anytype, comptime info: std.builtin.Type.Struct, comptime T: type, value: T) @TypeOf(stream).Error!void {
439 inline for (info.fields) |field| {
440 try serialize(stream, @field(value, field.name));
441 }
442 }
443
444 pub fn serializeEnum(stream: anytype, comptime T: type, value: T) @TypeOf(stream).Error!void {
445 const tag: u32 = @intFromEnum(value);
446 try serialize(stream, tag);
447 }
448
449 pub fn serializeUnion(stream: anytype, comptime info: std.builtin.Type.Union, comptime T: type, value: T) @TypeOf(stream).Error!void {
450 if (info.tag_type) |UnionTagType| {
451 const tag: u32 = @intFromEnum(value);
452 try serialize(stream, tag);
453 inline for (info.fields) |field| {
454 if (value == @field(UnionTagType, field.name)) {
455 try serialize(stream, @field(value, field.name));
456 }
457 }
458 } else {
459 unsupportedType(T);
460 }
461 }
462
463 fn unsupportedType(comptime T: type) noreturn {
464 @compileError("Unsupported type " ++ @typeName(T));
465 }
466
467 fn invalidProtocol(comptime message: []const u8) noreturn {
468 utils.print("Invalid protocol detected: %.*s\n", .{ @as(c_int, @intCast(message.len)), message.ptr });
469 std.process.exit(1);
470 }
471
472 test "example" {
473 const bincode = @This(); //@import("bincode-zig");
474
475 const Shared = struct {
476 name: []const u8,
477 age: u32,
478 };
479
480 const example = Shared{ .name = "Cat", .age = 5 };
481
482 // Serialize Shared to buffer
483 var buffer: [8192]u8 = undefined;
484 var output_stream = std.io.fixedBufferStream(buffer[0..]);
485 try bincode.serialize(output_stream.writer(), example);
486
487 // Use an arena to gather allocations from deserializer to make
488 // them easy to clean up together. Allocations are required for
489 // slices.
490 var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
491 defer arena.deinit();
492
493 // Read what we wrote
494 var input_stream = std.io.fixedBufferStream(output_stream.getWritten());
495 const copy = try bincode.deserializeAlloc(
496 input_stream.reader(),
497 arena.allocator(),
498 Shared,
499 );
500
501 // Make sure it is the same
502 try std.testing.expectEqualStrings("Cat", copy.name);
503 try std.testing.expectEqual(@as(u32, 5), copy.age);
504 }