# paste.ha -rw-r--r-- 836 bytes View raw
                                                                                
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
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
use encoding::utf8;
use fmt;
use io;
use os;
use strings;
use strio;
use types;

export fn main() void = {
	let buf: [16]u8 = [0...];
	let sink = strio::fixed(buf);

	for (let i = 0u8; i < 16; i += 1) {
		io::write(&sink, ['a' + i])!;
	};

	fmt::println(strio::string(&sink))!;

	// Alternate approach without strio, still bounds-checks the buffer:
	for (let i = 0u8; i < 8; i += 1) {
		buf[i] = 'a' + i;
	};

	fmt::println(strings::fromutf8(buf[..8]))!;
};

// Implementation of strings::fromutf8 for reference:
export fn fromutf8(in: []u8) str = {
	let s = fromutf8_unsafe(in);
	assert(utf8::valid(s), "attempted to load invalid UTF-8 string");
	return s;
};

export fn fromutf8_unsafe(in: []u8) str = {
	const s = types::string {
		data     = in: *[*]u8,
		length   = len(in),
		capacity = len(in),
	};
	return *(&s: *const str);
};