]>
Commit | Line | Data |
---|---|---|
bfff8b1b | 1 | /* Copyright (C) 2011-2017 Free Software Foundation, Inc. |
63d143a2 CM |
2 | This file is part of the GNU C Library. |
3 | Contributed by Chris Metcalf <cmetcalf@tilera.com>, 2011. | |
4 | ||
5 | The GNU C Library is free software; you can redistribute it and/or | |
6 | modify it under the terms of the GNU Lesser General Public | |
7 | License as published by the Free Software Foundation; either | |
8 | version 2.1 of the License, or (at your option) any later version. | |
9 | ||
10 | The GNU C Library is distributed in the hope that it will be useful, | |
11 | but WITHOUT ANY WARRANTY; without even the implied warranty of | |
12 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU | |
13 | Lesser General Public License for more details. | |
14 | ||
15 | You should have received a copy of the GNU Lesser General Public | |
ab84e3ff PE |
16 | License along with the GNU C Library. If not, see |
17 | <http://www.gnu.org/licenses/>. */ | |
63d143a2 CM |
18 | |
19 | #include <string.h> | |
20 | #include <stdint.h> | |
21 | ||
22 | void * | |
23 | __memchr (const void *s, int c, size_t n) | |
24 | { | |
25 | const uint32_t *last_word_ptr; | |
26 | const uint32_t *p; | |
27 | const char *last_byte_ptr; | |
28 | uintptr_t s_int; | |
29 | uint32_t goal, before_mask, v, bits; | |
30 | char *ret; | |
31 | ||
32 | if (__builtin_expect (n == 0, 0)) | |
33 | { | |
34 | /* Don't dereference any memory if the array is empty. */ | |
35 | return NULL; | |
36 | } | |
37 | ||
38 | /* Get an aligned pointer. */ | |
39 | s_int = (uintptr_t) s; | |
40 | p = (const uint32_t *) (s_int & -4); | |
41 | ||
42 | /* Create four copies of the byte for which we are looking. */ | |
43 | goal = 0x01010101 * (uint8_t) c; | |
44 | ||
45 | /* Read the first word, but munge it so that bytes before the array | |
46 | will not match goal. Note that this shift count expression works | |
47 | because we know shift counts are taken mod 32. */ | |
48 | before_mask = (1 << (s_int << 3)) - 1; | |
49 | v = (*p | before_mask) ^ (goal & before_mask); | |
50 | ||
51 | /* Compute the address of the last byte. */ | |
52 | last_byte_ptr = (const char *) s + n - 1; | |
53 | ||
54 | /* Compute the address of the word containing the last byte. */ | |
55 | last_word_ptr = (const uint32_t *) ((uintptr_t) last_byte_ptr & -4); | |
56 | ||
57 | while ((bits = __insn_seqb (v, goal)) == 0) | |
58 | { | |
59 | if (__builtin_expect (p == last_word_ptr, 0)) | |
60 | { | |
61 | /* We already read the last word in the array, so give up. */ | |
62 | return NULL; | |
63 | } | |
64 | v = *++p; | |
65 | } | |
66 | ||
67 | /* We found a match, but it might be in a byte past the end of the array. */ | |
68 | ret = ((char *) p) + (__insn_ctz (bits) >> 3); | |
69 | return (ret <= last_byte_ptr) ? ret : NULL; | |
70 | } | |
71 | weak_alias (__memchr, memchr) | |
72 | libc_hidden_builtin_def (memchr) |