C16RTOMB(3) | Library Functions Manual | C16RTOMB(3) |
c16rtomb
—
#include <uchar.h>
size_t
c16rtomb
(char * restrict s,
char16_t c16, mbstate_t * restrict
ps);
c16rtomb
function decodes UTF-16 and converts it to
multibyte characters in the current locale, keeping state to remember
incremental progress if restarted.
Each call to c16rtomb
updates the
conversion state ps with a UTF-16 code unit
c16, writes up to MB_CUR_MAX
bytes to s (possibly none), and returns either the
number of bytes written to s or
(size_t)-1
to denote error.
If s is a null pointer, no output is
produced and ps is reset to the initial conversion
state, as if the call had been
c8rtomb
(buf,
0
, ps); for some internal
buffer buf.
If c16 is zero,
c16rtomb
discards any pending incomplete UTF-16 code
unit sequence in ps, outputs a (possibly empty) shift
sequence to restore the initial state followed by a NUL byte, and resets
ps to the initial conversion state.
If ps is a null pointer,
c16rtomb
uses an internal
mbstate_t object with static storage duration,
distinct from all other mbstate_t objects (including
those used by other functions such as
mbrtoc16(3)), which is
initialized at program startup to the initial conversion state.
c16rtomb
function returns the number of bytes
written to s on success, or sets
errno(2) and returns
(size_t)-1
on failure.
char16_t c16[] = { 0xd83d, 0xdca9 }; char buf[(__arraycount(c16) + 1)*MB_LEN_MAX], *s = buf; size_t i; mbstate_t mbs = {0}; /* initial conversion state */ for (i = 0; i < __arraycount(c16); i++) { size_t len; len = c16rtomb(s, c16[i], &mbs); if (len == (size_t)-1) err(1, "c16rtomb"); assert(len < sizeof(buf) - (s - buf)); s += len; } len = c16rtomb(s, 0, &mbs); /* NUL-terminate */ if (len == (size_t)-1) err(1, "c16rtomb"); assert(len <= sizeof(buf) - (s - buf)); printf("%s\n", buf);
To avoid a variable-length array, this code uses
MB_LEN_MAX
, which is a constant upper bound on the
locale-dependent MB_CUR_MAX
.
The Unicode Standard, https://www.unicode.org/versions/Unicode15.0.0/UnicodeStandard-15.0.pdf, The Unicode Consortium, September 2022, Version 15.0 — Core Specification.
P. Hoffman and F. Yergeau, UTF-16, an encoding of ISO 10646, Internet Engineering Task Force, RFC 2781, https://datatracker.ietf.org/doc/html/rfc2781, February 2000.
c16rtomb
function conforms to
ISO/IEC 9899:2011 (“ISO C11”).
c16rtomb
function first appeared in
NetBSD 11.0.
However, some implementations such as FreeBSD
14.0, OpenBSD 7.4, and glibc 2.36 ignore this
clause and, if the zero was preceded by an incomplete UTF-16 code unit
sequence, fail with EILSEQ
instead.
August 14, 2024 | NetBSD 10.1 |