-
Notifications
You must be signed in to change notification settings - Fork 3
/
brainfuck.d
76 lines (73 loc) · 1.95 KB
/
brainfuck.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
import std.file;
import std.stdio;
import std.conv;
struct brainfuck {
string code;
byte[30000] data = [0];
int iptr;
int dptr;
}
void runbrainfuck(brainfuck bf){
while(bf.iptr < bf.code.length){
int count = 1;
switch(bf.code[bf.iptr]){
case '>':
bf.dptr++;
break;
case '<':
bf.dptr--;
break;
case '+':
bf.data[bf.dptr]++;
break;
case '-':
bf.data[bf.dptr]--;
break;
case '.':
write(to!char(bf.data[bf.dptr]));
break;
case ',':
char[1] tmp;
stdin.rawRead(tmp);
bf.data[bf.dptr] = to!byte(tmp[0]);
break;
case '[':
if(bf.data[bf.dptr] == 0){
bf.iptr++;
while(count > 0){
if(bf.code[bf.iptr] == '['){
count++;
}
else if(bf.code[bf.iptr] == ']'){
count--;
}
bf.iptr++;
}
bf.iptr--;
}
break;
case ']':
if(bf.data[bf.dptr] != 0){
bf.iptr--;
while(count > 0){
if(bf.code[bf.iptr] == ']'){
count++;
}
else if(bf.code[bf.iptr] == '['){
count--;
}
bf.iptr--;
}
}
break;
default: break;
}
bf.iptr++;
}
}
int main(string[] argv){
brainfuck bf;
bf.code = std.file.readText(argv[1]);
runbrainfuck(bf);
return 0;
}