-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathunsigned_varint.zig
More file actions
259 lines (218 loc) · 7.24 KB
/
Copy pathunsigned_varint.zig
File metadata and controls
259 lines (218 loc) · 7.24 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
const std = @import("std");
const testing = std.testing;
/// VarintError represents an error that occurred during varint encoding or decoding.
pub const VarintParseError = error{
Insufficient,
Overflow,
NotMinimal,
};
/// encode encodes a number into a varint and writes it to the buffer.
pub fn encode(comptime T: type, number: T, buffer: []u8) []u8 {
var n = number;
var i: usize = 0;
while (true) {
buffer[i] = (@as(u8, @truncate(n))) | 0x80;
n >>= 7;
if (n == 0) {
buffer[i] &= 0x7f;
break;
}
i += 1;
}
return buffer[0 .. i + 1];
}
/// decode decodes a varint from a buffer and returns the decoded number and the remaining bytes.
pub fn decode(comptime T: type, buffer: []const u8) !struct { value: T, remaining: []const u8 } {
var value: T = 0;
var i: usize = 0;
const max_bytes_len = maxBytesForType(T);
while (i < buffer.len) {
const b = buffer[i];
const k = @as(T, b & 0x7F);
value |= k << @intCast(i * 7);
if (isLast(b)) {
if (b == 0 and i > 0) {
return VarintParseError.NotMinimal;
}
return .{
.value = value,
.remaining = buffer[i + 1 ..],
};
}
i += 1;
if (i >= max_bytes_len) {
return VarintParseError.Overflow;
}
}
return VarintParseError.Insufficient;
}
fn isLast(b: u8) bool {
return (b & 0x80) == 0;
}
fn maxBytesForType(comptime T: type) usize {
return switch (T) {
u8 => 2,
u16 => 3,
u32 => 5,
u64 => 10,
u128 => 19,
usize => switch (@sizeOf(usize)) {
4 => 5, // 32-bit
8 => 10, // 64-bit
else => @compileError("Unsupported usize width"),
},
else => @compileError("Unsupported integer type"),
};
}
/// bufferSize returns the size of the buffer needed to encode a varint.
pub fn bufferSize(comptime T: type) usize {
return maxBytesForType(T);
}
/// encodeStream encodes a number into a varint and writes it to the writer.
pub fn encodeStream(writer: anytype, comptime T: type, number: T) !usize {
var buf: [bufferSize(T)]u8 = undefined;
const encoded = encode(T, number, &buf);
try writer.writeAll(encoded);
return encoded.len;
}
/// decodeStream decodes a varint from the reader and returns the decoded number.
pub fn decodeStream(reader: anytype, comptime T: type) !T {
var value: T = 0;
var i: usize = 0;
var continuation_bytes: usize = 0;
while (true) {
const byte = try reader.takeByte();
if (!isLast(byte)) {
continuation_bytes += 1;
if (continuation_bytes >= maxBytesForType(T)) {
return VarintParseError.Overflow;
}
}
const k = @as(T, byte & 0x7F);
value |= k << @intCast(i * 7);
if (isLast(byte)) {
if (byte == 0 and i > 0) {
return VarintParseError.NotMinimal;
}
return value;
}
i += 1;
}
}
test "identity_u8" {
var buf: [bufferSize(u8)]u8 = undefined;
var n: u8 = 0;
while (n < std.math.maxInt(u8)) : (n += 1) {
const encoded = encode(u8, n, &buf);
const decoded = try decode(u8, encoded);
try testing.expectEqual(n, decoded.value);
}
}
test "identity_u16" {
var buf: [bufferSize(u16)]u8 = undefined;
var n: u16 = 0;
while (n < std.math.maxInt(u16)) : (n += 1) {
const encoded = encode(u16, n, &buf);
const decoded = try decode(u16, encoded);
try testing.expectEqual(n, decoded.value);
}
}
test "identity_u32" {
var buf: [bufferSize(u32)]u8 = undefined;
var n: u32 = 0;
while (n < 1_000_000) : (n += 1) {
const encoded = encode(u32, n, &buf);
const decoded = try decode(u32, encoded);
try testing.expectEqual(n, decoded.value);
}
// Test max value
const encoded = encode(u32, std.math.maxInt(u32), &buf);
const decoded = try decode(u32, encoded);
try testing.expectEqual(std.math.maxInt(u32), decoded.value);
}
test "various" {
// Empty buffer test
try testing.expectError(error.Insufficient, decode(u8, &[_]u8{}));
// Single byte insufficient test
try testing.expectError(error.Insufficient, decode(u8, &[_]u8{0x80}));
// Simple values
{
const decoded = try decode(u8, &[_]u8{1});
try testing.expectEqual(@as(u8, 1), decoded.value);
}
{
const decoded = try decode(u8, &[_]u8{0b0111_1111});
try testing.expectEqual(@as(u8, 127), decoded.value);
}
{
const decoded = try decode(u8, &[_]u8{ 0b1000_0000, 1 });
try testing.expectEqual(@as(u8, 128), decoded.value);
}
{
const decoded = try decode(u8, &[_]u8{ 0b1111_1111, 1 });
try testing.expectEqual(@as(u8, 255), decoded.value);
}
// Overflow test
try testing.expectError(error.Overflow, decode(u64, &[_]u8{ 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80 }));
}
test "edge_cases" {
var buf: [bufferSize(u64)]u8 = undefined;
// Max values
{
const encoded = encode(u64, std.math.maxInt(u64), &buf);
const decoded = try decode(u64, encoded);
try testing.expectEqual(std.math.maxInt(u64), decoded.value);
}
// Zero
{
const encoded = encode(u64, 0, &buf);
const decoded = try decode(u64, encoded);
try testing.expectEqual(@as(u64, 0), decoded.value);
}
}
test "error_cases" {
// Empty buffer
try testing.expectError(error.Insufficient, decode(u8, &[_]u8{}));
// Incomplete sequence
try testing.expectError(error.Insufficient, decode(u8, &[_]u8{0x80}));
// Non-minimal encoding
try testing.expectError(error.NotMinimal, decode(u8, &[_]u8{ 0x80, 0x00 }));
// Overflow with too many continuation bytes
try testing.expectError(error.Overflow, decode(u64, &[_]u8{
0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80,
}));
}
test "specific_values" {
// Test some specific interesting values
const TestCase = struct {
value: u64,
encoded: []const u8,
};
const test_cases = [_]TestCase{
.{ .value = 1, .encoded = &[_]u8{1} },
.{ .value = 127, .encoded = &[_]u8{0x7f} },
.{ .value = 128, .encoded = &[_]u8{ 0x80, 0x01 } },
.{ .value = 255, .encoded = &[_]u8{ 0xff, 0x01 } },
.{ .value = 300, .encoded = &[_]u8{ 0xac, 0x02 } },
.{ .value = 16384, .encoded = &[_]u8{ 0x80, 0x80, 0x01 } },
};
for (test_cases) |case| {
const decoded = try decode(u64, case.encoded);
try testing.expectEqual(case.value, decoded.value);
}
}
test "stream_identity" {
var aw: std.Io.Writer.Allocating = .init(testing.allocator);
defer aw.deinit();
const numbers = [_]u64{ 1, 127, 128, 255, 300, 16384 };
for (numbers) |n| {
// Encode to stream
const written = try encodeStream(&aw.writer, u64, n);
try testing.expectEqual(written, aw.written().len);
// Decode from stream
var r = std.Io.Reader.fixed(aw.written());
const decoded = try decodeStream(&r, u64);
try testing.expectEqual(n, decoded);
aw.clearRetainingCapacity();
}
}