From 017d3864de1f337d01726e87534a4e2093c7265f Mon Sep 17 00:00:00 2001 From: Meghan Date: Wed, 9 Mar 2022 16:38:47 -0800 Subject: [PATCH] std: fix false positive for `zig.isValidId` with empty string (#11104) * std: fix false positive for `zig.isValidId` with empty string, fixes #11099 * std: add zig.isValidId tests --- lib/std/zig/fmt.zig | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/lib/std/zig/fmt.zig b/lib/std/zig/fmt.zig index 4351ab7987..8f59f59c3d 100644 --- a/lib/std/zig/fmt.zig +++ b/lib/std/zig/fmt.zig @@ -23,6 +23,7 @@ pub fn fmtId(bytes: []const u8) std.fmt.Formatter(formatId) { } pub fn isValidId(bytes: []const u8) bool { + if (bytes.len == 0) return false; if (mem.eql(u8, bytes, "_")) return false; for (bytes) |c, i| { switch (c) { @@ -34,6 +35,14 @@ pub fn isValidId(bytes: []const u8) bool { return std.zig.Token.getKeyword(bytes) == null; } +test "isValidId" { + try std.testing.expect(!isValidId("")); + try std.testing.expect(isValidId("foobar")); + try std.testing.expect(!isValidId("a b c")); + try std.testing.expect(!isValidId("3d")); + try std.testing.expect(!isValidId("enum")); +} + /// Print the string as escaped contents of a double quoted or single-quoted string. /// Format `{}` treats contents as a double-quoted string. /// Format `{'}` treats contents as a single-quoted string.