Advertisement
Guest User

Untitled

a guest
Oct 31st, 2018
142
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.82 KB | None | 0 0
  1. const std = @import("std");
  2.  
  3. pub fn box(comptime T: type, alloc: *std.mem.Allocator) type {
  4.     return struct {
  5.         const Self = @This();
  6.  
  7.         ptr: []T,
  8.  
  9.         fn new(item: T) !Self {
  10.             var heap: []T = try alloc.alloc(T, 1);
  11.             heap[0] = item;
  12.  
  13.             return Self {
  14.                 .ptr = heap
  15.             };
  16.         }
  17.  
  18.         fn drop(self: *const Self) void {
  19.             alloc.free(self.ptr);
  20.         }
  21.  
  22.         fn as_ref(self: *const Self) *const T {
  23.             return &self.ptr[0];
  24.         }
  25.  
  26.         fn as_mut(self: *Self) *T {
  27.             return &self.ptr[0];
  28.         }
  29.     };
  30. }
  31.  
  32. pub fn main() void {
  33.     const b = try box(i32, std.debug.global_allocator).new(100) catch unreachable;
  34.     defer b.drop();
  35.  
  36.     @import("std").debug.warn("{}\n", b.as_ref().*);
  37. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement