Commit 017d3864de

Meghan <hello@nektro.net>
2022-03-10 01:38:47
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
1 parent f32a77b
Changed files (1)
lib
std
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.