memset.c 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. #include <string.h>
  2. #include <stdint.h>
  3. void *memset(void *dest, int c, size_t n)
  4. {
  5. unsigned char *s = dest;
  6. size_t k;
  7. /* Fill head and tail with minimal branching. Each
  8. * conditional ensures that all the subsequently used
  9. * offsets are well-defined and in the dest region. */
  10. if (!n) return dest;
  11. s[0] = s[n-1] = c;
  12. if (n <= 2) return dest;
  13. s[1] = s[n-2] = c;
  14. s[2] = s[n-3] = c;
  15. if (n <= 6) return dest;
  16. s[3] = s[n-4] = c;
  17. if (n <= 8) return dest;
  18. /* Advance pointer to align it at a 4-byte boundary,
  19. * and truncate n to a multiple of 4. The previous code
  20. * already took care of any head/tail that get cut off
  21. * by the alignment. */
  22. k = -(uintptr_t)s & 3;
  23. s += k;
  24. n -= k;
  25. n &= -4;
  26. #ifdef __GNUC__
  27. typedef uint32_t __attribute__((__may_alias__)) u32;
  28. typedef uint64_t __attribute__((__may_alias__)) u64;
  29. u32 c32 = ((u32)-1)/255 * (unsigned char)c;
  30. /* In preparation to copy 32 bytes at a time, aligned on
  31. * an 8-byte bounary, fill head/tail up to 28 bytes each.
  32. * As in the initial byte-based head/tail fill, each
  33. * conditional below ensures that the subsequent offsets
  34. * are valid (e.g. !(n<=24) implies n>=28). */
  35. *(u32 *)(s+0) = c32;
  36. *(u32 *)(s+n-4) = c32;
  37. if (n <= 8) return dest;
  38. *(u32 *)(s+4) = c32;
  39. *(u32 *)(s+8) = c32;
  40. *(u32 *)(s+n-12) = c32;
  41. *(u32 *)(s+n-8) = c32;
  42. if (n <= 24) return dest;
  43. *(u32 *)(s+12) = c32;
  44. *(u32 *)(s+16) = c32;
  45. *(u32 *)(s+20) = c32;
  46. *(u32 *)(s+24) = c32;
  47. *(u32 *)(s+n-28) = c32;
  48. *(u32 *)(s+n-24) = c32;
  49. *(u32 *)(s+n-20) = c32;
  50. *(u32 *)(s+n-16) = c32;
  51. /* Align to a multiple of 8 so we can fill 64 bits at a time,
  52. * and avoid writing the same bytes twice as much as is
  53. * practical without introducing additional branching. */
  54. k = 24 + ((uintptr_t)s & 4);
  55. s += k;
  56. n -= k;
  57. /* If this loop is reached, 28 tail bytes have already been
  58. * filled, so any remainder when n drops below 32 can be
  59. * safely ignored. */
  60. u64 c64 = c32 | ((u64)c32 << 32);
  61. for (; n >= 32; n-=32, s+=32) {
  62. *(u64 *)(s+0) = c64;
  63. *(u64 *)(s+8) = c64;
  64. *(u64 *)(s+16) = c64;
  65. *(u64 *)(s+24) = c64;
  66. }
  67. #else
  68. /* Pure C fallback with no aliasing violations. */
  69. for (; n; n--, s++) *s = c;
  70. #endif
  71. return dest;
  72. }