1 /* @(#)fillbytes.c	1.18 10/08/21 Copyright 1987, 1995-2010 J. Schilling */
2 /*
3  *	fill memory with data
4  *
5  *	Copyright (c) 1987, 1995-2010 J. Schilling
6  */
7 /*
8  * The contents of this file are subject to the terms of the
9  * Common Development and Distribution License, Version 1.0 only
10  * (the "License").  You may not use this file except in compliance
11  * with the License.
12  *
13  * See the file CDDL.Schily.txt in this distribution for details.
14  * A copy of the CDDL is also available via the Internet at
15  * http://www.opensource.org/licenses/cddl1.txt
16  *
17  * When distributing Covered Code, include this CDDL HEADER in each
18  * file and include the License file CDDL.Schily.txt from this distribution.
19  */
20 
21 #include <schily/standard.h>
22 #include <schily/align.h>
23 #include <schily/types.h>
24 #include <schily/schily.h>
25 
26 #define	DO8(a)	a; a; a; a; a; a; a; a;
27 
28 #define	cval	((char)lval)
29 
30 /*
31  * fillbytes(to, cnt, val) is the same as memset(to, val, cnt)
32  */
33 #ifdef	PROTOTYPES
34 EXPORT char *
fillbytes(void * tov,ssize_t cnt,char val)35 fillbytes(void *tov, ssize_t cnt, char val)
36 #else
37 EXPORT char *
38 fillbytes(tov, cnt, val)
39 	void	*tov;
40 	ssize_t	cnt;
41 	char	val;
42 #endif
43 {
44 	register char	*to = (char *)tov;
45 	register ssize_t n;
46 	register long	lval;
47 
48 	/*
49 	 * If we change cnt to be unsigned, check for == instead of <=
50 	 */
51 	if ((n = cnt) <= 0)
52 		return (to);
53 
54 	lval = val & 0xFF;
55 
56 	/*
57 	 * Assign byte-wise until properly aligned for a long pointer.
58 	 */
59 	while (--n >= 0 && !laligned(to)) {
60 		*to++ = cval;
61 	}
62 	n++;
63 
64 	if (n >= (ssize_t)(8 * sizeof (long))) {
65 		register ssize_t rem = n % (8 * sizeof (long));
66 
67 		lval |= (lval<<8);
68 		lval |= (lval<<16);
69 #if SIZE_LONG > SIZE_INT
70 		lval |= (lval<<32);
71 #endif
72 
73 		n /= (8 * sizeof (long));
74 		{
75 			register long *tol = (long *)to;
76 
77 			do {
78 				DO8 (*tol++ = lval);
79 			} while (--n > 0);
80 
81 			to = (char *)tol;
82 		}
83 		n = rem;
84 
85 		if (n >= 8) {
86 			n -= 8;
87 			do {
88 				DO8 (*to++ = cval);
89 			} while ((n -= 8) >= 0);
90 			n += 8;
91 		}
92 		if (n > 0) do {
93 			*to++ = cval;
94 		} while (--n > 0);
95 		return (to);
96 	}
97 	if (n > 0) do {
98 		*to++ = cval;
99 	} while (--n > 0);
100 	return (to);
101 }
102