Skip to content

Commit

Permalink
strings: Implement poor mans memmove
Browse files Browse the repository at this point in the history
Implemented a simple memmove and added another "unittest" for that.

Signed-off-by: Martin Mazein <[email protected]>
  • Loading branch information
MegaMaddin committed Sep 3, 2020
1 parent 807d3c1 commit d131908
Show file tree
Hide file tree
Showing 2 changed files with 56 additions and 0 deletions.
32 changes: 32 additions & 0 deletions include/string.h
Original file line number Diff line number Diff line change
Expand Up @@ -106,6 +106,38 @@ static inline void *memcpy(void *d, void *s, size_t n) {
return d;
}

static inline void *memmove(void *d, const void *s, size_t n) {

/* dst and src are the same */
if (d == s) {
return d;
}

/* if we don't have a range overlap, just use memcpy */
if ((d > s && d > s + n) || (d < s && d + n < s)) {
return memcpy(d, (void *) s, n);
}

/*
* s ------
* d ------
* needs reverse moving
*/
if (s < d) {
while (n--)
*((char *) d + n) = *((char *) s + n);
}
else
/*
* s ------
* d -----
* normal copy
*/
return memcpy(d, (void *) s, n);

return d;
}

static inline int memcmp(const void *m1, const void *m2, size_t n) {
const uint8_t *_m1 = m1;
const uint8_t *_m2 = m2;
Expand Down
24 changes: 24 additions & 0 deletions tests/test.c
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,10 @@ bool_cmd("boolean", opt_bool);

static bool opt_booltwo = 0;
bool_cmd("booleantwo", opt_booltwo);

static char memmove_string[4];
static char range_string[] = "123456";
static char *src, *dst;
#endif

static int __user_text func(void *arg) { return 0; }
Expand Down Expand Up @@ -80,6 +84,26 @@ void test_main(void) {
else {
printk("Boolean parameter parsing works!\n");
}

printk("\nMemmove testing:\n");
(void) memmove(memmove_string, opt_string, sizeof(opt_string));
if (!strcmp(memmove_string, opt_string)) {
printk("Moving around memory works!\n");
}
else {
printk("Memmove'ing did not work: %s (%p) != %s (%p)\n", memmove_string,
memmove_string, opt_string, opt_string);
}

src = (char *) range_string;
dst = (char *) range_string + 2;
(void) memmove(dst, src, 4);
if (!strcmp(range_string, "121234")) {
printk("Moving around memory with overlaping ranges works!\n");
}
else {
printk("Overlaping memmove'ing did not work: %s != %s\n", range_string, "121234");
}
#endif

wait_for_all_tasks();
Expand Down

0 comments on commit d131908

Please sign in to comment.