Skip to content

Instantly share code, notes, and snippets.

@paulohrpinheiro
Created July 11, 2020 00:02
Show Gist options
  • Save paulohrpinheiro/3fc247d685b0ff4ee640a6bfb94ed772 to your computer and use it in GitHub Desktop.
Save paulohrpinheiro/3fc247d685b0ff4ee640a6bfb94ed772 to your computer and use it in GitHub Desktop.
A BF in zig (beggining)
const std = @import("std");
const MEMORY_SIZE :i32 = 30_000;
fn execute(program: []const u8) [MEMORY_SIZE]i8 {
var memory :[MEMORY_SIZE]i8 = [_]i8{0} ** MEMORY_SIZE;
var memory_index: u32 = 0;
var output = std.ArrayList(u8).init(std.heap.page_allocator);
defer output.deinit();
for (program) |command| {
switch (command) {
'+' => { memory[memory_index] += 1; },
'-' => { memory[memory_index] -= 1; },
'.' => { try output.append(@intCast(u8, memory[memory_index])); },
'>' => {
if(memory_index < MEMORY_SIZE-1) {
memory_index += 1;
} else {
memory_index = 0;
}
},
'<' => {
if(memory_index > 0) {
memory_index -= 1;
} else {
memory_index = MEMORY_SIZE-1;
}
},
else => {},
}
}
return memory;
}
test "Advance then add 1" {
var result :[MEMORY_SIZE]i8 = undefined;
result = execute(">+");
std.testing.expect(result[1] == 1);
}
// test if go to index -1
test "Step back and add 1" {
var result :[MEMORY_SIZE]i8 = undefined;
result = execute("<+");
std.testing.expect(result[MEMORY_SIZE-1] == 1);
}
test "Try a buffer overflow" {
var result :[MEMORY_SIZE]i8 = undefined;
result = execute("<>+");
std.testing.expect(result[0] == 1);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment