|
| 1 | +const std = @import("std"); |
| 2 | +const Prefix = @import("../root.zig").Prefix; |
| 3 | +const maxInt = std.math.maxInt; |
| 4 | +const log2 = std.math.log2; |
| 5 | + |
| 6 | +/// Generate a ext prefix. |
| 7 | +pub fn prefix(len: u32, extype: i8) Prefix { |
| 8 | + var result: Prefix = .{}; |
| 9 | + switch (len) { |
| 10 | + 1, 2, 4, 8, 16 => |b| { |
| 11 | + result.appendAssumeCapacity(0xd4 + log2(b)); |
| 12 | + result.writer().writeInt(i8, extype, .big) catch unreachable; |
| 13 | + }, |
| 14 | + 0...maxInt(u8) => { |
| 15 | + result.appendSliceAssumeCapacity(&.{ 0xc7, @truncate(len) }); |
| 16 | + result.writer().writeInt(i8, extype, .big) catch unreachable; |
| 17 | + }, |
| 18 | + maxInt(u8) + 1...maxInt(u16) => { |
| 19 | + result.appendAssumeCapacity(0xc8); |
| 20 | + result.writer().writeInt(u16, @truncate(len), .big) catch unreachable; |
| 21 | + result.writer().writeInt(i8, extype, .big) catch unreachable; |
| 22 | + }, |
| 23 | + maxInt(u16) + 1...maxInt(u32) => { |
| 24 | + result.appendAssumeCapacity(0xc9); |
| 25 | + result.writer().writeInt(u32, @truncate(len), .big) catch unreachable; |
| 26 | + result.writer().writeInt(i8, extype, .big) catch unreachable; |
| 27 | + }, |
| 28 | + } |
| 29 | + return result; |
| 30 | +} |
| 31 | + |
| 32 | +pub fn count(len: u32, extype: i8) usize { |
| 33 | + return @call(.always_inline, prefix, .{ len, extype }).len; |
| 34 | +} |
| 35 | + |
| 36 | +pub fn write(dst: []u8, len: u32, extype: i8) usize { |
| 37 | + const p = prefix(len, extype); |
| 38 | + @memcpy(dst, p.constSlice()); |
| 39 | + return p.len; |
| 40 | +} |
| 41 | + |
| 42 | +pub fn pipe(writer: anytype, len: u32, extype: i8) !usize { |
| 43 | + const p = prefix(len, extype); |
| 44 | + return try writer.write(p.constSlice()); |
| 45 | +} |
| 46 | + |
| 47 | +pub fn pipeVal(writer: anytype, extype: i8, value: []const u8) !usize { |
| 48 | + const sz0 = try pipe(writer, @intCast(value.len), extype); |
| 49 | + const sz1 = try writer.write(value); |
| 50 | + return sz0 + sz1; |
| 51 | +} |
0 commit comments