| 1 |
// SPDX-License-Identifier: MPL-2.0 |
| 2 |
// (c) Hare authors <https://harelang.org> |
| 3 |
|
| 4 |
use encoding::utf8; |
| 5 |
|
| 6 |
// Pads the start of a string 's' with rune 'p' until the string reaches length |
| 7 |
// 'maxlen'. The caller must free the return value. |
| 8 |
export fn lpad(s: str, p: rune, maxlen: size) (str | nomem) = { |
| 9 |
if (len(s) >= maxlen) { |
| 10 |
return dup(s)?; |
| 11 |
}; |
| 12 |
let res: []u8 = alloc([], maxlen)!; |
| 13 |
let ok = false; |
| 14 |
defer if (!ok) free(res); |
| 15 |
for (let i = 0z; i < maxlen - len(s); i += 1) { |
| 16 |
append(res, utf8::encoderune(p)...)?; |
| 17 |
}; |
| 18 |
append(res, toutf8(s)...)?; |
| 19 |
ok = true; |
| 20 |
return fromutf8_unsafe(res[..maxlen]); |
| 21 |
}; |
| 22 |
|
| 23 |
@test fn lpad() void = { |
| 24 |
let s = lpad("2", '0', 5)!; |
| 25 |
assert(s == "00002"); |
| 26 |
free(s); |
| 27 |
|
| 28 |
let s = lpad("12345", '0', 5)!; |
| 29 |
assert(s == "12345"); |
| 30 |
free(s); |
| 31 |
|
| 32 |
let s = lpad("", '0', 5)!; |
| 33 |
assert(s == "00000"); |
| 34 |
free(s); |
| 35 |
}; |
| 36 |
|
| 37 |
// Pads the end of a string 's' with rune 'p' until the string reaches length |
| 38 |
// 'maxlen'. The caller must free the return value. |
| 39 |
export fn rpad(s: str, p: rune, maxlen: size) (str | nomem) = { |
| 40 |
if (len(s) >= maxlen) { |
| 41 |
return dup(s)?; |
| 42 |
}; |
| 43 |
let res: []u8 = alloc([], maxlen)!; |
| 44 |
let ok = false; |
| 45 |
defer if (!ok) free(res); |
| 46 |
append(res, toutf8(s)...)!; |
| 47 |
for (let i = 0z; i < maxlen - len(s); i += 1) { |
| 48 |
append(res, utf8::encoderune(p)...)!; |
| 49 |
}; |
| 50 |
ok = true; |
| 51 |
return fromutf8_unsafe(res[..maxlen]); |
| 52 |
}; |
| 53 |
|
| 54 |
@test fn rpad() void = { |
| 55 |
let s = rpad("2", '0', 5)!; |
| 56 |
assert(s == "20000"); |
| 57 |
free(s); |
| 58 |
|
| 59 |
let s = rpad("12345", '0', 5)!; |
| 60 |
assert(s == "12345"); |
| 61 |
free(s); |
| 62 |
|
| 63 |
let s = rpad("", '0', 5)!; |
| 64 |
assert(s == "00000"); |
| 65 |
free(s); |
| 66 |
}; |