-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcommon.d
149 lines (132 loc) · 2.9 KB
/
common.d
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
138
139
140
141
142
143
144
145
146
147
148
149
module common;
import ldc.llvmasm;
extern (C):
enum SYS_PUTCHAR = 1;
enum SYS_GETCHAR = 2;
enum SYS_EXIT = 3;
enum SYS_READFILE = 4;
enum SYS_WRITEFILE = 5;
alias va_list = imported!"core.stdc.stdarg".va_list;
alias va_start = imported!"core.stdc.stdarg".va_start;
alias va_end = imported!"core.stdc.stdarg".va_end;
alias va_arg = imported!"core.stdc.stdarg".va_arg;
void putchar(char);
int getchar();
noreturn exit();
int readfile(const char*, char*, int);
int writefile(const char*, const char*, int);
void printf(const(char)* fmt, ...)
{
va_list vargs;
va_start(vargs, fmt);
while (*fmt)
{
if (*fmt == '%')
{
fmt++;
switch (*fmt)
{
case '\0':
putchar('%');
goto end;
case '%':
putchar('%');
break;
case 's':
{
const(char)* s = va_arg!(const(char)*)(vargs);
while (*s)
{
putchar(*s);
s++;
}
break;
}
case 'd':
{
int value = va_arg!int(vargs);
if (value < 0)
{
putchar('-');
value = -value;
}
int divisor = 1;
while (value / divisor > 9)
{
divisor *= 10;
}
while (divisor > 0)
{
putchar('0' + value / divisor);
value %= divisor;
divisor /= 10;
}
break;
}
case 'x':
{
int value = va_arg!int(vargs);
for (int i = 7; i >= 0; i--)
{
int nibble = (value >> (i * 4)) & 0xf;
putchar("0123456789abcdef"[nibble]);
}
break;
}
default:
break;
}
}
else
{
putchar(*fmt);
}
fmt++;
}
end:
va_end(vargs);
}
void* memset(void* buf, char c, size_t n)
{
ubyte* p = cast(ubyte*) buf;
while (n--)
{
*p++ = c;
}
return buf;
}
void* memcpy(void* dst, const(void)* src, size_t n)
{
ubyte* d = cast(ubyte*) dst;
const(ubyte)* s = cast(const(ubyte)*) src;
while (n--)
{
*d++ = *s++;
}
return dst;
}
char* strcpy(char* dst, const(char)* src)
{
char* d = dst;
while (*src)
{
*d++ = *src++;
}
*d = '\0';
return dst;
}
int strcmp(const char* s1, const char* s2)
{
char* p1 = cast(char*) s1;
char* p2 = cast(char*) s2;
while (*p1 && *p2)
{
if (*p1 != *p2)
{
break;
}
p1++;
p2++;
}
return *p1 - *p2;
}