File: valid.ha

package info (click to toggle)
hare 0.24.2-4
  • links: PTS, VCS
  • area: main
  • in suites: trixie
  • size: 6,756 kB
  • sloc: asm: 1,180; sh: 119; makefile: 116; lisp: 99
file content (27 lines) | stat: -rw-r--r-- 693 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
// SPDX-License-Identifier: MPL-2.0
// (c) Hare authors <https://harelang.org>

use strings;

// Returns true if a rune is a valid ASCII character.
export fn valid(c: rune) bool = c: u32 <= 0o177;

// Returns true if all runes in a string are valid ASCII characters.
export fn validstr(s: str) bool = {
	const bytes = strings::toutf8(s);
	for (let byte .. bytes) {
		if (byte >= 0o200) {
			return false;
		};
	};
	return true;
};

@test fn valid() void = {
	assert(valid('a') && valid('\0') && valid('\x7F'));
	assert(!valid('\u0080') && !valid('こ'));
	assert(validstr("abc\0"));
	assert(!validstr("š"));
	assert(!validstr("こんにちは"));
	assert(!validstr("ABCこんにちは"));
};