-
Notifications
You must be signed in to change notification settings - Fork 2
/
bf.zig
57 lines (52 loc) · 1.51 KB
/
bf.zig
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
const std = @import("std");
const io = std.io;
const sub = std.math.sub;
fn seekBack(src: []const u8, srcptr: u16) !u16 {
var depth:u16 = 1;
var ptr: u16 = srcptr;
while (depth > 0) {
ptr = sub(u16, ptr, 1) catch return error.OutOfBounds;
switch(src[ptr]) {
'[' => depth -= 1,
']' => depth += 1,
else => {}
}
}
return ptr;
}
fn seekForward(src: []const u8, srcptr: u16) !u16 {
var depth:u16 = 1;
var ptr: u16 = srcptr;
while (depth > 0) {
ptr += 1;
if (ptr >= src.len) return error.OutOfBounds;
switch(src[ptr]) {
'[' => depth += 1,
']' => depth -= 1,
else => {}
}
}
return ptr;
}
pub fn bf(src: []const u8, storage: []u8) !void {
const stdout = try std.io.getStdOut();
var outbuf: [1]u8 = undefined;
var memptr: u16 = 0;
var srcptr: u16 = 0;
while (srcptr < src.len) {
switch(src[srcptr]) {
'+' => storage[memptr] +%= 1,
'-' => storage[memptr] -%= 1,
'>' => memptr += 1,
'<' => memptr -= 1,
'[' => if (storage[memptr] == 0) { srcptr = try seekForward(src, srcptr); },
']' => if (storage[memptr] != 0) { srcptr = try seekBack(src, srcptr); },
'.' => {
const char = try std.fmt.bufPrint(outbuf[0..], "{c}", storage[memptr]);
try stdout.write(char);
},
else => {}
}
srcptr += 1;
}
}