1 /* Copyright (C) 2004 Andre Noll <maan@tuebingen.mpg.de>, see file COPYING. */
3 /** \file string.c Memory allocation and string handling functions. */
8 #include <sys/utsname.h> /* uname() */
18 * Reallocate an array, abort on failure or bugs.
20 * \param ptr Pointer to the memory block, may be NULL.
21 * \param nmemb Number of elements.
22 * \param size The size of one element in bytes.
24 * A wrapper for realloc(3) which aborts on invalid arguments or integer
25 * overflow. The wrapper also terminates the current process on allocation
26 * errors, so the caller does not need to check for failure.
28 * \return A pointer to newly allocated memory which is suitably aligned for
29 * any kind of variable and may be different from ptr.
33 __must_check void *arr_realloc(void *ptr, size_t nmemb, size_t size)
39 assert(!__builtin_mul_overflow(nmemb, size, &pr));
41 ptr = realloc(ptr, pr);
47 * Paraslash's version of realloc().
49 * \param p Pointer to the memory block, may be \p NULL.
50 * \param size The desired new size.
52 * A wrapper for realloc(3). It calls \p exit(\p EXIT_FAILURE) on errors,
53 * i.e. there is no need to check the return value in the caller.
55 * \return A pointer to newly allocated memory which is suitably aligned for
56 * any kind of variable and may be different from \a p.
60 __must_check void *para_realloc(void *p, size_t size)
62 return arr_realloc(p, 1, size);
66 * Paraslash's version of malloc().
68 * \param size The desired new size.
70 * A wrapper for malloc(3) which exits on errors.
72 * \return A pointer to the allocated memory, which is suitably aligned for any
77 __must_check __malloc void *alloc(size_t size)
84 PARA_EMERG_LOG("malloc failed (size = %zu), aborting\n",
92 * Allocate and initialize memory.
94 * \param size The desired new size.
96 * \return A pointer to the allocated and zeroed-out memory, which is suitably
97 * aligned for any kind of variable.
99 * \sa \ref alloc(), calloc(3).
101 __must_check __malloc void *zalloc(size_t size)
103 void *ret = alloc(size);
105 memset(ret, 0, size);
110 * Paraslash's version of strdup().
112 * \param s The string to be duplicated.
114 * A strdup(3)-like function which aborts if insufficient memory was available
115 * to allocate the duplicated string, absolving the caller from the
116 * responsibility to check for failure.
118 * \return A pointer to the duplicated string. Unlike strdup(3), the caller may
119 * pass NULL, in which case the function returns a pointer to an empty string.
120 * Regardless of whether or not NULL was passed, the returned string is
121 * allocated on the heap and has to be freed by the caller.
125 __must_check __malloc char *para_strdup(const char *s)
127 char *dupped_string = strdup(s? s: "");
129 assert(dupped_string);
130 return dupped_string;
134 * Print a formatted message to a dynamically allocated string.
136 * \param result The formatted string is returned here.
137 * \param fmt The format string.
138 * \param ap Initialized list of arguments.
140 * This function is similar to vasprintf(), a GNU extension which is not in C
141 * or POSIX. It allocates a string large enough to hold the output including
142 * the terminating null byte. The allocated string is returned via the first
143 * argument and must be freed by the caller. However, unlike vasprintf(), this
144 * function calls exit() if insufficient memory is available, while vasprintf()
145 * returns -1 in this case.
147 * \return Number of bytes written, not including the terminating \p NULL
150 * \sa printf(3), vsnprintf(3), va_start(3), vasprintf(3), \ref xasprintf().
152 __printf_2_0 unsigned xvasprintf(char **result, const char *fmt, va_list ap)
158 *result = alloc(size + 1);
160 ret = vsnprintf(*result, size, fmt, aq);
163 if (ret < size) /* OK */
166 *result = para_realloc(*result, size);
168 ret = vsnprintf(*result, size, fmt, aq);
170 assert(ret >= 0 && ret < size);
175 * Print to a dynamically allocated string, variable number of arguments.
177 * \param result See \ref xvasprintf().
178 * \param fmt Usual format string.
180 * \return The return value of the underlying call to \ref xvasprintf().
182 * \sa \ref xvasprintf() and the references mentioned there.
184 __printf_2_3 unsigned xasprintf(char **result, const char *fmt, ...)
190 ret = xvasprintf(result, fmt, ap);
196 * Allocate a sufficiently large string and print into it.
198 * \param fmt A usual format string.
200 * Produce output according to \p fmt. No artificial bound on the length of the
201 * resulting string is imposed.
203 * \return This function either returns a pointer to a string that must be
204 * freed by the caller or aborts without returning.
206 * \sa printf(3), \ref xasprintf().
208 __must_check __printf_1_2 __malloc char *make_message(const char *fmt, ...)
214 xvasprintf(&msg, fmt, ap);
220 * Free the content of a pointer and set it to NULL.
222 * \param arg A pointer to the pointer whose content should be freed.
224 * If arg is NULL, the function returns immediately. Otherwise it frees the
225 * memory pointed to by *arg and sets *arg to NULL. Hence callers have to pass
226 * the *address* of the pointer variable that points to the memory which should
229 void freep(void *arg)
239 * Paraslash's version of strcat().
241 * \param a String to be appended to.
242 * \param b String to append.
244 * Append \p b to \p a.
246 * \return If \a a is \p NULL, return a pointer to a copy of \a b, i.e.
247 * para_strcat(NULL, b) is equivalent to para_strdup(b). If \a b is \p NULL,
248 * return \a a without making a copy of \a a. Otherwise, construct the
249 * concatenation \a c, free \a a (but not \a b) and return \a c.
253 __must_check __malloc char *para_strcat(char *a, const char *b)
258 return para_strdup(b);
261 tmp = make_message("%s%s", a, b);
267 * Get the logname of the current user.
269 * \return A dynamically allocated string that must be freed by the caller. On
270 * errors, the string "unknown_user" is returned, i.e. this function never
275 __must_check __malloc char *para_logname(void)
277 struct passwd *pw = getpwuid(getuid());
278 return para_strdup(pw? pw->pw_name : "unknown_user");
282 * Get the home directory of the current user.
284 * \return A dynamically allocated string that must be freed by the caller. If
285 * the home directory could not be found, this function returns "/tmp".
287 __must_check __malloc char *para_homedir(void)
289 struct passwd *pw = getpwuid(getuid());
290 return para_strdup(pw? pw->pw_dir : "/tmp");
294 * Get the own hostname.
296 * \return A dynamically allocated string containing the hostname.
300 __malloc char *para_hostname(void)
305 return para_strdup(u.nodename);
309 * Call a custom function for each complete line.
311 * \param flags Any combination of flags defined in \ref for_each_line_flags.
312 * \param buf The buffer containing data separated by newlines.
313 * \param size The number of bytes in \a buf.
314 * \param line_handler The custom function.
315 * \param private_data Pointer passed to \a line_handler.
317 * For each complete line in \p buf, \p line_handler is called. The first
318 * argument to \p line_handler is (a copy of) the current line, and \p
319 * private_data is passed as the second argument. If the \p FELF_READ_ONLY
320 * flag is unset, a pointer into \a buf is passed to the line handler,
321 * otherwise a pointer to a copy of the current line is passed instead. This
322 * copy is freed immediately after the line handler returns.
324 * The function returns if \p line_handler returns a negative value or no more
325 * lines are in the buffer. The rest of the buffer (last chunk containing an
326 * incomplete line) is moved to the beginning of the buffer if FELF_READ_ONLY is
329 * \return On success this function returns the number of bytes not handled to
330 * \p line_handler. The only possible error is a negative return value from the
331 * line handler. In this case processing stops and the return value of the line
332 * handler is returned to indicate failure.
334 * \sa \ref for_each_line_flags.
336 int for_each_line(unsigned flags, char *buf, size_t size,
337 line_handler_t *line_handler, void *private_data)
339 char *start = buf, *end;
340 int ret, i, num_lines = 0;
342 // PARA_NOTICE_LOG("buf: %s\n", buf);
343 while (start < buf + size) {
347 next_cr = memchr(start, '\n', buf + size - start);
348 next_null = memchr(start, '\0', next_cr?
349 next_cr - start : buf + size - start);
350 if (!next_cr && !next_null)
357 if (!(flags & FELF_DISCARD_FIRST) || start != buf) {
358 if (flags & FELF_READ_ONLY) {
359 size_t s = end - start;
360 char *b = alloc(s + 1);
363 ret = line_handler(b, private_data);
367 ret = line_handler(start, private_data);
374 i = buf + size - start;
375 if (i && i != size && !(flags & FELF_READ_ONLY))
376 memmove(buf, start, i);
380 /** Return the hex characters of the lower 4 bits. */
381 #define hex(a) (hexchar[(a) & 15])
383 static void write_size_header(char *buf, int n)
385 static char hexchar[] = "0123456789abcdef";
387 buf[0] = hex(n >> 12);
388 buf[1] = hex(n >> 8);
389 buf[2] = hex(n >> 4);
395 * Read a four-byte hex-number and return its value.
397 * Each status item sent by para_server is prefixed with such a hex number in
398 * ASCII which describes the size of the status item.
400 * \param buf The buffer which must be at least four bytes long.
402 * \return The value of the hex number on success, \p -E_SIZE_PREFIX if the
403 * buffer did not contain only hex digits.
405 int read_size_header(const char *buf)
409 for (i = 0; i < 4; i++) {
410 unsigned char c = buf[i];
412 if (c >= '0' && c <= '9') {
416 if (c >= 'a' && c <= 'f') {
420 return -E_SIZE_PREFIX;
423 return -E_SIZE_PREFIX;
428 * Safely print into a buffer at a given offset.
430 * \param b Determines the buffer, its size, and the offset.
431 * \param fmt The format string.
433 * This function prints into the buffer given by \a b at the offset which is
434 * also given by \a b. If there is not enough space to hold the result, the
435 * buffer size is doubled until the underlying call to vsnprintf() succeeds
436 * or the size of the buffer exceeds the maximal size specified in \a b.
438 * In the latter case the unmodified \a buf and \a offset values as well as the
439 * private_data pointer of \a b are passed to the \a max_size_handler of \a b.
440 * If this function succeeds, i.e. returns a non-negative value, the offset of
441 * \a b is reset to zero and the given data is written to the beginning of the
442 * buffer. If \a max_size_handler() returns a negative value, this value is
443 * returned by \a para_printf().
445 * Upon return, the offset of \a b is adjusted accordingly so that subsequent
446 * calls to this function append data to what is already contained in the
449 * It's OK to call this function with \p b->buf being \p NULL. In this case, an
450 * initial buffer is allocated.
452 * \return The number of bytes printed into the buffer (not including the
453 * terminating \p NULL byte) on success, negative on errors. If there is no
454 * size-bound on \a b, i.e. if \p b->max_size is zero, this function never
457 * \sa make_message(), vsnprintf(3).
459 __printf_2_3 int para_printf(struct para_buffer *b, const char *fmt, ...)
461 int ret, sz_off = (b->flags & PBF_SIZE_PREFIX)? 5 : 0;
469 char *p = b->buf + b->offset;
470 size_t size = b->size - b->offset;
475 ret = vsnprintf(p + sz_off, size - sz_off, fmt, ap);
477 if (ret > -1 && ret < size - sz_off) { /* success */
478 b->offset += ret + sz_off;
480 write_size_header(p, ret);
484 /* check if we may grow the buffer */
485 if (!b->max_size || 2 * b->size < b->max_size) { /* yes */
486 /* try again with more space */
488 b->buf = para_realloc(b->buf, b->size);
491 /* can't grow buffer */
492 if (!b->offset || !b->max_size_handler) /* message too large */
493 return -ERRNO_TO_PARA_ERROR(ENOSPC);
494 ret = b->max_size_handler(b->buf, b->offset, b->private_data);
501 /** \cond llong_minmax */
502 /* LLONG_MAX and LLONG_MIN might not be defined. */
504 #define LLONG_MAX 9223372036854775807LL
507 #define LLONG_MIN (-LLONG_MAX - 1LL)
509 /** \endcond llong_minmax */
512 * Convert a string to a 64-bit signed integer value.
514 * \param str The string to be converted.
515 * \param value Result pointer.
519 * \sa \ref para_atoi32(), strtol(3), atoi(3).
521 int para_atoi64(const char *str, int64_t *value)
526 errno = 0; /* To distinguish success/failure after call */
527 tmp = strtoll(str, &endptr, 10);
528 if (errno == ERANGE && (tmp == LLONG_MAX || tmp == LLONG_MIN))
529 return -E_ATOI_OVERFLOW;
531 * If there were no digits at all, strtoll() stores the original value
535 return -E_ATOI_NO_DIGITS;
537 * The implementation may also set errno and return 0 in case no
538 * conversion was performed.
540 if (errno != 0 && tmp == 0)
541 return -E_ATOI_NO_DIGITS;
542 if (*endptr != '\0') /* Further characters after number */
543 return -E_ATOI_JUNK_AT_END;
549 * Convert a string to a 32-bit signed integer value.
551 * \param str The string to be converted.
552 * \param value Result pointer.
556 * \sa \ref para_atoi64().
558 int para_atoi32(const char *str, int32_t *value)
562 const int32_t max = 2147483647;
564 ret = para_atoi64(str, &tmp);
567 if (tmp > max || tmp < -max - 1)
568 return -E_ATOI_OVERFLOW;
573 static inline int loglevel_equal(const char *arg, const char * const ll)
575 return !strncasecmp(arg, ll, strlen(ll));
579 * Compute the loglevel number from its name.
581 * \param txt The name of the loglevel (debug, info, ...).
583 * \return The numeric representation of the loglevel name.
585 int get_loglevel_by_name(const char *txt)
587 if (loglevel_equal(txt, "debug"))
589 if (loglevel_equal(txt, "info"))
591 if (loglevel_equal(txt, "notice"))
593 if (loglevel_equal(txt, "warning"))
595 if (loglevel_equal(txt, "error"))
597 if (loglevel_equal(txt, "crit"))
599 if (loglevel_equal(txt, "emerg"))
604 static int get_next_word(const char *buf, const char *delim, char **word)
606 enum line_state_flags {LSF_HAVE_WORD = 1, LSF_BACKSLASH = 2,
607 LSF_SINGLE_QUOTE = 4, LSF_DOUBLE_QUOTE = 8};
612 out = alloc(strlen(buf) + 1);
615 for (in = buf; *in; in++) {
620 if (state & LSF_BACKSLASH) /* \\ */
622 state |= LSF_BACKSLASH;
623 state |= LSF_HAVE_WORD;
627 if (state & LSF_BACKSLASH) { /* \n or \t */
628 *out++ = (*in == 'n')? '\n' : '\t';
629 state &= ~LSF_BACKSLASH;
634 if (state & LSF_BACKSLASH) /* \" */
636 if (state & LSF_SINGLE_QUOTE) /* '" */
638 if (state & LSF_DOUBLE_QUOTE) {
639 state &= ~LSF_DOUBLE_QUOTE;
642 state |= LSF_HAVE_WORD;
643 state |= LSF_DOUBLE_QUOTE;
646 if (state & LSF_BACKSLASH) /* \' */
648 if (state & LSF_DOUBLE_QUOTE) /* "' */
650 if (state & LSF_SINGLE_QUOTE) {
651 state &= ~LSF_SINGLE_QUOTE;
654 state |= LSF_HAVE_WORD;
655 state |= LSF_SINGLE_QUOTE;
658 for (p = delim; *p; p++) {
661 if (state & LSF_BACKSLASH)
663 if (state & LSF_SINGLE_QUOTE)
665 if (state & LSF_DOUBLE_QUOTE)
667 if (state & LSF_HAVE_WORD)
671 if (*p) /* ignore delimiter at the beginning */
674 state |= LSF_HAVE_WORD;
676 state &= ~LSF_BACKSLASH;
679 if (!(state & LSF_HAVE_WORD))
681 ret = -ERRNO_TO_PARA_ERROR(EINVAL);
682 if (state & LSF_BACKSLASH) {
683 PARA_ERROR_LOG("trailing backslash\n");
686 if ((state & LSF_SINGLE_QUOTE) || (state & LSF_DOUBLE_QUOTE)) {
687 PARA_ERROR_LOG("unmatched quote character\n");
700 * Get the number of the word the cursor is on.
702 * \param buf The zero-terminated line buffer.
703 * \param delim Characters that separate words.
704 * \param point The cursor position.
706 * \return Zero-based word number.
708 int compute_word_num(const char *buf, const char *delim, int point)
714 for (p = buf, num_words = 0; ; p += ret, num_words++) {
715 ret = get_next_word(p, delim, &word);
719 if (p + ret >= buf + point)
726 * Free an array of words created by create_argv() or create_shifted_argv().
728 * \param argv A pointer previously obtained by \ref create_argv().
730 void free_argv(char **argv)
736 for (i = 0; argv[i]; i++)
741 static int create_argv_offset(int offset, const char *buf, const char *delim,
744 char *word, **argv = alloc((offset + 1) * sizeof(char *));
748 for (i = 0; i < offset; i++)
750 for (p = buf; p && *p; p += ret, i++) {
751 ret = get_next_word(p, delim, &word);
756 argv = arr_realloc(argv, i + 2, sizeof(char*));
771 * Split a buffer into words.
773 * This parser honors single and double quotes, backslash-escaped characters
774 * and special characters like \\n. The result contains pointers to copies of
775 * the words contained in buf and has to be freed by using \ref free_argv().
777 * \param buf The buffer to be split.
778 * \param delim Each character in this string is treated as a separator.
779 * \param result The array of words is returned here.
781 * It's OK to pass NULL as the buffer argument. This is equivalent to passing
784 * \return Number of words in buf, negative on errors. The array returned
785 * through the result pointer is NULL terminated.
787 int create_argv(const char *buf, const char *delim, char ***result)
789 return create_argv_offset(0, buf, delim, result);
793 * Split a buffer into words, offset one.
795 * This is similar to \ref create_argv() but the returned array is one element
796 * larger, words start at index one and element zero is initialized to \p NULL.
797 * Callers must set element zero to a non-NULL value before calling free_argv()
798 * on the returned array to avoid a memory leak.
800 * \param buf See \ref create_argv().
801 * \param delim See \ref create_argv().
802 * \param result See \ref create_argv().
804 * \return Number of words plus one on success, negative on errors.
806 int create_shifted_argv(const char *buf, const char *delim, char ***result)
808 return create_argv_offset(1, buf, delim, result);
812 * Find out if the given string is contained in the arg vector.
814 * \param arg The string to look for.
815 * \param argv The array to search.
817 * \return The first index whose value equals \a arg, or \p -E_ARG_NOT_FOUND if
818 * arg was not found in \a argv.
820 int find_arg(const char *arg, char **argv)
825 return -E_ARG_NOT_FOUND;
826 for (i = 0; argv[i]; i++)
827 if (strcmp(arg, argv[i]) == 0)
829 return -E_ARG_NOT_FOUND;
833 * Compile a regular expression.
835 * This simple wrapper calls regcomp() and logs a message on errors.
837 * \param preg See regcomp(3).
838 * \param regex See regcomp(3).
839 * \param cflags See regcomp(3).
843 int para_regcomp(regex_t *preg, const char *regex, int cflags)
847 int ret = regcomp(preg, regex, cflags);
851 size = regerror(ret, preg, NULL, 0);
853 regerror(ret, preg, buf, size);
854 PARA_ERROR_LOG("%s\n", buf);
860 * strdup() for not necessarily zero-terminated strings.
862 * \param src The source buffer.
863 * \param len The number of bytes to be copied.
865 * \return A 0-terminated buffer of length \a len + 1.
867 * This is similar to strndup(), which is a GNU extension. However, one
868 * difference is that strndup() returns \p NULL if insufficient memory was
869 * available while this function aborts in this case.
871 * \sa strdup(), \ref para_strdup().
873 char *safe_strdup(const char *src, size_t len)
877 assert(len < (size_t)-1);
886 * Copy the value of a key=value pair.
888 * This checks whether the given buffer starts with "key=", ignoring case. If
889 * yes, a copy of the value is returned. The source buffer may not be
892 * \param src The source buffer.
893 * \param len The number of bytes of the tag.
894 * \param key Only copy if it is the value of this key.
896 * \return A zero-terminated buffer, or \p NULL if the key was
897 * not of the given type.
899 char *key_value_copy(const char *src, size_t len, const char *key)
901 int keylen = strlen(key);
905 if (strncasecmp(src, key, keylen))
907 if (src[keylen] != '=')
909 return safe_strdup(src + keylen + 1, len - keylen - 1);
912 static bool utf8_mode(void)
914 static bool initialized, have_utf8;
917 char *info = nl_langinfo(CODESET);
918 have_utf8 = (info && strcmp(info, "UTF-8") == 0);
920 PARA_INFO_LOG("%susing UTF-8 character encoding\n",
921 have_utf8? "" : "not ");
926 static int xwcwidth(wchar_t wc, size_t pos)
930 /* special-case for tab */
931 if (wc == 0x09) /* tab */
932 return (pos | 7) + 1 - pos;
934 /* wcswidth() returns -1 for non-printable characters */
935 return n >= 0? n : 1;
938 static size_t xwcswidth(const wchar_t *s, size_t n)
943 w += xwcwidth(*s++, w);
948 * Skip a given number of cells at the beginning of a string.
950 * \param s The input string.
951 * \param cells_to_skip Desired number of cells that should be skipped.
952 * \param bytes_to_skip Result.
954 * This function computes how many input bytes must be skipped to advance a
955 * string by the given width. If the current character encoding is not UTF-8,
956 * this is simply the given number of cells, i.e. \a cells_to_skip. Otherwise,
957 * \a s is treated as a multibyte string and on successful return, \a s +
958 * bytes_to_skip points to the start of a multibyte string such that the total
959 * width of the multibyte characters that are skipped by advancing \a s that
960 * many bytes equals at least \a cells_to_skip.
964 int skip_cells(const char *s, size_t cells_to_skip, size_t *bytes_to_skip)
968 size_t n, bytes_parsed, cells_skipped;
971 if (cells_to_skip == 0)
974 *bytes_to_skip = cells_to_skip;
977 bytes_parsed = cells_skipped = 0;
978 memset(&ps, 0, sizeof(ps));
980 while (cells_to_skip > cells_skipped) {
983 mbret = mbrtowc(&wc, s + bytes_parsed, n - bytes_parsed, &ps);
985 if (mbret == (size_t)-1 || mbret == (size_t)-2)
986 return -ERRNO_TO_PARA_ERROR(EILSEQ);
987 bytes_parsed += mbret;
988 cells_skipped += xwcwidth(wc, cells_skipped);
990 *bytes_to_skip = bytes_parsed;
995 * Compute the width of an UTF-8 string.
997 * \param s The string.
998 * \param result The width of \a s is returned here.
1000 * If not in UTF8-mode. this function is just a wrapper for strlen(3).
1001 * Otherwise \a s is treated as an UTF-8 string and its display width is
1002 * computed. Note that this function may fail if the underlying call to
1003 * mbsrtowcs(3) fails, so the caller must check the return value.
1005 * \sa nl_langinfo(3), wcswidth(3).
1009 __must_check int strwidth(const char *s, size_t *result)
1011 const char *src = s;
1013 static wchar_t *dest;
1017 * Never call any log function here. This may result in an endless loop
1018 * as para_gui's para_log() calls this function.
1022 *result = strlen(s);
1025 memset(&state, 0, sizeof(state));
1027 num_wchars = mbsrtowcs(NULL, &src, 0, &state);
1028 if (num_wchars == (size_t)-1)
1029 return -ERRNO_TO_PARA_ERROR(errno);
1030 if (num_wchars == 0)
1032 dest = alloc((num_wchars + 1) * sizeof(*dest));
1034 memset(&state, 0, sizeof(state));
1035 num_wchars = mbsrtowcs(dest, &src, num_wchars, &state);
1036 assert(num_wchars > 0 && num_wchars != (size_t)-1);
1037 *result = xwcswidth(dest, num_wchars);
1043 * Truncate and sanitize a (wide character) string.
1045 * This replaces all non-printable characters by spaces and makes sure that the
1046 * modified string does not exceed the given maximal width.
1048 * \param src The source string in multi-byte form.
1049 * \param max_width The maximal number of cells the result may occupy.
1050 * \param result Sanitized multi-byte string, must be freed by caller.
1051 * \param width The width of the sanitized string, always <= max_width.
1053 * The function is wide-character aware but falls back to C strings for
1054 * non-UTF-8 locales.
1056 * \return Standard. On success, *result points to a sanitized copy of the
1057 * given string. This copy was allocated with malloc() and should hence be
1058 * freed when the caller is no longer interested in the result.
1060 * The function fails if the given string contains an invalid multibyte
1061 * sequence. In this case, *result is set to NULL, and *width to zero.
1063 __must_check int sanitize_str(const char *src, size_t max_width,
1064 char **result, size_t *width)
1067 static wchar_t *wcs;
1068 size_t num_wchars, n;
1071 *result = para_strdup(src);
1072 /* replace non-printable characters by spaces */
1073 for (n = 0; n < max_width && src[n]; n++) {
1074 if (!isprint((unsigned char)src[n]))
1077 (*result)[n] = '\0';
1083 memset(&state, 0, sizeof(state));
1084 num_wchars = mbsrtowcs(NULL, &src, 0, &state);
1085 if (num_wchars == (size_t)-1)
1086 return -ERRNO_TO_PARA_ERROR(errno);
1087 wcs = alloc((num_wchars + 1) * sizeof(*wcs));
1088 memset(&state, 0, sizeof(state));
1089 num_wchars = mbsrtowcs(wcs, &src, num_wchars + 1, &state);
1090 assert(num_wchars != (size_t)-1);
1091 for (n = 0; n < num_wchars && *width < max_width; n++) {
1092 if (!iswprint(wcs[n]))
1094 *width += xwcwidth(wcs[n], *width);
1097 n = wcstombs(NULL, wcs, 0) + 1;
1099 num_wchars = wcstombs(*result, wcs, n);
1100 assert(num_wchars != (size_t)-1);