Provide Io implementation at comptime

Hello there.

I started using Zig less than a week ago and fell in love with it. Development experience in Zig so far touched many concepts and reasonings I already saw in C and Rust that is thrillling!

I’m using Zig version 0.16.0

What I would like to do is initialize a buffer of a fixed length with random values at compile time. The problem is at comptime I don’t have the init variable as such I must provide an Io implementation myself.

In an attempt to be more clear I will share the (non working) cod of what I’m trying to accomplish.

const BUFFER_SIZE = 19;
const BUFFER = comptime fill_buffer();

fn fill_buffer() [BUFFER_SIZE]u8 {
    var buffer: [19]u8 = undefined;

    // I dont't have init. init.io.randomSecure(&buffer);
    return buffer;
}

I searched on Google, searched the source code of the zig’s std library (a quick global search on VSCode) and searched this forum still nothing reaped my attention.

Anybody with a solution and also Zig’s best practices to handle such situations and/or any link to share?

I think comptime aims to be deterministic, so generating random numbers at comptime seems to me like something that isn’t really intended (if it can be accomplished somehow).

You could add a build option that is @imported in the code, or generate a file/module and use @embedFile with that.

Can you describe your intention a bit more, should this value change on every build?

2 Likes