Redid memmove to not use copies

This commit is contained in:
NeGate 2022-06-07 22:42:08 -04:00
parent 9458655faf
commit 17a258f736
1 changed files with 13 additions and 6 deletions

View File

@ -6,8 +6,6 @@
#include <stdbool.h> #include <stdbool.h>
#include <stdlib.h> #include <stdlib.h>
// TODO: rewrite memmove to not allocate anything
typedef unsigned char byte; typedef unsigned char byte;
void *memcpy(void *restrict s1, const void *restrict s2, size_t n) { void *memcpy(void *restrict s1, const void *restrict s2, size_t n) {
@ -21,10 +19,19 @@ void *memcpy(void *restrict s1, const void *restrict s2, size_t n) {
} }
void *memmove(void *s1, const void *s2, size_t n) { void *memmove(void *s1, const void *s2, size_t n) {
void *buffer = malloc(n); byte* c1 = s1;
memcpy(buffer, s2, n); const byte* c2 = s2;
memcpy(s1, buffer, n);
free(buffer); if (c1 != c2) {
if (c1 < c2) {
// reverse copy
for (size_t i = n; i--;) c1[i] = c2[i];
} else {
// normal copy
for (size_t i = 0; i < n; i++) c1[i] = c2[i];
}
}
return s1; return s1;
} }