Error on invalid string passed to Uuid.parse

This commit is contained in:
jaina heartles 2022-05-12 22:46:34 -07:00
parent f56782a323
commit a7e4ff1777

View file

@ -23,6 +23,7 @@ pub const Uuid = struct {
data: [16]u8,
pub const Nil = Uuid{ .data = @bitCast([16]u8, @as(u128, 0)) };
pub const StringLen = 36;
pub fn eql(lhs: Uuid, rhs: Uuid) bool {
return std.mem.eql(u8, &lhs.data, &rhs.data);
@ -51,9 +52,10 @@ pub const Uuid = struct {
pub const ParseError = error{
InvalidCharacter,
InvalidLength,
};
pub fn parse(str: []const u8) ParseError!Uuid {
if (str.len < 36) return error.InvalidCharacter;
if (str.len != StringLen) return error.InvalidLength;
var uuid: Uuid = undefined;
var str_i: usize = 0;
@ -110,8 +112,10 @@ test "format uuid" {
};
try std.testing.expectFmt("f75f5160-12d3-42c2-a81d-ad2245b7a74b", "{}", .{uuid});
try std.testing.expectError(error.InvalidCharacter, Uuid.parse("fsdfs"));
try std.testing.expectError(error.InvalidLength, Uuid.parse("fsdfs"));
try std.testing.expectError(error.InvalidCharacter, Uuid.parse("00000000-0000-0000-xxxx-000000000000"));
try std.testing.expectError(error.InvalidLength, Uuid.parse("00000000-0000-0000-0000-000000000000fsdfs"));
try std.testing.expectError(error.InvalidCharacter, Uuid.parse("00000000-0000x0000-0000-000000000000"));
}
test "roundtrip random uuid" {