1 /* Copyright (C) 1991-2022 Free Software Foundation, Inc.
2 This file is part of the GNU C Library.
4 The GNU C Library is free software; you can redistribute it and/or
5 modify it under the terms of the GNU Lesser General Public
6 License as published by the Free Software Foundation; either
7 version 2.1 of the License, or (at your option) any later version.
9 The GNU C Library is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
12 Lesser General Public License for more details.
14 You should have received a copy of the GNU Lesser General Public
15 License along with the GNU C Library; if not, see
16 <https://www.gnu.org/licenses/>. */
24 # define STRLEN strlen
27 /* Return the length of the null-terminated string STR. Scan for
28 the null terminator quickly by testing four bytes at a time. */
30 STRLEN (const char *str
)
33 const unsigned long int *longword_ptr
;
34 unsigned long int longword
, himagic
, lomagic
;
36 /* Handle the first few characters by reading one character at a time.
37 Do this until CHAR_PTR is aligned on a longword boundary. */
38 for (char_ptr
= str
; ((unsigned long int) char_ptr
39 & (sizeof (longword
) - 1)) != 0;
41 if (*char_ptr
== '\0')
42 return char_ptr
- str
;
44 /* All these elucidatory comments refer to 4-byte longwords,
45 but the theory applies equally well to 8-byte longwords. */
47 longword_ptr
= (unsigned long int *) char_ptr
;
49 /* Computing (longword - lomagic) sets the high bit of any corresponding
50 byte that is either zero or greater than 0x80. The latter case can be
51 filtered out by computing (~longword & himagic). The final result
52 will always be non-zero if one of the bytes of longword is zero. */
53 himagic
= 0x80808080L
;
54 lomagic
= 0x01010101L
;
55 if (sizeof (longword
) > 4)
57 /* 64-bit version of the magic. */
58 /* Do the shift in two steps to avoid a warning if long has 32 bits. */
59 himagic
= ((himagic
<< 16) << 16) | himagic
;
60 lomagic
= ((lomagic
<< 16) << 16) | lomagic
;
62 if (sizeof (longword
) > 8)
65 /* Instead of the traditional loop which tests each character,
66 we will test a longword at a time. The tricky part is testing
67 if *any of the four* bytes in the longword in question are zero. */
70 longword
= *longword_ptr
++;
72 if (((longword
- lomagic
) & ~longword
& himagic
) != 0)
74 /* Which of the bytes was the zero? */
76 const char *cp
= (const char *) (longword_ptr
- 1);
86 if (sizeof (longword
) > 4)
100 libc_hidden_builtin_def (strlen
)