Cygwin: mmap: allow remapping part of an existing anonymous mapping
[newlib-cygwin.git] / newlib / libc / string / strlen.c
blobacffa49e1477bf309c7c5a75e62103cd64769ff4
1 /*
2 FUNCTION
3 <<strlen>>---character string length
5 INDEX
6 strlen
8 SYNOPSIS
9 #include <string.h>
10 size_t strlen(const char *<[str]>);
12 DESCRIPTION
13 The <<strlen>> function works out the length of the string
14 starting at <<*<[str]>>> by counting chararacters until it
15 reaches a <<NULL>> character.
17 RETURNS
18 <<strlen>> returns the character count.
20 PORTABILITY
21 <<strlen>> is ANSI C.
23 <<strlen>> requires no supporting OS subroutines.
25 QUICKREF
26 strlen ansi pure
29 #include <_ansi.h>
30 #include <string.h>
31 #include <limits.h>
33 #define LBLOCKSIZE (sizeof (long))
34 #define UNALIGNED(X) ((long)X & (LBLOCKSIZE - 1))
36 #if LONG_MAX == 2147483647L
37 #define DETECTNULL(X) (((X) - 0x01010101) & ~(X) & 0x80808080)
38 #else
39 #if LONG_MAX == 9223372036854775807L
40 /* Nonzero if X (a long int) contains a NULL byte. */
41 #define DETECTNULL(X) (((X) - 0x0101010101010101) & ~(X) & 0x8080808080808080)
42 #else
43 #error long int is not a 32bit or 64bit type.
44 #endif
45 #endif
47 #ifndef DETECTNULL
48 #error long int is not a 32bit or 64bit byte
49 #endif
51 size_t
52 strlen (const char *str)
54 const char *start = str;
56 #if !defined(PREFER_SIZE_OVER_SPEED) && !defined(__OPTIMIZE_SIZE__)
57 unsigned long *aligned_addr;
59 /* Align the pointer, so we can search a word at a time. */
60 while (UNALIGNED (str))
62 if (!*str)
63 return str - start;
64 str++;
67 /* If the string is word-aligned, we can check for the presence of
68 a null in each word-sized block. */
69 aligned_addr = (unsigned long *)str;
70 while (!DETECTNULL (*aligned_addr))
71 aligned_addr++;
73 /* Once a null is detected, we check each byte in that block for a
74 precise position of the null. */
75 str = (char *) aligned_addr;
77 #endif /* not PREFER_SIZE_OVER_SPEED */
79 while (*str)
80 str++;
81 return str - start;