Skip to content

Instantly share code, notes, and snippets.

@jserv
Created October 8, 2013 15:46
Show Gist options
  • Save jserv/6886791 to your computer and use it in GitHub Desktop.
Save jserv/6886791 to your computer and use it in GitHub Desktop.
The missing string.c
#include <stddef.h>
#include <stdint.h>
#include <limits.h>
#define ALIGN (sizeof(size_t))
#define ONES ((size_t)-1/UCHAR_MAX)
#define HIGHS (ONES * (UCHAR_MAX/2+1))
#define HASZERO(x) ((x)-ONES & ~(x) & HIGHS)
#define SS (sizeof(size_t))
void *memset(void *dest, int c, size_t n)
{
unsigned char *s = dest;
c = (unsigned char)c;
for (; ((uintptr_t)s & ALIGN) && n; n--) *s++ = c;
if (n) {
size_t *w, k = ONES * c;
for (w = (void *)s; n>=SS; n-=SS, w++) *w = k;
for (s = (void *)w; n; n--, s++) *s = c;
}
return dest;
}
char *strncpy(char *dest, const char *src, size_t n)
{
const unsigned char *s = src;
unsigned char *d = dest;
while (n--)
*d++ = *s++;
return dest;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment