aboutsummaryrefslogtreecommitdiffstats
path: root/memcmove.c
blob: a5382502f63495a99db22b56dc943dca9d08a5d0 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
/* See LICENSE file for copyright and license details. */
#include "common.h"
#ifndef TEST


void *
libsimple_memcmove(void *d_, const void *s_, int c_, size_t n)
{
	char *d = d_, c = (char)c_, *p;
	const char *s = s_;
	if (d <= s) {
		for (; n; n--, s++)
			if ((*d++ = *s) == c)
				return d;
	} else {
		for (p = *(char **)(void *)&s; n; n--, p++) {
			if (*p == c) {
				n = (size_t)(p - s);
				p = &d[n + 1];
				do { d[n] = s[n]; } while (n--);
				return p;
			}
		}
		for (n = (size_t)(p - s); n;) {
			n--;
			d[n] = s[n];
		}
	}
	return NULL;
}


#else
#include "test.h"

int
main(void)
{
	char buf[1024];

	memset(buf, '-', sizeof(buf));
	buf[sizeof(buf) - 1] = '\0';
	stpcpy(&buf[5], "hello")[0] = '-';
	assert(libsimple_memcmove(&buf[5], &buf[5], 'o', 5) == &buf[5 + 5]);
	assert(!strncmp(buf, "-----hello-", 11));

	memset(buf, '-', sizeof(buf));
	buf[sizeof(buf) - 1] = '\0';
	stpcpy(&buf[5], "hello")[0] = '-';
	assert(libsimple_memcmove(&buf[5], &buf[5], 'l', 5) == &buf[5 + 3]);
	assert(!strncmp(buf, "-----hello-", 11));

	memset(buf, '-', sizeof(buf));
	buf[sizeof(buf) - 1] = '\0';
	stpcpy(&buf[5], "hello")[0] = '-';
	assert(libsimple_memcmove(&buf[5], &buf[5], 'x', 5) == NULL);
	assert(!strncmp(buf, "-----hello-", 11));


	memset(buf, '-', sizeof(buf));
	buf[sizeof(buf) - 1] = '\0';
	stpcpy(&buf[5], "hello")[0] = '-';
	assert(libsimple_memcmove(&buf[3], &buf[5], 'o', 5) == &buf[3 + 5]);
	assert(!strncmp(buf, "---hellolo-", 11));

	memset(buf, '-', sizeof(buf));
	buf[sizeof(buf) - 1] = '\0';
	stpcpy(&buf[5], "hello")[0] = '-';
	assert(libsimple_memcmove(&buf[3], &buf[5], 'l', 5) == &buf[3 + 3]);
	assert(!strncmp(buf, "---helello-", 11));

	memset(buf, '-', sizeof(buf));
	buf[sizeof(buf) - 1] = '\0';
	stpcpy(&buf[5], "hello")[0] = '-';
	assert(libsimple_memcmove(&buf[3], &buf[5], 'x', 5) == NULL);
	assert(!strncmp(buf, "---hellolo-", 11));


	memset(buf, '-', sizeof(buf));
	buf[sizeof(buf) - 1] = '\0';
	stpcpy(&buf[5], "hello")[0] = '-';
	assert(libsimple_memcmove(&buf[8], &buf[5], 'o', 5) == &buf[8 + 5]);
	assert(!strncmp(buf, "-----helhello-", 14));

	memset(buf, '-', sizeof(buf));
	buf[sizeof(buf) - 1] = '\0';
	stpcpy(&buf[5], "hello")[0] = '-';
	assert(libsimple_memcmove(&buf[8], &buf[5], 'l', 5) == &buf[8 + 3]);
	assert(!strncmp(buf, "-----helhel-", 12));

	memset(buf, '-', sizeof(buf));
	buf[sizeof(buf) - 1] = '\0';
	stpcpy(&buf[5], "hello")[0] = '-';
	assert(libsimple_memcmove(&buf[8], &buf[5], 'x', 5) == NULL);
	assert(!strncmp(buf, "-----helhello-", 14));

	return 0;
}

#endif