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