memset.c 1.01 KB
Newer Older
1
/*
2
 * Copyright (c) 2013-2020, ARM Limited and Contributors. All rights reserved.
3
4
5
6
7
8
 *
 * SPDX-License-Identifier: BSD-3-Clause
 */

#include <stddef.h>
#include <string.h>
9
#include <stdint.h>
10
11
12

void *memset(void *dst, int val, size_t count)
{
13
	uint8_t *ptr = dst;
14
15
	uint64_t *ptr64;
	uint64_t fill = (unsigned char)val;
16

17
	/* Simplify code below by making sure we write at least one byte. */
18
	if (count == 0U) {
19
20
21
22
		return dst;
	}

	/* Handle the first part, until the pointer becomes 64-bit aligned. */
23
24
25
26
	while (((uintptr_t)ptr & 7U) != 0U) {
		*ptr = (uint8_t)val;
		ptr++;
		if (--count == 0U) {
27
28
29
30
31
32
33
34
35
36
			return dst;
		}
	}

	/* Duplicate the fill byte to the rest of the 64-bit word. */
	fill |= fill << 8;
	fill |= fill << 16;
	fill |= fill << 32;

	/* Use 64-bit writes for as long as possible. */
37
38
39
40
	ptr64 = (uint64_t *)ptr;
	for (; count >= 8U; count -= 8) {
		*ptr64 = fill;
		ptr64++;
41
42
43
	}

	/* Handle the remaining part byte-per-byte. */
44
45
46
47
	ptr = (uint8_t *)ptr64;
	while (count-- > 0U)  {
		*ptr = (uint8_t)val;
		ptr++;
48
	}
49
50
51

	return dst;
}