File: pad.ha

package info (click to toggle)
hare 0.25.2-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 6,948 kB
  • sloc: asm: 1,264; makefile: 123; sh: 114; lisp: 101
file content (66 lines) | stat: -rw-r--r-- 1,542 bytes parent folder | download
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
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
// SPDX-License-Identifier: MPL-2.0
// (c) Hare authors <https://harelang.org>

use encoding::utf8;

// Pads the start of a string 's' with rune 'p' until the string reaches length
// 'maxlen'. The caller must free the return value.
export fn lpad(s: str, p: rune, maxlen: size) (str | nomem) = {
	if (len(s) >= maxlen) {
		return dup(s)?;
	};
	let res: []u8 = alloc([], maxlen)!;
	let ok = false;
	defer if (!ok) free(res);
	for (let i = 0z; i < maxlen - len(s); i += 1) {
		append(res, utf8::encoderune(p)...)?;
	};
	append(res, toutf8(s)...)?;
	ok = true;
	return fromutf8_unsafe(res[..maxlen]);
};

@test fn lpad() void = {
	let s = lpad("2", '0', 5)!;
	assert(s == "00002");
	free(s);

	let s = lpad("12345", '0', 5)!;
	assert(s == "12345");
	free(s);

	let s = lpad("", '0', 5)!;
	assert(s == "00000");
	free(s);
};

// Pads the end of a string 's' with rune 'p' until the string reaches length
// 'maxlen'. The caller must free the return value.
export fn rpad(s: str, p: rune, maxlen: size) (str | nomem) = {
	if (len(s) >= maxlen) {
		return dup(s)?;
	};
	let res: []u8 = alloc([], maxlen)!;
	let ok = false;
	defer if (!ok) free(res);
	append(res, toutf8(s)...)!;
	for (let i = 0z; i < maxlen - len(s); i += 1) {
		append(res, utf8::encoderune(p)...)!;
	};
	ok = true;
	return fromutf8_unsafe(res[..maxlen]);
};

@test fn rpad() void = {
	let s = rpad("2", '0', 5)!;
	assert(s == "20000");
	free(s);

	let s = rpad("12345", '0', 5)!;
	assert(s == "12345");
	free(s);

	let s = rpad("", '0', 5)!;
	assert(s == "00000");
	free(s);
};