2 * Copyright (C) 2004 Andre Noll <maan@tuebingen.mpg.de>
4 * Licensed under the GPL v2. For licencing details see COPYING.
7 /** \file string.c Memory allocation and string handling functions. */
12 #include <sys/utsname.h> /* uname() */
23 * Paraslash's version of realloc().
25 * \param p Pointer to the memory block, may be \p NULL.
26 * \param size The desired new size.
28 * A wrapper for realloc(3). It calls \p exit(\p EXIT_FAILURE) on errors,
29 * i.e. there is no need to check the return value in the caller.
31 * \return A pointer to newly allocated memory which is suitably aligned for
32 * any kind of variable and may be different from \a p.
36 __must_check void *para_realloc(void *p, size_t size)
39 * No need to check for NULL pointers: If p is NULL, the call
40 * to realloc is equivalent to malloc(size)
43 if (!(p = realloc(p, size))) {
44 PARA_EMERG_LOG("realloc failed (size = %zu), aborting\n",
52 * Paraslash's version of malloc().
54 * \param size The desired new size.
56 * A wrapper for malloc(3) which exits on errors.
58 * \return A pointer to the allocated memory, which is suitably aligned for any
63 __must_check __malloc void *para_malloc(size_t size)
70 PARA_EMERG_LOG("malloc failed (size = %zu), aborting\n",
78 * Paraslash's version of calloc().
80 * \param size The desired new size.
82 * A wrapper for calloc(3) which exits on errors.
84 * \return A pointer to the allocated and zeroed-out memory, which is suitably
85 * aligned for any kind of variable.
89 __must_check __malloc void *para_calloc(size_t size)
91 void *ret = para_malloc(size);
98 * Paraslash's version of strdup().
100 * \param s The string to be duplicated.
102 * A wrapper for strdup(3). It calls \p exit(EXIT_FAILURE) on errors, i.e.
103 * there is no need to check the return value in the caller.
105 * \return A pointer to the duplicated string. If \a s was the \p NULL pointer,
106 * an pointer to an empty string is returned.
110 __must_check __malloc char *para_strdup(const char *s)
114 if ((ret = strdup(s? s: "")))
116 PARA_EMERG_LOG("strdup failed, aborting\n");
121 * Print a formated message to a dynamically allocated string.
123 * \param result The formated string is returned here.
124 * \param fmt The format string.
125 * \param ap Initialized list of arguments.
127 * This function is similar to vasprintf(), a GNU extension which is not in C
128 * or POSIX. It allocates a string large enough to hold the output including
129 * the terminating null byte. The allocated string is returned via the first
130 * argument and must be freed by the caller. However, unlike vasprintf(), this
131 * function calls exit() if insufficient memory is available, while vasprintf()
132 * returns -1 in this case.
134 * \return Number of bytes written, not including the terminating \p NULL
137 * \sa printf(3), vsnprintf(3), va_start(3), vasprintf(3), \ref xasprintf().
139 __printf_2_0 unsigned xvasprintf(char **result, const char *fmt, va_list ap)
145 *result = para_malloc(size + 1);
147 ret = vsnprintf(*result, size, fmt, aq);
150 if (ret < size) /* OK */
153 *result = para_realloc(*result, size);
155 ret = vsnprintf(*result, size, fmt, aq);
157 assert(ret >= 0 && ret < size);
162 * Print to a dynamically allocated string, variable number of arguments.
164 * \param result See \ref xvasprintf().
165 * \param fmt Usual format string.
167 * \return The return value of the underlying call to \ref xvasprintf().
169 * \sa \ref xvasprintf() and the references mentioned there.
171 __printf_2_3 unsigned xasprintf(char **result, const char *fmt, ...)
177 ret = xvasprintf(result, fmt, ap);
183 * Allocate a sufficiently large string and print into it.
185 * \param fmt A usual format string.
187 * Produce output according to \p fmt. No artificial bound on the length of the
188 * resulting string is imposed.
190 * \return This function either returns a pointer to a string that must be
191 * freed by the caller or aborts without returning.
193 * \sa printf(3), xasprintf().
195 __must_check __printf_1_2 __malloc char *make_message(const char *fmt, ...)
201 xvasprintf(&msg, fmt, ap);
207 * Free the content of a pointer and set it to \p NULL.
209 * This is equivalent to "free(*arg); *arg = NULL;".
211 * \param arg The pointer whose content should be freed.
213 void freep(void *arg)
215 void **ptr = (void **)arg;
221 * Paraslash's version of strcat().
223 * \param a String to be appended to.
224 * \param b String to append.
226 * Append \p b to \p a.
228 * \return If \a a is \p NULL, return a pointer to a copy of \a b, i.e.
229 * para_strcat(NULL, b) is equivalent to para_strdup(b). If \a b is \p NULL,
230 * return \a a without making a copy of \a a. Otherwise, construct the
231 * concatenation \a c, free \a a (but not \a b) and return \a c.
235 __must_check __malloc char *para_strcat(char *a, const char *b)
240 return para_strdup(b);
243 tmp = make_message("%s%s", a, b);
249 * Paraslash's version of dirname().
251 * \param name Pointer to the full path.
253 * Compute the directory component of \p name.
255 * \return If \a name is \p NULL or the empty string, return \p NULL.
256 * Otherwise, Make a copy of \a name and return its directory component. Caller
257 * is responsible to free the result.
259 __must_check __malloc char *para_dirname(const char *name)
265 ret = para_strdup(name);
266 p = strrchr(ret, '/');
275 * Paraslash's version of basename().
277 * \param name Pointer to the full path.
279 * Compute the filename component of \a name.
281 * \return \p NULL if (a) \a name is the empty string or \p NULL, or (b) name
282 * ends with a slash. Otherwise, a pointer within \a name is returned. Caller
283 * must not free the result.
285 __must_check char *para_basename(const char *name)
291 ret = strrchr(name, '/');
299 * Get the logname of the current user.
301 * \return A dynamically allocated string that must be freed by the caller. On
302 * errors, the string "unknown_user" is returned, i.e. this function never
307 __must_check __malloc char *para_logname(void)
309 struct passwd *pw = getpwuid(getuid());
310 return para_strdup(pw? pw->pw_name : "unknown_user");
314 * Get the home directory of the current user.
316 * \return A dynamically allocated string that must be freed by the caller. If
317 * the home directory could not be found, this function returns "/tmp".
319 __must_check __malloc char *para_homedir(void)
321 struct passwd *pw = getpwuid(getuid());
322 return para_strdup(pw? pw->pw_dir : "/tmp");
326 * Get the own hostname.
328 * \return A dynamically allocated string containing the hostname.
332 __malloc char *para_hostname(void)
337 return para_strdup(u.nodename);
341 * Call a custom function for each complete line.
343 * \param flags Any combination of flags defined in \ref for_each_line_flags.
344 * \param buf The buffer containing data separated by newlines.
345 * \param size The number of bytes in \a buf.
346 * \param line_handler The custom function.
347 * \param private_data Pointer passed to \a line_handler.
349 * For each complete line in \p buf, \p line_handler is called. The first
350 * argument to \p line_handler is (a copy of) the current line, and \p
351 * private_data is passed as the second argument. If the \p FELF_READ_ONLY
352 * flag is unset, a pointer into \a buf is passed to the line handler,
353 * otherwise a pointer to a copy of the current line is passed instead. This
354 * copy is freed immediately after the line handler returns.
356 * The function returns if \p line_handler returns a negative value or no more
357 * lines are in the buffer. The rest of the buffer (last chunk containing an
358 * incomplete line) is moved to the beginning of the buffer if FELF_READ_ONLY is
361 * \return On success this function returns the number of bytes not handled to
362 * \p line_handler. The only possible error is a negative return value from the
363 * line handler. In this case processing stops and the return value of the line
364 * handler is returned to indicate failure.
366 * \sa \ref for_each_line_flags.
368 int for_each_line(unsigned flags, char *buf, size_t size,
369 line_handler_t *line_handler, void *private_data)
371 char *start = buf, *end;
372 int ret, i, num_lines = 0;
374 // PARA_NOTICE_LOG("buf: %s\n", buf);
375 while (start < buf + size) {
379 next_cr = memchr(start, '\n', buf + size - start);
380 next_null = memchr(start, '\0', next_cr?
381 next_cr - start : buf + size - start);
382 if (!next_cr && !next_null)
389 if (!(flags & FELF_DISCARD_FIRST) || start != buf) {
390 if (flags & FELF_READ_ONLY) {
391 size_t s = end - start;
392 char *b = para_malloc(s + 1);
395 ret = line_handler(b, private_data);
399 ret = line_handler(start, private_data);
406 i = buf + size - start;
407 if (i && i != size && !(flags & FELF_READ_ONLY))
408 memmove(buf, start, i);
412 /** Return the hex characters of the lower 4 bits. */
413 #define hex(a) (hexchar[(a) & 15])
415 static void write_size_header(char *buf, int n)
417 static char hexchar[] = "0123456789abcdef";
419 buf[0] = hex(n >> 12);
420 buf[1] = hex(n >> 8);
421 buf[2] = hex(n >> 4);
427 * Read a four-byte hex-number and return its value.
429 * Each status item sent by para_server is prefixed with such a hex number in
430 * ASCII which describes the size of the status item.
432 * \param buf The buffer which must be at least four bytes long.
434 * \return The value of the hex number on success, \p -E_SIZE_PREFIX if the
435 * buffer did not contain only hex digits.
437 int read_size_header(const char *buf)
441 for (i = 0; i < 4; i++) {
442 unsigned char c = buf[i];
444 if (c >= '0' && c <= '9') {
448 if (c >= 'a' && c <= 'f') {
452 return -E_SIZE_PREFIX;
455 return -E_SIZE_PREFIX;
460 * Safely print into a buffer at a given offset.
462 * \param b Determines the buffer, its size, and the offset.
463 * \param fmt The format string.
465 * This function prints into the buffer given by \a b at the offset which is
466 * also given by \a b. If there is not enough space to hold the result, the
467 * buffer size is doubled until the underlying call to vsnprintf() succeeds
468 * or the size of the buffer exceeds the maximal size specified in \a b.
470 * In the latter case the unmodified \a buf and \a offset values as well as the
471 * private_data pointer of \a b are passed to the \a max_size_handler of \a b.
472 * If this function succeeds, i.e. returns a non-negative value, the offset of
473 * \a b is reset to zero and the given data is written to the beginning of the
474 * buffer. If \a max_size_handler() returns a negative value, this value is
475 * returned by \a para_printf().
477 * Upon return, the offset of \a b is adjusted accordingly so that subsequent
478 * calls to this function append data to what is already contained in the
481 * It's OK to call this function with \p b->buf being \p NULL. In this case, an
482 * initial buffer is allocated.
484 * \return The number of bytes printed into the buffer (not including the
485 * terminating \p NULL byte) on success, negative on errors. If there is no
486 * size-bound on \a b, i.e. if \p b->max_size is zero, this function never
489 * \sa make_message(), vsnprintf(3).
491 __printf_2_3 int para_printf(struct para_buffer *b, const char *fmt, ...)
493 int ret, sz_off = (b->flags & PBF_SIZE_PREFIX)? 5 : 0;
496 b->buf = para_malloc(128);
501 char *p = b->buf + b->offset;
502 size_t size = b->size - b->offset;
507 ret = vsnprintf(p + sz_off, size - sz_off, fmt, ap);
509 if (ret > -1 && ret < size - sz_off) { /* success */
510 b->offset += ret + sz_off;
512 write_size_header(p, ret);
516 /* check if we may grow the buffer */
517 if (!b->max_size || 2 * b->size < b->max_size) { /* yes */
518 /* try again with more space */
520 b->buf = para_realloc(b->buf, b->size);
523 /* can't grow buffer */
524 if (!b->offset || !b->max_size_handler) /* message too large */
525 return -ERRNO_TO_PARA_ERROR(ENOSPC);
526 ret = b->max_size_handler(b->buf, b->offset, b->private_data);
533 /** \cond llong_minmax */
534 /* LLONG_MAX and LLONG_MIN might not be defined. */
536 #define LLONG_MAX 9223372036854775807LL
539 #define LLONG_MIN (-LLONG_MAX - 1LL)
541 /** \endcond llong_minmax */
544 * Convert a string to a 64-bit signed integer value.
546 * \param str The string to be converted.
547 * \param value Result pointer.
551 * \sa para_atoi32(), strtol(3), atoi(3).
553 int para_atoi64(const char *str, int64_t *value)
558 errno = 0; /* To distinguish success/failure after call */
559 tmp = strtoll(str, &endptr, 10);
560 if (errno == ERANGE && (tmp == LLONG_MAX || tmp == LLONG_MIN))
561 return -E_ATOI_OVERFLOW;
563 * If there were no digits at all, strtoll() stores the original value
567 return -E_ATOI_NO_DIGITS;
569 * The implementation may also set errno and return 0 in case no
570 * conversion was performed.
572 if (errno != 0 && tmp == 0)
573 return -E_ATOI_NO_DIGITS;
574 if (*endptr != '\0') /* Further characters after number */
575 return -E_ATOI_JUNK_AT_END;
581 * Convert a string to a 32-bit signed integer value.
583 * \param str The string to be converted.
584 * \param value Result pointer.
590 int para_atoi32(const char *str, int32_t *value)
594 const int32_t max = 2147483647;
596 ret = para_atoi64(str, &tmp);
599 if (tmp > max || tmp < -max - 1)
600 return -E_ATOI_OVERFLOW;
605 static inline int loglevel_equal(const char *arg, const char * const ll)
607 return !strncasecmp(arg, ll, strlen(ll));
611 * Compute the loglevel number from its name.
613 * \param txt The name of the loglevel (debug, info, ...).
615 * \return The numeric representation of the loglevel name.
617 int get_loglevel_by_name(const char *txt)
619 if (loglevel_equal(txt, "debug"))
621 if (loglevel_equal(txt, "info"))
623 if (loglevel_equal(txt, "notice"))
625 if (loglevel_equal(txt, "warning"))
627 if (loglevel_equal(txt, "error"))
629 if (loglevel_equal(txt, "crit"))
631 if (loglevel_equal(txt, "emerg"))
636 static int get_next_word(const char *buf, const char *delim, char **word)
638 enum line_state_flags {LSF_HAVE_WORD = 1, LSF_BACKSLASH = 2,
639 LSF_SINGLE_QUOTE = 4, LSF_DOUBLE_QUOTE = 8};
644 out = para_malloc(strlen(buf) + 1);
647 for (in = buf; *in; in++) {
652 if (state & LSF_BACKSLASH) /* \\ */
654 state |= LSF_BACKSLASH;
655 state |= LSF_HAVE_WORD;
659 if (state & LSF_BACKSLASH) { /* \n or \t */
660 *out++ = (*in == 'n')? '\n' : '\t';
661 state &= ~LSF_BACKSLASH;
666 if (state & LSF_BACKSLASH) /* \" */
668 if (state & LSF_SINGLE_QUOTE) /* '" */
670 if (state & LSF_DOUBLE_QUOTE) {
671 state &= ~LSF_DOUBLE_QUOTE;
674 state |= LSF_HAVE_WORD;
675 state |= LSF_DOUBLE_QUOTE;
678 if (state & LSF_BACKSLASH) /* \' */
680 if (state & LSF_DOUBLE_QUOTE) /* "' */
682 if (state & LSF_SINGLE_QUOTE) {
683 state &= ~LSF_SINGLE_QUOTE;
686 state |= LSF_HAVE_WORD;
687 state |= LSF_SINGLE_QUOTE;
690 for (p = delim; *p; p++) {
693 if (state & LSF_BACKSLASH)
695 if (state & LSF_SINGLE_QUOTE)
697 if (state & LSF_DOUBLE_QUOTE)
699 if (state & LSF_HAVE_WORD)
703 if (*p) /* ignore delimiter at the beginning */
706 state |= LSF_HAVE_WORD;
708 state &= ~LSF_BACKSLASH;
711 if (!(state & LSF_HAVE_WORD))
713 ret = -ERRNO_TO_PARA_ERROR(EINVAL);
714 if (state & LSF_BACKSLASH) {
715 PARA_ERROR_LOG("trailing backslash\n");
718 if ((state & LSF_SINGLE_QUOTE) || (state & LSF_DOUBLE_QUOTE)) {
719 PARA_ERROR_LOG("unmatched quote character\n");
732 * Get the number of the word the cursor is on.
734 * \param buf The zero-terminated line buffer.
735 * \param delim Characters that separate words.
736 * \param point The cursor position.
738 * \return Zero-based word number.
740 int compute_word_num(const char *buf, const char *delim, int point)
746 for (p = buf, num_words = 0; ; p += ret, num_words++) {
747 ret = get_next_word(p, delim, &word);
751 if (p + ret >= buf + point)
758 * Free an array of words created by create_argv() or create_shifted_argv().
760 * \param argv A pointer previously obtained by \ref create_argv().
762 void free_argv(char **argv)
768 for (i = 0; argv[i]; i++)
773 static int create_argv_offset(int offset, const char *buf, const char *delim,
776 char *word, **argv = para_malloc((offset + 1) * sizeof(char *));
780 for (i = 0; i < offset; i++)
782 for (p = buf; p && *p; p += ret, i++) {
783 ret = get_next_word(p, delim, &word);
788 argv = para_realloc(argv, (i + 2) * sizeof(char*));
803 * Split a buffer into words.
805 * This parser honors single and double quotes, backslash-escaped characters
806 * and special characters like \p \\n. The result contains pointers to copies
807 * of the words contained in \a buf and has to be freed by using \ref
810 * \param buf The buffer to be split.
811 * \param delim Each character in this string is treated as a separator.
812 * \param result The array of words is returned here.
814 * \return Number of words in \a buf, negative on errors.
816 int create_argv(const char *buf, const char *delim, char ***result)
818 return create_argv_offset(0, buf, delim, result);
822 * Split a buffer into words, offset one.
824 * This is similar to \ref create_argv() but the returned array is one element
825 * larger, words start at index one and element zero is initialized to \p NULL.
826 * Callers must set element zero to a non-NULL value before calling free_argv()
827 * on the returned array to avoid a memory leak.
829 * \param buf See \ref create_argv().
830 * \param delim See \ref create_argv().
831 * \param result See \ref create_argv().
833 * \return Number of words plus one on success, negative on errors.
835 int create_shifted_argv(const char *buf, const char *delim, char ***result)
837 return create_argv_offset(1, buf, delim, result);
841 * Find out if the given string is contained in the arg vector.
843 * \param arg The string to look for.
844 * \param argv The array to search.
846 * \return The first index whose value equals \a arg, or \p -E_ARG_NOT_FOUND if
847 * arg was not found in \a argv.
849 int find_arg(const char *arg, char **argv)
854 return -E_ARG_NOT_FOUND;
855 for (i = 0; argv[i]; i++)
856 if (strcmp(arg, argv[i]) == 0)
858 return -E_ARG_NOT_FOUND;
862 * Compile a regular expression.
864 * This simple wrapper calls regcomp() and logs a message on errors.
866 * \param preg See regcomp(3).
867 * \param regex See regcomp(3).
868 * \param cflags See regcomp(3).
872 int para_regcomp(regex_t *preg, const char *regex, int cflags)
876 int ret = regcomp(preg, regex, cflags);
880 size = regerror(ret, preg, NULL, 0);
881 buf = para_malloc(size);
882 regerror(ret, preg, buf, size);
883 PARA_ERROR_LOG("%s\n", buf);
889 * strdup() for not necessarily zero-terminated strings.
891 * \param src The source buffer.
892 * \param len The number of bytes to be copied.
894 * \return A 0-terminated buffer of length \a len + 1.
896 * This is similar to strndup(), which is a GNU extension. However, one
897 * difference is that strndup() returns \p NULL if insufficient memory was
898 * available while this function aborts in this case.
900 * \sa strdup(), \ref para_strdup().
902 char *safe_strdup(const char *src, size_t len)
906 assert(len < (size_t)-1);
907 p = para_malloc(len + 1);
915 * Copy the value of a key=value pair.
917 * This checks whether the given buffer starts with "key=", ignoring case. If
918 * yes, a copy of the value is returned. The source buffer may not be
921 * \param src The source buffer.
922 * \param len The number of bytes of the tag.
923 * \param key Only copy if it is the value of this key.
925 * \return A zero-terminated buffer, or \p NULL if the key was
926 * not of the given type.
928 char *key_value_copy(const char *src, size_t len, const char *key)
930 int keylen = strlen(key);
934 if (strncasecmp(src, key, keylen))
936 if (src[keylen] != '=')
938 return safe_strdup(src + keylen + 1, len - keylen - 1);
941 static bool utf8_mode(void)
943 static bool initialized, have_utf8;
946 char *info = nl_langinfo(CODESET);
947 have_utf8 = (info && strcmp(info, "UTF-8") == 0);
949 PARA_INFO_LOG("%susing UTF-8 character encoding\n",
950 have_utf8? "" : "not ");
955 static int xwcwidth(wchar_t wc, size_t pos)
959 /* special-case for tab */
960 if (wc == 0x09) /* tab */
961 return (pos | 7) + 1 - pos;
963 /* wcswidth() returns -1 for non-printable characters */
964 return n >= 0? n : 1;
967 static size_t xwcswidth(const wchar_t *s, size_t n)
972 w += xwcwidth(*s++, w);
977 * Skip a given number of cells at the beginning of a string.
979 * \param s The input string.
980 * \param cells_to_skip Desired number of cells that should be skipped.
981 * \param bytes_to_skip Result.
983 * This function computes how many input bytes must be skipped to advance a
984 * string by the given width. If the current character encoding is not UTF-8,
985 * this is simply the given number of cells, i.e. \a cells_to_skip. Otherwise,
986 * \a s is treated as a multibyte string and on successful return, \a s +
987 * bytes_to_skip points to the start of a multibyte string such that the total
988 * width of the multibyte characters that are skipped by advancing \a s that
989 * many bytes equals at least \a cells_to_skip.
993 int skip_cells(const char *s, size_t cells_to_skip, size_t *bytes_to_skip)
997 size_t n, bytes_parsed, cells_skipped;
1000 if (cells_to_skip == 0)
1003 *bytes_to_skip = cells_to_skip;
1006 bytes_parsed = cells_skipped = 0;
1007 memset(&ps, 0, sizeof(ps));
1009 while (cells_to_skip > cells_skipped) {
1012 mbret = mbrtowc(&wc, s + bytes_parsed, n - bytes_parsed, &ps);
1014 if (mbret == (size_t)-1 || mbret == (size_t)-2)
1015 return -ERRNO_TO_PARA_ERROR(EILSEQ);
1016 bytes_parsed += mbret;
1017 cells_skipped += xwcwidth(wc, cells_skipped);
1019 *bytes_to_skip = bytes_parsed;
1024 * Compute the width of an UTF-8 string.
1026 * \param s The string.
1027 * \param result The width of \a s is returned here.
1029 * If not in UTF8-mode. this function is just a wrapper for strlen(3).
1030 * Otherwise \a s is treated as an UTF-8 string and its display width is
1031 * computed. Note that this function may fail if the underlying call to
1032 * mbsrtowcs(3) fails, so the caller must check the return value.
1034 * \sa nl_langinfo(3), wcswidth(3).
1038 __must_check int strwidth(const char *s, size_t *result)
1040 const char *src = s;
1042 static wchar_t *dest;
1046 * Never call any log function here. This may result in an endless loop
1047 * as para_gui's para_log() calls this function.
1051 *result = strlen(s);
1054 memset(&state, 0, sizeof(state));
1056 num_wchars = mbsrtowcs(NULL, &src, 0, &state);
1057 if (num_wchars == (size_t)-1)
1058 return -ERRNO_TO_PARA_ERROR(errno);
1059 if (num_wchars == 0)
1061 dest = para_malloc((num_wchars + 1) * sizeof(*dest));
1063 memset(&state, 0, sizeof(state));
1064 num_wchars = mbsrtowcs(dest, &src, num_wchars, &state);
1065 assert(num_wchars > 0 && num_wchars != (size_t)-1);
1066 *result = xwcswidth(dest, num_wchars);
1072 * Truncate and sanitize a (wide character) string.
1074 * This replaces all non-printable characters by spaces and makes sure that the
1075 * modified string does not exceed the given maximal width.
1077 * \param src The source string in multi-byte form.
1078 * \param max_width The maximal number of cells the result may occupy.
1079 * \param result Sanitized multi-byte string, must be freed by caller.
1080 * \param width The width of the sanitized string, always <= max_width.
1082 * The function is wide-character aware but falls back to C strings for
1083 * non-UTF-8 locales.
1085 * \return Standard. On success, *result points to a sanitized copy of the
1086 * given string. This copy was allocated with malloc() and should hence be
1087 * freed when the caller is no longer interested in the result.
1089 * The function fails if the given string contains an invalid multibyte
1090 * sequence. In this case, *result is set to NULL, and *width to zero.
1092 __must_check int sanitize_str(const char *src, size_t max_width,
1093 char **result, size_t *width)
1096 static wchar_t *wcs;
1097 size_t num_wchars, n;
1100 *result = para_strdup(src);
1101 /* replace non-printable characters by spaces */
1102 for (n = 0; n < max_width && src[n]; n++) {
1103 if (!isprint((unsigned char)src[n]))
1106 (*result)[n] = '\0';
1112 memset(&state, 0, sizeof(state));
1113 num_wchars = mbsrtowcs(NULL, &src, 0, &state);
1114 if (num_wchars == (size_t)-1)
1115 return -ERRNO_TO_PARA_ERROR(errno);
1116 wcs = para_malloc((num_wchars + 1) * sizeof(*wcs));
1117 memset(&state, 0, sizeof(state));
1118 num_wchars = mbsrtowcs(wcs, &src, num_wchars + 1, &state);
1119 assert(num_wchars != (size_t)-1);
1120 for (n = 0; n < num_wchars && *width < max_width; n++) {
1121 if (!iswprint(wcs[n]))
1123 *width += xwcwidth(wcs[n], *width);
1126 n = wcstombs(NULL, wcs, 0) + 1;
1127 *result = para_malloc(n);
1128 num_wchars = wcstombs(*result, wcs, n);
1129 assert(num_wchars != (size_t)-1);