memchr_32.c 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  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. /* Get an aligned pointer. */
  20. const uintptr_t s_int = (uintptr_t) s;
  21. const uint32_t *p = (const uint32_t *)(s_int & -4);
  22. /* Create four copies of the byte for which we are looking. */
  23. const uint32_t goal = 0x01010101 * (uint8_t) c;
  24. /* Read the first word, but munge it so that bytes before the array
  25. * will not match goal.
  26. *
  27. * Note that this shift count expression works because we know
  28. * shift counts are taken mod 32.
  29. */
  30. const uint32_t before_mask = (1 << (s_int << 3)) - 1;
  31. uint32_t v = (*p | before_mask) ^ (goal & before_mask);
  32. /* Compute the address of the last byte. */
  33. const char *const last_byte_ptr = (const char *)s + n - 1;
  34. /* Compute the address of the word containing the last byte. */
  35. const uint32_t *const last_word_ptr =
  36. (const uint32_t *)((uintptr_t) last_byte_ptr & -4);
  37. uint32_t bits;
  38. char *ret;
  39. if (__builtin_expect(n == 0, 0)) {
  40. /* Don't dereference any memory if the array is empty. */
  41. return NULL;
  42. }
  43. while ((bits = __insn_seqb(v, goal)) == 0) {
  44. if (__builtin_expect(p == last_word_ptr, 0)) {
  45. /* We already read the last word in the array,
  46. * so give up.
  47. */
  48. return NULL;
  49. }
  50. v = *++p;
  51. }
  52. /* We found a match, but it might be in a byte past the end
  53. * of the array.
  54. */
  55. ret = ((char *)p) + (__insn_ctz(bits) >> 3);
  56. return (ret <= last_byte_ptr) ? ret : NULL;
  57. }
  58. EXPORT_SYMBOL(memchr);