feat(string): implement core string/memory functions (level 1)
Word-at-a-time memcpy/memmove/memset/strlen/strcmp implementing the level-1 string slice. memcpy carries an optimize(no-tree-loop- distribute-patterns) attribute: GCC's loop-distribution pass rewrites its word-copy loop into a self-recursive memcpy@plt call at -O2/-O3 otherwise. Ultraworked with [Sisyphus](https://github.com/code-yeongyu/oh-my-openagent) Co-authored-by: Sisyphus <[email protected]>
This commit is contained in:
@@ -0,0 +1,71 @@
|
||||
#ifdef HAVE_CONFIG_H
|
||||
#include <config.h>
|
||||
#endif
|
||||
|
||||
#include <string.h>
|
||||
|
||||
/*
|
||||
* Copy n bytes from src to dst. The regions may overlap, so the copy
|
||||
* direction is chosen by the relative positions: forward when dst starts
|
||||
* at or before src, or at or after the end of src; backward when dst
|
||||
* starts inside src. Word-at-a-time in both directions, with byte heads
|
||||
* and tails; word loads and stores go through __builtin_memcpy.
|
||||
*/
|
||||
void *
|
||||
memmove(void *dst, const void *src, size_t n)
|
||||
{
|
||||
const unsigned long word = sizeof(unsigned long);
|
||||
unsigned char *d = dst;
|
||||
const unsigned char *s = src;
|
||||
|
||||
if (d <= s || d >= s + n)
|
||||
{
|
||||
/* Forward copy. */
|
||||
for (; (unsigned long)d % word != 0 && n != 0; n--)
|
||||
{
|
||||
*d++ = *s++;
|
||||
}
|
||||
while (n >= word)
|
||||
{
|
||||
unsigned long w;
|
||||
|
||||
__builtin_memcpy(&w, s, sizeof w);
|
||||
__builtin_memcpy(d, &w, sizeof w);
|
||||
d += word;
|
||||
s += word;
|
||||
n -= word;
|
||||
}
|
||||
while (n != 0)
|
||||
{
|
||||
*d++ = *s++;
|
||||
n--;
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
/* Backward copy, starting from the last byte. */
|
||||
d += n;
|
||||
s += n;
|
||||
for (; (unsigned long)d % word != 0 && n != 0; n--)
|
||||
{
|
||||
*--d = *--s;
|
||||
}
|
||||
while (n >= word)
|
||||
{
|
||||
unsigned long w;
|
||||
|
||||
d -= word;
|
||||
s -= word;
|
||||
__builtin_memcpy(&w, s, sizeof w);
|
||||
__builtin_memcpy(d, &w, sizeof w);
|
||||
n -= word;
|
||||
}
|
||||
while (n != 0)
|
||||
{
|
||||
*--d = *--s;
|
||||
n--;
|
||||
}
|
||||
}
|
||||
|
||||
return dst;
|
||||
}
|
||||
Reference in New Issue
Block a user