1 /** @file
2   Copyright (c) 2016, Daryl McDaniel. All rights reserved.<BR>
3   Copyright (c) 2012, Intel Corporation. All rights reserved.<BR>
4   This program and the accompanying materials
5   are licensed and made available under the terms and conditions of the BSD License
6   which accompanies this distribution.  The full text of the license may be found at
7   http://opensource.org/licenses/bsd-license.php
8 
9   THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
10   WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
11 **/
12 #include  <assert.h>
13 #include  <string.h>
14 #include  <errno.h>
15 #include  <stdlib.h>
16 #include  <wchar.h>
17 #include  <sys/types.h>
18 #include  <limits.h>
19 
20 typedef int      ch_UCS4;
21 
22 static  mbstate_t     LocalConvState = {0};
23 
24 /** Map a UTF-8 encoded prefix byte to a sequence length.
25     Zero means illegal prefix, but valid surrogate if < 0xC0.
26     One indicates an ASCII-7 equivalent character.
27     Two, three, and four are the first byte for 2, 3, and 4 byte sequences, respectively.
28     See RFC 3629 for details.
29 
30   TABLE ENCODING:
31     Low Nibble decodes the first byte into the number of bytes in the sequence.
32       A value of zero indicates an invalid byte.
33     The High Nibble encodes a bit mask to be used to match against the high nibble of the second byte.
34 
35     example:
36       SequenceLength = code[c0] & 0x0F;
37       Mask           = 0x80 | code[c0];
38 
39       Surrogate bytes are valid if: code[cX] & Mask > 0x80;
40 
41 */
42 static
43 UINT8 utf8_code_length[256] = {
44   0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, /* 00-0F */
45   0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01,
46   0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01,
47   0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01,
48   0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01,
49   0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01,
50   0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01,
51   0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, /* 70-7F */
52   0x90, 0x90, 0x90, 0x90, 0x90, 0x90, 0x90, 0x90, 0x90, 0x90, 0x90, 0x90, 0x90, 0x90, 0x90, 0x90, /* 80-8F */
53   0xA0, 0xA0, 0xA0, 0xA0, 0xA0, 0xA0, 0xA0, 0xA0, 0xA0, 0xA0, 0xA0, 0xA0, 0xA0, 0xA0, 0xA0, 0xA0, /* 90-9F */
54   0xC0, 0xC0, 0xC0, 0xC0, 0xC0, 0xC0, 0xC0, 0xC0, 0xC0, 0xC0, 0xC0, 0xC0, 0xC0, 0xC0, 0xC0, 0xC0, /* A0-AF */
55   0xC0, 0xC0, 0xC0, 0xC0, 0xC0, 0xC0, 0xC0, 0xC0, 0xC0, 0xC0, 0xC0, 0xC0, 0xC0, 0xC0, 0xC0, 0xC0, /* B0-BF */
56   0x00, 0x00, 0x72, 0x72, 0x72, 0x72, 0x72, 0x72, 0x72, 0x72, 0x72, 0x72, 0x72, 0x72, 0x72, 0x72, /* C0-C1 + C2-CF */
57   0x72, 0x72, 0x72, 0x72, 0x72, 0x72, 0x72, 0x72, 0x72, 0x72, 0x72, 0x72, 0x72, 0x72, 0x72, 0x72, /* D0-DF */
58   0x43, 0x73, 0x73, 0x73, 0x73, 0x73, 0x73, 0x73, 0x73, 0x73, 0x73, 0x73, 0x73, 0x33, 0x73, 0x73, /* E0-EF */
59   0x64, 0x74, 0x74, 0x74, 0x14, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00  /* F0-F4 + F5-FF */
60 };
61 
62 /** Process one byte of a multibyte character.
63 
64     @param[in]      ch    One byte of a multibyte character.
65     @param[in,out]  ps    Pointer to a conversion state object.
66 
67     @retval   -2      ch is an incomplete but potentially valid character.
68     @retval   -1      ch is not valid in this context.
69     @retval   1:4     The length, in bytes, of the character ch just completed.
70 **/
71 static
72 int
ProcessOneByte(unsigned char ch,mbstate_t * ps)73 ProcessOneByte(unsigned char ch, mbstate_t *ps)
74 {
75   UINT32    Mask;
76   UINT32    Length;
77   int       RetVal = 0;
78 
79   if(ps->A > 3) {
80     // We are in an invalid state
81     ps->A = 0;    // Initial State
82   }
83   ps->C[ps->A] = ch;  // Save the current byte
84   Mask = utf8_code_length[ch];
85 
86   if(ps->A == 0) {    // Initial State.  First byte of sequence.
87     ps->E   = Mask | 0x80;
88     Length  = Mask & 0xF;
89     switch(Length) {
90       case 0:                       // State 0, Code 0
91         errno = EILSEQ;
92         RetVal = -1;
93         ps->E = 1;        // Consume this byte
94         break;
95       case 1:                       // State 0, Code 1
96         // ASCII-7 Character
97         ps->B = ps->D[0] = ch;
98         RetVal = 1;
99         break;
100       default:                      // State 0, Code 2, 3, 4
101         ps->A = 1;    // Next state is State-1
102         RetVal = -2;  // Incomplete but potentially valid character
103         break;
104     }
105   }
106   else {
107     // We are in state 1, 2, or 3 and processing a surrogate byte
108     Length  = ps->E & 0xF;
109     if((Mask & ps->E) > 0x80) {
110       // This byte is valid
111       switch(ps->A) {   // Process based upon our current state
112         case 1:             // Second byte of the sequence.
113           if(Length == 2) {         // State 1, Code 2
114             Length = ((ps->C[0] & 0x1f) << 6) + (ps->C[1] & 0x3f);
115             assert ((Length > 0x007F) && (Length <= 0x07FF));
116             ps->B = ps->D[0] = (UINT16)Length;
117             ps->A = 0;      // Next state is State-0
118             RetVal = 2;
119           }
120           else {    // This isn't the last byte, get more.  State 1, Code 3 or 4
121             ps->A = 2;
122             RetVal = -2;
123           }
124           break;
125         case 2:             // Third byte of the sequence
126           if(Length == 3) {
127             Length = ((ps->C[0] & 0x0f) << 12) + ((ps->C[1] & 0x3f) << 6) + (ps->C[2] & 0x3f);
128             assert ((Length > 0x07FF) && (Length <= 0xFFFF));
129             ps->B = ps->D[0] = (UINT16)Length;
130             ps->A = 0;      // Next state is State-0
131             RetVal = 3;
132           }
133           else {
134             ps->A = 3;
135             RetVal = -2;
136           }
137           break;
138         case 3:             // Fourth byte of the sequence
139           if(Length == 4) {
140             Length = ((ps->C[0] & 0x7) << 18) + ((ps->C[1] & 0x3f) << 12) +
141                      ((ps->C[2] & 0x3f) << 6) + (ps->C[3] & 0x3f);
142             ps->B = Length;
143             assert ((Length > 0xFFFF) && (Length <= 0x10ffff));
144 
145             /*  compute and append the two surrogates: */
146 
147             /*  translate from 10000..10FFFF to 0..FFFF */
148             Length -= 0x10000;
149 
150             /*  high surrogate = top 10 bits added to D800 */
151             ps->D[0] = (UINT16)(0xD800 + (Length >> 10));
152 
153             /*  low surrogate = bottom 10 bits added to DC00 */
154             ps->D[1] = (UINT16)(0xDC00 + (Length & 0x03FF));
155             ps->A = 0;      // Next state is State-0
156             RetVal = 4;
157           }
158           else {
159             errno = EILSEQ;
160             ps->A = 0;
161             RetVal = -1;
162             ps->E = 4;      // Can't happen, but consume this byte anyway
163           }
164           break;
165       }
166     }
167     else {                // Invalid surrogate byte
168       errno = EILSEQ;
169       ps->A = 0;          // Next is State-0
170       RetVal = -1;
171       ps->E = 0;            // Don't Consume, it may be an initial byte
172     }
173   }
174   return RetVal;
175 }
176 
177 /** Convert one Multibyte sequence.
178 
179     @param[out]   Dest      Pointer to output location, or NULL
180     @param[in]    Src       Multibyte Source (UTF8)
181     @param[in]    Len       Max Number of bytes to convert
182     @param[in]    pS        Pointer to State struct., or NULL
183 
184     @retval   -2      Bytes processed comprise an incomplete, but potentially valid, character.
185     @retval   -1      An encoding error was encountered.  ps->E indicates the number of bytes consumed.
186     @retval   0       Either Src is NULL or it points to a NUL character.
187     @retval   1:N     N bytes were consumed producing a valid wide character.
188 **/
189 int
DecodeOneStateful(wchar_t * Dest,const char * Src,ssize_t Len,mbstate_t * pS)190 DecodeOneStateful(
191   wchar_t    *Dest,       // Pointer to output location, or NULL
192   const char *Src,        // Multibyte Source (UTF8)
193   ssize_t     Len,        // Max Number of bytes to convert
194   mbstate_t  *pS          // Pointer to State struct., or NULL
195   )
196 {
197   const char   *SrcEnd;
198   int           NumConv;
199   unsigned char ch;
200 
201   if(pS == NULL) {
202     pS = &LocalConvState;
203   }
204   NumConv = 0;
205   if(Src != NULL) {
206     if(*Src != 0) {
207       SrcEnd  = Src + Len;
208       while(Src < SrcEnd) {
209         ch = (unsigned char)*Src++;
210         NumConv = ProcessOneByte(ch, pS);
211         if(NumConv != -2) {
212           break;
213         }
214       }
215     }
216     else if(Dest != NULL) {
217       *Dest = 0;
218     }
219   }
220   if((NumConv > 0) && (Dest != NULL)) {
221     Dest[0] = pS->D[0];
222     if(NumConv == 4) {
223       Dest[1] = pS->D[1];
224     }
225   }
226   return NumConv;
227 }
228 
229 /*  Determine the number of bytes needed to represent a Wide character
230     as a MBCS character.
231 
232     A single wide character may convert into a one, two, three, or four byte
233     narrow (MBCS or UTF-8) character.  The number of MBCS bytes can be determined
234     as follows.
235 
236     If WCS char      < 0x00000080      One Byte
237     Else if WCS char < 0x0000D800      Two Bytes
238     Else                               Three Bytes
239 
240     Since UEFI only supports the Unicode Base Multilingual Plane (BMP),
241     Four-byte characters are not supported.
242 
243     @param[in]    InCh      Wide character to test.
244 
245     @retval     -1      Improperly formed character
246     @retval      0      InCh is 0x0000
247     @retval     >0      Number of bytes needed for the MBCS character
248 */
249 int
250 EFIAPI
OneWcToMcLen(const wchar_t InCh)251 OneWcToMcLen(const wchar_t InCh)
252 {
253   ssize_t   NumBytes;
254 
255   if(InCh == 0) {             //    Is this a NUL, 0x0000 ?
256     NumBytes = 0;
257   }
258   else if(InCh < 0x0080) {    //    Is this a 1-byte character?
259     NumBytes = 1;
260   }
261   else if(InCh < 0x0800) {    //    Is this a 2-byte character?
262     NumBytes = 2;
263   }
264   else if((InCh >= 0xD800) && (InCh < 0xE000)) {    //    Is this a surrogate?
265     NumBytes = -1;
266   }
267   else {
268     NumBytes = 3;             //    Otherwise, it must be a 3-byte character.
269   }
270   return (int)NumBytes;      // Return extimate of required bytes.
271 }
272 
273 /*  Determine the number of bytes needed to represent a Wide character string
274     as a MBCS string of given maximum length.  Will optionally return the number
275     of wide characters that would be consumed.
276 
277     A single wide character may convert into a one, two, three, or four byte
278     narrow (MBCS or UTF-8) character.  The number of MBCS bytes can be determined
279     as follows.
280 
281     If WCS char      < 0x00000080      One Byte
282     Else if WCS char < 0x00000800      Two Bytes
283     Else if WCS char < 0x00010000      Three Bytes
284     Else                               Four Bytes
285 
286     Since UEFI only supports the Unicode Base Multilingual Plane (BMP),
287     Four-byte characters should not be encountered.
288 
289     @param[in]    Src       Pointer to a wide character string.
290     @param[in]    Limit     Maximum number of bytes the converted string may occupy.
291     @param[out]   NumChar   Pointer to where to store the number of wide characters
292                             consumed, or NULL.
293 
294     @return     The number of bytes required to convert Src to MBCS,
295                 not including the terminating NUL.  If NumChar is not NULL, the number
296                 of characters represented by the return value will be written to
297                 where it points.
298 */
299 size_t
300 EFIAPI
EstimateWtoM(const wchar_t * Src,size_t Limit,size_t * NumChar)301 EstimateWtoM(const wchar_t * Src, size_t Limit, size_t *NumChar)
302 {
303   ssize_t    Estimate;
304   size_t    CharCount;
305   ssize_t   NumBytes;
306   wchar_t   EChar;
307 
308   Estimate  = 0;
309   CharCount = 0;
310   EChar = *Src++;               // Get the initial character and point to next
311   while(((NumBytes = OneWcToMcLen(EChar)) > 0)  &&
312         ((size_t)(Estimate + NumBytes) < Limit))
313   {                             // Until one of the source characters is NUL
314     ++CharCount;                //    Count this character.
315     Estimate += NumBytes;       //    Count the Bytes for this character
316     EChar = *Src++;             //    Get the next source character and point to the next.
317   }
318   if(NumChar != NULL) {
319     *NumChar = CharCount;
320   }
321   return (size_t)Estimate;      // Return esimate of required bytes.
322 }
323 
324 /*  Determine the number of characters in a MBCS string.
325     MBCS characters are one to four bytes long.  By examining the first byte
326     of a MBCS character, one can determine the number of bytes comprising the
327     character.
328 
329     0x00 - 0x7F     One
330     0xC0 - 0xDF     Two
331     0xE0 - 0xEF     Three
332     0xF0 - 0xF7     Four
333 
334     Since UEFI only supports the Unicode Base Multilingual Plane (BMP),
335     Four-byte characters should not be encountered.
336 
337     @param[in]    Src     The string to examine
338 
339     @return   The number of characters represented by the MBCS string.
340 **/
341 size_t
342 EFIAPI
CountMbcsChars(const char * Src)343 CountMbcsChars(const char *Src)
344 {
345   size_t      Count;
346   char        EChar;
347 
348   Count = 0;
349   EChar = *Src++;
350   while(EChar != 0) {
351     if(EChar < 0x80) {
352       ++Count;
353     }
354     else if(EChar < 0xE0) {
355       Count += 2;
356       ++Src;
357     }
358     else if(EChar < 0xF0) {
359       Count += 3;
360       Src += 2;
361     }
362     else {
363       // Ill-formed character
364       break;
365     }
366   }
367   return Count;
368 }
369 
370 /** Convert a wide character (UTF16) into a multibyte character (UTF8)
371 
372     Converts a wide character into a corresponding multibyte character that
373     begins in the conversion state described by the object pointed to by ps.
374     If dst is not a null pointer, the converted character is then stored into
375     the array pointed to by dst.
376 
377     It is the caller's responsibility to ensure that Dest is large enough to
378     hold the resulting MBCS sequence.
379 
380     @param  s       Pointer to the wide-character string to convert
381     @param  Dest    Pointer to the buffer in which to place the converted sequence, or NULL.
382 
383     @retval   -1    An error occurred.  The error reason is in errno.
384     @retval   >=0   The number of bytes stored into Dest.
385 **/
386 ssize_t
EncodeUtf8(char * Dest,wchar_t ch)387 EncodeUtf8(char *Dest, wchar_t ch)
388 {
389   char       *p;              /* next free byte in build buffer */
390   int         NumInBuff;      // number of bytes in Buff
391   char        Buff[4];        // Buffer into which each character is built
392 
393     p = Buff;
394 
395   NumInBuff = 0;
396   if (ch < 0x80) {
397     /* Encode ASCII -- One Byte */
398     *p++ = (char) ch;
399     NumInBuff = 1;
400   }
401   else if (ch < 0x0800) {
402     /* Encode Latin-1 -- Two Byte */
403     *p++ = (char)(0xc0 | (ch >> 6));
404     *p++ = (char)(0x80 | (ch & 0x3f));
405     NumInBuff = 2;
406   }
407   else {
408       /* Encode UCS2 Unicode ordinals -- Three Byte */
409     /* Special case: check for surrogate -- Shouldn't happen in UEFI */
410     if (0xD800 <= ch && ch < 0xE000) {
411       errno = EILSEQ;
412       return -1;
413       }
414     else {
415       *p++ = (char)(0xe0 | (ch >> 12));
416       *p++ = (char)(0x80 | ((ch >> 6) & 0x3f));
417       *p++ = (char)(0x80 | (ch & 0x3f));
418       NumInBuff = 3;
419     }
420   }
421   /*  At this point, Buff holds the converted character which is NumInBuff bytes long.
422       NumInBuff is the value 1, 2, 3, or 4
423   */
424   if(Dest != NULL) {        // Save character if Dest is not NULL
425     memcpy(Dest, Buff, NumInBuff);
426   }
427   return NumInBuff;             // Tell the caller
428 }
429 
430 // ########################  Narrow to Wide Conversions #######################
431 
432 /** If ps is not a null pointer, the mbsinit function determines whether the
433     pointed-to mbstate_t object describes an initial conversion state.
434 
435     @param[in]  ps    Pointer to the conversion state object to test.
436 
437     @return     The mbsinit function returns nonzero if ps is a null pointer
438                 or if the pointed-to object describes an initial conversion
439                 state; otherwise, it returns zero.
440 
441     Declared in: wchar.h
442 **/
443 int
mbsinit(const mbstate_t * ps)444 mbsinit(const mbstate_t *ps)
445 {
446   if((ps == NULL) || (ps->A == 0)) {
447     return 1;
448   }
449   return 0;
450 }
451 
452 /** The mbrlen function is equivalent to the call:<BR>
453 @verbatim
454     mbrtowc(NULL, s, n, ps != NULL ? ps : &internal)
455 @endverbatim
456     where internal is the mbstate_t object for the mbrlen function, except that
457     the expression designated by ps is evaluated only once.
458 
459     @param[in]  s     Pointer to a multibyte character sequence.
460     @param[in]  n     Maximum number of bytes to examine.
461     @param[in]  pS    Pointer to the conversion state object.
462 
463     @retval   0       The next n or fewer characters complete a NUL.
464     @retval   1..n    The number of bytes that complete the multibyte character.
465     @retval   -2      The next n bytes contribute to an incomplete (but potentially valid) multibyte character.
466     @retval   -1      An encoding error occurred.
467 
468     Declared in: wchar.h
469 **/
470 size_t
mbrlen(const char * s,size_t n,mbstate_t * pS)471 mbrlen(
472   const char *s,
473   size_t n,
474   mbstate_t *pS
475   )
476 {
477   return mbrtowc(NULL, s, n, pS);
478 }
479 
480 /** Determine the number of bytes comprising a multibyte character.
481 
482   If S is not a null pointer, the mblen function determines the number of bytes
483   contained in the multibyte character pointed to by S. Except that the
484   conversion state of the mbtowc function is not affected, it is equivalent to
485     mbtowc((wchar_t *)0, S, N);
486 
487   @param[in]  S   NULL to query whether multibyte characters have
488                   state-dependent encodings.  Otherwise, points to a
489                   multibyte character.
490   @param[in]  N   The maximum number of bytes in a multibyte character.
491 
492   @return   If S is a null pointer, the mblen function returns a nonzero or
493             zero value, if multibyte character encodings, respectively, do
494             or do not have state-dependent encodings. If S is not a null
495             pointer, the mblen function either returns 0 (if S points to the
496             null character), or returns the number of bytes that are contained
497             in the multibyte character (if the next N or fewer bytes form a
498             valid multibyte character), or returns -1 (if they do not form a
499             valid multibyte character).
500 
501     Declared in: stdlib.h
502 **/
503 int
mblen(const char * s,size_t n)504 mblen(
505   const char *s,
506   size_t n
507   )
508 {
509   return (int)mbrlen(s, n, NULL);
510 }
511 
512 /**
513 If S is a null pointer, the mbrtowc function is equivalent to the call:<BR>
514 @verbatim
515         mbrtowc(NULL, "", 1, ps)
516 @endverbatim
517 
518 In this case, the values of the parameters pwc and n are ignored.
519 
520 If S is not a null pointer, the mbrtowc function inspects at most n bytes beginning with
521 the byte pointed to by S to determine the number of bytes needed to complete the next
522 multibyte character (including any shift sequences). If the function determines that the
523 next multibyte character is complete and valid, it determines the value of the
524 corresponding wide character and then, if pwc is not a null pointer, stores that value in
525 the object pointed to by pwc. If the corresponding wide character is the null wide
526 character, the resulting state described is the initial conversion state.
527 
528     @param[out]   pwc   Pointer to where the resulting wide character is to be stored.
529     @param[in]     s    Pointer to a multibyte character "string".
530     @param[in]     n    The maximum number of bytes to inspect.
531     @param[in]     ps   Pointer to a conversion state object.
532 
533     @retval   0             if the next n or fewer bytes complete the multibyte
534                             character that corresponds to the null wide
535                             character (which is the value stored).
536     @retval   between_1_and_n_inclusive   if the next n or fewer bytes complete
537                             a valid multibyte character (which is the value
538                             stored); the value returned is the number of bytes
539                             that complete the multibyte character.
540     @retval   (size_t)(-2)  if the next n bytes contribute to an incomplete
541                             (but potentially valid) multibyte character, and
542                             all n bytes have been processed (no value is stored).
543     @retval   (size_t)(-1)  if an encoding error occurs, in which case the next
544                             n or fewer bytes do not contribute to a complete and
545                             valid multibyte character (no value is stored); the
546                             value of the macro EILSEQ is stored in errno, and
547                             the conversion state is unspecified.
548 
549     Declared in: wchar.h
550 **/
551 size_t
mbrtowc(wchar_t * pwc,const char * s,size_t n,mbstate_t * ps)552 mbrtowc(
553   wchar_t *pwc,
554   const char *s,
555   size_t n,
556   mbstate_t *ps
557   )
558 {
559   int     RetVal;
560 
561   RetVal = DecodeOneStateful(pwc, s, (ssize_t)n, ps);
562   return (size_t)RetVal;
563 }
564 
565 /** Convert a multibyte character into a wide character.
566 
567     If S is not a null pointer, the mbtowc function inspects at most N bytes
568     beginning with the byte pointed to by S to determine the number of bytes
569     needed to complete the next multibyte character (including any shift
570     sequences). If the function determines that the next multibyte character
571     is complete and valid, it determines the value of the corresponding wide
572     character and then, if Pwc is not a null pointer, stores that value in
573     the object pointed to by Pwc. If the corresponding wide character is the
574     null wide character, the function is left in the initial conversion state.
575 
576     @param[out]   Pwc Pointer to a wide-character object to receive the converted character.
577     @param[in]    S   Pointer to a multibyte character to convert.
578     @param[in]    N   Maximum number of bytes in a multibyte character.
579 
580     @return   If S is a null pointer, the mbtowc function returns a nonzero or
581               zero value, if multibyte character encodings, respectively, do
582               or do not have state-dependent encodings. If S is not a null
583               pointer, the mbtowc function either returns 0 (if S points to
584               the null character), or returns the number of bytes that are
585               contained in the converted multibyte character (if the next N or
586               fewer bytes form a valid multibyte character), or returns -1
587               (if they do not form a valid multibyte character).
588 
589               In no case will the value returned be greater than N or the value
590               of the MB_CUR_MAX macro.
591 
592     Declared in: stdlib.h
593 **/
594 int
mbtowc(wchar_t * pwc,const char * s,size_t n)595 mbtowc(
596   wchar_t *pwc,
597   const char *s,
598   size_t n
599   )
600 {
601   return (int)mbrtowc(pwc, s, n, NULL);
602 }
603 
604 /**
605 The mbsrtowcs function converts a sequence of multibyte characters that begins in the
606 conversion state described by the object pointed to by ps, from the array indirectly
607 pointed to by src into a sequence of corresponding wide characters. If dst is not a null
608 pointer, the converted characters are stored into the array pointed to by dst. Conversion
609 continues up to and including a terminating null character, which is also stored.
610 Conversion stops earlier in two cases: when a sequence of bytes is encountered that does
611 not form a valid multibyte character, or (if dst is not a null pointer) when len wide
612 characters have been stored into the array pointed to by dst. Each conversion takes
613 place as if by a call to the mbrtowc function.
614 
615 If dst is not a null pointer, the pointer object pointed to by src is assigned either a null
616 pointer (if conversion stopped due to reaching a terminating null character) or the address
617 just past the last multibyte character converted (if any). If conversion stopped due to
618 reaching a terminating null character and if dst is not a null pointer, the resulting state
619 described is the initial conversion state.
620 
621     @param[out]   dst   Pointer to where the resulting wide character sequence is stored.
622     @param[in]    src   Pointer to a pointer to the multibyte character sequence to convert.
623     @param[in]    len   Maximum number of wide characters to be stored into dst.
624     @param[in]    ps    Pointer to a conversion state object.
625 
626     @return   If the input conversion encounters a sequence of bytes that do
627               not form a valid multibyte character, an encoding error occurs:
628               the mbsrtowcs function stores the value of the macro EILSEQ in
629               errno and returns (size_t)(-1); the conversion state is
630               unspecified. Otherwise, it returns the number of multibyte
631               characters successfully converted, not including the terminating
632               null character (if any).
633 
634     Declared in: wchar.h
635 **/
636 size_t
mbsrtowcs(wchar_t * dst,const char ** src,size_t len,mbstate_t * ps)637 mbsrtowcs(
638   wchar_t      *dst,
639   const char  **src,
640   size_t        len,
641   mbstate_t    *ps
642   )
643 {
644   int           x;
645   size_t        RetVal = 0;
646   const char   *MySrc;
647 
648   if((src == NULL) || (*src == NULL)) {
649     return 0;
650   }
651 
652   MySrc = *src;
653   for(x = 1 ; (len != 0) && (x > 0); --len) {
654     x = DecodeOneStateful(dst, MySrc, MB_LEN_MAX, ps);
655     switch(x) {
656       case -2:    // Incomplete character
657       case -1:    // Encoding error
658         RetVal = (size_t)x;
659         break;
660       case 0:     // Encountered NUL character: done.
661         if(dst != NULL) {
662           *dst = 0;
663           *src = NULL;
664         }
665         break;
666       default:    // Successfully decoded a character, continue with next
667         MySrc += x;
668         if(dst != NULL) {
669           ++dst;
670           if(x == 4) {
671             ++dst;
672           }
673           *src = MySrc;
674         }
675         ++RetVal;
676         break;
677     }
678   }
679   return RetVal;
680 }
681 
682 /** Convert a multibyte character string into a wide-character string.
683 
684     The mbstowcs function converts a sequence of multibyte characters that
685     begins in the initial shift state from the array pointed to by Src into
686     a sequence of corresponding wide characters and stores not more than limit
687     wide characters into the array pointed to by Dest.  No multibyte
688     characters that follow a null character (which is converted into a null
689     wide character) will be examined or converted. Each multibyte character
690     is converted as if by a call to the mbtowc function, except that the
691     conversion state of the mbtowc function is not affected.
692 
693     No more than Limit elements will be modified in the array pointed to by Dest.
694     If copying takes place between objects that overlap,
695     the behavior is undefined.
696 
697     @param[out]   Dest    Pointer to the array to receive the converted string.
698     @param[in]    Src     Pointer to the string to be converted.
699     @param[in]    Limit   Maximum number of elements to be written to Dest.
700 
701     @return   If an invalid multibyte character is encountered, the mbstowcs
702               function returns (size_t)(-1). Otherwise, the mbstowcs function
703               returns the number of array elements modified, not including a
704               terminating null wide character, if any.
705 
706     Declared in: stdlib.h
707 **/
708 size_t
mbstowcs(wchar_t * Dest,const char * Src,size_t Limit)709 mbstowcs(
710   wchar_t *Dest,
711   const char *Src,
712   size_t Limit
713   )
714 {
715 
716   /* Dest may be NULL */
717   /* Src may be NULL */
718 
719   return mbsrtowcs(Dest, &Src, Limit, NULL);
720 }
721 
722 /** The btowc function determines whether C constitutes a valid single-byte
723     character in the initial shift state.
724 
725     @param[in]    C   A narrow character to test or convert to wide.
726 
727     @return   The btowc function returns WEOF if c has the value EOF or if
728               (unsigned char)C does not constitute a valid single-byte
729               character in the initial shift state. Otherwise, it returns the
730               wide character representation of that character.
731 
732     Declared in: wchar.h
733 **/
734 wint_t
btowc(int c)735 btowc(int c)
736 {
737   int       x;
738   wchar_t   Dest;
739   wint_t    RetVal = WEOF;
740 
741   if (c == EOF)
742     return WEOF;
743   x = DecodeOneStateful(&Dest, (const char *)&c, 1, NULL);
744   if(x == 0) {
745     RetVal = 0;
746   }
747   else if(x == 1) {
748     RetVal = (wint_t)Dest;
749   }
750   return RetVal;
751 }
752 
753 // ########################  Wide to Narrow Conversions #######################
754 
755 /**
756 If S is a null pointer, the wcrtomb function is equivalent to the call:<BR>
757 @verbatim
758         wcrtomb(buf, L'\0', ps)
759 @endverbatim
760 where buf is an internal buffer.
761 
762 If S is not a null pointer, the wcrtomb function determines the number of bytes needed
763 to represent the multibyte character that corresponds to the wide character given by wc
764 (including any shift sequences), and stores the multibyte character representation in the
765 array whose first element is pointed to by S. At most MB_CUR_MAX bytes are stored. If
766 wc is a null wide character, a null byte is stored, preceded by any shift sequence needed
767 to restore the initial shift state; the resulting state described is the initial conversion state.
768 
769     @param[out]     Dest    Pointer to the location in which to store the resulting
770                             multibyte character.  Otherwise, NULL to reset the
771                             conversion state.
772     @param[in]      wchar   The wide character to convert.
773     @param[in,out]  pS      Pointer to a conversion state object, or NULL.
774 
775     @return   The wcrtomb function returns the number of bytes stored in the
776               array object (including any shift sequences). When wc is not a
777               valid wide character, an encoding error occurs: the function
778               stores the value of the macro EILSEQ in errno and
779               returns (size_t)(-1); the conversion state is unspecified.
780 
781     Declared in: wchar.h
782 **/
783 size_t
wcrtomb(char * Dest,wchar_t wchar,mbstate_t * pS)784 wcrtomb(
785   char *Dest,
786   wchar_t wchar,
787   mbstate_t *pS
788   )
789 {
790   size_t    RetVal;
791 
792   /* Dest may be NULL */
793   if (Dest == NULL) {
794     RetVal = 1;
795   }
796   else {
797     if (wchar == L'\0') {
798       *Dest = '\0';
799       RetVal = 1;
800     }
801     else {
802       RetVal = EncodeUtf8(Dest, wchar);
803     }
804   }
805   if(pS == NULL) {
806     pS = &LocalConvState;
807   }
808   pS->A = 0;      // Set ps to the initial conversion state
809 
810   return RetVal;
811 }
812 
813 /** Convert a wide character into a multibyte character.
814 
815     The wctomb function determines the number of bytes needed to represent the
816     multibyte character corresponding to the wide character given by WC
817     (including any shift sequences), and stores the multibyte character
818     representation in the array whose first element is pointed to by S (if S is
819     not a null pointer). At most MB_CUR_MAX characters are stored. If WC is a
820     null wide character, a null byte is stored, preceded by any shift sequence
821     needed to restore the initial shift state, and the function is left in the
822     initial conversion state.
823 
824     @param[out]   S   Pointer to the object to receive the converted multibyte character.
825     @param[in]    WC  Wide character to be converted.
826 
827     @return   If S is a null pointer, the wctomb function returns a nonzero or
828               zero value, if multibyte character encodings, respectively, do or
829               do not have state-dependent encodings. If S is not a null pointer,
830               the wctomb function returns -1 if the value of WC does not
831               correspond to a valid multibyte character, or returns the number
832               of bytes that are contained in the multibyte character
833               corresponding to the value of WC.
834 
835               In no case will the value returned be greater than the value of
836               the MB_CUR_MAX macro.
837 
838     Declared in: stdlib.h
839 **/
840 int
wctomb(char * s,wchar_t wchar)841 wctomb(
842   char *s,
843   wchar_t wchar
844   )
845 {
846   /*
847     If s is NULL just return whether MB Characters have state
848     dependent encodings -- they don't.
849   */
850   if (s == NULL)
851     return 0;
852 
853   return (int)wcrtomb(s, wchar, NULL);
854 }
855 
856 /** The wcsrtombs function converts a sequence of wide characters from the array
857     indirectly pointed to by Src into a sequence of corresponding multibyte
858     characters that begins in the conversion state described by the object
859     pointed to by ps.
860 
861     If Dest is not a null pointer, the converted characters are stored into the
862     array pointed to by Dest.  Conversion continues up to and including a
863     terminating null wide character, which is also stored. Conversion stops
864     earlier in two cases: when a wide character is reached that does not
865     correspond to a valid multibyte character, or (if Dest is not a null
866     pointer) when the next multibyte character would exceed the limit of Limit
867     total bytes to be stored into the array pointed to by Dest. Each conversion
868     takes place as if by a call to the wcrtomb function.)
869 
870     If Dest is not a null pointer, the pointer object pointed to by Src is
871     assigned either a null pointer (if conversion stopped due to reaching
872     a terminating null wide character) or the address just past the last wide
873     character converted (if any). If conversion stopped due to reaching a
874     terminating null wide character, the resulting state described is the
875     initial conversion state.
876 
877     @param[in]      Dest
878     @param[in,out]  Src
879     @param[in]      Limit   Max number of bytes to store in Dest.
880     @param[in,out]  ps
881 
882     @return     If conversion stops because a wide character is reached that
883                 does not correspond to a valid multibyte character, an
884                 encoding error occurs: the wcsrtombs function stores the
885                 value of the macro EILSEQ in errno and returns (size_t)(-1);
886                 the conversion state is unspecified. Otherwise, it returns
887                 the number of bytes in the resulting multibyte character
888                 sequence, not including the terminating null character (if any).
889 
890     Declared in: wchar.h
891 **/
892 size_t
wcsrtombs(char * Dest,const wchar_t ** Src,size_t Limit,mbstate_t * ps)893 wcsrtombs(
894   char           *Dest,
895   const wchar_t **Src,
896   size_t          Limit,
897   mbstate_t      *ps
898 )
899 {
900   size_t  NumStored;
901   ssize_t MaxBytes;
902   int     count;
903   wchar_t InCh;
904 
905   NumStored = 0;
906   MaxBytes  = (ssize_t)Limit;
907 
908   /* Dest may be NULL */
909   /* Src may be NULL */
910   /* ps appears to be unused */
911 
912   if (Src == NULL || *Src == NULL)
913     return (0);
914 
915   if (Dest == NULL) {
916     NumStored = EstimateWtoM(*Src, ASCII_STRING_MAX, NULL);
917   }
918   else {
919     if((MaxBytes < 0) || (MaxBytes > ASCII_STRING_MAX)) {
920       MaxBytes = ASCII_STRING_MAX;
921     }
922     while ((MaxBytes > 0) && (OneWcToMcLen(InCh = *(*Src)++) <= MaxBytes)) {
923       if(InCh == 0) {
924         *Src = NULL;
925         *Dest = 0;      // NUL terminate Dest string, but don't count the NUL
926         break;
927       }
928       count = (int)wcrtomb(Dest, InCh, NULL);
929       if(count >= 0) {
930         Dest += count;
931         MaxBytes -= count;
932         NumStored += count;
933       }
934       else {
935         NumStored = (size_t)(-1);
936       }
937     }
938   }
939 
940 
941   return NumStored;
942 }
943 
944 /** Convert a wide-character string into a multibyte character string.
945 
946     The wcstombs function converts a sequence of wide characters from the
947     array pointed to by Src into a sequence of corresponding multibyte
948     characters that begins in the initial shift state, and stores these
949     multibyte characters into the array pointed to by Dest, stopping if a
950     multibyte character would exceed the limit of Limit total bytes or if a
951     null character is stored. Each wide character is converted as if by
952     a call to the wctomb function, except that the conversion state of
953     the wctomb function is not affected.
954 
955     No more than Limit bytes will be modified in the array pointed to by Dest.
956     If copying takes place between objects that overlap,
957     the behavior is undefined.
958 
959     @param[out]   Dest    Pointer to the array to receive the converted string.
960     @param[in]    Src     Pointer to the string to be converted.
961     @param[in]    Limit   Maximum number of elements to be written to Dest.
962 
963     @return   If a wide character is encountered that does not correspond to a
964               valid multibyte character, the wcstombs function returns
965               (size_t)(-1). Otherwise, the wcstombs function returns the number
966               of bytes in the resulting multibyte character sequence,
967               not including the terminating null character (if any).
968 
969     Declared in: stdlib.h
970 **/
971 size_t
wcstombs(char * Dest,const wchar_t * Src,size_t Limit)972 wcstombs(
973   char           *Dest,
974   const wchar_t  *Src,
975   size_t          Limit
976 )
977 {
978   /* Dest may be NULL */
979   return wcsrtombs(Dest, &Src, Limit, NULL);
980 }
981 
982 /** The wctob function determines whether C corresponds to a member of the extended
983     character set whose multibyte character representation is a single byte when in the initial
984     shift state.
985 
986     wctob needs to be consistent with wcrtomb.
987     If wcrtomb says that a character is representable in 1 byte,
988     then wctob needs to also represent the character as 1 byte.
989 
990     @return     The wctob function returns EOF if C does not correspond to a multibyte
991                 character with length one in the initial shift state. Otherwise, it
992                 returns the single-byte representation of that character as an
993                 unsigned char converted to an int.
994 
995     Declared in: wchar.h
996 **/
997 int
wctob(wint_t c)998 wctob(wint_t c)
999 {
1000   int   RetVal;
1001 
1002   RetVal = EOF;
1003   if(c == 0) {
1004     RetVal = 0;
1005   }
1006   else if (OneWcToMcLen((const wchar_t)c) == 1) {
1007     RetVal = (int)(c & 0xFF);
1008   }
1009   return RetVal;
1010 }
1011