3 <<memrchr>>---reverse search for character in memory
10 void *memrchr(const void *<[src]>, int <[c]>, size_t <[length]>);
13 This function searches memory starting at <[length]> bytes
14 beyond <<*<[src]>>> backwards for the character <[c]>.
15 The search only ends with the first occurrence of <[c]>; in
16 particular, <<NUL>> does not terminate the search.
19 If the character <[c]> is found within <[length]> characters
20 of <<*<[src]>>>, a pointer to the character is returned. If
21 <[c]> is not found, then <<NULL>> is returned.
24 <<memrchr>> is a GNU extension.
26 <<memrchr>> requires no supporting OS subroutines.
36 /* Nonzero if X is not aligned on a "long" boundary. */
37 #define UNALIGNED(X) ((long)(X + 1) & (sizeof (long) - 1))
39 /* How many bytes are loaded each iteration of the word copy loop. */
40 #define LBLOCKSIZE (sizeof (long))
42 /* Threshhold for punting to the bytewise iterator. */
43 #define TOO_SMALL(LEN) ((LEN) < LBLOCKSIZE)
45 #if LONG_MAX == 2147483647L
46 #define DETECTNULL(X) (((X) - 0x01010101) & ~(X) & 0x80808080)
48 #if LONG_MAX == 9223372036854775807L
49 /* Nonzero if X (a long int) contains a NULL byte. */
50 #define DETECTNULL(X) (((X) - 0x0101010101010101) & ~(X) & 0x8080808080808080)
52 #error long int is not a 32bit or 64bit type.
57 #error long int is not a 32bit or 64bit byte
60 /* DETECTCHAR returns nonzero if (long)X contains the byte used
61 to fill (long)MASK. */
62 #define DETECTCHAR(X,MASK) (DETECTNULL(X ^ MASK))
65 memrchr (const void *src_void
,
69 const unsigned char *src
= (const unsigned char *) src_void
+ length
- 1;
72 #if !defined(PREFER_SIZE_OVER_SPEED) && !defined(__OPTIMIZE_SIZE__)
77 while (UNALIGNED (src
))
86 if (!TOO_SMALL (length
))
88 /* If we get this far, we know that length is large and src is
90 /* The fast code reads the source one word at a time and only
91 performs the bytewise search on word-sized segments if they
92 contain the search character, which is detected by XORing
93 the word-sized segment with a word-sized block of the search
94 character and then detecting for the presence of NUL in the
96 asrc
= (unsigned long *) (src
- LBLOCKSIZE
+ 1);
98 mask
= mask
<< 16 | mask
;
99 for (i
= 32; i
< LBLOCKSIZE
* 8; i
<<= 1)
100 mask
= (mask
<< i
) | mask
;
102 while (length
>= LBLOCKSIZE
)
104 if (DETECTCHAR (*asrc
, mask
))
106 length
-= LBLOCKSIZE
;
110 /* If there are fewer than LBLOCKSIZE characters left,
111 then we resort to the bytewise loop. */
113 src
= (unsigned char *) asrc
+ LBLOCKSIZE
- 1;
116 #endif /* not PREFER_SIZE_OVER_SPEED */