xref: /freebsd/contrib/unbound/compat/memmove.c (revision 4232f826683298e85d469c0ef17259cecd13b2c7)
1 /*
2  *	memmove.c: memmove compat implementation.
3  *
4  *	Copyright (c) 2001-2006, NLnet Labs. All rights reserved.
5  *
6  * See LICENSE for the license.
7 */
8 
9 #include <config.h>
10 #include <stdlib.h>
11 
12 void *memmove(void *dest, const void *src, size_t n);
13 
14 void *memmove(void *dest, const void *src, size_t n)
15 {
16 	uint8_t* from = (uint8_t*) src;
17 	uint8_t* to = (uint8_t*) dest;
18 
19 	if (from == to || n == 0)
20 		return dest;
21 	if (to > from && to-from < (int)n) {
22 		/* to overlaps with from */
23 		/*  <from......>         */
24 		/*         <to........>  */
25 		/* copy in reverse, to avoid overwriting from */
26 		int i;
27 		for(i=n-1; i>=0; i--)
28 			to[i] = from[i];
29 		return dest;
30 	}
31 	if (from > to && from-to < (int)n) {
32 		/* to overlaps with from */
33 		/*        <from......>   */
34 		/*  <to........>         */
35 		/* copy forwards, to avoid overwriting from */
36 		size_t i;
37 		for(i=0; i<n; i++)
38 			to[i] = from[i];
39 		return dest;
40 	}
41 	memcpy(dest, src, n);
42 	return dest;
43 }
44