1#include <string.h>
2#include <stdint.h>
3#include <ctype.h>
4
5void* memcpy(void* dest, const void* src, size_t len)
6{
7  if ((((uintptr_t)dest | (uintptr_t)src | len) & (sizeof(uintptr_t)-1)) == 0) {
8    const uintptr_t* s = src;
9    uintptr_t *d = dest;
10    while (d < (uintptr_t*)(dest + len))
11      *d++ = *s++;
12  } else {
13    const char* s = src;
14    char *d = dest;
15    while (d < (char*)(dest + len))
16      *d++ = *s++;
17  }
18  return dest;
19}
20
21void* memset(void* dest, int byte, size_t len)
22{
23  if ((((uintptr_t)dest | len) & (sizeof(uintptr_t)-1)) == 0) {
24    uintptr_t word = byte & 0xFF;
25    word |= word << 8;
26    word |= word << 16;
27    word |= word << 16 << 16;
28
29    uintptr_t *d = dest;
30    while (d < (uintptr_t*)(dest + len))
31      *d++ = word;
32  } else {
33    char *d = dest;
34    while (d < (char*)(dest + len))
35      *d++ = byte;
36  }
37  return dest;
38}
39
40size_t strlen(const char *s)
41{
42  const char *p = s;
43  while (*p)
44    p++;
45  return p - s;
46}
47
48int strcmp(const char* s1, const char* s2)
49{
50  unsigned char c1, c2;
51
52  do {
53    c1 = *s1++;
54    c2 = *s2++;
55  } while (c1 != 0 && c1 == c2);
56
57  return c1 - c2;
58}
59
60int memcmp(const void* s1, const void* s2, size_t n)
61{
62  if ((((uintptr_t)s1 | (uintptr_t)s2) & (sizeof(uintptr_t)-1)) == 0) {
63    const uintptr_t* u1 = s1;
64    const uintptr_t* u2 = s2;
65    const uintptr_t* end = u1 + (n / sizeof(uintptr_t));
66    while (u1 < end) {
67      if (*u1 != *u2)
68        break;
69      u1++;
70      u2++;
71    }
72    n -= (const void*)u1 - s1;
73    s1 = u1;
74    s2 = u2;
75  }
76
77  while (n--) {
78    unsigned char c1 = *(const unsigned char*)s1++;
79    unsigned char c2 = *(const unsigned char*)s2++;
80    if (c1 != c2)
81      return c1 - c2;
82  }
83
84  return 0;
85}
86
87char* strcpy(char* dest, const char* src)
88{
89  char* d = dest;
90  while ((*d++ = *src++))
91    ;
92  return dest;
93}
94
95long atol(const char* str)
96{
97  long res = 0;
98  int sign = 0;
99
100  while (*str == ' ')
101    str++;
102
103  if (*str == '-' || *str == '+') {
104    sign = *str == '-';
105    str++;
106  }
107
108  while (*str) {
109    res *= 10;
110    res += *str++ - '0';
111  }
112
113  return sign ? -res : res;
114}
115