diff options
| author | Bruce Hill <bruce@bruce-hill.com> | 2025-03-07 16:56:23 -0500 |
|---|---|---|
| committer | Bruce Hill <bruce@bruce-hill.com> | 2025-03-07 16:56:23 -0500 |
| commit | 2ebe7893fe18c953967f602c73f6d3f32185eeb6 (patch) | |
| tree | 6f2b5b83bc038907d8c387850ee3dd979bad2e71 /stdlib | |
| parent | 9b485be020b6021f2cb86d97efb5b05166901bdf (diff) | |
Add text padding functions: :left_pad(), :right_pad(), :middle_pad()
Diffstat (limited to 'stdlib')
| -rw-r--r-- | stdlib/text.c | 41 | ||||
| -rw-r--r-- | stdlib/text.h | 3 |
2 files changed, 44 insertions, 0 deletions
diff --git a/stdlib/text.c b/stdlib/text.c index c8700739..adbac3f0 100644 --- a/stdlib/text.c +++ b/stdlib/text.c @@ -512,6 +512,47 @@ public Text_t Text$repeat(Text_t text, Int_t count) return ret; } +static Text_t Text$repeat_to_length(Text_t to_repeat, int64_t length) +{ + if (length <= 0) + return EMPTY_TEXT; + + Text_t repeated = EMPTY_TEXT; + while (repeated.length + to_repeat.length <= length) + repeated = concat2(repeated, to_repeat); + + if (repeated.length < length) + repeated = concat2(repeated, Text$slice(to_repeat, I_small(1), I(length - repeated.length))); + + assert(repeated.length == length); + return repeated; +} + +public Text_t Text$left_pad(Text_t text, Int_t count, Text_t padding) +{ + if (padding.length == 0) + fail("Cannot pad with an empty text!"); + + return concat2(Text$repeat_to_length(padding, Int64$from_int(count, false) - text.length), text); +} + +public Text_t Text$right_pad(Text_t text, Int_t count, Text_t padding) +{ + if (padding.length == 0) + fail("Cannot pad with an empty text!"); + + return concat2(text, Text$repeat_to_length(padding, Int64$from_int(count, false) - text.length)); +} + +public Text_t Text$middle_pad(Text_t text, Int_t count, Text_t padding) +{ + if (padding.length == 0) + fail("Cannot pad with an empty text!"); + + int64_t needed = Int64$from_int(count, false) - text.length; + return Texts(Text$repeat_to_length(padding, needed/2), text, Text$repeat_to_length(padding, (needed+1)/2)); +} + public Text_t Text$slice(Text_t text, Int_t first_int, Int_t last_int) { int64_t first = Int64$from_int(first_int, false); diff --git a/stdlib/text.h b/stdlib/text.h index d3aba3f3..9923403c 100644 --- a/stdlib/text.h +++ b/stdlib/text.h @@ -68,6 +68,9 @@ Array_t Text$lines(Text_t text); Closure_t Text$by_line(Text_t text); Text_t Text$join(Text_t glue, Array_t pieces); Text_t Text$repeat(Text_t text, Int_t count); +Text_t Text$left_pad(Text_t text, Int_t count, Text_t padding); +Text_t Text$right_pad(Text_t text, Int_t count, Text_t padding); +Text_t Text$middle_pad(Text_t text, Int_t count, Text_t padding); int32_t Text$get_grapheme_fast(TextIter_t *state, int64_t index); uint32_t Text$get_main_grapheme_fast(TextIter_t *state, int64_t index); void Text$serialize(const void *obj, FILE *out, Table_t *, const TypeInfo_t *); |
