Last active
July 8, 2024 09:36
-
-
Save hanshoglund/332368f59c7c8a4a549c763bc529d713 to your computer and use it in GitHub Desktop.
memory_safe.zig
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Memory-safe and leak-free Zig | |
// By using no heap allocation | |
// All data is in the single state var, allocated up-front | |
// Also thread-safe by being single thread (if concurrency needed, use separate message queue/pipes) | |
const std = @import("std"); | |
const Employee = struct { | |
id: i32, | |
name: [10]u8, | |
salary: f32, | |
}; | |
const Employees = enum { e1, e2 }; // need to know max num of employees in advance | |
const Days = enum { mon, tues, wed }; | |
pub fn main() void { | |
const state = struct { | |
var employees: [2]Employee = undefined; // should init deterministically here | |
fn getEmployee(e: Employees) *Employee { | |
return (&employees[@intFromEnum(e)]); | |
} | |
}; | |
state.getEmployee(Employees.e1).id = 1; | |
@memcpy(&state.getEmployee(Employees.e1).name, "hans "); | |
std.debug.print("id: {s}",.{state.getEmployee(Employees.e1).name}); | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment