Skip to content

Instantly share code, notes, and snippets.

@winksaville
Last active July 19, 2018 18:41
Show Gist options
  • Save winksaville/9cf76218c81106e841f2cae572a77da0 to your computer and use it in GitHub Desktop.
Save winksaville/9cf76218c81106e841f2cae572a77da0 to your computer and use it in GitHub Desktop.
Some zig code and compileLog at the bottom showing some types
const std = @import("std");
const warn = std.debug.warn;
fn Buffer(comptime buffer_size: usize) type {
return struct {
const Self = this;
pub buffer: [buffer_size]u8,
// Initialize if allocated in the stack
pub fn initStack() Self {
var self: Self = undefined;
self.fill();
@compileLog("initStack typeOf(Self): ", @typeOf(Self));
@compileLog("initStack typeOf(self): ", @typeOf(self));
@compileLog("initStack typeof(self.buffer): ", @typeOf(self.buffer));
return self;
}
// Initialize if allocated in the heap
pub fn initHeap(self: *Self) void {
@compileLog("initHeap typeof(self): ", @typeOf(self));
self.fill();
}
fn fill(self: *Self) void {
@compileLog("fill typeof(self): ", @typeOf(self));
for (self.buffer) |*ptr, i| {
@compileLog("fill typeof(ptr):", @typeOf(ptr));
@compileLog("fill typeof(ptr.*):", @typeOf(ptr.*));
ptr.* = @truncate(u8, i);
}
}
};
}
pub fn main() u8 {
const Buffer4k = Buffer(0x1000);
var buf = Buffer4k.initStack();
warn("buf.buffer[254]={}\n", buf.buffer[254]);
var direct_allocator = std.heap.DirectAllocator.init();
defer direct_allocator.deinit();
var allocator = &direct_allocator.allocator;
var bufAlloced = allocator.alloc(Buffer4k, 1) catch { std.debug.warn("OOM\n"); return 0xFF; };
bufAlloced[0].initHeap();
var r1 = bufAlloced[0].buffer[254];
warn("bufAlloced[0].buffer[254]={}\n", r1);
return buf.buffer[254];
}
$ zig build-exe main.y.zig
| "initStack typeOf(Self): ", type
| "initStack typeOf(self): ", Buffer(4096)
| "initStack typeof(self.buffer): ", [4096]u8
| "initHeap typeof(self): ", *Buffer(4096)
| "fill typeof(self): ", *Buffer(4096)
| "fill typeof(ptr):", *u8
| "fill typeof(ptr.*):", u8
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment