diff --git a/vlib/builtin/string.v b/vlib/builtin/string.v index 08de6da1fa..fc4bc78a67 100644 --- a/vlib/builtin/string.v +++ b/vlib/builtin/string.v @@ -2002,3 +2002,8 @@ pub fn (name string) match_glob(pattern string) bool { // Matched all of `pattern` to all of `name` return true } + +// is_ascii returns true if all characters belong to the US-ASCII set ([` `..`~`]) +pub fn (s string) is_ascii() bool { + return !s.bytes().any(it < u8(` `) || it > u8(`~`)) +} diff --git a/vlib/builtin/string_test.v b/vlib/builtin/string_test.v index 1ae0d289f6..ff34c646b4 100644 --- a/vlib/builtin/string_test.v +++ b/vlib/builtin/string_test.v @@ -989,6 +989,16 @@ fn test_string_f32() { assert '-123.456'.f32() - (-123.456) <= f32_epsilon } +fn test_string_is_ascii() { + assert ''.is_ascii() == true + assert ' '.is_ascii() == true + assert '~~'.is_ascii() == true + assert ' Az~'.is_ascii() == true + assert ' Aö~'.is_ascii() == false + assert '👋'.is_ascii() == false + assert 'a👋bc'.is_ascii() == false +} + fn test_string_with_zero_byte_escape() { assert '\x00'.bytes() == [u8(0)] }