Back to index

glibc  2.9
mblen.c
Go to the documentation of this file.
00001 /* Copyright (C) 1991,1997,1998,1999,2000,2002 Free Software Foundation, Inc.
00002    This file is part of the GNU C Library.
00003 
00004    The GNU C Library is free software; you can redistribute it and/or
00005    modify it under the terms of the GNU Lesser General Public
00006    License as published by the Free Software Foundation; either
00007    version 2.1 of the License, or (at your option) any later version.
00008 
00009    The GNU C Library is distributed in the hope that it will be useful,
00010    but WITHOUT ANY WARRANTY; without even the implied warranty of
00011    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
00012    Lesser General Public License for more details.
00013 
00014    You should have received a copy of the GNU Lesser General Public
00015    License along with the GNU C Library; if not, write to the Free
00016    Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
00017    02111-1307 USA.  */
00018 
00019 #include <stdlib.h>
00020 #include <string.h>
00021 #include <wchar.h>
00022 #include <gconv.h>
00023 #include <wcsmbs/wcsmbsload.h>
00024 
00025 
00026 /* Internal state.  */
00027 static mbstate_t state;
00028 
00029 /* Return the length of the multibyte character (if there is one)
00030    at S which is no longer than N characters.
00031    The ISO C standard says that the `mblen' function must not change
00032    the state of the `mbtowc' function.  */
00033 int
00034 mblen (const char *s, size_t n)
00035 {
00036   int result;
00037 
00038   /* If S is NULL the function has to return null or not null
00039      depending on the encoding having a state depending encoding or
00040      not.  */
00041   if (s == NULL)
00042     {
00043       const struct gconv_fcts *fcts;
00044 
00045       /* Get the conversion functions.  */
00046       fcts = get_gconv_fcts (_NL_CURRENT_DATA (LC_CTYPE));
00047 
00048       /* Reset the state.  */
00049       memset (&state, '\0', sizeof state);
00050 
00051       result = fcts->towc->__stateful;
00052     }
00053   else if (*s == '\0')
00054     /* According to the ISO C 89 standard this is the expected behaviour.  */
00055     result = 0;
00056   else
00057     {
00058       memset (&state, '\0', sizeof state);
00059 
00060       result = __mbrtowc (NULL, s, n, &state);
00061 
00062       /* The `mbrtowc' functions tell us more than we need.  Fold the -1
00063         and -2 result into -1.  */
00064       if (result < 0)
00065        result = -1;
00066     }
00067 
00068   return result;
00069 }