BoundedArray from a slice?

Is there an API in the standard library similar to bounded array but for a slice?
Kind of like fixedBufferStream but for types other than u8.

For example,

I have been given a slice and I would like to append() to the slice starting from index zero in the slice.

In order to append, you need to have free space at the end of the slice. If the space comes from a pre-determined array, that’s BoundedArray. If the space needs to be allocated from the heap, it’s ArrayList. How would like to obtain the space for appending?

Append may have been unclear.

Something like this:

pub fn SliceBoundedArray(comptime T: type, slice: []T) type {
    return struct {
        slice: []T = slice,
        len: usize,

        fn append(self: @This(), item: T) error{NoSpaceLeft}!void {
            if (self.len == self.slice.len) return error.NoSpaceLeft;
            slice[self.len] = item;
            self.len += 1;
        }
    };
}

This looks good to me. If you want to reuse code from the std library, you could just initialize an array list with your slice, and give it a failing allocator. Then append is forced to only use the space you provided.

ArrayListUnmanaged(T).initBuffer(slice): Zig Documentation

1 Like

This, by itself, doesn’t work, because you can’t call append or any other allocating function. You’d have to provide a failing allocator to make this legal again.

True, my mistake.

It’s a bit footgun-y, but this is the intended use-case for initBuffer

Context: std: use BoundedArray less by andrewrk · Pull Request #18067 · ziglang/zig · GitHub

The use-case would be improved by std.array_list: Add *NoResize functions to ArrayListUnmanaged by notcancername · Pull Request #18361 · ziglang/zig · GitHub (and this PR is on my list of PRs to revive)

2 Likes