memchr_64.c 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. /*
  2. * Copyright 2011 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. #include "string-endian.h"
  18. void *memchr(const void *s, int c, size_t n)
  19. {
  20. const uint64_t *last_word_ptr;
  21. const uint64_t *p;
  22. const char *last_byte_ptr;
  23. uintptr_t s_int;
  24. uint64_t goal, before_mask, v, bits;
  25. char *ret;
  26. if (__builtin_expect(n == 0, 0)) {
  27. /* Don't dereference any memory if the array is empty. */
  28. return NULL;
  29. }
  30. /* Get an aligned pointer. */
  31. s_int = (uintptr_t) s;
  32. p = (const uint64_t *)(s_int & -8);
  33. /* Create eight copies of the byte for which we are looking. */
  34. goal = copy_byte(c);
  35. /* Read the first word, but munge it so that bytes before the array
  36. * will not match goal.
  37. */
  38. before_mask = MASK(s_int);
  39. v = (*p | before_mask) ^ (goal & before_mask);
  40. /* Compute the address of the last byte. */
  41. last_byte_ptr = (const char *)s + n - 1;
  42. /* Compute the address of the word containing the last byte. */
  43. last_word_ptr = (const uint64_t *)((uintptr_t) last_byte_ptr & -8);
  44. while ((bits = __insn_v1cmpeq(v, goal)) == 0) {
  45. if (__builtin_expect(p == last_word_ptr, 0)) {
  46. /* We already read the last word in the array,
  47. * so give up.
  48. */
  49. return NULL;
  50. }
  51. v = *++p;
  52. }
  53. /* We found a match, but it might be in a byte past the end
  54. * of the array.
  55. */
  56. ret = ((char *)p) + (CFZ(bits) >> 3);
  57. return (ret <= last_byte_ptr) ? ret : NULL;
  58. }
  59. EXPORT_SYMBOL(memchr);