pad.ha (1396B)
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 = { 9 if (len(s) >= maxlen) { 10 return dup(s); 11 }; 12 let res: []u8 = alloc([], maxlen); 13 for (let i = 0z; i < maxlen - len(s); i += 1) { 14 append(res, utf8::encoderune(p)...); 15 }; 16 append(res, toutf8(s)...); 17 return fromutf8_unsafe(res[..maxlen]); 18 }; 19 20 @test fn lpad() void = { 21 let s = lpad("2", '0', 5); 22 assert(s == "00002"); 23 free(s); 24 25 let s = lpad("12345", '0', 5); 26 assert(s == "12345"); 27 free(s); 28 29 let s = lpad("", '0', 5); 30 assert(s == "00000"); 31 free(s); 32 }; 33 34 // Pads the end of a string 's' with rune 'p' until the string reaches length 35 // 'maxlen'. The caller must free the return value. 36 export fn rpad(s: str, p: rune, maxlen: size) str = { 37 if (len(s) >= maxlen) { 38 return dup(s); 39 }; 40 let res: []u8 = alloc([], maxlen); 41 append(res, toutf8(s)...); 42 for (let i = 0z; i < maxlen - len(s); i += 1) { 43 append(res, utf8::encoderune(p)...); 44 }; 45 return fromutf8_unsafe(res[..maxlen]); 46 }; 47 48 @test fn rpad() void = { 49 let s = rpad("2", '0', 5); 50 assert(s == "20000"); 51 free(s); 52 53 let s = rpad("12345", '0', 5); 54 assert(s == "12345"); 55 free(s); 56 57 let s = rpad("", '0', 5); 58 assert(s == "00000"); 59 free(s); 60 };