-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbf.c
105 lines (95 loc) · 2 KB
/
bf.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
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <fcntl.h>
#define MAX_PROG (32 << 9)
#define MAX_CELLS (32 << 9)
static char prog[MAX_PROG];
static char cells[MAX_CELLS];
int main(int argc, char** argv) {
int prog_fd;
size_t prog_size, level;
char *dp, *ip;
if (argc > 2) {
fprintf(stderr, "USAGE: %s [INPUT-FILE]", argv[0]);
return -1;
}
prog_fd = argc < 2 || strcmp(argv[1], "-") == 0 ? 0 : open(argv[1], O_RDONLY);
prog_size = read(prog_fd, prog, MAX_PROG);
memset(cells, 0, MAX_CELLS);
dp = cells;
ip = prog;
while (ip < &prog[prog_size]) {
switch (*ip) {
case '>':
if (++dp >= &cells[MAX_CELLS])
dp = &cells[0];
break;
case '<':
if (--dp < &cells[0])
dp = &cells[MAX_CELLS - 1];
break;
case '+':
++(*dp);
break;
case '-':
--(*dp);
break;
case '.':
if (write(1, dp, 1) < 0) {
perror("write");
return -1;
}
break;
case ',':
if (read(0, dp, 1) < 0) {
perror("read");
return -1;
}
break;
case '[':
if (*dp)
break;
level = 0;
while (++ip < &prog[prog_size]) {
if (*ip == '[')
++level;
else if (*ip == ']') {
if (level > 0)
--level;
else
break;
}
}
if (*ip != ']' || level)
return -1;
break;
case ']':
if (!*dp)
break;
level = 0;
while (--ip >= &prog[0]) {
if (*ip == ']')
++level;
else if (*ip == '[') {
if (level > 0)
--level;
else
break;
}
}
if (*ip != '[' || level)
return -1;
break;
case '\n':
case '\t':
case ' ':
break;
default:
return *ip;
}
++ip;
}
close(prog_fd);
return 0;
}