memchr_32.c 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. /*
  2. * Copyright 2010 Tilera Corporation. All Rights Reserved.
  3. *
  4. * This program is free software; you can redistribute it and/or
  5. * modify it under the terms of the GNU General Public License
  6. * as published by the Free Software Foundation, version 2.
  7. *
  8. * This program is distributed in the hope that it will be useful, but
  9. * WITHOUT ANY WARRANTY; without even the implied warranty of
  10. * MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE, GOOD TITLE or
  11. * NON INFRINGEMENT. See the GNU General Public License for
  12. * more details.
  13. */
  14. #include <linux/types.h>
  15. #include <linux/string.h>
  16. #include <linux/module.h>
  17. void *memchr(const void *s, int c, size_t n)
  18. {
  19. const uint32_t *last_word_ptr;
  20. const uint32_t *p;
  21. const char *last_byte_ptr;
  22. uintptr_t s_int;
  23. uint32_t goal, before_mask, v, bits;
  24. char *ret;
  25. if (__builtin_expect(n == 0, 0)) {
  26. /* Don't dereference any memory if the array is empty. */
  27. return NULL;
  28. }
  29. /* Get an aligned pointer. */
  30. s_int = (uintptr_t) s;
  31. p = (const uint32_t *)(s_int & -4);
  32. /* Create four copies of the byte for which we are looking. */
  33. goal = 0x01010101 * (uint8_t) c;
  34. /* Read the first word, but munge it so that bytes before the array
  35. * will not match goal.
  36. *
  37. * Note that this shift count expression works because we know
  38. * shift counts are taken mod 32.
  39. */
  40. before_mask = (1 << (s_int << 3)) - 1;
  41. v = (*p | before_mask) ^ (goal & before_mask);
  42. /* Compute the address of the last byte. */
  43. last_byte_ptr = (const char *)s + n - 1;
  44. /* Compute the address of the word containing the last byte. */
  45. last_word_ptr = (const uint32_t *)((uintptr_t) last_byte_ptr & -4);
  46. while ((bits = __insn_seqb(v, goal)) == 0) {
  47. if (__builtin_expect(p == last_word_ptr, 0)) {
  48. /* We already read the last word in the array,
  49. * so give up.
  50. */
  51. return NULL;
  52. }
  53. v = *++p;
  54. }
  55. /* We found a match, but it might be in a byte past the end
  56. * of the array.
  57. */
  58. ret = ((char *)p) + (__insn_ctz(bits) >> 3);
  59. return (ret <= last_byte_ptr) ? ret : NULL;
  60. }
  61. EXPORT_SYMBOL(memchr);