-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcommon.c
More file actions
120 lines (101 loc) · 2.67 KB
/
Copy pathcommon.c
File metadata and controls
120 lines (101 loc) · 2.67 KB
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
#include "common.h"
/* don't like this but whatever */
extern void putchar(char);
void *memcpy(void *dst, const void *src, size_t n) {
uint8_t *d = (uint8_t *)dst;
const uint8_t *s = (const uint8_t *)src;
for (size_t i = 0; i < n; i++) {
d[i] = s[i];
}
return dst;
}
void *memset(void *buf, char c, size_t n) {
uint8_t *p = (uint8_t *)buf;
for (size_t i = 0; i < n; i++) {
*p = c;
}
/* this is returned for chaining */
return buf;
}
char *strcpy(char *dst, const char *src) {
char *d = dst;
while (*src) {
*d = *src;
src++;
d++;
}
*dst = '\0';
return dst;
}
int strcmp(const char *s1, const char *s2) {
while (*s1 && *s2) {
if (*s1 != *s2) {
break;
}
s1++;
s2++;
}
return *s1 - *s2; /* fuck the posix spec */
}
void printf(const char *fmt, ...) {
va_list v_args;
va_start(v_args, fmt);
while (*fmt) {
if (*fmt == '%') {
fmt++;
switch (*fmt) {
case '\0': {
putchar('\0');
fmt--; /* edge case */
break;
}
case '%': {
putchar('%');
break;
}
case 's': {
const char *s = va_arg(v_args, const char *);
while (*s) {
putchar(*s);
s++;
}
break;
}
case 'd': {
int val = va_arg(v_args, int);
/* binary to decimal conversion */
char out[11]; /* 32bit signed int holds 10 chars max + 1 char for null term */
int abs_val;
if (val >= 0) {
abs_val = val;
} else {
abs_val = -val;
putchar('-');
}
int i = 0;
do {
out[i++] = '0' + abs_val % 10; /* digit to char */
abs_val /= 10;
} while (abs_val > 0);
for (i -= 1; i >= 0; i--) {
putchar(out[i]);
}
break;
}
case 'x': {
/* binary to hex conversion */
const char *hex_table = "0123456789abcdef";
int val = va_arg(v_args, int);
for (int i = 7; i >= 0; i--) {
int blob = (val >> (4 * i)) & 0xf;
putchar(hex_table[blob]);
}
break;
}
}
} else {
putchar(*fmt);
}
fmt++;
}
}