Tue Oct 10 23:08:53 1995 Roland McGrath <roland@churchy.gnu.ai.mit.edu>
[glibc.git] / sysdeps / alpha / memchr.c
blob11ff542f257ddb190be2ecedd9bc5a4f89e6fe75
1 /* Copyright (C) 1992, 1993, 1994 Free Software Foundation, Inc.
3 The GNU C Library is free software; you can redistribute it and/or
4 modify it under the terms of the GNU Library General Public License as
5 published by the Free Software Foundation; either version 2 of the
6 License, or (at your option) any later version.
8 The GNU C Library is distributed in the hope that it will be useful,
9 but WITHOUT ANY WARRANTY; without even the implied warranty of
10 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
11 Library General Public License for more details.
13 You should have received a copy of the GNU Library General Public
14 License along with the GNU C Library; see the file COPYING.LIB. If
15 not, write to the Free Software Foundation, Inc., 675 Mass Ave,
16 Cambridge, MA 02139, USA. */
18 #include <string.h>
20 /* Search no more than N bytes of S for C. */
22 void *
23 memchr (const void *s, int c, size_t n)
25 const char *char_ptr;
26 const unsigned long int *longword_ptr;
27 unsigned long int charmask;
28 size_t x;
30 c = (unsigned char) c;
32 /* Handle the first few characters by reading one character at a time.
33 Do this until STR is aligned on a 8-byte border. */
34 for (char_ptr = s; n > 0 && ((unsigned long int) char_ptr & 7) != 0;
35 --n, ++char_ptr)
36 if (*char_ptr == c)
37 return (void *) char_ptr;
39 if (n == (size_t)0)
40 return NULL;
42 x = n;
44 longword_ptr = (unsigned long int *) char_ptr;
46 /* Set up a longword, each of whose bytes is C. */
47 charmask = c | (c << 8);
48 charmask |= charmask << 16;
49 charmask |= charmask << 32;
51 for (;;)
53 const unsigned long int longword = *longword_ptr++;
54 int ge, le;
56 if (x < 4)
57 x = (size_t) 0;
58 else
59 x -= 4;
61 /* Set bits in GE if bytes in CHARMASK are >= bytes in LONGWORD. */
62 asm ("cmpbge %1, %2, %0" : "=r" (ge) : "r" (charmask), "r" (longword));
64 /* Set bits in LE if bytes in CHARMASK are <= bytes in LONGWORD. */
65 asm ("cmpbge %2, %1, %0" : "=r" (le) : "r" (charmask), "r" (longword));
67 /* Bytes that are both <= and >= are == to C. */
68 if (ge & le)
70 /* Which of the bytes was the C? */
72 unsigned char *cp = (unsigned char *) (longword_ptr - 1);
73 int i;
75 for (i = 0; i < 6; i++)
76 if (cp[i] == c)
77 return &cp[i];
78 return &cp[7];
81 if (x == (size_t)0)
82 break;
85 return NULL;