From bf4e733688b3bac9d48d463d584a95d1e6d73efb Mon Sep 17 00:00:00 2001 From: Max Wash Date: Fri, 17 Apr 2020 11:22:23 +0100 Subject: [PATCH] Implemented memcpy() --- photon/libc/include/string.h | 6 +++++ photon/libc/string/memcpy.c | 43 ++++++++++++++++++++++++++++++++++++ 2 files changed, 49 insertions(+) create mode 100644 photon/libc/string/memcpy.c diff --git a/photon/libc/include/string.h b/photon/libc/include/string.h index 631f22e..a0b904f 100644 --- a/photon/libc/include/string.h +++ b/photon/libc/include/string.h @@ -7,7 +7,13 @@ extern "C" { #endif +extern void *memcpy(void *dest, const void *src, size_t sz); +extern void *memcmp(const void *a, const void *b, size_t sz); +extern void *memmove(void *dest, const void *src, size_t sz); + extern size_t strlen(const char *str); +extern int strcmp(const char *a, const char *b); +extern int strncmp(const char *a, const char *b, size_t sz); #if defined(__cplusplus) } /* extern "C" */ diff --git a/photon/libc/string/memcpy.c b/photon/libc/string/memcpy.c new file mode 100644 index 0000000..7a1dc1d --- /dev/null +++ b/photon/libc/string/memcpy.c @@ -0,0 +1,43 @@ +#include + +#define ALIGNED(p) (!((long)p & (sizeof(long) - 1))) +#define QUADBLOCKSIZE (sizeof(long) << 2) +#define BLOCKSIZE (sizeof(long)) + +void *memcpy(void *dest, const void *src, size_t sz) +{ + /* Only try word-writing if the pointers are aligned and + * the buffer is big enough */ + if (sz >= BLOCKSIZE && ALIGNED(dest) && ALIGNED(src)) { + long *dest_word = dest; + const long *src_word = src; + + /* First try copying 4x blocks per iteration */ + while (sz >= QUADBLOCKSIZE) { + *dest_word++ = *src_word++; + *dest_word++ = *src_word++; + *dest_word++ = *src_word++; + *dest_word++ = *src_word++; + sz -= QUADBLOCKSIZE; + } + + /* Then try copying 1x words per iteration */ + while (sz >= BLOCKSIZE) { + *dest_word++ = *src_word++; + sz -= BLOCKSIZE; + } + + /* Then go back to the byte-level copying */ + dest = dest_word; + src = src_word; + } + + char *dest0 = dest; + const char *src0 = src; + + while (sz-- > 0) { + *dest0++ = *src0++; + } + + return dest; +}