zig icon indicating copy to clipboard operation
zig copied to clipboard

Add `std.heap.static_allocator`

Open agathazeren opened this issue 1 year ago • 5 comments

An allocator with a always failing alloc and resize, and a no-op free, for use with a statically allocated buffer being passed into an api that takes an Allocator in order to free its data.

agathazeren avatar Feb 29 '24 00:02 agathazeren

The idea of this API is to use for a structure that holds a reference to an object (most likely a string), conceptually owning it, but the data could also be static data.

So instead of :

union(enum) {
    owned: struct { data: []const u8, allocator: Allocator },
    static_data: []const u8,
}

Writing

struct {
    data: []const u8,
    allocator: Allocator, // can be static_allocator for static data
},

making the use of the struct much simpler.

agathazeren avatar Feb 29 '24 19:02 agathazeren

How about renaming it to noop_allocator so it's clearer what it actually does? The intended usage would be part of the doc comment instead of the name.

lacc97 avatar Mar 01 '24 00:03 lacc97

yeah this is more like https://github.com/nektro/gimme/blob/master/src/FailingAllocator.zig

nektro avatar Mar 01 '24 00:03 nektro

A "failing allocator" already exists as std.testing.failing_allocator.

Vexu avatar Mar 01 '24 14:03 Vexu

It may be prudent to move failing_allocator to heap to clarify such a use case.

cc @IntegratedQuantum, you seemed discontent with this use case previously.

notcancername avatar Mar 04 '24 11:03 notcancername

The idea of this API is to use for a structure that holds a reference to an object (most likely a string), conceptually owning it, but the data could also be static data.

So instead of :

union(enum) {
    owned: struct { data: []const u8, allocator: Allocator },
    static_data: []const u8,
}

Writing

struct {
    data: []const u8,
    allocator: Allocator, // can be static_allocator for static data
},

making the use of the struct much simpler.

This could be easily handled using optionals and a simple if to decide whether to call free

struct {
    data: []const u8,
    allocator: ?Allocator, // when null `data` is static
}

der-teufel-programming avatar Jul 14 '24 22:07 der-teufel-programming