Skip to content

Instantly share code, notes, and snippets.

@DutchGhost
Created August 9, 2019 20:03
Show Gist options
  • Select an option

  • Save DutchGhost/78292ba229b2b2d9cff77e59fc90425f to your computer and use it in GitHub Desktop.

Select an option

Save DutchGhost/78292ba229b2b2d9cff77e59fc90425f to your computer and use it in GitHub Desktop.
MaybeUninit in Zig
pub inline fn MaybeUninit(comptime T: type) type {
return packed union {
value: T,
uninit: void,
const Self = @This();
inline fn init(value: T) Self {
return Self { .value = value };
}
inline fn uninit() Self {
return Self { .uninit = {} };
}
inline fn zeroed() Self {
var u = Self.uninit();
var bytes = @ptrCast([*]u8, u.as_mut_ptr());
@memset(bytes, 0, @sizeOf(T));
return u;
}
inline fn as_ptr(self: *const Self) *const T {
return &self.value;
}
inline fn as_mut_ptr(self: *Self) *T {
return &self.value;
}
inline fn assume_init(self: Self) T {
return self.value;
}
inline fn read(self: *const Self) T {
return self.as_ptr().*;
}
inline fn first_ptr(this: []const Self) *const T {
return @ptrCast(*const T, this.ptr);
}
inline fn first_ptr_mut(this: []Self) *Self {
return @ptrCast(*T, this.ptr);
}
};
}
const std = @import("std");
const testing = std.testing;
test "test" {
var maybe = MaybeUninit(u64).zeroed();
var ptr = maybe.as_mut_ptr();
testing.expectEqual(ptr.*, 0);
ptr.* = 10;
testing.expectEqual(maybe.read(), 10);
testing.expectEqual(@sizeOf(MaybeUninit(u64)), @sizeOf(u64));
testing.expectEqual(@alignOf(MaybeUninit(u64)), @alignOf(u64));
}
test "first_ptr" {
var maybe = [2]MaybeUninit(i64) {MaybeUninit(i64).init(10), MaybeUninit(i64).uninit()};
var ptr = MaybeUninit(i64).first_ptr(&maybe);
testing.expectEqual(ptr.*, 10);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment