Merge from coreutils.
[gnulib.git] / lib / memrchr.c
1 /* memrchr -- find the last occurrence of a byte in a memory block
2
3    Copyright (C) 1991, 1993, 1996, 1997, 1999, 2000, 2003, 2004 Free
4    Software Foundation, Inc.
5
6    Based on strlen implementation by Torbjorn Granlund (tege@sics.se),
7    with help from Dan Sahlin (dan@sics.se) and
8    commentary by Jim Blandy (jimb@ai.mit.edu);
9    adaptation to memchr suggested by Dick Karpinski (dick@cca.ucsf.edu),
10    and implemented by Roland McGrath (roland@ai.mit.edu).
11
12    This program is free software; you can redistribute it and/or modify
13    it under the terms of the GNU General Public License as published by
14    the Free Software Foundation; either version 2, or (at your option)
15    any later version.
16
17    This program is distributed in the hope that it will be useful,
18    but WITHOUT ANY WARRANTY; without even the implied warranty of
19    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
20    GNU General Public License for more details.
21
22    You should have received a copy of the GNU General Public License along
23    with this program; if not, write to the Free Software Foundation,
24    Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.  */
25
26 #ifdef HAVE_CONFIG_H
27 # include <config.h>
28 #endif
29
30 #include <string.h>
31
32 #include <stddef.h>
33
34 #if defined _LIBC
35 # include <memcopy.h>
36 #else
37 # define reg_char char
38 #endif
39
40 #include <limits.h>
41
42 #undef __memrchr
43 #undef memrchr
44
45 #ifndef weak_alias
46 # define __memrchr memrchr
47 #endif
48
49 /* Search no more than N bytes of S for C.  */
50 void *
51 __memrchr (void const *s, int c_in, size_t n)
52 {
53   const unsigned char *char_ptr;
54   const unsigned long int *longword_ptr;
55   unsigned long int longword, magic_bits, charmask;
56   unsigned reg_char c;
57   int i;
58
59   c = (unsigned char) c_in;
60
61   /* Handle the last few characters by reading one character at a time.
62      Do this until CHAR_PTR is aligned on a longword boundary.  */
63   for (char_ptr = (const unsigned char *) s + n;
64        n > 0 && (size_t) char_ptr % sizeof longword != 0;
65        --n)
66     if (*--char_ptr == c)
67       return (void *) char_ptr;
68
69   /* All these elucidatory comments refer to 4-byte longwords,
70      but the theory applies equally well to any size longwords.  */
71
72   longword_ptr = (const unsigned long int *) char_ptr;
73
74   /* Bits 31, 24, 16, and 8 of this number are zero.  Call these bits
75      the "holes."  Note that there is a hole just to the left of
76      each byte, with an extra at the end:
77
78      bits:  01111110 11111110 11111110 11111111
79      bytes: AAAAAAAA BBBBBBBB CCCCCCCC DDDDDDDD
80
81      The 1-bits make sure that carries propagate to the next 0-bit.
82      The 0-bits provide holes for carries to fall into.  */
83
84   /* Set MAGIC_BITS to be this pattern of 1 and 0 bits.
85      Set CHARMASK to be a longword, each of whose bytes is C.  */
86
87   magic_bits = 0xfefefefe;
88   charmask = c | (c << 8);
89   charmask |= charmask << 16;
90 #if 0xffffffffU < ULONG_MAX
91   magic_bits |= magic_bits << 32;
92   charmask |= charmask << 32;
93   if (8 < sizeof longword)
94     for (i = 64; i < sizeof longword * 8; i *= 2)
95       {
96         magic_bits |= magic_bits << i;
97         charmask |= charmask << i;
98       }
99 #endif
100   magic_bits = (ULONG_MAX >> 1) & (magic_bits | 1);
101
102   /* Instead of the traditional loop which tests each character,
103      we will test a longword at a time.  The tricky part is testing
104      if *any of the four* bytes in the longword in question are zero.  */
105   while (n >= sizeof longword)
106     {
107       /* We tentatively exit the loop if adding MAGIC_BITS to
108          LONGWORD fails to change any of the hole bits of LONGWORD.
109
110          1) Is this safe?  Will it catch all the zero bytes?
111          Suppose there is a byte with all zeros.  Any carry bits
112          propagating from its left will fall into the hole at its
113          least significant bit and stop.  Since there will be no
114          carry from its most significant bit, the LSB of the
115          byte to the left will be unchanged, and the zero will be
116          detected.
117
118          2) Is this worthwhile?  Will it ignore everything except
119          zero bytes?  Suppose every byte of LONGWORD has a bit set
120          somewhere.  There will be a carry into bit 8.  If bit 8
121          is set, this will carry into bit 16.  If bit 8 is clear,
122          one of bits 9-15 must be set, so there will be a carry
123          into bit 16.  Similarly, there will be a carry into bit
124          24.  If one of bits 24-30 is set, there will be a carry
125          into bit 31, so all of the hole bits will be changed.
126
127          The one misfire occurs when bits 24-30 are clear and bit
128          31 is set; in this case, the hole at bit 31 is not
129          changed.  If we had access to the processor carry flag,
130          we could close this loophole by putting the fourth hole
131          at bit 32!
132
133          So it ignores everything except 128's, when they're aligned
134          properly.
135
136          3) But wait!  Aren't we looking for C, not zero?
137          Good point.  So what we do is XOR LONGWORD with a longword,
138          each of whose bytes is C.  This turns each byte that is C
139          into a zero.  */
140
141       longword = *--longword_ptr ^ charmask;
142
143       /* Add MAGIC_BITS to LONGWORD.  */
144       if ((((longword + magic_bits)
145
146             /* Set those bits that were unchanged by the addition.  */
147             ^ ~longword)
148
149            /* Look at only the hole bits.  If any of the hole bits
150               are unchanged, most likely one of the bytes was a
151               zero.  */
152            & ~magic_bits) != 0)
153         {
154           /* Which of the bytes was C?  If none of them were, it was
155              a misfire; continue the search.  */
156
157           const unsigned char *cp = (const unsigned char *) longword_ptr;
158
159           if (8 < sizeof longword)
160             for (i = sizeof longword - 1; 8 <= i; i--)
161               if (cp[i] == c)
162                 return (void *) &cp[i];
163           if (7 < sizeof longword && cp[7] == c)
164             return (void *) &cp[7];
165           if (6 < sizeof longword && cp[6] == c)
166             return (void *) &cp[6];
167           if (5 < sizeof longword && cp[5] == c)
168             return (void *) &cp[5];
169           if (4 < sizeof longword && cp[4] == c)
170             return (void *) &cp[4];
171           if (cp[3] == c)
172             return (void *) &cp[3];
173           if (cp[2] == c)
174             return (void *) &cp[2];
175           if (cp[1] == c)
176             return (void *) &cp[1];
177           if (cp[0] == c)
178             return (void *) cp;
179         }
180
181       n -= sizeof longword;
182     }
183
184   char_ptr = (const unsigned char *) longword_ptr;
185
186   while (n-- > 0)
187     {
188       if (*--char_ptr == c)
189         return (void *) char_ptr;
190     }
191
192   return 0;
193 }
194 #ifdef weak_alias
195 weak_alias (__memrchr, memrchr)
196 #endif