-
Notifications
You must be signed in to change notification settings - Fork 10
/
string.c
137 lines (110 loc) · 2.09 KB
/
string.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
#include <string.h>
static void *__memmove_down(void *__dest, __const void *__src, size_t __n)
{
unsigned char *d = (unsigned char *)__dest, *s = (unsigned char *)__src;
while (__n--)
*d++ = *s++;
return __dest;
}
static void *__memmove_up(void *__dest, __const void *__src, size_t __n)
{
unsigned char *d = (unsigned char *)__dest + __n - 1, *s = (unsigned char *)__src + __n - 1;
while (__n--)
*d-- = *s--;
return __dest;
}
void *(memcpy)(void *__dest, __const void *__src, size_t __n)
{
return __memmove_down(__dest, __src, __n);
}
void *(memmove)(void *__dest, __const void *__src, size_t __n)
{
if(__dest > __src)
return __memmove_up(__dest, __src, __n);
else
return __memmove_down(__dest, __src, __n);
}
void *(memchr)(void const *s, int c, size_t n)
{
unsigned char const *_s = (unsigned char const *)s;
while(n && *_s != c) {
++_s;
--n;
}
if(n)
return (void *)_s; /* the C library casts const away */
else
return (void *)0;
}
size_t (strlen)(const char *s)
{
const char *sc = s;
while (*sc != '\0')
sc++;
return sc - s;
}
void *(memset)(void *s, int c, size_t count)
{
char *xs = s;
while (count--)
*xs++ = c;
return s;
}
int (memcmp)(void const *p1, void const *p2, size_t n)
{
unsigned char const *_p1 = p1;
unsigned char const *_p2 = p2;
while(n--) {
if(*_p1 < *_p2)
return -1;
else if(*_p1 > *_p2)
return 1;
++_p1;
++_p2;
}
return 0;
}
int (strcmp)(char const *s1, char const *s2)
{
while(*s1 && *s2) {
if(*s1 < *s2)
return -1;
else if(*s1 > *s2)
return 1;
++s1;
++s2;
}
if(!*s1 && !*s2)
return 0;
else if(!*s1)
return -1;
else
return 1;
}
int (strncmp)(char const *s1, char const *s2, size_t n)
{
while(*s1 && *s2 && n--) {
if(*s1 < *s2)
return -1;
else if(*s1 > *s2)
return 1;
++s1;
++s2;
}
if(n == 0 || (!*s1 && !*s2))
return 0;
else if(!*s1)
return -1;
else
return 1;
}
char *(strchr)(char const *s, int c)
{
unsigned char const *_s = (unsigned char const *)s;
while(*_s && *_s != c)
++_s;
if(*_s)
return (char *)_s; /* the C library casts const away */
else
return (char *)0;
}