Fix integer overflow, add selection buffer.

This commit is contained in:
KikooDX 2021-01-27 12:06:33 +01:00
parent cf65e74492
commit 900586d374
1 changed files with 26 additions and 16 deletions

View File

@ -13,31 +13,38 @@ const cell_t = u16;
width: u16,
height: u16,
buffer: []cell_t,
content: []cell_t,
selected: []bool,
/// Create structure and allocate required memory. The `buffer` array size will
/// Create structure and allocate required memory. The `content` array size will
/// be equal to `width` times `height`.
pub fn init(allocator: *std.mem.Allocator, width: u16, height: u16) !Self {
var self = Self{
.width = width,
.height = height,
.buffer = undefined,
.content = undefined,
.selected = undefined,
};
// Try to allocate necessary memory.
self.buffer = try allocator.alloc(cell_t, width * height);
errdefer allocator.free(self.buffer);
const size: u32 = @intCast(u32, width) * @intCast(u32, height);
self.content = try allocator.alloc(cell_t, size);
errdefer allocator.free(self.content);
self.selected = try allocator.alloc(bool, size);
// Fill with 0s to avoid undefined behavior.
var i: u16 = 0;
while (i < self.width * self.height) : (i += 1)
self.buffer[i] = 0;
var i: u32 = 0;
while (i < size) : (i += 1) {
self.content[i] = 0;
self.selected[i] = false;
}
return self;
}
/// Free the level buffer.
/// Free the level content.
pub fn deinit(self: *Self, allocator: *std.mem.Allocator) void {
allocator.free(self.buffer);
allocator.free(self.selected);
allocator.free(self.content);
}
/// Draw level tiles from `offset` to fill the window.
@ -50,7 +57,7 @@ pub fn draw(self: *Self, offset: Vec2) void {
while (cx < self.width) {
var cy: Vec2.int_type = offset.y;
while (cy < self.height) {
const cell_content: cell_t = self.buffer[cx * self.width + cy];
const cell_content: cell_t = self.content[cx * self.width + cy];
const color = switch (cell_content) {
0 => ray.GRAY,
1 => ray.WHITE,
@ -75,12 +82,15 @@ test "create level buffer" {
// Initialize level struct and allocate space (twice 'cause why not?).
var level: Self = try Self.init(allocator, 64, 32);
level.deinit(allocator);
level = try Self.init(allocator, 64, 64);
level = try Self.init(allocator, 256, 256);
defer level.deinit(allocator);
level.buffer[128] = 32;
level.content[128] = 32;
level.selected[128] = true;
expect(level.buffer[128] == 32);
expect(level.width == 64);
expect(level.height == 64);
expect(level.width == 256);
expect(level.height == 256);
expect(level.content[128] == 32);
expect(level.selected[128]);
}