@@ 73,6 73,9 @@ call `deinit` on a `Decoder` to free any memory that was allocated.
All BARE types are supported, although `data<length>` and `data` are the same
as `[length]u8` and `[]u8`, and `string` is also the same as `[]u8`.
+`usize` and `c_uint` are encoded as variable-length unsigned integers,
+and `isize` and `c_int` are encoded as variable-length signed integers.
+
For `map[type A]type B`, `std.HashMap` is used.
When using `Encoder`, all BARE invariants are enforced at compile-time.
@@ 71,20 71,28 @@ pub fn Decoder(comptime ReaderType: type) type {
}
fn decodeInt(self: *Self, comptime T: type) !T {
- return if (T == usize or T == c_uint)
- self.decodeVarUint(T)
- else if (T == isize or T == c_int)
- self.decodeVarInt(T)
- else switch (@bitSizeOf(T)) {
- 8, 16, 32, 64 => self.reader.readInt(T, .little),
+ return switch (T) {
+ usize, c_uint => self.decodeVarUint(T),
+ isize, c_int => self.decodeVarInt(T),
+ i8,
+ u8,
+ i16,
+ u16,
+ i32,
+ u32,
+ i64,
+ u64,
+ => self.reader.readInt(T, .little),
else => @compileError("unsupported integer type " ++ @typeName(T)),
};
}
fn decodeFloat(self: *Self, comptime T: type) !T {
- const bits = @bitSizeOf(T);
- return switch (bits) {
- 32, 64 => @bitCast(try self.reader.readInt(meta.Int(.unsigned, bits), .little)),
+ return switch (T) {
+ f32, f64 => @bitCast(try self.reader.readInt(
+ meta.Int(.unsigned, @bitSizeOf(T)),
+ .little,
+ )),
else => @compileError("unsupported float type " ++ @typeName(T)),
};
}
@@ 251,16 259,26 @@ pub fn Encoder(comptime WriterType: type) type {
}
fn encodeInt(self: *Self, comptime T: type, value: T) !void {
- return switch (@bitSizeOf(T)) {
- 8, 16, 32, 64 => self.writer.writeInt(T, value, .little),
+ return switch (T) {
+ usize, c_uint => self.encodeVarUint(T),
+ isize, c_int => self.encodeVarInt(T),
+ i8,
+ u8,
+ i16,
+ u16,
+ i32,
+ u32,
+ i64,
+ u64,
+ => self.writer.writeInt(T, value, .little),
else => @compileError("unsupported integer type " ++ @typeName(T)),
};
}
fn encodeFloat(self: *Self, comptime T: type, value: T) !void {
- const I = switch (@bitSizeOf(T)) {
- 32 => u32,
- 64 => u64,
+ const I = switch (T) {
+ f32 => u32,
+ f64 => u64,
else => @compileError("unsupported float type " ++ @typeName(T)),
};
const x: I = @bitCast(value);