diff options
author | dequis <dx@dxzone.com.ar> | 2016-10-17 01:34:11 -0300 |
---|---|---|
committer | dequis <dx@dxzone.com.ar> | 2016-10-17 01:34:11 -0300 |
commit | 4466e3e85fa08ddbdab86508c7d47325b9e5fa2a (patch) | |
tree | d8f0f231e866461a96a433769d6eb3b51df39be7 /lib/misc.c | |
parent | 399d65a68619538c4ecacddc5fb6f14312647bb6 (diff) |
misc: Add str_pad_and_truncate() helper function
Useful for tables. See following commit.
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); + } +} |