Changeset 4466e3e


Ignore:
Timestamp:
2016-10-17T04:34:11Z (4 years ago)
Author:
dequis <dx@…>
Branches:
master
Children:
f95e606
Parents:
399d65a
Message:

misc: Add str_pad_and_truncate() helper function

Useful for tables. See following commit.

Location:
lib
Files:
2 edited

Legend:

Unmodified
Added
Removed
  • lib/misc.c

    r399d65a r4466e3e  
    787787        return string;
    788788}
     789
     790/* Returns a string that is exactly 'char_len' utf8 characters long (not bytes),
     791 * padded to the right with spaces or truncated with the 'ellipsis' parameter
     792 * if specified (can be NULL).
     793 * Returns a newly allocated string, or NULL on invalid parameters. */
     794char *str_pad_and_truncate(const char *string, long char_len, const char *ellipsis)
     795{
     796        size_t string_len = strlen(string);
     797        size_t ellipsis_len = (ellipsis) ? strlen(ellipsis) : 0;
     798        long orig_len = g_utf8_strlen(string, -1);
     799
     800        g_return_val_if_fail(char_len > ellipsis_len, NULL);
     801
     802        if (orig_len > char_len) {
     803                char *ret = g_malloc(string_len + 1);
     804                g_utf8_strncpy(ret, string, char_len - ellipsis_len);
     805                if (ellipsis) {
     806                        g_strlcat(ret, ellipsis, string_len);
     807                }
     808                return ret;
     809        } else if (orig_len < char_len) {
     810                return g_strdup_printf("%s%*s", string, (int) (char_len - orig_len), "");
     811        } else {
     812                return g_strdup(string);
     813        }
     814}
  • lib/misc.h

    r399d65a r4466e3e  
    151151G_MODULE_EXPORT gboolean parse_int64(char *string, int base, guint64 *number);
    152152G_MODULE_EXPORT char *str_reject_chars(char *string, const char *reject, char replacement);
     153G_MODULE_EXPORT char *str_pad_and_truncate(const char *string, long char_len, const char *ellipsis);
    153154
    154155#endif
Note: See TracChangeset for help on using the changeset viewer.