fn int(comptime T: type, value: []const u8) error T: typevalue: []const u8113
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
141fn int(comptime T: type, value: []const u8) error{ NonCanonical, LargeValue }!T {
const info = @typeInfo(T).int;
if (info.bits % 8 != 0) @compileError("T must be byte aligned");
if (value.len == 0) return error.NonCanonical;
if (value.len >= 2) {
if (value[0] == 0x00 and value[1] & 0x80 == 0) return error.NonCanonical;
if (value[0] == 0xff and value[1] & 0x80 != 0) return error.NonCanonical;
}
const had_sign_byte = value.len >= 2 and value[0] == 0x00;
const bytes = if (had_sign_byte) value[1..] else value;
const der_negative = !had_sign_byte and bytes[0] & 0x80 != 0;
switch (info.signedness) {
.unsigned => {
if (der_negative) return error.LargeValue;
if (bytes.len > @sizeOf(T)) return error.LargeValue;
},
.signed => {
const max_len: usize = if (had_sign_byte) @sizeOf(T) - 1 else @sizeOf(T);
if (bytes.len > max_len) return error.LargeValue;
},
}
var buf: [@sizeOf(T)]u8 = @splat(if (der_negative) 0xff else 0);
@memcpy(buf[buf.len - bytes.len ..], bytes);
return std.mem.readInt(T, &buf, .big);
}