diff --git a/src/unicode.c b/src/unicode.c index c5a971f..368dd7d 100644 --- a/src/unicode.c +++ b/src/unicode.c @@ -387,4 +387,23 @@ uint32_t *u32_strnrstr(const uint32_t *s1, const uint32_t *s2, const size_t s2_l } + +void u32_insert_space_at(uint32_t **s, const size_t idx, const size_t n) +{ + if (s == NULL || n == 0) { + return; + } + + size_t len = u32_strlen(*s); + size_t x = idx; + if (idx > len) { + x = len; + } + + *s = (uint32_t *) realloc(*s, (len + 1 + n) * sizeof(uint32_t)); + u32_move(*s + x + n, *s + x, len - x); + u32_set(*s + x, char_space, n); +} + + /* vim: set cindent sw=4: */ diff --git a/src/unicode.h b/src/unicode.h index 3dcd9c8..4125b3f 100644 --- a/src/unicode.h +++ b/src/unicode.h @@ -248,6 +248,15 @@ uint32_t *u32_nspaces(const size_t n); uint32_t *u32_strnrstr(const uint32_t *s1, const uint32_t *s2, const size_t s2_len, int skip); +/** + * Insert `n` spaces at position `idx` into `s`. This modifies the given string. + * @param s the string to modify + * @param idx the position at which to insert. The character previously at this position will move to the right. + * @param n the number of spaces to insert + */ +void u32_insert_space_at(uint32_t **s, const size_t idx, const size_t n); + + #endif /* vim: set cindent sw=4: */ diff --git a/utest/main.c b/utest/main.c index 1277731..b7871ce 100644 --- a/utest/main.c +++ b/utest/main.c @@ -116,7 +116,8 @@ int main(void) cmocka_unit_test(test_is_allowed_in_shape), cmocka_unit_test(test_is_allowed_in_filename), cmocka_unit_test(test_is_allowed_in_kv_string), - cmocka_unit_test(test_u32_strnrstr) + cmocka_unit_test(test_u32_strnrstr), + cmocka_unit_test(test_u32_insert_space_at) }; const struct CMUnitTest bxstring_tests[] = { diff --git a/utest/unicode_test.c b/utest/unicode_test.c index f0156f6..d8d13a3 100644 --- a/utest/unicode_test.c +++ b/utest/unicode_test.c @@ -26,6 +26,7 @@ #include #include #include +#include #include "boxes.h" #include "tools.h" @@ -183,4 +184,26 @@ void test_u32_strnrstr(void **state) } + +void test_u32_insert_space_at(void **state) +{ + UNUSED(state); + + uint32_t *expected = u32_strconv_from_arg("x xxx ", "ASCII"); + assert_non_null(expected); + uint32_t *s = u32_strconv_from_arg("xxxx", "ASCII"); + assert_non_null(s); + + u32_insert_space_at(NULL, 2, 3); + u32_insert_space_at(&s, 3, 0); + u32_insert_space_at(&s, 1, 1); + u32_insert_space_at(&s, 10000, 2); + + assert_int_equal(0, u32_strcmp(expected, s)); + + BFREE(s); + BFREE(expected); +} + + /* vim: set cindent sw=4: */ \ No newline at end of file diff --git a/utest/unicode_test.h b/utest/unicode_test.h index 0ed1785..3e89522 100644 --- a/utest/unicode_test.h +++ b/utest/unicode_test.h @@ -28,6 +28,8 @@ void test_is_allowed_in_shape(void **state); void test_is_allowed_in_filename(void **state); void test_is_allowed_in_kv_string(void **state); void test_u32_strnrstr(void **state); +void test_u32_insert_space_at(void **state); + #endif