diff --git a/include/util.h b/include/util.h index 3f2d80a..066a91c 100644 --- a/include/util.h +++ b/include/util.h @@ -19,6 +19,7 @@ bool read_press_nb(u_char* length, char* out, struct timeval* tv); bool utf8_iscont(char byte); size_t utf8len(const char* str); size_t utf8len_until(const char* str, const char* until); +size_t utf8trunc(char* str, size_t n); const char* utf8back(const char* str); const char* utf8seek(const char* str); const char* utf8seekn(const char* str, size_t n); diff --git a/src/ui.c b/src/ui.c index 725a71f..a0f21c6 100644 --- a/src/ui.c +++ b/src/ui.c @@ -3,6 +3,7 @@ #include #include +#include #include #include #include @@ -108,30 +109,22 @@ static char* fmt_time(const char* fmt) { } } -char* trunc_gethostname(const size_t MAXSIZE, const char* const ELLIPSIS) { - if (utf8len(ELLIPSIS) > MAXSIZE) return NULL; - size_t alloc_size = MAXSIZE + 1; +char* trunc_gethostname(const size_t MAXLEN, const char* const ELLIPSIS) { + if (utf8len(ELLIPSIS) > MAXLEN) return NULL; + size_t alloc_size = HOST_NAME_MAX + strlen(ELLIPSIS) + 1; char* buf = malloc(alloc_size); if (!buf) return NULL; - while (true) { - if (gethostname(buf, alloc_size) == 0) return buf; - if (errno == ENAMETOOLONG) { - buf[alloc_size] = '\0'; - if (utf8len(buf) > MAXSIZE - utf8len(ELLIPSIS)) { - strcpy(&buf[MAXSIZE - utf8len(ELLIPSIS)], ELLIPSIS); - return buf; - } - alloc_size *= 2; - char* nbuf = realloc(buf, alloc_size); - if (!nbuf) goto fail; - buf = nbuf; - } else - goto fail; + if(gethostname(buf, alloc_size) != 0) { + free(buf); + return NULL; } -fail: - free(buf); - return NULL; + + if (utf8len(buf) > MAXLEN) { + int end = utf8trunc(buf, MAXLEN - utf8len(ELLIPSIS)); + strcpy(&buf[end], ELLIPSIS); + } + return buf; } void ui_update_cursor_focus() { diff --git a/src/util.c b/src/util.c index 981ddfe..0b882d4 100644 --- a/src/util.c +++ b/src/util.c @@ -103,6 +103,24 @@ size_t utf8len_until(const char* str, const char* until) { return len; } +size_t utf8trunc(char* str, size_t n) { + size_t bytes = 0; + while (true) { + if(str[bytes] == '\0') break; + if (utf8_iscont(str[bytes])) { + bytes++; + continue; + } + if(n == 0) { + str[bytes] = '\0'; + break; + } + bytes++; + n--; + } + return bytes; +} + const char* utf8back(const char* str) { while (utf8_iscont(*(--str))) { }