authorgravatar for timonkruiper@gmail.comTimon Kruiper <timonkruiper@gmail.com> 2020-01-06 21:38:11+01:00
committergravatar for andrew@ziglang.orgAndrew Kelley <andrew@ziglang.org> 2020-01-06 19:24:17-05:00
log0deab8fd3bba3fa25ab70f6cf2e04b234aba8eb4
tree9aa525827437edc242147b3d46e83dffe4e66ed8
parentbaaef7ed977a8c3d5df2aef673185101abc381d4

Add std.mem.zeroes to the standard library

This zero initializes the type passed in. Can be used to zero initialize c structs.

1 files changed, 27 insertions(+), 0 deletions(-)

lib/std/mem.zig+27
...@@ -273,6 +273,33 @@ pub fn set(comptime T: type, dest: []T, value: T) void {...@@ -273,6 +273,33 @@ pub fn set(comptime T: type, dest: []T, value: T) void {
273 d.* = value;273 d.* = value;
274}274}
275275
276/// Zero initializes the type.
277/// This can be used to zero initialize a C-struct.
278pub fn zeroes(comptime T: type) T {
279 if (@sizeOf(T) == 0) return T{};
280
281 if (comptime meta.containerLayout(T) != .Extern) {
282 @compileError("TODO: Currently this only works for extern types");
283 }
284
285 var item: T = undefined;
286 @memset(@ptrCast([*]u8, &item), 0, @sizeOf(T));
287 return item;
288}
289
290test "mem.zeroes" {
291 const C_struct = extern struct {
292 x: u32,
293 y: u32,
294 };
295
296 var a = zeroes(C_struct);
297 a.y += 10;
298
299 testing.expect(a.x == 0);
300 testing.expect(a.y == 10);
301}
302
276pub fn secureZero(comptime T: type, s: []T) void {303pub fn secureZero(comptime T: type, s: []T) void {
277 // NOTE: We do not use a volatile slice cast here since LLVM cannot304 // NOTE: We do not use a volatile slice cast here since LLVM cannot
278 // see that it can be replaced by a memset.305 // see that it can be replaced by a memset.