Last active
December 19, 2022 22:45
-
-
Save teepark/a50d9823f28b8b5a8bede62bb6a4cb6f to your computer and use it in GitHub Desktop.
(minimal?) POC
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const std = @import("std"); | |
const debug = std.debug; | |
const heap = std.heap; | |
const mem = std.mem; | |
// $ zig run wat.zig | |
// (main) grid is 7x5 | |
// (set) grid is 2x6159346672 | |
// failure | |
// Segmentation fault at address 0x16f204000 | |
pub fn main() !void { | |
var gpa = heap.GeneralPurposeAllocator(.{}){}; | |
const alloc = gpa.allocator(); | |
defer { | |
if (gpa.deinit()) { | |
debug.print("memory leak detected\n", .{}); | |
} | |
} | |
var grid = try Grid.init(alloc, 5, 7); | |
debug.print("(main) grid is {d}x{d}\n", .{grid.width, grid.height}); | |
if (!grid.set(2, 4, .water)) { | |
debug.print("failure\n", .{}); | |
} | |
defer grid.deinit(); | |
} | |
const Filler = enum { | |
air, water, sand, stone, | |
}; | |
const Grid = struct { | |
data: []Filler, | |
width: usize, | |
height: usize, | |
allocator: mem.Allocator, | |
fn init(alloc: mem.Allocator, rows: usize, cols: usize) !*Grid { | |
const g = &Grid{ | |
.width = cols, | |
.height = rows, | |
.data = try alloc.alloc(Filler, rows * cols), | |
.allocator = alloc, | |
}; | |
mem.set(Filler, g.data, .air); | |
return g; | |
} | |
fn deinit(self: *Grid) void { | |
self.allocator.free(self.data); | |
} | |
fn set(self: *Grid, x: usize, y: usize, value: Filler) bool { | |
debug.print("(set) grid is {d}x{d}\n", .{self.width, self.height}); | |
if (y >= self.height or x >= self.width) { | |
return false; | |
} | |
self.data[y * self.width + x] = value; | |
return true; | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment