diff options
-rw-r--r-- | pk/memset.c | 30 | ||||
-rw-r--r-- | pk/strlen.c | 15 |
2 files changed, 30 insertions, 15 deletions
diff --git a/pk/memset.c b/pk/memset.c index f062ad4..c77c45c 100644 --- a/pk/memset.c +++ b/pk/memset.c @@ -1,26 +1,33 @@ -#include <stdlib.h> #include <limits.h> #include <string.h> +#if ULONG_MAX != 18446744073709551615UL && ULONG_MAX != 4294967295UL +# error need sizeof(long) == 4 or sizeof(long) == 8 +#endif + void* memset(void* m, int ch, size_t s) { + size_t i; char* mem = (char*)m; - while(((long)m & (sizeof(long)-1)) && s) + if((long)m & (sizeof(long)-1)) { - *mem++ = ch; - s--; + size_t n = sizeof(long) - ((long)m & (sizeof(long)-1)); + for(i = 0; i < n; i++) + mem[i] = ch; + + mem += n; + s -= n; } long l = ch & 0xFF; l = l | (l << 8); l = l | (l << 16); - if(sizeof(long) == 8) - l = l | (l << 32); - else if(sizeof(long) != 4) - abort(); + #if ULONG_MAX == 18446744073709551615UL + l = l | (l << 32); + #endif long* lmem = (long*)mem; - for(size_t i = 0; i < (s+sizeof(long)-1)/sizeof(long)*sizeof(long); i += 8) + for(i = 0; i < s/sizeof(long) - 7; i += 8) { lmem[i+0] = l; lmem[i+1] = l; @@ -32,7 +39,10 @@ void* memset(void* m, int ch, size_t s) lmem[i+7] = l; } - for(size_t i = (s+sizeof(long)-1)/sizeof(long)*sizeof(long); i < s; i++) + for( ; i < s/sizeof(long); i++) + lmem[i] = l; + + for(i *= sizeof(long); i < s; i++) mem[i] = ch; return m; diff --git a/pk/strlen.c b/pk/strlen.c index f600d47..12b3836 100644 --- a/pk/strlen.c +++ b/pk/strlen.c @@ -1,13 +1,18 @@ #include <string.h> -#include <stdlib.h> +#include <limits.h> + +#if ULONG_MAX != 18446744073709551615UL && ULONG_MAX != 4294967295UL +# error need sizeof(long) == 4 or sizeof(long) == 8 +#endif // from http://www-graphics.stanford.edu/~seander/bithacks.html static inline long hasZeroByte(long l) { - if(sizeof(long) == 4) - return (l - 0x01010101UL) & ~l & 0x80808080UL; - else if(sizeof(long) == 8) - return (l - 0x0101010101010101UL) & ~l & 0x8080808080808080UL; +#if ULONG_MAX == 4294967295UL + return (l - 0x01010101UL) & ~l & 0x80808080UL; +#else + return (l - 0x0101010101010101UL) & ~l & 0x8080808080808080UL; +#endif } size_t strlen(const char* s) |