Chunk
parent
9a1a2494fb
commit
d28a6730ab
|
@ -0,0 +1,44 @@
|
|||
const std = @import("std");
|
||||
|
||||
const OpCode = enum {
|
||||
OP_RETURN,
|
||||
};
|
||||
|
||||
pub const Chunk = struct {
|
||||
code: []u8,
|
||||
count: usize,
|
||||
capacity: usize,
|
||||
allocator: std.mem.Allocator,
|
||||
|
||||
pub fn init(allocator: std.mem.Allocator) !Chunk {
|
||||
return .{
|
||||
.count = 0,
|
||||
.capacity = 0,
|
||||
.allocator = allocator,
|
||||
.code = try allocator.alloc(u8, 0),
|
||||
};
|
||||
}
|
||||
|
||||
pub fn write_chunck(self: *Chunk, byte: u8) !void {
|
||||
// If the code slice is full
|
||||
if (self.count == self.capacity) {
|
||||
const old_capacity = self.capacity;
|
||||
self.capacity = if (old_capacity < 8) 8 else old_capacity * 2;
|
||||
self.code = try self.allocator.realloc(self.code, self.capacity);
|
||||
}
|
||||
|
||||
self.code[self.count] = byte;
|
||||
self.count += 1;
|
||||
}
|
||||
|
||||
/// Reinitializes the state of the chunk.
|
||||
pub fn free_chunck(self: *Chunk) !void {
|
||||
self.count = 0;
|
||||
self.capacity = 0;
|
||||
self.code = try self.allocator.realloc(self.code, 0);
|
||||
}
|
||||
|
||||
pub fn deinit(self: Chunk) void {
|
||||
self.allocator.free(self.code);
|
||||
}
|
||||
};
|
29
src/main.zig
29
src/main.zig
|
@ -1,24 +1,27 @@
|
|||
const std = @import("std");
|
||||
const chunk = @import("./chunk.zig");
|
||||
|
||||
pub fn main() !void {
|
||||
// Prints to stderr (it's a shortcut based on `std.io.getStdErr()`)
|
||||
std.debug.print("All your {s} are belong to us.\n", .{"codebase"});
|
||||
|
||||
// stdout is for the actual output of your application, for example if you
|
||||
// are implementing gzip, then only the compressed bytes should be sent to
|
||||
// stdout, not any debugging messages.
|
||||
const stdout_file = std.io.getStdOut().writer();
|
||||
var bw = std.io.bufferedWriter(stdout_file);
|
||||
const stdout = bw.writer();
|
||||
var mem = std.heap.GeneralPurposeAllocator(.{}){};
|
||||
const alloc = mem.allocator();
|
||||
|
||||
try stdout.print("Run `zig build test` to run the tests.\n", .{});
|
||||
var c = try chunk.Chunk.init(alloc);
|
||||
defer c.deinit();
|
||||
|
||||
try bw.flush(); // don't forget to flush!
|
||||
try c.write_chunck('a');
|
||||
try c.free_chunck();
|
||||
}
|
||||
|
||||
test "simple test" {
|
||||
var list = std.ArrayList(i32).init(std.testing.allocator);
|
||||
defer list.deinit(); // try commenting this out and see if zig detects the memory leak!
|
||||
try list.append(42);
|
||||
try std.testing.expectEqual(@as(i32, 42), list.pop());
|
||||
test "chunk test" {
|
||||
var c = try chunk.Chunk.init(std.testing.allocator);
|
||||
defer c.deinit();
|
||||
|
||||
try c.write_chunck('a');
|
||||
try c.write_chunck('b');
|
||||
try c.free_chunck();
|
||||
try c.write_chunck('J');
|
||||
try c.write_chunck('H');
|
||||
}
|
||||
|
|
Loading…
Reference in New Issue