From: n3rdopolis Date: Mon, 20 Mar 2023 02:39:12 +0000 (-0400) Subject: ply-utils: Add ply_utf8_string_get_substring_range () to split UTF-8 strings at a... X-Git-Url: http://git.ipfire.org/cgi-bin/gitweb.cgi?a=commitdiff_plain;h=35819ff63e34855bb0e1e89a75c128038ce03a9a;p=thirdparty%2Fplymouth.git ply-utils: Add ply_utf8_string_get_substring_range () to split UTF-8 strings at a number character, to a specified range --- diff --git a/src/libply/ply-utils.c b/src/libply/ply-utils.c index ed6b054a..6968a96c 100644 --- a/src/libply/ply-utils.c +++ b/src/libply/ply-utils.c @@ -776,6 +776,39 @@ ply_utf8_string_get_length (const char *string, return count; } +char * +ply_utf8_string_get_substring (const char *string, + size_t offset, + size_t range) +{ + int charlen; + size_t utf8_char_count = 0; + size_t utf8_byte_offset = 0, utf8_byte_range = 0; + ssize_t range_max; + + range_max = strlen (string) + 1; + + while (utf8_char_count < offset && range_max >= 0) { + charlen = ply_utf8_character_get_size (string + utf8_byte_offset, range_max); + if (charlen <= 0) break; + utf8_char_count++; + utf8_byte_offset += charlen; + range_max -= charlen; + } + + utf8_char_count = 0; + + while (utf8_char_count <= range && range_max >= 0) { + charlen = ply_utf8_character_get_size (string + utf8_byte_offset + utf8_byte_range, range_max); + if (charlen <= 0) break; + utf8_char_count++; + utf8_byte_range += charlen; + range_max -= charlen; + } + + return strndup (string + utf8_byte_offset, utf8_byte_range); +} + char * ply_get_process_command_line (pid_t pid) { diff --git a/src/libply/ply-utils.h b/src/libply/ply-utils.h index 09507e09..8e0fa4dc 100644 --- a/src/libply/ply-utils.h +++ b/src/libply/ply-utils.h @@ -116,6 +116,9 @@ int ply_utf8_character_get_size (const char *string, size_t n); int ply_utf8_string_get_length (const char *string, size_t n); +char *ply_utf8_string_get_substring (const char *string, + size_t offset, + size_t range); char *ply_get_process_command_line (pid_t pid); pid_t ply_get_process_parent_pid (pid_t pid);