Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- const std = @import("std");
- pub fn box(comptime T: type, alloc: *std.mem.Allocator) type {
- return struct {
- const Self = @This();
- ptr: []T,
- fn new(item: T) !Self {
- var heap: []T = try alloc.alloc(T, 1);
- heap[0] = item;
- return Self {
- .ptr = heap
- };
- }
- fn drop(self: *const Self) void {
- alloc.free(self.ptr);
- }
- fn as_ref(self: *const Self) *const T {
- return &self.ptr[0];
- }
- fn as_mut(self: *Self) *T {
- return &self.ptr[0];
- }
- };
- }
- pub fn main() void {
- const b = try box(i32, std.debug.global_allocator).new(100) catch unreachable;
- defer b.drop();
- @import("std").debug.warn("{}\n", b.as_ref().*);
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement