zig

fork of https://codeberg.org/ziglang/zig
Log | Files | Refs | README | LICENSE

commit 0deab8fd3bba3fa25ab70f6cf2e04b234aba8eb4 (tree)
parent baaef7ed977a8c3d5df2aef673185101abc381d4
Author: Timon Kruiper <timonkruiper@gmail.com>
Date:   Mon,  6 Jan 2020 21:38:11 +0100

Add std.mem.zeroes to the standard library

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

Diffstat:
Mlib/std/mem.zig | 27+++++++++++++++++++++++++++
1 file changed, 27 insertions(+), 0 deletions(-)

diff --git a/lib/std/mem.zig b/lib/std/mem.zig @@ -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) { + @compileError("TODO: Currently this only works for extern types"); + } + + 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.