Changeset 537d9b9 for lib/misc.c


Ignore:
Timestamp:
2016-11-20T08:40:36Z (8 years ago)
Author:
dequis <dx@…>
Children:
3f44e43
Parents:
ba52ac5 (diff), 9f03c47 (diff)
Note: this is a merge changeset, the changes displayed below correspond to the merge itself.
Use the (diff) links above to see all the changes relative to each parent.
Message:

Merge master up to commit '9f03c47' into parson

File:
1 edited

Legend:

Unmodified
Added
Removed
  • lib/misc.c

    rba52ac5 r537d9b9  
    549549}
    550550
    551 /* Word wrapping. Yes, I know this isn't UTF-8 clean. I'm willing to take the risk. */
    552551char *word_wrap(const char *msg, int line_len)
    553552{
     
    582581                }
    583582                if (i == 0) {
    584                         g_string_append_len(ret, msg, line_len);
     583                        const char *end;
     584                        size_t len;
     585
     586                        g_utf8_validate(msg, line_len, &end);
     587
     588                        len = (end != msg) ? end - msg : line_len;
     589
     590                        g_string_append_len(ret, msg, len);
    585591                        g_string_append_c(ret, '\n');
    586                         msg += line_len;
     592                        msg += len;
    587593                }
    588594        }
     
    787793        return string;
    788794}
     795
     796/* Returns a string that is exactly 'char_len' utf8 characters long (not bytes),
     797 * padded to the right with spaces or truncated with the 'ellipsis' parameter
     798 * if specified (can be NULL).
     799 * Returns a newly allocated string, or NULL on invalid parameters. */
     800char *str_pad_and_truncate(const char *string, long char_len, const char *ellipsis)
     801{
     802        size_t string_len = strlen(string);
     803        size_t ellipsis_len = (ellipsis) ? strlen(ellipsis) : 0;
     804        long orig_len = g_utf8_strlen(string, -1);
     805
     806        g_return_val_if_fail(char_len > ellipsis_len, NULL);
     807
     808        if (orig_len > char_len) {
     809                char *ret = g_malloc(string_len + 1);
     810                g_utf8_strncpy(ret, string, char_len - ellipsis_len);
     811                if (ellipsis) {
     812                        g_strlcat(ret, ellipsis, string_len);
     813                }
     814                return ret;
     815        } else if (orig_len < char_len) {
     816                return g_strdup_printf("%s%*s", string, (int) (char_len - orig_len), "");
     817        } else {
     818                return g_strdup(string);
     819        }
     820}
Note: See TracChangeset for help on using the changeset viewer.