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