exp2l: Work around a NetBSD 10.0/i386 bug.
[gnulib.git] / lib / mbscspn.c
blob69a63e958d86d7d927246df7fc9c0b5c726c35ee
1 /* Searching a string for a character among a given set of characters.
2 Copyright (C) 1999, 2002, 2006-2024 Free Software Foundation, Inc.
3 Written by Bruno Haible <bruno@clisp.org>, 2007.
5 This file is free software: you can redistribute it and/or modify
6 it under the terms of the GNU Lesser General Public License as
7 published by the Free Software Foundation, either version 3 of the
8 License, or (at your option) any later version.
10 This file is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 GNU Lesser General Public License for more details.
15 You should have received a copy of the GNU Lesser General Public License
16 along with this program. If not, see <https://www.gnu.org/licenses/>. */
18 #include <config.h>
20 /* Specification. */
21 #include <string.h>
23 #include <stdlib.h>
25 #if GNULIB_MCEL_PREFER
26 # include "mcel.h"
27 #else
28 # include "mbuiterf.h"
29 #endif
31 /* Find the first occurrence in the character string STRING of any character
32 in the character string ACCEPT. Return the number of bytes from the
33 beginning of the string to this occurrence, or to the end of the string
34 if none exists. */
35 size_t
36 mbscspn (const char *string, const char *accept)
38 /* Optimize two cases. */
39 if (accept[0] == '\0')
40 return strlen (string);
41 if (accept[1] == '\0')
43 const char *ptr = mbschr (string, accept[0]);
44 return (ptr != NULL ? ptr - string : strlen (string));
46 /* General case. */
47 if (MB_CUR_MAX > 1)
49 #if GNULIB_MCEL_PREFER
50 mcel_t a, g;
51 size_t i;
52 for (i = 0; string[i]; i += g.len)
54 g = mcel_scanz (string + i);
55 if (g.len == 1)
57 if (mbschr (accept, string[i]))
58 return i;
60 else
61 for (char const *aiter = accept; *aiter; aiter += a.len)
63 a = mcel_scanz (aiter);
64 if (mcel_cmp (g, a) == 0)
65 return i;
68 return i;
69 #else
70 mbuif_state_t state;
71 const char *iter;
72 for (mbuif_init (state), iter = string; mbuif_avail (state, iter); )
74 mbchar_t cur = mbuif_next (state, iter);
75 if (mb_len (cur) == 1)
77 if (mbschr (accept, *iter))
78 goto found;
80 else
82 mbuif_state_t astate;
83 const char *aiter;
84 for (mbuif_init (astate), aiter = accept;
85 mbuif_avail (astate, aiter); )
87 mbchar_t acur = mbuif_next (astate, aiter);
88 if (mb_equal (acur, cur))
89 goto found;
90 aiter += mb_len (acur);
93 iter += mb_len (cur);
95 found:
96 return iter - string;
97 #endif
99 else
100 return strcspn (string, accept);