#dynamic? comptime array

1 messages · Page 1 of 1 (latest)

kindred juniper
#
files: std.ArrayListUnmanaged(File),

pub fn init(allocator: std.mem.Allocator) Template {
    return .{ .allocator = allocator, .files = std.ArrayListUnmanaged(File).empty };
}

pub fn deinit(self: *Template) void {
    self.files.deinit(self.allocator);
}

pub fn addFile(self: *Template, path: ?[]const u8, name: []const u8, content: []const u8) void {
    self.files.append(self.allocator, File.init(path, name, content)) catch {
        std.process.fatal("If this can be comptime I wont need this !!!! :3", .{});
    };
}

pub fn write(...) void {
  // do runtime stuff with files
}

Hi, I am looking for resources that will teach me how to make my above struct be able to have files added to it during comptime, so I don't have to allocate memory to add files. Below is what I would like

var template = Template.init(); //comptime
template.addFile(null, "init.lua", @embedFile(
    "../lua/templates/channel/init.lua",
)); //comptime
template.addFile("packages", "init.lua", @embedFile(
    "../lua/templates/channel/packages/init.lua",
)); //comptime
template.write(path); //runtime
brave thunder
#

There is not yet any comptime allocator in the standard library(see issue #1291).
If you know the amount of files at compile time, I would suggest using an array instead of your ArrayList and just filling it, or if you only know an upper bound, you can use std.BoundedArray
There is probably another way to do it, but it all depends on what are the exact requirements(only comptime values/both comptime and runtime/unknown size). It it is unknown size, it is propably possible to use some kind of opaque pointer, but I wouldn't really be sure that's the best option.

GitHub

General-purpose programming language and toolchain for maintaining robust, optimal, and reusable software. - ziglang/zig

fallen quartz
rigid ridge
#

there's mention of a comptime allocator here https://github.com/ziglang/zig/issues/23872#issuecomment-2908782296. note that its pretty easy to run into limitations if you use it with std data structures, at least in my limited experience. for instance, you can't use it with ArrayHashMaps. i hit either @intFromPtr or @ptrFromInt at comptime compile error i forget which. but mlugg said that he was able to use it with MultiArrayList.

rigid ridge
#

but if all you need to do is build a comptime list you don't need an allocator, just use ++ to build up a list. note that the list must be []const Template and not []Template

#

maybe it would look something like this:

const template = comptime blk: {
    var template = Template.init();
    template.addFile(null, "init.lua", @embedFile("/templates/channel/init.lua");
    template.addFile("packages", "init.lua", @embedFile("../lua/templates/channel/packages/init.lua"));
    break :blk template;
};
template.write(path); //runtime