Skip to content

Commit c79f84d

Browse files
authored
builtin: add input_character/0 and print_character/1 (#19502)
1 parent 0904a9e commit c79f84d

File tree

2 files changed

+61
-0
lines changed

2 files changed

+61
-0
lines changed

vlib/builtin/character_inout.c.v

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
module builtin
2+
3+
// input_character gives back a single character, read from the standard input.
4+
// It returns -1 on error (when the input is finished (EOF), on a broken pipe etc).
5+
pub fn input_character() int {
6+
mut ch := 0
7+
$if freestanding {
8+
// TODO
9+
return -1
10+
} $else $if vinix {
11+
// TODO
12+
return -1
13+
} $else {
14+
ch = C.getchar()
15+
if ch == C.EOF {
16+
return -1
17+
}
18+
}
19+
return ch
20+
}
21+
22+
// print_character writes the single character `ch` to the standard output.
23+
// It returns -1 on error (when the output is closed, on a broken pipe, etc).
24+
// Note: this function does not allocate memory, unlike `print(ch.ascii_str())`
25+
// which does, and is thus cheaper to call, which is important, if you have
26+
// to output many characters one by one. If you instead want to print entire
27+
// strings at once, use `print(your_string)`.
28+
pub fn print_character(ch u8) int {
29+
$if android && !termux {
30+
C.android_print(C.stdout, c'%.*s', 1, voidptr(&ch))
31+
} $else $if freestanding {
32+
bare_print(voidptr(&ch), u64(1))
33+
} $else $if vinix {
34+
// TODO
35+
return 0
36+
} $else {
37+
x := C.putchar(ch)
38+
if x == C.EOF {
39+
return -1
40+
}
41+
}
42+
return ch
43+
}

vlib/builtin/character_inout_test.v

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
fn test_print_character() {
2+
assert print_character(u8(`a`)) > 0
3+
assert print_character(u8(`A`)) > 0
4+
println('')
5+
assert print_character(rune(`a`)) > 0
6+
assert print_character(rune(`A`)) > 0
7+
println('')
8+
assert print_character(u8(char(`a`))) > 0
9+
assert print_character(u8(char(`A`))) > 0
10+
println('')
11+
assert print_character(u8(int(`a`))) > 0
12+
assert print_character(u8(int(`A`))) > 0
13+
println('')
14+
}
15+
16+
fn test_input_character() {
17+
// TODO: add an `expect` based test on Linux
18+
}

0 commit comments

Comments
 (0)