diff options
author | Marius Halden <marius.h@lden.org> | 2016-10-17 09:37:20 +0200 |
---|---|---|
committer | Marius Halden <marius.h@lden.org> | 2016-10-17 09:37:20 +0200 |
commit | bfce290626ae7b771f8dafdc1e0c77279ce16fc8 (patch) | |
tree | 575fa544231b6ae925fc377ccccc5edf04b7a126 /lib/misc.c | |
parent | 305a1ddb6c5b03615f98ad45e80ee3d7a5387a3a (diff) | |
parent | f95e606e153c785dab62a2ac4eab1bc34d41e50a (diff) |
Merge branch 'master' into patched-master
Diffstat (limited to 'lib/misc.c')
-rw-r--r-- | lib/misc.c | 26 |
1 files changed, 26 insertions, 0 deletions
@@ -786,3 +786,29 @@ char *str_reject_chars(char *string, const char *reject, char replacement) return string; } + +/* Returns a string that is exactly 'char_len' utf8 characters long (not bytes), + * padded to the right with spaces or truncated with the 'ellipsis' parameter + * if specified (can be NULL). + * Returns a newly allocated string, or NULL on invalid parameters. */ +char *str_pad_and_truncate(const char *string, long char_len, const char *ellipsis) +{ + size_t string_len = strlen(string); + size_t ellipsis_len = (ellipsis) ? strlen(ellipsis) : 0; + long orig_len = g_utf8_strlen(string, -1); + + g_return_val_if_fail(char_len > ellipsis_len, NULL); + + if (orig_len > char_len) { + char *ret = g_malloc(string_len + 1); + g_utf8_strncpy(ret, string, char_len - ellipsis_len); + if (ellipsis) { + g_strlcat(ret, ellipsis, string_len); + } + return ret; + } else if (orig_len < char_len) { + return g_strdup_printf("%s%*s", string, (int) (char_len - orig_len), ""); + } else { + return g_strdup(string); + } +} |