1 /*
2 Copyright (c) 1990 Regents of the University of California.
3 All rights reserved.
4  */
5 /*
6 FUNCTION
7 <<mblen>>---minimal multibyte length function
8 
9 INDEX
10 	mblen
11 
12 SYNOPSIS
13 	#include <stdlib.h>
14 	int mblen(const char *<[s]>, size_t <[n]>);
15 
16 DESCRIPTION
17 When _MB_CAPABLE is not defined, this is a minimal ANSI-conforming
18 implementation of <<mblen>>.  In this case, the
19 only ``multi-byte character sequences'' recognized are single bytes,
20 and thus <<1>> is returned unless <[s]> is the null pointer or
21 has a length of 0 or is the empty string.
22 
23 When _MB_CAPABLE is defined, this routine calls <<__MBTOWC>> to perform
24 the conversion, passing a state variable to allow state dependent
25 decoding.  The result is based on the locale setting which may
26 be restricted to a defined set of locales.
27 
28 RETURNS
29 This implementation of <<mblen>> returns <<0>> if
30 <[s]> is <<NULL>> or the empty string; it returns <<1>> if not _MB_CAPABLE or
31 the character is a single-byte character; it returns <<-1>>
32 if the multi-byte character is invalid; otherwise it returns
33 the number of bytes in the multibyte character.
34 
35 PORTABILITY
36 <<mblen>> is required in the ANSI C standard.  However, the precise
37 effects vary with the locale.
38 
39 <<mblen>> requires no supporting OS subroutines.
40 */
41 
42 #include <stdlib.h>
43 #include <wchar.h>
44 #include "local.h"
45 
46 int
mblen(const char * s,size_t n)47 mblen (const char *s,
48         size_t n)
49 {
50 #ifdef _MB_CAPABLE
51   int retval = 0;
52   static NEWLIB_THREAD_LOCAL _mbstate_t _mblen_state;
53 
54   retval = __MBTOWC (NULL, s, n, &_mblen_state);
55   if (retval < 0)
56     {
57       _mblen_state.__count = 0;
58       return -1;
59     }
60   else
61     return retval;
62 
63 #else /* not _MB_CAPABLE */
64   if (s == NULL || *s == '\0')
65     return 0;
66   if (n == 0)
67     return -1;
68   return 1;
69 #endif /* not _MB_CAPABLE */
70 }
71