1 | /* |
---|
2 | FUNCTION |
---|
3 | <<wcswidth>>---number of column positions of a wide-character string |
---|
4 | |
---|
5 | INDEX |
---|
6 | wcswidth |
---|
7 | |
---|
8 | SYNOPSIS |
---|
9 | #include <wchar.h> |
---|
10 | int wcswidth(const wchar_t *<[pwcs]>, size_t <[n]>); |
---|
11 | |
---|
12 | DESCRIPTION |
---|
13 | The <<wcswidth>> function shall determine the number of column |
---|
14 | positions required for <[n]> wide-character codes (or fewer than <[n]> |
---|
15 | wide-character codes if a null wide-character code is encountered |
---|
16 | before <[n]> wide-character codes are exhausted) in the string pointed |
---|
17 | to by <[pwcs]>. |
---|
18 | |
---|
19 | RETURNS |
---|
20 | The <<wcswidth>> function either shall return 0 (if <[pwcs]> points to a |
---|
21 | null wide-character code), or return the number of column positions |
---|
22 | to be occupied by the wide-character string pointed to by <[pwcs]>, or |
---|
23 | return -1 (if any of the first <[n]> wide-character codes in the |
---|
24 | wide-character string pointed to by <[pwcs]> is not a printable |
---|
25 | wide-character code). |
---|
26 | |
---|
27 | PORTABILITY |
---|
28 | <<wcswidth>> has been introduced in the Single UNIX Specification Volume 2. |
---|
29 | <<wcswidth>> has been marked as an extension in the Single UNIX Specification Volume 3. |
---|
30 | */ |
---|
31 | |
---|
32 | #include <_ansi.h> |
---|
33 | #include <wchar.h> |
---|
34 | #include "local.h" |
---|
35 | |
---|
36 | int |
---|
37 | wcswidth (const wchar_t *pwcs, |
---|
38 | size_t n) |
---|
39 | |
---|
40 | { |
---|
41 | int w, len = 0; |
---|
42 | if (!pwcs || n == 0) |
---|
43 | return 0; |
---|
44 | do { |
---|
45 | wint_t wi = *pwcs; |
---|
46 | |
---|
47 | #ifdef _MB_CAPABLE |
---|
48 | wi = _jp2uc (wi); |
---|
49 | /* First half of a surrogate pair? */ |
---|
50 | if (sizeof (wchar_t) == 2 && wi >= 0xd800 && wi <= 0xdbff) |
---|
51 | { |
---|
52 | wint_t wi2; |
---|
53 | |
---|
54 | /* Extract second half and check for validity. */ |
---|
55 | if (--n == 0 || (wi2 = _jp2uc (*++pwcs)) < 0xdc00 || wi2 > 0xdfff) |
---|
56 | return -1; |
---|
57 | /* Compute actual unicode value to use in call to __wcwidth. */ |
---|
58 | wi = (((wi & 0x3ff) << 10) | (wi2 & 0x3ff)) + 0x10000; |
---|
59 | } |
---|
60 | #endif /* _MB_CAPABLE */ |
---|
61 | if ((w = __wcwidth (wi)) < 0) |
---|
62 | return -1; |
---|
63 | len += w; |
---|
64 | } while (*pwcs++ && --n > 0); |
---|
65 | return len; |
---|
66 | } |
---|