home *** CD-ROM | disk | FTP | other *** search
/ Tricks of the Windows Gam…ming Gurus (2nd Edition) / Disc2.iso / vc98 / crt / src / _mbslen.c < prev    next >
C/C++ Source or Header  |  1998-06-17  |  2KB  |  83 lines

  1. /***
  2. *_mbslen.c - Return number of multibyte characters in a multibyte string
  3. *
  4. *       Copyright (c) 1989-1997, Microsoft Corporation. All rights reserved.
  5. *
  6. *Purpose:
  7. *       Return number of multibyte characters in a multibyte string
  8. *       excluding the terminal null.  Locale-dependent.
  9. *
  10. *******************************************************************************/
  11.  
  12. #include <cruntime.h>
  13. #include <internal.h>
  14. #include <stdlib.h>
  15. #include <ctype.h>
  16. #include <mtdll.h>
  17. #include <locale.h>
  18. #include <setlocal.h>
  19. #include <dbgint.h>
  20.  
  21. /***
  22. *_mbstrlen - Return number of multibyte characters in a multibyte string
  23. *
  24. *Purpose:
  25. *       Return number of multibyte characters in a multibyte string
  26. *       excluding the terminal null.  Locale-dependent.
  27. *
  28. *Entry:
  29. *       char *s = string
  30. *
  31. *Exit:
  32. *       Returns the number of multibyte characters in the string, or
  33. *       (size_t)-1 if the string contains an invalid multibyte character.
  34. *
  35. *Exceptions:
  36. *
  37. *******************************************************************************/
  38.  
  39. size_t __cdecl _mbstrlen(
  40.         const char *s
  41.         )
  42. {
  43.         int n;
  44. #ifdef _MT
  45.         int local_lock_flag;
  46. #endif  /* _MT */
  47.  
  48.         _ASSERTE (MB_CUR_MAX == 1 || MB_CUR_MAX == 2);
  49.  
  50.         if ( MB_CUR_MAX == 1 )
  51.             /* handle single byte character sets */
  52.             return (int)strlen(s);
  53.  
  54.  
  55.         _lock_locale( local_lock_flag )
  56.  
  57.         /* verify all valid MB chars */
  58.         if ( MultiByteToWideChar( __lc_codepage,
  59.                                   MB_PRECOMPOSED | MB_ERR_INVALID_CHARS,
  60.                                   s,
  61.                                   -1,
  62.                                   NULL,
  63.                                   0 )
  64.              == 0 ) {
  65.             /* bad MB char */
  66.             _unlock_locale( local_lock_flag )
  67.             return (size_t)-1;
  68.         }
  69.  
  70.         /* count MB chars */
  71.         for (n = 0; *s; n++, s++) {
  72.             if ( isleadbyte((unsigned char)*s) ) {
  73.                 if (*++s == '\0')
  74.                     break;
  75.             }
  76.         }
  77.  
  78.         _unlock_locale( local_lock_flag )
  79.  
  80.  
  81.         return(n);
  82. }
  83.