memset.c (1225B)
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 * Use of this source code is governed by a MIT-style 10 * license that can be found in the LICENSE file or at 11 * https://opensource.org/licenses/MIT 12 */ 13 #include <string.h> 14 #include <stdint.h> 15 16 void * 17 memset(void *s, int c, size_t count) { 18 char *xs = (char *) s; 19 size_t len = (-(size_t)s) & (sizeof(size_t)-1); 20 size_t cc = c & 0xff; 21 22 if ( count > len ) { 23 count -= len; 24 cc |= cc << 8; 25 cc |= cc << 16; 26 if (sizeof(size_t) == 8) 27 cc |= (uint64_t)cc << 32; // should be optimized out on 32 bit machines 28 29 // write to non-aligned memory byte-wise 30 for ( ; len > 0; len-- ) 31 *xs++ = c; 32 33 // write to aligned memory dword-wise 34 for ( len = count/sizeof(size_t); len > 0; len-- ) { 35 *((size_t *)xs) = (size_t)cc; 36 xs += sizeof(size_t); 37 } 38 39 count &= sizeof(size_t)-1; 40 } 41 42 // write remaining bytes 43 for ( ; count > 0; count-- ) 44 *xs++ = c; 45 46 return s; 47 }