Skip to content

Commit

Permalink
Add std.mem.zeroes to the standard library
Browse files Browse the repository at this point in the history
This zero initializes the type passed in. Can be used to zero
initialize c structs.
  • Loading branch information
FireFox317 committed Jan 6, 2020
1 parent c30106c commit b0a9f7c
Showing 1 changed file with 21 additions and 0 deletions.
21 changes: 21 additions & 0 deletions lib/std/mem.zig
Original file line number Diff line number Diff line change
Expand Up @@ -273,6 +273,27 @@ pub fn set(comptime T: type, dest: []T, value: T) void {
d.* = value;
}

/// Zero initializes the type.
/// This can be used to zero initialize a C-struct.
pub fn zeroes(comptime T: type) T {
var item: T = undefined;
@memset(@ptrCast([*]u8, &item), 0, @sizeOf(T));
return item;
}

test "mem.zeroes" {
const C_struct = extern struct {
x: u32,
y: u32,
};

var a = zeroes(C_struct);
a.y += 10;

testing.expect(a.x == 0);
testing.expect(a.y == 10);
}

pub fn secureZero(comptime T: type, s: []T) void {
// NOTE: We do not use a volatile slice cast here since LLVM cannot
// see that it can be replaced by a memset.
Expand Down

0 comments on commit b0a9f7c

Please sign in to comment.