1 | /* |
---|
2 | FUNCTION |
---|
3 | <<strlen>>---character string length |
---|
4 | |
---|
5 | INDEX |
---|
6 | strlen |
---|
7 | |
---|
8 | SYNOPSIS |
---|
9 | #include <string.h> |
---|
10 | size_t strlen(const char *<[str]>); |
---|
11 | |
---|
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. |
---|
16 | |
---|
17 | RETURNS |
---|
18 | <<strlen>> returns the character count. |
---|
19 | |
---|
20 | PORTABILITY |
---|
21 | <<strlen>> is ANSI C. |
---|
22 | |
---|
23 | <<strlen>> requires no supporting OS subroutines. |
---|
24 | |
---|
25 | QUICKREF |
---|
26 | strlen ansi pure |
---|
27 | */ |
---|
28 | |
---|
29 | #include <_ansi.h> |
---|
30 | #include <string.h> |
---|
31 | #include <limits.h> |
---|
32 | |
---|
33 | #define LBLOCKSIZE (sizeof (long)) |
---|
34 | #define UNALIGNED(X) ((long)X & (LBLOCKSIZE - 1)) |
---|
35 | |
---|
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 |
---|
46 | |
---|
47 | #ifndef DETECTNULL |
---|
48 | #error long int is not a 32bit or 64bit byte |
---|
49 | #endif |
---|
50 | |
---|
51 | size_t |
---|
52 | strlen (const char *str) |
---|
53 | { |
---|
54 | const char *start = str; |
---|
55 | |
---|
56 | #if !defined(PREFER_SIZE_OVER_SPEED) && !defined(__OPTIMIZE_SIZE__) |
---|
57 | unsigned long *aligned_addr; |
---|
58 | |
---|
59 | /* Align the pointer, so we can search a word at a time. */ |
---|
60 | while (UNALIGNED (str)) |
---|
61 | { |
---|
62 | if (!*str) |
---|
63 | return str - start; |
---|
64 | str++; |
---|
65 | } |
---|
66 | |
---|
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++; |
---|
72 | |
---|
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; |
---|
76 | |
---|
77 | #endif /* not PREFER_SIZE_OVER_SPEED */ |
---|
78 | |
---|
79 | while (*str) |
---|
80 | str++; |
---|
81 | return str - start; |
---|
82 | } |
---|