Stack allocated strings

Understandable. It’s another item in a long list of possible invariants one must maintain as you modify code (“things to think about”). Invariants are what assertions are for. The important part is not necessarily remembering to update your buffer size but adding the checks to detect when your buffer has become too small (incorrect) or too big (wasteful).

I think there is one small trick with allocators that could make life much better.

Make FixedBufferAllocator.reset receive an optional checkpoint index, so that the caller can do this:

const checkpoint = fba.checkpoint();  // just gets the end index
defer fba.resetTo(checkpoint);

...

This avoids having to fiddle with ad hoc on stack buffers, while keeping almost zero overhead.

2 Likes

One more solution to this problem – stack-allocated values with a small expected size but a large upper bound, harming memory locality – is an @alloca(size, upper_bound). It could trivially be implemented as allocating a fixed upper_bound, but in release mode it could allocate less.

But why? If it’s statically known that there’s a safe upper bound, then why not always allocate that amount?

2 Likes

As I said, it hurts memory locality (related memory is further apart, leading to far cache misses) and for dynamic stacks will grow the stack much faster.

3 Likes

A variation using the same buffer for several prints, using Marler’s Maneuver of passing a comptime mutable pointer to size bound:

fn f(x: u32, y: u64) void {
    comptime var buffer_size: u16 = 64;
    var buffer = stack_buffer(buffer_size);

    const a = buffer.print(&buffer_size, "Hello, {d}", .{x});
    const b = buffer.print(&buffer_size, "Hi, {d}", .{y});
    std.debug.print("{s}\n{s}", .{a, b});

    // main.zig:31:25: error: overflow of integer type 'u16' with value '-20'
    // const c = buffer.print(&buffer_size, "noooooooooo {d} {d}", .{x, y});
    // std.debug.print("{s}\n", .{c});
}
fn stack_buffer(comptime size_max: u16) StackBufferType(size_max) {
    return  .{};
}

fn StackBufferType(comptime size_max: u16) type {
    return struct {
        buffer: [size_max]u8 = undefined,
        size: u16 = 0,

        pub inline fn print(self: *@This(), comptime size_left: *u16, comptime fmt: []const u8, args: anytype, ) []const u8 {
            size_left.* -= comptime print_size_max(fmt, @TypeOf(args));
            return self.print_runtime(fmt, args);
        }

        fn print_runtime(self: *@This(), comptime fmt: []const u8, args: anytype) []const u8 {
            const result =  std.fmt.bufPrint(self.buffer[self.size..], fmt, args) catch |err| switch (err) {
                error.NoSpaceLeft => unreachable,
            };
            self.size += @intCast(result.len);
            return result;
        }

        fn print_size_max(comptime fmt: []const u8, Args: type) u16 {
            // The same as in the OP. 
        }
    };
}
2 Likes

That is very interesting. I was under the impression that no information can be preserved between two calls of the same comptime function. I guess inline was the piece I was missing.

1 Like