aboutsummaryrefslogtreecommitdiffstats
path: root/lib/misc.c
diff options
context:
space:
mode:
Diffstat (limited to 'lib/misc.c')
-rw-r--r--lib/misc.c26
1 files changed, 26 insertions, 0 deletions
diff --git a/lib/misc.c b/lib/misc.c
index 1c93f65a..b4c02ed1 100644
--- a/lib/misc.c
+++ b/lib/misc.c
@@ -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);
+ }
+}