xref: /csrg-svn/lib/libc/string/memset.c (revision 59959)
1 /*-
2  * Copyright (c) 1990 The Regents of the University of California.
3  * All rights reserved.
4  *
5  * This code is derived from software contributed to Berkeley by
6  * Mike Hibler and Chris Torek.
7  *
8  * %sccs.include.redist.c%
9  */
10 
11 #if defined(LIBC_SCCS) && !defined(lint)
12 static char sccsid[] = "@(#)memset.c	5.7 (Berkeley) 05/12/93";
13 #endif /* LIBC_SCCS and not lint */
14 
15 #include <sys/types.h>
16 
17 #include <limits.h>
18 #include <string.h>
19 
20 #define	wsize	sizeof(u_int)
21 #define	wmask	(wsize - 1)
22 
23 void *
24 memset(dst0, c0, length)
25 	void *dst0;
26 	register int c0;
27 	register size_t length;
28 {
29 	register size_t t;
30 	register u_int c;
31 	register char *dst;
32 
33 	dst = (char *)dst0;
34 	/*
35 	 * If not enough words, just fill bytes.  A length >= 2 words
36 	 * guarantees that at least one of them is `complete' after
37 	 * any necessary alignment.  For instance:
38 	 *
39 	 *	|-----------|-----------|-----------|
40 	 *	|00|01|02|03|04|05|06|07|08|09|0A|00|
41 	 *	          ^---------------------^
42 	 *		 dst		 dst+length-1
43 	 *
44 	 * but we use a minimum of 3 here since the overhead of the code
45 	 * to do word writes is substantial.
46 	 */
47 	if (length < 3 * wsize) {
48 		while (length != 0) {
49 			*dst++ = c0;
50 			--length;
51 		}
52 		return (dst0);
53 	}
54 
55 	if ((c = (u_char)c0) != 0) {	/* Copy value into the word. */
56 		c = (c << 8) | c;	/* u_int is 16 bits. */
57 #if UINT_MAX > 65535
58 		c = (c << 16) | c;	/* u_int is 32 bits. */
59 #endif
60 #if UINT_MAX > 0xffffffff		/* GCC will bitch, otherwise. */
61 		c = (c << 32) | c;	/* u_int is 64 bits. */
62 #endif
63 	}
64 
65 	/* Align destination by filling in bytes. */
66 	if ((t = (int)dst & wmask) != 0) {
67 		t = wsize - t;
68 		length -= t;
69 		do {
70 			*dst++ = c0;
71 		} while (--t != 0);
72 	}
73 
74 	/* Fill words.  Length was >= 2*words so we know t >= 1 here. */
75 	t = length / wsize;
76 	do {
77 		*(u_int *)dst = c;
78 		dst += wsize;
79 	} while (--t != 0);
80 
81 	/* Mop up trailing bytes, if any. */
82 	t = length & wmask;
83 	if (t != 0)
84 		do {
85 			*dst++ = c0;
86 		} while (--t != 0);
87 	return (dst0);
88 }
89