valid.ha (693B)
1 // SPDX-License-Identifier: MPL-2.0 2 // (c) Hare authors <https://harelang.org> 3 4 use strings; 5 6 // Returns true if a rune is a valid ASCII character. 7 export fn valid(c: rune) bool = c: u32 <= 0o177; 8 9 // Returns true if all runes in a string are valid ASCII characters. 10 export fn validstr(s: str) bool = { 11 const bytes = strings::toutf8(s); 12 for (let byte .. bytes) { 13 if (byte >= 0o200) { 14 return false; 15 }; 16 }; 17 return true; 18 }; 19 20 @test fn valid() void = { 21 assert(valid('a') && valid('\0') && valid('\x7F')); 22 assert(!valid('\u0080') && !valid('こ')); 23 assert(validstr("abc\0")); 24 assert(!validstr("š")); 25 assert(!validstr("こんにちは")); 26 assert(!validstr("ABCこんにちは")); 27 };