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 * Allocate an array, abort on failure or bugs.
49 * \param nmemb See \ref arr_realloc().
50 * \param size See \ref arr_realloc().
52 * Like \ref arr_realloc(), this aborts on invalid arguments, integer overflow
53 * and allocation errors.
55 * \return A pointer to newly allocated memory which is suitably aligned for
56 * any kind of variable.
58 * \sa See \ref arr_realloc().
60 __must_check __malloc void *arr_alloc(size_t nmemb, size_t size)
62 return arr_realloc(NULL, nmemb, size);
66 * Allocate and initialize an array, abort on failure or bugs.
68 * \param nmemb See \ref arr_realloc().
69 * \param size See \ref arr_realloc().
71 * This calls \ref arr_alloc() and zeroes-out the array.
73 * \return See \ref arr_alloc().
75 __must_check __malloc void *arr_zalloc(size_t nmemb, size_t size)
77 void *ptr = arr_alloc(nmemb, size);
80 * This multiplication can not overflow because the above call to \ref
81 * arr_alloc() aborts on overflow.
83 memset(ptr, 0, nmemb * size);
88 * Allocate and initialize memory.
90 * \param size The desired new size.
92 * \return A pointer to the allocated and zeroed-out memory, which is suitably
93 * aligned for any kind of variable.
95 * \sa \ref alloc(), calloc(3).
97 __must_check void *zalloc(size_t size)
99 return arr_zalloc(1, size);
103 * Paraslash's version of realloc().
105 * \param p Pointer to the memory block, may be \p NULL.
106 * \param size The desired new size.
108 * A wrapper for realloc(3). It calls \p exit(\p EXIT_FAILURE) on errors,
109 * i.e. there is no need to check the return value in the caller.
111 * \return A pointer to newly allocated memory which is suitably aligned for
112 * any kind of variable and may be different from \a p.
116 __must_check void *para_realloc(void *p, size_t size)
118 return arr_realloc(p, 1, size);
122 * Paraslash's version of malloc().
124 * \param size The desired new size.
126 * A wrapper for malloc(3) which exits on errors.
128 * \return A pointer to the allocated memory, which is suitably aligned for any
133 __must_check __malloc void *alloc(size_t size)
135 return arr_alloc(1, size);
139 * Paraslash's version of strdup().
141 * \param s The string to be duplicated.
143 * A strdup(3)-like function which aborts if insufficient memory was available
144 * to allocate the duplicated string, absolving the caller from the
145 * responsibility to check for failure.
147 * \return A pointer to the duplicated string. Unlike strdup(3), the caller may
148 * pass NULL, in which case the function returns a pointer to an empty string.
149 * Regardless of whether or not NULL was passed, the returned string is
150 * allocated on the heap and has to be freed by the caller.
154 __must_check __malloc char *para_strdup(const char *s)
156 char *dupped_string = strdup(s? s: "");
158 assert(dupped_string);
159 return dupped_string;
163 * Print a formatted message to a dynamically allocated string.
165 * \param result The formatted string is returned here.
166 * \param fmt The format string.
167 * \param ap Initialized list of arguments.
169 * This function is similar to vasprintf(), a GNU extension which is not in C
170 * or POSIX. It allocates a string large enough to hold the output including
171 * the terminating null byte. The allocated string is returned via the first
172 * argument and must be freed by the caller. However, unlike vasprintf(), this
173 * function calls exit() if insufficient memory is available, while vasprintf()
174 * returns -1 in this case.
176 * \return Number of bytes written, not including the terminating \p NULL
179 * \sa printf(3), vsnprintf(3), va_start(3), vasprintf(3), \ref xasprintf().
181 __printf_2_0 unsigned xvasprintf(char **result, const char *fmt, va_list ap)
187 *result = alloc(size + 1);
189 ret = vsnprintf(*result, size, fmt, aq);
192 if (ret < size) /* OK */
195 *result = para_realloc(*result, size);
197 ret = vsnprintf(*result, size, fmt, aq);
199 assert(ret >= 0 && ret < size);
204 * Print to a dynamically allocated string, variable number of arguments.
206 * \param result See \ref xvasprintf().
207 * \param fmt Usual format string.
209 * \return The return value of the underlying call to \ref xvasprintf().
211 * \sa \ref xvasprintf() and the references mentioned there.
213 __printf_2_3 unsigned xasprintf(char **result, const char *fmt, ...)
219 ret = xvasprintf(result, fmt, ap);
225 * Allocate a sufficiently large string and print into it.
227 * \param fmt A usual format string.
229 * Produce output according to \p fmt. No artificial bound on the length of the
230 * resulting string is imposed.
232 * \return This function either returns a pointer to a string that must be
233 * freed by the caller or aborts without returning.
235 * \sa printf(3), \ref xasprintf().
237 __must_check __printf_1_2 __malloc char *make_message(const char *fmt, ...)
243 xvasprintf(&msg, fmt, ap);
249 * Free the content of a pointer and set it to NULL.
251 * \param arg A pointer to the pointer whose content should be freed.
253 * If arg is NULL, the function returns immediately. Otherwise it frees the
254 * memory pointed to by *arg and sets *arg to NULL. Hence callers have to pass
255 * the *address* of the pointer variable that points to the memory which should
258 void freep(void *arg)
268 * Paraslash's version of strcat().
270 * \param a String to be appended to.
271 * \param b String to append.
273 * Append \p b to \p a.
275 * \return If \a a is \p NULL, return a pointer to a copy of \a b, i.e.
276 * para_strcat(NULL, b) is equivalent to para_strdup(b). If \a b is \p NULL,
277 * return \a a without making a copy of \a a. Otherwise, construct the
278 * concatenation \a c, free \a a (but not \a b) and return \a c.
282 __must_check __malloc char *para_strcat(char *a, const char *b)
287 return para_strdup(b);
290 tmp = make_message("%s%s", a, b);
296 * Get the logname of the current user.
298 * \return A dynamically allocated string that must be freed by the caller. On
299 * errors, the string "unknown_user" is returned, i.e. this function never
304 __must_check __malloc char *para_logname(void)
306 struct passwd *pw = getpwuid(getuid());
307 return para_strdup(pw? pw->pw_name : "unknown_user");
311 * Get the home directory of the current user.
313 * \return A dynamically allocated string that must be freed by the caller. If
314 * the home directory could not be found, this function returns "/tmp".
316 __must_check __malloc char *para_homedir(void)
318 struct passwd *pw = getpwuid(getuid());
319 return para_strdup(pw? pw->pw_dir : "/tmp");
323 * Get the own hostname.
325 * \return A dynamically allocated string containing the hostname.
329 __malloc char *para_hostname(void)
334 return para_strdup(u.nodename);
338 * Call a custom function for each complete line.
340 * \param flags Any combination of flags defined in \ref for_each_line_flags.
341 * \param buf The buffer containing data separated by newlines.
342 * \param size The number of bytes in \a buf.
343 * \param line_handler The custom function.
344 * \param private_data Pointer passed to \a line_handler.
346 * For each complete line in \p buf, \p line_handler is called. The first
347 * argument to \p line_handler is (a copy of) the current line, and \p
348 * private_data is passed as the second argument. If the \p FELF_READ_ONLY
349 * flag is unset, a pointer into \a buf is passed to the line handler,
350 * otherwise a pointer to a copy of the current line is passed instead. This
351 * copy is freed immediately after the line handler returns.
353 * The function returns if \p line_handler returns a negative value or no more
354 * lines are in the buffer. The rest of the buffer (last chunk containing an
355 * incomplete line) is moved to the beginning of the buffer if FELF_READ_ONLY is
358 * \return On success this function returns the number of bytes not handled to
359 * \p line_handler. The only possible error is a negative return value from the
360 * line handler. In this case processing stops and the return value of the line
361 * handler is returned to indicate failure.
363 * \sa \ref for_each_line_flags.
365 int for_each_line(unsigned flags, char *buf, size_t size,
366 line_handler_t *line_handler, void *private_data)
368 char *start = buf, *end;
369 int ret, i, num_lines = 0;
371 // PARA_NOTICE_LOG("buf: %s\n", buf);
372 while (start < buf + size) {
376 next_cr = memchr(start, '\n', buf + size - start);
377 next_null = memchr(start, '\0', next_cr?
378 next_cr - start : buf + size - start);
379 if (!next_cr && !next_null)
386 if (!(flags & FELF_DISCARD_FIRST) || start != buf) {
387 if (flags & FELF_READ_ONLY) {
388 size_t s = end - start;
389 char *b = alloc(s + 1);
392 ret = line_handler(b, private_data);
396 ret = line_handler(start, private_data);
403 i = buf + size - start;
404 if (i && i != size && !(flags & FELF_READ_ONLY))
405 memmove(buf, start, i);
409 /** Return the hex characters of the lower 4 bits. */
410 #define hex(a) (hexchar[(a) & 15])
412 static void write_size_header(char *buf, int n)
414 static char hexchar[] = "0123456789abcdef";
416 buf[0] = hex(n >> 12);
417 buf[1] = hex(n >> 8);
418 buf[2] = hex(n >> 4);
424 * Read a four-byte hex-number and return its value.
426 * Each status item sent by para_server is prefixed with such a hex number in
427 * ASCII which describes the size of the status item.
429 * \param buf The buffer which must be at least four bytes long.
431 * \return The value of the hex number on success, \p -E_SIZE_PREFIX if the
432 * buffer did not contain only hex digits.
434 int read_size_header(const char *buf)
438 for (i = 0; i < 4; i++) {
439 unsigned char c = buf[i];
441 if (c >= '0' && c <= '9') {
445 if (c >= 'a' && c <= 'f') {
449 return -E_SIZE_PREFIX;
452 return -E_SIZE_PREFIX;
457 * Safely print into a buffer at a given offset.
459 * \param b Determines the buffer, its size, and the offset.
460 * \param fmt The format string.
462 * This function prints into the buffer given by \a b at the offset which is
463 * also given by \a b. If there is not enough space to hold the result, the
464 * buffer size is doubled until the underlying call to vsnprintf() succeeds
465 * or the size of the buffer exceeds the maximal size specified in \a b.
467 * In the latter case the unmodified \a buf and \a offset values as well as the
468 * private_data pointer of \a b are passed to the \a max_size_handler of \a b.
469 * If this function succeeds, i.e. returns a non-negative value, the offset of
470 * \a b is reset to zero and the given data is written to the beginning of the
471 * buffer. If \a max_size_handler() returns a negative value, this value is
472 * returned by \a para_printf().
474 * Upon return, the offset of \a b is adjusted accordingly so that subsequent
475 * calls to this function append data to what is already contained in the
478 * It's OK to call this function with \p b->buf being \p NULL. In this case, an
479 * initial buffer is allocated.
481 * \return The number of bytes printed into the buffer (not including the
482 * terminating \p NULL byte) on success, negative on errors. If there is no
483 * size-bound on \a b, i.e. if \p b->max_size is zero, this function never
486 * \sa make_message(), vsnprintf(3).
488 __printf_2_3 int para_printf(struct para_buffer *b, const char *fmt, ...)
490 int ret, sz_off = (b->flags & PBF_SIZE_PREFIX)? 5 : 0;
498 char *p = b->buf + b->offset;
499 size_t size = b->size - b->offset;
504 ret = vsnprintf(p + sz_off, size - sz_off, fmt, ap);
506 if (ret > -1 && ret < size - sz_off) { /* success */
507 b->offset += ret + sz_off;
509 write_size_header(p, ret);
513 /* check if we may grow the buffer */
514 if (!b->max_size || 2 * b->size < b->max_size) { /* yes */
515 /* try again with more space */
517 b->buf = para_realloc(b->buf, b->size);
520 /* can't grow buffer */
521 if (!b->offset || !b->max_size_handler) /* message too large */
522 return -ERRNO_TO_PARA_ERROR(ENOSPC);
523 ret = b->max_size_handler(b->buf, b->offset, b->private_data);
530 /** \cond llong_minmax */
531 /* LLONG_MAX and LLONG_MIN might not be defined. */
533 #define LLONG_MAX 9223372036854775807LL
536 #define LLONG_MIN (-LLONG_MAX - 1LL)
538 /** \endcond llong_minmax */
541 * Convert a string to a 64-bit signed integer value.
543 * \param str The string to be converted.
544 * \param value Result pointer.
548 * \sa \ref para_atoi32(), strtol(3), atoi(3).
550 int para_atoi64(const char *str, int64_t *value)
555 errno = 0; /* To distinguish success/failure after call */
556 tmp = strtoll(str, &endptr, 10);
557 if (errno == ERANGE && (tmp == LLONG_MAX || tmp == LLONG_MIN))
558 return -E_ATOI_OVERFLOW;
560 * If there were no digits at all, strtoll() stores the original value
564 return -E_ATOI_NO_DIGITS;
566 * The implementation may also set errno and return 0 in case no
567 * conversion was performed.
569 if (errno != 0 && tmp == 0)
570 return -E_ATOI_NO_DIGITS;
571 if (*endptr != '\0') /* Further characters after number */
572 return -E_ATOI_JUNK_AT_END;
578 * Convert a string to a 32-bit signed integer value.
580 * \param str The string to be converted.
581 * \param value Result pointer.
585 * \sa \ref para_atoi64().
587 int para_atoi32(const char *str, int32_t *value)
591 const int32_t max = 2147483647;
593 ret = para_atoi64(str, &tmp);
596 if (tmp > max || tmp < -max - 1)
597 return -E_ATOI_OVERFLOW;
602 static int get_next_word(const char *buf, const char *delim, char **word)
604 enum line_state_flags {LSF_HAVE_WORD = 1, LSF_BACKSLASH = 2,
605 LSF_SINGLE_QUOTE = 4, LSF_DOUBLE_QUOTE = 8};
610 out = alloc(strlen(buf) + 1);
613 for (in = buf; *in; in++) {
618 if (state & LSF_BACKSLASH) /* \\ */
620 state |= LSF_BACKSLASH;
621 state |= LSF_HAVE_WORD;
625 if (state & LSF_BACKSLASH) { /* \n or \t */
626 *out++ = (*in == 'n')? '\n' : '\t';
627 state &= ~LSF_BACKSLASH;
632 if (state & LSF_BACKSLASH) /* \" */
634 if (state & LSF_SINGLE_QUOTE) /* '" */
636 if (state & LSF_DOUBLE_QUOTE) {
637 state &= ~LSF_DOUBLE_QUOTE;
640 state |= LSF_HAVE_WORD;
641 state |= LSF_DOUBLE_QUOTE;
644 if (state & LSF_BACKSLASH) /* \' */
646 if (state & LSF_DOUBLE_QUOTE) /* "' */
648 if (state & LSF_SINGLE_QUOTE) {
649 state &= ~LSF_SINGLE_QUOTE;
652 state |= LSF_HAVE_WORD;
653 state |= LSF_SINGLE_QUOTE;
656 for (p = delim; *p; p++) {
659 if (state & LSF_BACKSLASH)
661 if (state & LSF_SINGLE_QUOTE)
663 if (state & LSF_DOUBLE_QUOTE)
665 if (state & LSF_HAVE_WORD)
669 if (*p) /* ignore delimiter at the beginning */
672 state |= LSF_HAVE_WORD;
674 state &= ~LSF_BACKSLASH;
677 if (!(state & LSF_HAVE_WORD))
679 ret = -ERRNO_TO_PARA_ERROR(EINVAL);
680 if (state & LSF_BACKSLASH) {
681 PARA_ERROR_LOG("trailing backslash\n");
684 if ((state & LSF_SINGLE_QUOTE) || (state & LSF_DOUBLE_QUOTE)) {
685 PARA_ERROR_LOG("unmatched quote character\n");
698 * Get the number of the word the cursor is on.
700 * \param buf The zero-terminated line buffer.
701 * \param delim Characters that separate words.
702 * \param point The cursor position.
704 * \return Zero-based word number.
706 int compute_word_num(const char *buf, const char *delim, int point)
712 for (p = buf, num_words = 0; ; p += ret, num_words++) {
713 ret = get_next_word(p, delim, &word);
717 if (p + ret >= buf + point)
724 * Free an array of words created by create_argv() or create_shifted_argv().
726 * \param argv A pointer previously obtained by \ref create_argv().
728 void free_argv(char **argv)
734 for (i = 0; argv[i]; i++)
739 static int create_argv_offset(int offset, const char *buf, const char *delim,
742 char *word, **argv = arr_alloc(offset + 1, sizeof(char *));
746 for (i = 0; i < offset; i++)
748 for (p = buf; p && *p; p += ret, i++) {
749 ret = get_next_word(p, delim, &word);
754 argv = arr_realloc(argv, i + 2, sizeof(char*));
769 * Split a buffer into words.
771 * This parser honors single and double quotes, backslash-escaped characters
772 * and special characters like \\n. The result contains pointers to copies of
773 * the words contained in buf and has to be freed by using \ref free_argv().
775 * \param buf The buffer to be split.
776 * \param delim Each character in this string is treated as a separator.
777 * \param result The array of words is returned here.
779 * It's OK to pass NULL as the buffer argument. This is equivalent to passing
782 * \return Number of words in buf, negative on errors. The array returned
783 * through the result pointer is NULL terminated.
785 int create_argv(const char *buf, const char *delim, char ***result)
787 return create_argv_offset(0, buf, delim, result);
791 * Split a buffer into words, offset one.
793 * This is similar to \ref create_argv() but the returned array is one element
794 * larger, words start at index one and element zero is initialized to \p NULL.
795 * Callers must set element zero to a non-NULL value before calling free_argv()
796 * on the returned array to avoid a memory leak.
798 * \param buf See \ref create_argv().
799 * \param delim See \ref create_argv().
800 * \param result See \ref create_argv().
802 * \return Number of words plus one on success, negative on errors.
804 int create_shifted_argv(const char *buf, const char *delim, char ***result)
806 return create_argv_offset(1, buf, delim, result);
810 * Compile a regular expression.
812 * This simple wrapper calls regcomp() and logs a message on errors.
814 * \param preg See regcomp(3).
815 * \param regex See regcomp(3).
816 * \param cflags See regcomp(3).
820 int para_regcomp(regex_t *preg, const char *regex, int cflags)
824 int ret = regcomp(preg, regex, cflags);
828 size = regerror(ret, preg, NULL, 0);
830 regerror(ret, preg, buf, size);
831 PARA_ERROR_LOG("%s\n", buf);
837 * strdup() for not necessarily zero-terminated strings.
839 * \param src The source buffer.
840 * \param len The number of bytes to be copied.
842 * \return A 0-terminated buffer of length \a len + 1.
844 * This is similar to strndup(), which is a GNU extension. However, one
845 * difference is that strndup() returns \p NULL if insufficient memory was
846 * available while this function aborts in this case.
848 * \sa strdup(), \ref para_strdup().
850 char *safe_strdup(const char *src, size_t len)
854 assert(len < (size_t)-1);
863 * Copy the value of a key=value pair.
865 * This checks whether the given buffer starts with "key=", ignoring case. If
866 * yes, a copy of the value is returned. The source buffer may not be
869 * \param src The source buffer.
870 * \param len The number of bytes of the tag.
871 * \param key Only copy if it is the value of this key.
873 * \return A zero-terminated buffer, or \p NULL if the key was
874 * not of the given type.
876 char *key_value_copy(const char *src, size_t len, const char *key)
878 int keylen = strlen(key);
882 if (strncasecmp(src, key, keylen))
884 if (src[keylen] != '=')
886 return safe_strdup(src + keylen + 1, len - keylen - 1);
889 static bool utf8_mode(void)
891 static bool initialized, have_utf8;
894 char *info = nl_langinfo(CODESET);
895 have_utf8 = (info && strcmp(info, "UTF-8") == 0);
897 PARA_INFO_LOG("%susing UTF-8 character encoding\n",
898 have_utf8? "" : "not ");
903 static int xwcwidth(wchar_t wc, size_t pos)
907 /* special-case for tab */
908 if (wc == 0x09) /* tab */
909 return (pos | 7) + 1 - pos;
911 /* wcswidth() returns -1 for non-printable characters */
912 return n >= 0? n : 1;
915 static size_t xwcswidth(const wchar_t *s, size_t n)
920 w += xwcwidth(*s++, w);
925 * Skip a given number of cells at the beginning of a string.
927 * \param s The input string.
928 * \param cells_to_skip Desired number of cells that should be skipped.
929 * \param bytes_to_skip Result.
931 * This function computes how many input bytes must be skipped to advance a
932 * string by the given width. If the current character encoding is not UTF-8,
933 * this is simply the given number of cells, i.e. \a cells_to_skip. Otherwise,
934 * \a s is treated as a multibyte string and on successful return, \a s +
935 * bytes_to_skip points to the start of a multibyte string such that the total
936 * width of the multibyte characters that are skipped by advancing \a s that
937 * many bytes equals at least \a cells_to_skip.
941 int skip_cells(const char *s, size_t cells_to_skip, size_t *bytes_to_skip)
945 size_t n, bytes_parsed, cells_skipped;
948 if (cells_to_skip == 0)
951 *bytes_to_skip = cells_to_skip;
954 bytes_parsed = cells_skipped = 0;
955 memset(&ps, 0, sizeof(ps));
957 while (cells_to_skip > cells_skipped) {
960 mbret = mbrtowc(&wc, s + bytes_parsed, n - bytes_parsed, &ps);
962 if (mbret == (size_t)-1 || mbret == (size_t)-2)
963 return -ERRNO_TO_PARA_ERROR(EILSEQ);
964 bytes_parsed += mbret;
965 cells_skipped += xwcwidth(wc, cells_skipped);
967 *bytes_to_skip = bytes_parsed;
972 * Compute the width of an UTF-8 string.
974 * \param s The string.
975 * \param result The width of \a s is returned here.
977 * If not in UTF8-mode. this function is just a wrapper for strlen(3).
978 * Otherwise \a s is treated as an UTF-8 string and its display width is
979 * computed. Note that this function may fail if the underlying call to
980 * mbsrtowcs(3) fails, so the caller must check the return value.
982 * \sa nl_langinfo(3), wcswidth(3).
986 __must_check int strwidth(const char *s, size_t *result)
990 static wchar_t *dest;
994 * Never call any log function here. This may result in an endless loop
995 * as para_gui's para_log() calls this function.
1002 memset(&state, 0, sizeof(state));
1004 num_wchars = mbsrtowcs(NULL, &src, 0, &state);
1005 if (num_wchars == (size_t)-1)
1006 return -ERRNO_TO_PARA_ERROR(errno);
1007 if (num_wchars == 0)
1009 dest = arr_alloc(num_wchars + 1, sizeof(*dest));
1011 memset(&state, 0, sizeof(state));
1012 num_wchars = mbsrtowcs(dest, &src, num_wchars, &state);
1013 assert(num_wchars > 0 && num_wchars != (size_t)-1);
1014 *result = xwcswidth(dest, num_wchars);
1020 * Truncate and sanitize a (wide character) string.
1022 * This replaces all non-printable characters by spaces and makes sure that the
1023 * modified string does not exceed the given maximal width.
1025 * \param src The source string in multi-byte form.
1026 * \param max_width The maximal number of cells the result may occupy.
1027 * \param result Sanitized multi-byte string, must be freed by caller.
1028 * \param width The width of the sanitized string, always <= max_width.
1030 * The function is wide-character aware but falls back to C strings for
1031 * non-UTF-8 locales.
1033 * \return Standard. On success, *result points to a sanitized copy of the
1034 * given string. This copy was allocated with malloc() and should hence be
1035 * freed when the caller is no longer interested in the result.
1037 * The function fails if the given string contains an invalid multibyte
1038 * sequence. In this case, *result is set to NULL, and *width to zero.
1040 __must_check int sanitize_str(const char *src, size_t max_width,
1041 char **result, size_t *width)
1044 static wchar_t *wcs;
1045 size_t num_wchars, n;
1048 *result = para_strdup(src);
1049 /* replace non-printable characters by spaces */
1050 for (n = 0; n < max_width && src[n]; n++) {
1051 if (!isprint((unsigned char)src[n]))
1054 (*result)[n] = '\0';
1060 memset(&state, 0, sizeof(state));
1061 num_wchars = mbsrtowcs(NULL, &src, 0, &state);
1062 if (num_wchars == (size_t)-1)
1063 return -ERRNO_TO_PARA_ERROR(errno);
1064 wcs = arr_alloc(num_wchars + 1, sizeof(*wcs));
1065 memset(&state, 0, sizeof(state));
1066 num_wchars = mbsrtowcs(wcs, &src, num_wchars + 1, &state);
1067 assert(num_wchars != (size_t)-1);
1068 for (n = 0; n < num_wchars && *width < max_width; n++) {
1069 if (!iswprint(wcs[n]))
1071 *width += xwcwidth(wcs[n], *width);
1074 n = wcstombs(NULL, wcs, 0) + 1;
1076 num_wchars = wcstombs(*result, wcs, n);
1077 assert(num_wchars != (size_t)-1);