Merge branch 'kristate-std-fmt-hexToBytes'

master
Andrew Kelley 2018-09-02 19:25:07 -04:00
commit 8558caecb5
No known key found for this signature in database
GPG Key ID: 4E7CD66038A4D47C
1 changed files with 20 additions and 1 deletions

View File

@ -350,7 +350,7 @@ pub fn formatText(
comptime var width = 0;
if (fmt.len > 1) width = comptime (parseUnsigned(usize, fmt[1..], 10) catch unreachable);
return formatBuf(bytes, width, context, Errors, output);
} else if ((fmt[0] == 'x') or (fmt[0] == 'X') ) {
} else if ((fmt[0] == 'x') or (fmt[0] == 'X')) {
for (bytes) |c| {
try formatInt(c, 16, fmt[0] == 'X', 2, context, Errors, output);
}
@ -1331,3 +1331,22 @@ pub fn isWhiteSpace(byte: u8) bool {
else => false,
};
}
pub fn hexToBytes(out: []u8, input: []const u8) !void {
if (out.len * 2 < input.len)
return error.InvalidLength;
var in_i: usize = 0;
while (in_i != input.len) : (in_i += 2) {
const hi = try charToDigit(input[in_i], 16);
const lo = try charToDigit(input[in_i + 1], 16);
out[in_i / 2] = (hi << 4) | lo;
}
}
test "fmt.hexToBytes" {
const test_hex_str = "909A312BB12ED1F819B3521AC4C1E896F2160507FFC1C8381E3B07BB16BD1706";
var pb: [32]u8 = undefined;
try hexToBytes(pb[0..], test_hex_str);
try testFmt(test_hex_str, "{X}", pb);
}