strspn.c 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. /* Copyright (C) 1991-2019 Free Software Foundation, Inc.
  2. This file is part of the GNU C Library.
  3. The GNU C Library is free software; you can redistribute it and/or
  4. modify it under the terms of the GNU Lesser General Public
  5. License as published by the Free Software Foundation; either
  6. version 2.1 of the License, or (at your option) any later version.
  7. The GNU C Library is distributed in the hope that it will be useful,
  8. but WITHOUT ANY WARRANTY; without even the implied warranty of
  9. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  10. Lesser General Public License for more details.
  11. You should have received a copy of the GNU Lesser General Public
  12. License along with the GNU C Library; if not, see
  13. <http://www.gnu.org/licenses/>. */
  14. #include <string.h>
  15. #include <stdint.h>
  16. #include <libc-pointer-arith.h>
  17. #undef strspn
  18. #ifndef STRSPN
  19. # define STRSPN strspn
  20. #endif
  21. /* Return the length of the maximum initial segment
  22. of S which contains only characters in ACCEPT. */
  23. size_t
  24. STRSPN (const char *str, const char *accept)
  25. {
  26. if (accept[0] == '\0')
  27. return 0;
  28. if (__glibc_unlikely (accept[1] == '\0'))
  29. {
  30. const char *a = str;
  31. for (; *str == *accept; str++);
  32. return str - a;
  33. }
  34. /* Use multiple small memsets to enable inlining on most targets. */
  35. unsigned char table[256];
  36. unsigned char *p = memset (table, 0, 64);
  37. memset (p + 64, 0, 64);
  38. memset (p + 128, 0, 64);
  39. memset (p + 192, 0, 64);
  40. unsigned char *s = (unsigned char*) accept;
  41. /* Different from strcspn it does not add the NULL on the table
  42. so can avoid check if str[i] is NULL, since table['\0'] will
  43. be 0 and thus stopping the loop check. */
  44. do
  45. p[*s++] = 1;
  46. while (*s);
  47. s = (unsigned char*) str;
  48. if (!p[s[0]]) return 0;
  49. if (!p[s[1]]) return 1;
  50. if (!p[s[2]]) return 2;
  51. if (!p[s[3]]) return 3;
  52. s = (unsigned char *) PTR_ALIGN_DOWN (s, 4);
  53. unsigned int c0, c1, c2, c3;
  54. do {
  55. s += 4;
  56. c0 = p[s[0]];
  57. c1 = p[s[1]];
  58. c2 = p[s[2]];
  59. c3 = p[s[3]];
  60. } while ((c0 & c1 & c2 & c3) != 0);
  61. size_t count = s - (unsigned char *) str;
  62. return (c0 & c1) == 0 ? count + c0 : count + c2 + 2;
  63. }
  64. libc_hidden_builtin_def (strspn)