memset.c 1.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. /*
  2. * Copyright (c) 2013-2020, Arm Limited and Contributors. All rights reserved.
  3. *
  4. * SPDX-License-Identifier: BSD-3-Clause
  5. */
  6. #include <stddef.h>
  7. #include <string.h>
  8. #include <stdint.h>
  9. void *memset(void *dst, int val, size_t count)
  10. {
  11. uint8_t *ptr = dst;
  12. uint64_t *ptr64;
  13. uint64_t fill = (unsigned char)val;
  14. /* Simplify code below by making sure we write at least one byte. */
  15. if (count == 0U) {
  16. return dst;
  17. }
  18. /* Handle the first part, until the pointer becomes 64-bit aligned. */
  19. while (((uintptr_t)ptr & 7U) != 0U) {
  20. *ptr = (uint8_t)val;
  21. ptr++;
  22. if (--count == 0U) {
  23. return dst;
  24. }
  25. }
  26. /* Duplicate the fill byte to the rest of the 64-bit word. */
  27. fill |= fill << 8;
  28. fill |= fill << 16;
  29. fill |= fill << 32;
  30. /* Use 64-bit writes for as long as possible. */
  31. ptr64 = (uint64_t *)ptr;
  32. for (; count >= 8U; count -= 8) {
  33. *ptr64 = fill;
  34. ptr64++;
  35. }
  36. /* Handle the remaining part byte-per-byte. */
  37. ptr = (uint8_t *)ptr64;
  38. while (count-- > 0U) {
  39. *ptr = (uint8_t)val;
  40. ptr++;
  41. }
  42. return dst;
  43. }