xref: /reactos/sdk/lib/ucrt/mbstring/mbsrchr.cpp (revision fe11f7a2)
1 /***
2 *mbsrchr.c - Search for last occurence of character (MBCS)
3 *
4 *       Copyright (c) Microsoft Corporation.  All rights reserved.
5 *
6 *Purpose:
7 *       Search for last occurence of character (MBCS)
8 *
9 *
10 *******************************************************************************/
11 #ifndef _MBCS
12     #error This file should only be compiled with _MBCS defined
13 #endif
14 
15 #include <corecrt_internal_mbstring.h>
16 #include <locale.h>
17 #include <stddef.h>
18 #include <string.h>
19 
20 #pragma warning(disable:__WARNING_POTENTIAL_BUFFER_OVERFLOW_NULLTERMINATED) // 26018
21 
22 /***
23 * _mbsrchr - Search for last occurence of character (MBCS)
24 *
25 *Purpose:
26 *       Find the last occurrence of the specified character in
27 *       the supplied string.  Handles MBCS chars/strings correctly.
28 *
29 *Entry:
30 *       unsigned char *str = string to search in
31 *       unsigned int c = character to search for
32 *
33 *Exit:
34 *       returns pointer to last occurrence of c in str
35 *       returns nullptr if c not found
36 *
37 *Exceptions:
38 *       Input parameters are validated. Refer to the validation section of the function.
39 *
40 *******************************************************************************/
41 
42 extern "C" _CONST_RETURN unsigned char * __cdecl _mbsrchr_l(
43         const unsigned char *str,
44         unsigned int c,
45         _locale_t plocinfo
46         )
47 {
48         char *r = nullptr;
49         unsigned int cc;
50         _LocaleUpdate _loc_update(plocinfo);
51 
52         /* validation section */
53         _VALIDATE_RETURN(str != nullptr, EINVAL, 0);
54 
55         if (_loc_update.GetLocaleT()->mbcinfo->ismbcodepage == 0)
56             return (_CONST_RETURN unsigned char *)strrchr((const char *)str, c);
57 
58         do {
59             cc = *str;
60             if ( _ismbblead_l(cc, _loc_update.GetLocaleT()) ) {
61                 if(*++str) {
62                     if (c == ((cc<<8)|*str))
63                         r = (char *)str - 1;
64                 }
65                 else if(!r)
66                     /* return pointer to '\0' */
67                     r = (char *)str;
68             }
69             else if (c == cc)
70                 r = (char *)str;
71         }
72         while (*str++);
73 
74         return((_CONST_RETURN unsigned char *)r);
75 }
76 
77 extern "C" _CONST_RETURN unsigned char * (__cdecl _mbsrchr)(
78         const unsigned char *str,
79         unsigned int c
80         )
81 {
82     return _mbsrchr_l(str, c, nullptr);
83 }
84