Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

binarytrees/1.zig Node allocator #408

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
31 changes: 14 additions & 17 deletions bench/algorithm/binarytrees/1.zig
Original file line number Diff line number Diff line change
@@ -1,6 +1,4 @@
const std = @import("std");
const builtin = @import("builtin");
const math = std.math;
const Allocator = std.mem.Allocator;
const MIN_DEPTH = 4;

Expand All @@ -9,14 +7,15 @@ const global_allocator = std.heap.c_allocator;
pub fn main() !void {
const stdout = std.io.getStdOut().writer();
const n = try get_n();
const max_depth = math.max(MIN_DEPTH + 2, n);
const max_depth: usize = @max(MIN_DEPTH + 2, n);
Node.init(global_allocator);
{
const stretch_depth = max_depth + 1;
const stretch_tree = Node.make(stretch_depth, global_allocator).?;
const stretch_tree = Node.make(stretch_depth).?;
defer stretch_tree.deinit();
try stdout.print("stretch tree of depth {d}\t check: {d}\n", .{ stretch_depth, stretch_tree.check() });
}
const long_lived_tree = Node.make(max_depth, global_allocator).?;
const long_lived_tree = Node.make(max_depth).?;
defer long_lived_tree.deinit();

var depth: usize = MIN_DEPTH;
Expand All @@ -25,7 +24,7 @@ pub fn main() !void {
var sum: usize = 0;
var i: usize = 0;
while (i < iterations) : (i += 1) {
const tree = Node.make(depth, global_allocator).?;
const tree = Node.make(depth).?;
defer tree.deinit();
sum += tree.check();
}
Expand All @@ -45,15 +44,13 @@ fn get_n() !usize {
const Node = struct {
const Self = @This();

allocator: Allocator,
var allocator: Allocator = undefined;

left: ?*Self = null,
right: ?*Self = null,

pub fn init(allocator: Allocator) !*Self {
var node = try allocator.create(Self);
node.* = .{ .allocator = allocator };
return node;
pub fn init(alloc: Allocator) void {
Self.allocator = alloc;
}

pub fn deinit(self: *Self) void {
Expand All @@ -63,15 +60,15 @@ const Node = struct {
if (self.right != null) {
self.right.?.deinit();
}
self.allocator.destroy(self);
allocator.destroy(self);
}

pub fn make(depth: usize, allocator: Allocator) ?*Self {
var node = Self.init(allocator) catch return null;
pub fn make(depth: usize) ?*Self {
var node = allocator.create(Node) catch return null;
node.* = .{ };
if (depth > 0) {
const d = depth - 1;
node.left = Self.make(d, allocator);
node.right = Self.make(d, allocator);
node.left = Self.make(depth-1);
node.right = Self.make(depth-1);
}
return node;
}
Expand Down