Embedded Artistry libc
C Standard Library Support for Bare-metal Systems
memset.c
Go to the documentation of this file.
1
// MUSL memset implementation:
2
// https://github.com/esmil/musl/blob/master/src/string/memset.c
3
4
#include <
stdint.h
>
5
#include <
string.h
>
6
7
void
*
__attribute__
((weak))
memset
(
void
* dest,
int
c,
size_t
n)
8
{
9
unsigned
char
* s = dest;
10
size_t
k;
11
12
/* Fill head and tail with minimal branching. Each
13
* conditional ensures that all the subsequently used
14
* offsets are well-defined and in the dest region. */
15
16
if
(!n)
17
{
18
return
dest;
19
}
20
s[0] = s[n - 1] = (
unsigned
char)c;
21
if
(n <= 2)
22
{
23
return
dest;
24
}
25
s[1] = s[n - 2] = (
unsigned
char)c;
26
s[2] = s[n - 3] = (
unsigned
char)c;
27
if
(n <= 6)
28
{
29
return
dest;
30
}
31
s[3] = s[n - 4] = (
unsigned
char)c;
32
if
(n <= 8)
33
{
34
return
dest;
35
}
36
37
/* Advance pointer to align it at a 4-byte boundary,
38
* and truncate n to a multiple of 4. The previous code
39
* already took care of any head/tail that get cut off
40
* by the alignment. */
41
42
k = -(uintptr_t)s & 3;
43
s += k;
44
n -= k;
45
n &= (
unsigned
long)-4;
46
n /= 4;
47
48
// Cast to void first to prevent alignment warning
49
uint32_t* ws = (uint32_t*)(
void
*)s;
50
uint32_t wc = c & 0xFF;
51
wc |= ((wc << 8) | (wc << 16) | (wc << 24));
52
53
/* Pure C fallback with no aliasing violations. */
54
for
(; n; n--, ws++)
55
{
56
{
57
*ws = wc;
58
}
59
}
60
61
return
dest;
62
}
string.h
__attribute__
void * __attribute__((weak))
Definition:
memset.c:7
memset
void * memset(void *dest, int c, size_t n)
Copies the value c into each of the first n characters of the object pointed to by dest.
stdint.h
src
string
memset.c
Generated by
1.8.15