Zig 0.17.0-dev (Split by item)

This is an example of documentation generated by ZigDoc, an alternative to Zig's built-in Auto Doc feature. See also examples in other modes/formats. The project being documented here (as the example) is the Zig library itself.

simple_allocator

Simple allocator interface, to avoid pulling in the while std allocator implementation.

emutls.simple_allocator
const simple_allocator = struct

File

lib/compiler_rt/emutls.zig:32

Code

const simple_allocator = struct {
    /// Allocate a memory chunk for requested type. Return a pointer on the data.
    pub fn alloc(comptime T: type) *T {
        return @ptrCast(@alignCast(advancedAlloc(@alignOf(T), @sizeOf(T))));
    }

    /// Allocate a slice of T, with len elements.
    pub fn allocSlice(comptime T: type, len: usize) []T {
        return @as([*]T, @ptrCast(@alignCast(
            advancedAlloc(@alignOf(T), @sizeOf(T) * len),
        )))[0 .. len - 1];
    }

    /// Allocate a memory chunk.
    pub fn advancedAlloc(alignment: u29, size: usize) [*]u8 {
        const minimal_alignment = @max(@alignOf(usize), alignment);

        var aligned_ptr: ?*anyopaque = undefined;
        if (std.c.posix_memalign(&aligned_ptr, minimal_alignment, size) != 0) {
            abort();
        }

        return @ptrCast(aligned_ptr);
    }

    /// Resize a slice.
    pub fn reallocSlice(comptime T: type, slice: []T, len: usize) []T {
        const c_ptr: *anyopaque = @ptrCast(slice.ptr);
        const new_array: [*]T = @ptrCast(@alignCast(std.c.realloc(c_ptr, @sizeOf(T) * len) orelse abort()));
        return new_array[0..len];
    }

    /// Free a memory chunk allocated with simple_allocator.
    pub fn free(ptr: anytype) void {
        std.c.free(@ptrCast(ptr));
    }
}