aboutsummaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authordequis <dx@dxzone.com.ar>2016-10-17 01:34:11 -0300
committerdequis <dx@dxzone.com.ar>2016-10-17 01:34:11 -0300
commit4466e3e85fa08ddbdab86508c7d47325b9e5fa2a (patch)
treed8f0f231e866461a96a433769d6eb3b51df39be7
parent399d65a68619538c4ecacddc5fb6f14312647bb6 (diff)
misc: Add str_pad_and_truncate() helper function
Useful for tables. See following commit.
-rw-r--r--lib/misc.c26
-rw-r--r--lib/misc.h1
2 files changed, 27 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);
+ }
+}
diff --git a/lib/misc.h b/lib/misc.h
index 73f71e85..581e7a76 100644
--- a/lib/misc.h
+++ b/lib/misc.h
@@ -150,5 +150,6 @@ G_MODULE_EXPORT char *get_rfc822_header(const char *text, const char *header, in
G_MODULE_EXPORT int truncate_utf8(char *string, int maxlen);
G_MODULE_EXPORT gboolean parse_int64(char *string, int base, guint64 *number);
G_MODULE_EXPORT char *str_reject_chars(char *string, const char *reject, char replacement);
+G_MODULE_EXPORT char *str_pad_and_truncate(const char *string, long char_len, const char *ellipsis);
#endif