1 /*
2 ** Copyright 2005, Michael Noisternig. All rights reserved.
3 ** Copyright 2001, Travis Geiselbrecht. All rights reserved.
4 ** Distributed under the terms of the NewOS License.
5 */
6 /*
7 * Copyright (c) 2008 Travis Geiselbrecht
8 *
9 * Permission is hereby granted, free of charge, to any person obtaining
10 * a copy of this software and associated documentation files
11 * (the "Software"), to deal in the Software without restriction,
12 * including without limitation the rights to use, copy, modify, merge,
13 * publish, distribute, sublicense, and/or sell copies of the Software,
14 * and to permit persons to whom the Software is furnished to do so,
15 * subject to the following conditions:
16 *
17 * The above copyright notice and this permission notice shall be
18 * included in all copies or substantial portions of the Software.
19 *
20 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
21 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
22 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
23 * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
24 * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
25 * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
26 * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
27 */
28 #include <stdint.h>
29 #include <string.h>
30 #include <sys/types.h>
31
32 void *
memset(void * s,int c,size_t count)33 memset(void *s, int c, size_t count)
34 {
35 char *xs = (char *) s;
36 size_t len_mask = sizeof(size_t) - 1;
37 size_t len_delta = (size_t)-(intptr_t)s;
38 size_t len = len_delta & len_mask;
39 size_t cc = c & 0xff;
40
41 if ( count > len ) {
42 count -= len;
43 cc |= cc << 8;
44 cc |= cc << 16;
45 if (sizeof(size_t) == 8)
46 cc |= (uint64_t)cc << 32; // should be optimized out on 32 bit machines
47
48 // write to non-aligned memory byte-wise
49 for ( ; len > 0; len-- )
50 *xs++ = c;
51
52 // write to aligned memory dword-wise
53 for ( len = count/sizeof(size_t); len > 0; len-- ) {
54 *((size_t *)xs) = (size_t)cc;
55 xs += sizeof(size_t);
56 }
57
58 count &= sizeof(size_t)-1;
59 }
60
61 // write remaining bytes
62 for ( ; count > 0; count-- )
63 *xs++ = (char)c;
64
65 return s;
66 }
67