1 /*
2 FUNCTION
3 	<<strlen>>---character string length
4 
5 INDEX
6 	strlen
7 
8 ANSI_SYNOPSIS
9 	#include <string.h>
10 	size_t strlen(const char *<[str]>);
11 
12 TRAD_SYNOPSIS
13 	#include <string.h>
14 	size_t strlen(<[str]>)
15 	char *<[src]>;
16 
17 DESCRIPTION
18 	The <<strlen>> function works out the length of the string
19 	starting at <<*<[str]>>> by counting chararacters until it
20 	reaches a <<NULL>> character.
21 
22 RETURNS
23 	<<strlen>> returns the character count.
24 
25 PORTABILITY
26 <<strlen>> is ANSI C.
27 
28 <<strlen>> requires no supporting OS subroutines.
29 
30 QUICKREF
31 	strlen ansi pure
32 */
33 
34 #include <section_config.h>
35 #include <basic_types.h>
36 
37 #include <_ansi.h>
38 #include <string.h>
39 #include <limits.h>
40 
41 #define LBLOCKSIZE   (sizeof (long))
42 #define UNALIGNED(X) ((long)X & (LBLOCKSIZE - 1))
43 
44 #if LONG_MAX == 2147483647L
45 #define DETECTNULL(X) (((X) - 0x01010101) & ~(X) & 0x80808080)
46 #else
47 #if LONG_MAX == 9223372036854775807L
48 /* Nonzero if X (a long int) contains a NULL byte. */
49 #define DETECTNULL(X) (((X) - 0x0101010101010101) & ~(X) & 0x8080808080808080)
50 #else
51 #error long int is not a 32bit or 64bit type.
52 #endif
53 #endif
54 
55 #ifndef DETECTNULL
56 #error long int is not a 32bit or 64bit byte
57 #endif
58 
59 LIBC_ROM_TEXT_SECTION
60 _LONG_CALL_
_strlen(const char * str)61 size_t _strlen(const char *str)
62 {
63   const char *start = str;
64 
65 #if !defined(PREFER_SIZE_OVER_SPEED)
66   unsigned long *aligned_addr;
67 
68   /* Align the pointer, so we can search a word at a time.  */
69   while (UNALIGNED (str))
70     {
71       if (!*str)
72 	return str - start;
73       str++;
74     }
75 
76   /* If the string is word-aligned, we can check for the presence of
77      a null in each word-sized block.  */
78   aligned_addr = (unsigned long *)str;
79   while (!DETECTNULL (*aligned_addr))
80     aligned_addr++;
81 
82   /* Once a null is detected, we check each byte in that block for a
83      precise position of the null.  */
84   str = (char *) aligned_addr;
85 
86 #endif /* not PREFER_SIZE_OVER_SPEED */
87 
88   while (*str)
89     str++;
90   return str - start;
91 }
92