-
Notifications
You must be signed in to change notification settings - Fork 0
/
brainfuck_extended_1.go
86 lines (80 loc) · 1.51 KB
/
brainfuck_extended_1.go
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
package brainfuck
import (
"bufio"
"errors"
"io"
)
func BrainfuckExtended1(file io.Reader) (string, error) {
scanner := bufio.NewScanner(file)
var code string
for scanner.Scan() {
code += scanner.Text()
}
return interpretBrainfuckExtended1([]rune(code))
}
// _
func interpretBrainfuckExtended1(code []rune) (string, error) {
memory := make([]byte, 30000)
var pointer int
output := make([]byte, 0)
var storage byte
for i := 0; i < len(code); i++ {
switch code[i] {
case '>':
pointer++
case '<':
pointer--
case '+':
memory[pointer]++
case '-':
memory[pointer]--
case '.':
output = append(output, memory[pointer])
case '[':
if memory[pointer] == 0 {
loopCount := 1
for loopCount > 0 {
i++
if code[i] == '[' {
loopCount++
} else if code[i] == ']' {
loopCount--
}
}
}
case ']':
if memory[pointer] != 0 {
loopCount := 1
for loopCount > 0 {
i--
if code[i] == ']' {
loopCount++
} else if code[i] == '[' {
loopCount--
}
}
}
case '@':
return string(output), nil
case '$':
storage = memory[pointer]
case '!':
memory[pointer] = storage
case '}':
memory[pointer] >>= 1
case '{':
memory[pointer] <<= 1
case '~':
memory[pointer] = ^memory[pointer]
case '^':
memory[pointer] ^= storage
case '&':
memory[pointer] &= storage
case '|':
memory[pointer] |= storage
default:
return "", errors.New("compiler error: unknown char")
}
}
return string(output), nil
}