source: trunk/libs/newlib/src/newlib/libc/string/strlen.c @ 444

Last change on this file since 444 was 444, checked in by satin@…, 6 years ago

add newlib,libalmos-mkh, restructure shared_syscalls.h and mini-libc

File size: 1.7 KB
Line 
1/*
2FUNCTION
3        <<strlen>>---character string length
4
5INDEX
6        strlen
7
8SYNOPSIS
9        #include <string.h>
10        size_t strlen(const char *<[str]>);
11
12DESCRIPTION
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
17RETURNS
18        <<strlen>> returns the character count.
19
20PORTABILITY
21<<strlen>> is ANSI C.
22
23<<strlen>> requires no supporting OS subroutines.
24
25QUICKREF
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
51size_t
52strlen (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}
Note: See TracBrowser for help on using the repository browser.