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

Add std.mem.zeroes to the standard library #4092

Merged
merged 1 commit into from
Jan 7, 2020
Merged
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
27 changes: 27 additions & 0 deletions lib/std/mem.zig
Original file line number Diff line number Diff line change
Expand Up @@ -273,6 +273,33 @@ 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 {
if (@sizeOf(T) == 0) return T{};

if (comptime meta.containerLayout(T) != .Extern) {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Should allow packed as well?

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

not necessary for merge, made complicated by #3133

@compileError("TODO: Currently this only works for extern types");
}

var item: T = undefined;
@memset(@ptrCast([*]u8, &item), 0, @sizeOf(T));
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is this defined? e.g. if T was a u24 then the size is 3 but @sizeOf returns 4.
See e.g. #4093

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The code is correct. @sizeOf gives the number of bytes the type takes up in memory. This function is valid for types which have well-defined memory layout, which includes extern structs (the main use case).

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