跳转到内容
标准库Zig 0.17.1官方原文
源码std/heap.zig

第 1 行

std.heap.Alignment

别名

第 10 行

别名目标 std.mem.Alignment

std.heap.Allocator

别名

第 8 行

别名目标 std.mem.Allocator

std.heap.ArenaAllocator

别名

第 12 行

别名目标 std.heap.ArenaAllocator

std.heap.assert

别名

第 4 行

别名目标 std.debug.assert

std.heap.brk_allocator

常量

第 363 行

支持单线程 WebAssembly 和 Linux。

Allocator

std.heap.BrkAllocator

别名

第 19 行

别名目标 std.heap.BrkAllocator

std.heap.BufferFirstAllocator

别名

第 16 行

别名目标 std.heap.BufferFirstAllocator

std.heap.builtin

常量

第 2 行

std.heap.c

别名

第 7 行

别名目标 std.c

std.heap.c_allocator

常量

第 137 行

封装 C 内存分配 API,支持完整 Allocator 接口,包括任意对齐。尽可能使用普通 malloc 调用, 但请求较大对齐时,可能需要更大缓冲区 才能满足要求。除 malloc、realloc 和 free 外, 若可用,还使用扩展函数 malloc_usable_size 和 posix_memalign。

Allocator

std.heap.c_allocator_impl

命名空间

第 141 行

std.heap.c_allocator_impl.alloc

函数

第 206 行

fn alloc( _: *anyopaque, len: usize, alignment: Alignment, return_address: usize, ) ?[*]u8

参数

_: *anyopaque
len: usize
alignment: Alignment
return_address: usize

std.heap.c_allocator_impl.allocStrat

类型函数

第 174 行

fn allocStrat(need_align: Alignment) union(enum) { raw, posix_memalign: if (have_posix_memalign) void else noreturn, manual_align: if (have_posix_memalign) noreturn else void, }

参数

need_align: Alignment

std.heap.c_allocator_impl.free

函数

第 319 行

fn free( _: *anyopaque, memory: []u8, alignment: Alignment, return_address: usize, ) void

参数

_: *anyopaque
memory: []u8
alignment: Alignment
return_address: usize

std.heap.c_allocator_impl.have_posix_memalign

常量

第 155 行

std.heap.c_allocator_impl.manualAlignHeader

函数

第 202 行

如果 allocStrat(a) == .manual_align,分配的布局如下:

unaligned_ptr hdr_ptr aligned_ptr v v v +---------------+--------+--------------+

填充区域 头部 可用字节

+---------------+--------+--------------+

  • unaligned_ptr 是 malloc 原样返回的值。
  • aligned_ptr 通过将 unaligned_ptr 向前对齐得到,也是 alloc 返回的值。
  • hdr_ptr 指向紧邻可用空间之前、大小为一个指针的头部。此头部 保存 unaligned_ptr 的值,以便之后将其传给 free。 这是必需的,因为填充区域的宽度未知。

此函数接受 aligned_ptr,向后偏移并返回 hdr_ptr。

fn manualAlignHeader(aligned_ptr: [*]u8) *[*]u8

参数

aligned_ptr: [*]u8

std.heap.c_allocator_impl.remap

函数

第 289 行

fn remap( ctx: *anyopaque, memory: []u8, alignment: Alignment, new_len: usize, return_address: usize, ) ?[*]u8

参数

ctx: *anyopaque
memory: []u8
alignment: Alignment
new_len: usize
return_address: usize

std.heap.c_allocator_impl.resize

函数

第 259 行

fn resize( _: *anyopaque, memory: []u8, alignment: Alignment, new_len: usize, return_address: usize, ) bool

参数

_: *anyopaque
memory: []u8
alignment: Alignment
new_len: usize
return_address: usize

std.heap.c_allocator_impl.vtable

常量

第 148 行

Allocator.VTable

std.heap.Check

容器

第 26 行

已弃用。

字段

ok
leak

std.heap.DebugAllocator

别名

第 24 行

已弃用;请使用 SafeAllocator。

别名目标 std.heap.debug_allocator.DebugAllocator

std.heap.DebugAllocatorConfig

别名

第 22 行

已弃用;请使用 SafeAllocator.Options。

别名目标 std.heap.debug_allocator.Config

std.heap.defaultQueryPageSize

函数

第 73 行

std.options.queryPageSize 的默认实现。 断言页大小位于 page_size_min 和 page_size_max 之间

pub fn defaultQueryPageSize() usize

用法示例

test defaultQueryPageSize {
    if (builtin.cpu.arch.isWasm()) return error.SkipZigTest;
    assert(std.math.isPowerOfTwo(defaultQueryPageSize()));
}

std.heap.defaultQueryPageSize.cached_result

变量

第 75 行

std.atomic.Value(usize)

std.heap.FixedBufferAllocator

别名

第 15 行

别名目标 std.heap.FixedBufferAllocator

std.heap.mem

别名

第 6 行

别名目标 std.mem

std.heap.memory_pool

别名

第 35 行

别名目标 std.heap.memory_pool

std.heap.MemoryPool

类型函数

第 32 行

可以极快分配单一类型对象的内存池。 需要分配大量同类型对象时使用, 因为它比通用分配器性能更高。 可能分配内存的函数接受 Allocator 参数。

pub fn MemoryPool(comptime Item: type) type

参数

Item: type

std.heap.page_allocator

常量

第 339 行

在支持内存映射的操作系统上,此分配器对每次 分配和释放都直接发起系统调用。

否则退回该目标首选的单例分配器。

线程安全。

Allocator

std.heap.page_size_max

常量

第 54 行

目标的编译期已知最大页大小。

目标系统页大小更大时,可能需要覆盖 std.options.page_size_max,并提供相应链接器选项。

实际页大小只能在运行时通过 pageSize 确定。

usize

std.heap.page_size_max_default

常量

第 732 行

?usize

std.heap.page_size_min

常量

第 46 行

目标的编译期已知最小页大小。

mmap 或 NtAllocateVirtualMemory 返回的所有指针,至少按 page_size_min 对齐,但实际对齐要求可能更大。

可通过 std.options.page_size_min 覆盖此值。

许多系统只能在运行时通过 pageSize 确定实际页大小。

usize

std.heap.page_size_min_default

常量

第 567 行

?usize

std.heap.PageAllocator

别名

第 17 行

别名目标 std.heap.PageAllocator

std.heap.pageSize

函数

第 62 行

若页面大小编译时已知,则返回值为编译时值。 否则调用 std.options.queryPageSize,默认在运行时查询 宿主操作系统。

pub inline fn pageSize() usize

用法示例

test pageSize {
    assert(std.math.isPowerOfTwo(pageSize()));
}

std.heap.root

常量

第 3 行

std.heap.SafeAllocator

别名

第 14 行

别名目标 std.heap.SafeAllocator

std.heap.smp_allocator

常量

第 351 行

Allocator

std.heap.SmpAllocator

别名

第 13 行

别名目标 std.heap.SmpAllocator

std.heap.std

别名

第 1 行

别名目标 std

std.heap.testAllocator

函数

第 430 行

此实现不应尝试超过 C malloc 可处理范围的对齐值。

pub fn testAllocator(base_allocator: mem.Allocator) !void

参数

base_allocator: mem.Allocator

std.heap.testAllocatorAligned

函数

第 479 行

pub fn testAllocatorAligned(base_allocator: mem.Allocator) !void

参数

base_allocator: mem.Allocator

std.heap.testAllocatorAlignedShrink

函数

第 535 行

pub fn testAllocatorAlignedShrink(base_allocator: mem.Allocator) !void

参数

base_allocator: mem.Allocator

std.heap.testAllocatorLargeAlignment

函数

第 506 行

pub fn testAllocatorLargeAlignment(base_allocator: mem.Allocator) !void

参数

base_allocator: mem.Allocator

std.heap.testing

别名

第 5 行

别名目标 std.testing

std.heap.wasm_allocator

常量

第 357 行

此分配器快速、精简,专用于 WebAssembly。

Allocator

std.heap.WasmAllocator

常量

第 18 行

std.heap.windows

别名

第 9 行

别名目标 std.os.windows

源码

std/heap.zig

const std = @import("std.zig");
const builtin = @import("builtin");
const root = @import("root");
const assert = std.debug.assert;
const testing = std.testing;
const mem = std.mem;
const c = std.c;
const Allocator = std.mem.Allocator;
const windows = std.os.windows;
const Alignment = std.mem.Alignment;

pub const ArenaAllocator = @import("heap/ArenaAllocator.zig");
pub const SmpAllocator = @import("heap/SmpAllocator.zig");
pub const SafeAllocator = @import("heap/SafeAllocator.zig");
pub const FixedBufferAllocator = @import("heap/FixedBufferAllocator.zig");
pub const BufferFirstAllocator = @import("heap/BufferFirstAllocator.zig");
pub const PageAllocator = @import("heap/PageAllocator.zig");
pub const WasmAllocator = if (builtin.single_threaded) BrkAllocator else @compileError("unimplemented");
pub const BrkAllocator = @import("heap/BrkAllocator.zig");

/// 已弃用;请使用 `SafeAllocator.Options`。
pub const DebugAllocatorConfig = @import("heap/debug_allocator.zig").Config;
/// 已弃用;请使用 `SafeAllocator`。
pub const DebugAllocator = @import("heap/debug_allocator.zig").DebugAllocator;
/// 已弃用。
pub const Check = enum { ok, leak };

/// 可以极快分配单一类型对象的内存池。
/// 需要分配大量同类型对象时使用,
/// 因为它比通用分配器性能更高。
/// 可能分配内存的函数接受 `Allocator` 参数。
pub fn MemoryPool(comptime Item: type) type {
    return memory_pool.Extra(Item, .{ .alignment = null });
}
pub const memory_pool = @import("heap/memory_pool.zig");

/// 目标的编译期已知最小页大小。
///
/// `mmap` 或 `NtAllocateVirtualMemory` 返回的所有指针,至少按 `page_size_min` 对齐,但实际对齐要求可能更大。
///
/// 可通过 `std.options.page_size_min` 覆盖此值。
///
/// 许多系统只能在运行时通过 `pageSize` 确定实际页大小。
///
///
pub const page_size_min: usize = std.options.page_size_min orelse (page_size_min_default orelse @compileError(@tagName(builtin.cpu.arch) ++ "-" ++ @tagName(builtin.os.tag) ++ " has unknown page_size_min; populate std.options.page_size_min"));
/// 目标的编译期已知最大页大小。
///
/// 目标系统页大小更大时,可能需要覆盖 `std.options.page_size_max`,并提供相应链接器选项。
///
/// 实际页大小只能在运行时通过 `pageSize` 确定。
///
///
pub const page_size_max: usize = std.options.page_size_max orelse (page_size_max_default orelse if (builtin.os.tag == .freestanding or builtin.os.tag == .other)
    @compileError("freestanding/other page_size_max must provided with std.options.page_size_max")
else
    @compileError(@tagName(builtin.cpu.arch) ++ "-" ++ @tagName(builtin.os.tag) ++ " has unknown page_size_max; populate std.options.page_size_max"));

/// 若页面大小编译时已知,则返回值为编译时值。
/// 否则调用 `std.options.queryPageSize`,默认在运行时查询
/// 宿主操作系统。
pub inline fn pageSize() usize {
    if (page_size_min == page_size_max) return page_size_min;
    return std.options.queryPageSize();
}

test pageSize {
    assert(std.math.isPowerOfTwo(pageSize()));
}

/// `std.options.queryPageSize` 的默认实现。
/// 断言页大小位于 `page_size_min` 和 `page_size_max` 之间
pub fn defaultQueryPageSize() usize {
    const global = struct {
        var cached_result: std.atomic.Value(usize) = .init(0);
    };
    var size = global.cached_result.load(.unordered);
    if (size > 0) return size;
    size = size: switch (builtin.os.tag) {
        .linux => if (builtin.link_libc)
            @max(std.c.sysconf(@backingInt(std.c._SC.PAGESIZE)), 0)
        else
            std.os.linux.getauxval(std.elf.AT.PAGESZ),
        .driverkit, .ios, .maccatalyst, .macos, .tvos, .visionos, .watchos => {
            const task_port = std.c.mach_task_self();
            // mach_task_self 可能在“出现任何资源失败或其他错误”时失败。
            if (task_port == std.c.TASK.NULL) break :size 0;
            var info_count = std.c.TASK.VM.INFO_COUNT;
            var vm_info: std.c.task_vm_info_data_t = undefined;
            vm_info.page_size = 0;
            _ = std.c.task_info(
                task_port,
                std.c.TASK.VM.INFO,
                @as(std.c.task_info_t, @ptrCast(&vm_info)),
                &info_count,
            );
            break :size @intCast(vm_info.page_size);
        },
        .windows => {
            var sbi: windows.SYSTEM.BASIC_INFORMATION = undefined;
            switch (windows.ntdll.NtQuerySystemInformation(
                .Basic,
                &sbi,
                @sizeOf(windows.SYSTEM.BASIC_INFORMATION),
                null,
            )) {
                .SUCCESS => break :size sbi.PageSize,
                else => break :size 0,
            }
        },
        else => if (builtin.link_libc)
            @max(std.c.sysconf(@backingInt(std.c._SC.PAGESIZE)), 0)
        else if (builtin.os.tag == .freestanding or builtin.os.tag == .other)
            @compileError("unsupported target: freestanding/other")
        else
            @compileError("pageSize on " ++ @tagName(builtin.cpu.arch) ++ "-" ++ @tagName(builtin.os.tag) ++ " is not supported without linking libc, using the default implementation"),
    };
    if (size == 0) size = page_size_max;

    assert(size >= page_size_min);
    assert(size <= page_size_max);
    global.cached_result.store(size, .unordered);

    return size;
}

test defaultQueryPageSize {
    if (builtin.cpu.arch.isWasm()) return error.SkipZigTest;
    assert(std.math.isPowerOfTwo(defaultQueryPageSize()));
}

/// 封装 C 内存分配 API,支持完整 `Allocator`
/// 接口,包括任意对齐。尽可能使用普通 `malloc` 调用,
/// 但请求较大对齐时,可能需要更大缓冲区
/// 才能满足要求。除 `malloc`、`realloc` 和 `free` 外,
/// 若可用,还使用扩展函数 `malloc_usable_size` 和 `posix_memalign`。
pub const c_allocator: Allocator = .{
    .ptr = undefined,
    .vtable = &c_allocator_impl.vtable,
};
const c_allocator_impl = struct {
    comptime {
        if (!builtin.link_libc) {
            @compileError("C allocator is only available when linking against libc");
        }
    }

    const vtable: Allocator.VTable = .{
        .alloc = alloc,
        .resize = resize,
        .remap = remap,
        .free = free,
    };

    const have_posix_memalign = switch (builtin.os.tag) {
        .dragonfly,
        .netbsd,
        .freebsd,
        .illumos,
        .openbsd,
        .linux,
        .driverkit,
        .ios,
        .maccatalyst,
        .macos,
        .tvos,
        .visionos,
        .watchos,
        .serenity,
        => true,
        else => false,
    };

    fn allocStrat(need_align: Alignment) union(enum) {
        raw,
        posix_memalign: if (have_posix_memalign) void else noreturn,
        manual_align: if (have_posix_memalign) noreturn else void,
    } {
        // 如果 `malloc` 保证 `need_align`,则始终优先采用原始分配。
        if (Alignment.compare(need_align, .lte, .of(c.max_align_t))) {
            return .raw;
        }
        // 若可用则使用 `posix_memalign`,否则必须手动对齐分配结果。
        return if (have_posix_memalign) .posix_memalign else .manual_align;
    }

    /// 如果 `allocStrat(a) == .manual_align`,分配的布局如下:
    ///
    /// unaligned_ptr   hdr_ptr  aligned_ptr
    /// v               v        v
    /// +---------------+--------+--------------+
    /// |    填充区域   |  头部  |   可用字节   |
    /// +---------------+--------+--------------+
    ///
    /// * `unaligned_ptr` 是 `malloc` 原样返回的值。
    /// * `aligned_ptr` 通过将 `unaligned_ptr` 向前对齐得到,也是 `alloc` 返回的值。
    /// * `hdr_ptr` 指向紧邻可用空间之前、大小为一个指针的头部。此头部
    ///   保存 `unaligned_ptr` 的值,以便之后将其传给 `free`。
    ///   这是必需的,因为填充区域的宽度未知。
    ///
    /// 此函数接受 `aligned_ptr`,向后偏移并返回 `hdr_ptr`。
    fn manualAlignHeader(aligned_ptr: [*]u8) *[*]u8 {
        return @ptrCast(@alignCast(aligned_ptr - @sizeOf(usize)));
    }

    fn alloc(
        _: *anyopaque,
        len: usize,
        alignment: Alignment,
        return_address: usize,
    ) ?[*]u8 {
        _ = return_address;
        assert(len > 0);
        switch (allocStrat(alignment)) {
            .raw => {
                // 仅考虑 `std.c.max_align_t` 并不完整,因为如果 `len` 小于
                // 所有对齐为 `max_align_t` 的 C 类型大小,分配的对齐可以更低。
                // 实现只需保证任何长度为 `len` 的类型
                // 都能得到适当对齐。
                //
                // 例如,若 `len == 8` 且 `alignment == .@"16"`,则 `malloc` 可能
                // 无法满足请求,因为不存在大小为 8 字节、
                // 对齐却为 16 字节的 C 类型。
                //
                // 理论上,由此得出的规则与目标平台有关;但实际上,
                // 对齐为 `max_align_t` 的最小类型大小也相同,通常是
                // `c_longdouble`,因此必要时只需将分配大小扩展至
                // `max_align_t` 的对齐大小。
                const actual_len = @max(len, @alignOf(std.c.max_align_t));
                const ptr = c.malloc(actual_len) orelse return null;
                assert(alignment.check(@intFromPtr(ptr)));
                return @ptrCast(ptr);
            },
            .posix_memalign => {
                // posix_memalign 仅接受为指针大小倍数的对齐值
                //
                const effective_alignment = @max(alignment.toByteUnits(), @sizeOf(usize));
                var aligned_ptr: ?*anyopaque = undefined;
                if (c.posix_memalign(&aligned_ptr, effective_alignment, len) != 0) {
                    return null;
                }
                assert(alignment.check(@intFromPtr(aligned_ptr)));
                return @ptrCast(aligned_ptr);
            },
            .manual_align => {
                // 额外分配空间以容纳对齐填充,并在对齐地址之前存储 `malloc` 返回的原始指针。
                //
                const padded_len = len + @sizeOf(usize) + alignment.toByteUnits() - 1;
                const unaligned_ptr: [*]u8 = @ptrCast(c.malloc(padded_len) orelse return null);
                const unaligned_addr = @intFromPtr(unaligned_ptr);
                const aligned_addr = alignment.forward(unaligned_addr + @sizeOf(usize));
                const aligned_ptr = unaligned_ptr + (aligned_addr - unaligned_addr);
                manualAlignHeader(aligned_ptr).* = unaligned_ptr;
                return aligned_ptr;
            },
        }
    }

    fn resize(
        _: *anyopaque,
        memory: []u8,
        alignment: Alignment,
        new_len: usize,
        return_address: usize,
    ) bool {
        _ = return_address;
        assert(new_len > 0);
        if (new_len <= memory.len) {
            return true; // 原地缩小始终有效
        }
        const mallocSize = func: {
            if (@TypeOf(c.malloc_size) != void) break :func c.malloc_size;
            if (@TypeOf(c.malloc_usable_size) != void) break :func c.malloc_usable_size;
            if (@TypeOf(c._msize) != void) break :func c._msize;
            return false; // 无法确定实际可用空间的大小。
        };
        const usable_len: usize = switch (allocStrat(alignment)) {
            .raw, .posix_memalign => mallocSize(memory.ptr),
            .manual_align => usable_len: {
                const unaligned_ptr = manualAlignHeader(memory.ptr).*;
                const full_len = mallocSize(unaligned_ptr);
                const padding = @intFromPtr(memory.ptr) - @intFromPtr(unaligned_ptr);
                break :usable_len full_len - padding;
            },
        };
        return new_len <= usable_len;
    }

    fn remap(
        ctx: *anyopaque,
        memory: []u8,
        alignment: Alignment,
        new_len: usize,
        return_address: usize,
    ) ?[*]u8 {
        assert(new_len > 0);
        // 若可能,优先原地调整大小,因为即使合法,`realloc` 也可能很昂贵。
        if (resize(ctx, memory, alignment, new_len, return_address)) {
            return memory.ptr;
        }
        switch (allocStrat(alignment)) {
            .raw => {
                // `malloc` 等函数保证所需对齐,因此可以尝试 `realloc`。
                // 由于对象对齐规则,C 只需保证不超过分配大小的 `max_align_t` 对齐。
                // 必要时扩展分配大小。
                const actual_len = @max(new_len, @alignOf(std.c.max_align_t));
                const new_ptr = c.realloc(memory.ptr, actual_len) orelse return null;
                assert(alignment.check(@intFromPtr(new_ptr)));
                return @ptrCast(new_ptr);
            },
            .posix_memalign, .manual_align => {
                // `realloc` 可能返回不满足原始对齐要求的新分配,
                // 因此无法再做更多处理。
                return null;
            },
        }
    }

    fn free(
        _: *anyopaque,
        memory: []u8,
        alignment: Alignment,
        return_address: usize,
    ) void {
        _ = return_address;
        switch (allocStrat(alignment)) {
            .raw, .posix_memalign => c.free(memory.ptr),
            .manual_align => c.free(manualAlignHeader(memory.ptr).*),
        }
    }
};

/// 在支持内存映射的操作系统上,此分配器对每次
/// 分配和释放都直接发起系统调用。
///
/// 否则退回该目标首选的单例分配器。
///
/// 线程安全。
pub const page_allocator: Allocator = if (@hasDecl(root, "os") and
    @hasDecl(root.os, "heap") and
    @hasDecl(root.os.heap, "page_allocator"))
    root.os.heap.page_allocator
else if (builtin.target.cpu.arch.isWasm()) .{
    .ptr = undefined,
    .vtable = &WasmAllocator.vtable,
} else .{
    .ptr = undefined,
    .vtable = &PageAllocator.vtable,
};

pub const smp_allocator: Allocator = .{
    .ptr = undefined,
    .vtable = &SmpAllocator.vtable,
};

/// 此分配器快速、精简,专用于 WebAssembly。
pub const wasm_allocator: Allocator = .{
    .ptr = undefined,
    .vtable = &WasmAllocator.vtable,
};

/// 支持单线程 WebAssembly 和 Linux。
pub const brk_allocator: Allocator = .{
    .ptr = undefined,
    .vtable = &BrkAllocator.vtable,
};

test c_allocator {
    if (builtin.link_libc) {
        try testAllocator(c_allocator);
        try testAllocatorAligned(c_allocator);
        try testAllocatorLargeAlignment(c_allocator);
        try testAllocatorAlignedShrink(c_allocator);
    }
}

test smp_allocator {
    if (builtin.single_threaded) return;
    try testAllocator(smp_allocator);
    try testAllocatorAligned(smp_allocator);
    try testAllocatorLargeAlignment(smp_allocator);
    try testAllocatorAlignedShrink(smp_allocator);
}

test SafeAllocator {
    var instance: SafeAllocator = .init(page_allocator, .{});
    defer _ = instance.deinit();
    const allocator = instance.allocator();

    try testAllocator(allocator);
    try testAllocatorAligned(allocator);
    try testAllocatorLargeAlignment(allocator);
    try testAllocatorAlignedShrink(allocator);
}

test PageAllocator {
    const allocator = page_allocator;
    try testAllocator(allocator);
    try testAllocatorAligned(allocator);
    if (!builtin.target.cpu.arch.isWasm()) {
        try testAllocatorLargeAlignment(allocator);
        try testAllocatorAlignedShrink(allocator);
    }

    if (builtin.os.tag == .windows) {
        const slice = try allocator.alignedAlloc(u8, .fromByteUnits(page_size_min), 128);
        slice[0] = 0x12;
        slice[127] = 0x34;
        allocator.free(slice);
    }
    {
        var buf = try allocator.alloc(u8, pageSize() + 1);
        defer allocator.free(buf);
        buf = try allocator.realloc(buf, 1); // 收缩越过页边界
    }
}

test ArenaAllocator {
    var arena_allocator = ArenaAllocator.init(page_allocator);
    defer arena_allocator.deinit();
    const allocator = arena_allocator.allocator();

    try testAllocator(allocator);
    try testAllocatorAligned(allocator);
    try testAllocatorLargeAlignment(allocator);
    try testAllocatorAlignedShrink(allocator);
}

/// 此实现不应尝试超过 C malloc 可处理范围的对齐值。
pub fn testAllocator(base_allocator: mem.Allocator) !void {
    var validationAllocator = mem.validationWrap(base_allocator);
    const allocator = validationAllocator.allocator();

    var slice = try allocator.alloc(*i32, 100);
    try testing.expect(slice.len == 100);
    for (slice, 0..) |*item, i| {
        item.* = try allocator.create(i32);
        item.*.* = @as(i32, @intCast(i));
    }

    slice = try allocator.realloc(slice, 20000);
    try testing.expect(slice.len == 20000);

    for (slice[0..100], 0..) |item, i| {
        try testing.expect(item.* == @as(i32, @intCast(i)));
        allocator.destroy(item);
    }

    if (allocator.resize(slice, 50)) {
        slice = slice[0..50];
        if (allocator.resize(slice, 25)) {
            slice = slice[0..25];
            try testing.expect(allocator.resize(slice, 0));
            slice = slice[0..0];
            slice = try allocator.realloc(slice, 10);
            try testing.expect(slice.len == 10);
        }
    }
    allocator.free(slice);

    // 零长度分配
    const empty = try allocator.alloc(u8, 0);
    allocator.free(empty);
    // 零大小类型的分配
    const zero_bit_ptr = try allocator.create(u0);
    zero_bit_ptr.* = 0;
    allocator.destroy(zero_bit_ptr);
    const zero_len_array = try allocator.create([0]u64);
    allocator.destroy(zero_len_array);

    const oversize = try allocator.alignedAlloc(u32, null, 5);
    try testing.expect(oversize.len >= 5);
    for (oversize) |*item| {
        item.* = 0xDEADBEEF;
    }
    allocator.free(oversize);
}

pub fn testAllocatorAligned(base_allocator: mem.Allocator) !void {
    var validationAllocator = mem.validationWrap(base_allocator);
    const allocator = validationAllocator.allocator();

    // 测试几个小于和大于类型自身对齐值的对齐值
    inline for ([_]Alignment{ .@"1", .@"2", .@"4", .@"8", .@"16", .@"32", .@"64" }) |alignment| {
        // 初始
        var slice = try allocator.alignedAlloc(u8, alignment, 10);
        try testing.expect(slice.len == 10);
        // 增长
        slice = try allocator.realloc(slice, 100);
        try testing.expect(slice.len == 100);
        if (allocator.resize(slice, 10)) {
            slice = slice[0..10];
        }
        try testing.expect(allocator.resize(slice, 0));
        slice = slice[0..0];
        // 从零大小重新分配
        slice = try allocator.realloc(slice, 100);
        try testing.expect(slice.len == 100);
        if (allocator.resize(slice, 10)) {
            slice = slice[0..10];
        }
        try testing.expect(allocator.resize(slice, 0));
    }
}

pub fn testAllocatorLargeAlignment(base_allocator: mem.Allocator) !void {
    var validationAllocator = mem.validationWrap(base_allocator);
    const allocator = validationAllocator.allocator();

    const large_align: usize = page_size_min / 2;

    var align_mask: usize = undefined;
    align_mask = @shlWithOverflow(~@as(usize, 0), @as(Allocator.Log2Align, @ctz(large_align)))[0];

    var slice = try allocator.alignedAlloc(u8, .fromByteUnits(large_align), 500);
    try testing.expect(@intFromPtr(slice.ptr) & align_mask == @intFromPtr(slice.ptr));

    if (allocator.resize(slice, 100)) {
        slice = slice[0..100];
    }

    slice = try allocator.realloc(slice, 5000);
    try testing.expect(@intFromPtr(slice.ptr) & align_mask == @intFromPtr(slice.ptr));

    if (allocator.resize(slice, 10)) {
        slice = slice[0..10];
    }

    slice = try allocator.realloc(slice, 20000);
    try testing.expect(@intFromPtr(slice.ptr) & align_mask == @intFromPtr(slice.ptr));

    allocator.free(slice);
}

pub fn testAllocatorAlignedShrink(base_allocator: mem.Allocator) !void {
    var validationAllocator = mem.validationWrap(base_allocator);
    const allocator = validationAllocator.allocator();

    var debug_buffer: [1000]u8 = undefined;
    var fib = FixedBufferAllocator.init(&debug_buffer);
    const debug_allocator = fib.allocator();

    const alloc_size = pageSize() * 2 + 50;
    var slice = try allocator.alignedAlloc(u8, .@"16", alloc_size);
    defer allocator.free(slice);

    var stuff_to_free = std.array_list.Managed([]align(16) u8).init(debug_allocator);
    // 在 Windows 上,VirtualAlloc 返回按 64K 边界对齐的地址,
    // 即 16 页,因此这里使用 32。如果测试失败,
    // 可能需要增大提供给 `allocator` 参数的分配大小,
    // 因为这里需要如此高的额外对齐。
    while (@intFromPtr(slice.ptr) == mem.alignForward(usize, @intFromPtr(slice.ptr), pageSize() * 32)) {
        try stuff_to_free.append(slice);
        slice = try allocator.alignedAlloc(u8, .@"16", alloc_size);
    }
    while (stuff_to_free.pop()) |item| {
        allocator.free(item);
    }
    slice[0] = 0x12;
    slice[60] = 0x34;

    slice = try allocator.reallocAdvanced(slice, alloc_size / 2, 0);
    try testing.expect(slice[0] == 0x12);
    try testing.expect(slice[60] == 0x34);
}

const page_size_min_default: ?usize = switch (builtin.os.tag) {
    .driverkit, .ios, .maccatalyst, .macos, .tvos, .visionos, .watchos => switch (builtin.cpu.arch) {
        .x86_64 => 4 << 10,
        .aarch64 => 16 << 10,
        else => null,
    },
    .windows => switch (builtin.cpu.arch) {
        // -- <https://devblogs.microsoft.com/oldnewthing/20210510-00/?p=105200>
        .x86, .x86_64 => 4 << 10,
        // SuperH => 4 << 10,
        .mips, .mipsel, .mips64, .mips64el => 4 << 10,
        .powerpc, .powerpcle, .powerpc64, .powerpc64le => 4 << 10,
        // DEC Alpha => 8 << 10,
        // Itanium => 8 << 10,
        .thumb, .thumbeb, .arm, .armeb, .aarch64, .aarch64_be => 4 << 10,
        else => null,
    },
    .wasi => switch (builtin.cpu.arch) {
        .wasm32, .wasm64 => 64 << 10,
        else => null,
    },
    // https://github.com/tianocore/edk2/blob/b158dad150bf02879668f72ce306445250838201/MdePkg/Include/Uefi/UefiBaseType.h#L180-L187
    .uefi => 4 << 10,
    .freebsd => switch (builtin.cpu.arch) {
        // FreeBSD/sys/*
        .x86, .x86_64 => 4 << 10,
        .thumb, .thumbeb, .arm, .armeb => 4 << 10,
        .aarch64, .aarch64_be => 4 << 10,
        .powerpc, .powerpc64, .powerpc64le, .powerpcle => 4 << 10,
        .riscv32, .riscv64 => 4 << 10,
        else => null,
    },
    .netbsd => switch (builtin.cpu.arch) {
        // NetBSD/sys/arch/*
        .alpha => 8 << 10,
        .x86, .x86_64 => 4 << 10,
        .thumb, .thumbeb, .arm, .armeb => 4 << 10,
        .aarch64, .aarch64_be => 4 << 10,
        .hppa => 4 << 10,
        .mips, .mipsel, .mips64, .mips64el => 4 << 10,
        .powerpc, .powerpc64, .powerpc64le, .powerpcle => 4 << 10,
        .sh, .sheb => 4 << 10,
        .sparc => 4 << 10,
        .sparc64 => 8 << 10,
        .riscv32, .riscv64 => 4 << 10,
        // Sun-2
        .m68k => 2 << 10,
        else => null,
    },
    .dragonfly => switch (builtin.cpu.arch) {
        .x86, .x86_64 => 4 << 10,
        else => null,
    },
    .openbsd => switch (builtin.cpu.arch) {
        // OpenBSD/sys/arch/*
        .alpha => 8 << 10,
        .hppa => 4 << 10,
        .x86, .x86_64 => 4 << 10,
        .thumb, .thumbeb, .arm, .armeb, .aarch64, .aarch64_be => 4 << 10,
        .m88k => 4 << 10,
        .mips64, .mips64el => 4 << 10,
        .powerpc, .powerpc64, .powerpc64le, .powerpcle => 4 << 10,
        .riscv64 => 4 << 10,
        .sh, .sheb => 4 << 10,
        .sparc64 => 8 << 10,
        else => null,
    },
    .illumos => switch (builtin.cpu.arch) {
        // src/uts/*/sys/machparam.h
        .x86, .x86_64 => 4 << 10,
        .sparc, .sparc64 => 8 << 10,
        else => null,
    },
    .fuchsia => switch (builtin.cpu.arch) {
        // fuchsia/kernel/arch/*/include/arch/defines.h
        .x86_64 => 4 << 10,
        .aarch64, .aarch64_be => 4 << 10,
        .riscv64 => 4 << 10,
        else => null,
    },
    // https://github.com/SerenityOS/serenity/blob/62b938b798dc009605b5df8a71145942fc53808b/Kernel/API/POSIX/sys/limits.h#L11-L13
    .serenity => 4 << 10,
    .haiku => switch (builtin.cpu.arch) {
        // haiku/headers/posix/arch/*/limits.h
        .thumb, .thumbeb, .arm, .armeb => 4 << 10,
        .aarch64, .aarch64_be => 4 << 10,
        .m68k => 4 << 10,
        .mips, .mipsel, .mips64, .mips64el => 4 << 10,
        .powerpc, .powerpc64, .powerpc64le, .powerpcle => 4 << 10,
        .riscv64 => 4 << 10,
        .sparc64 => 8 << 10,
        .x86, .x86_64 => 4 << 10,
        else => null,
    },
    .hurd => switch (builtin.cpu.arch) {
        // gnumach/*/include/mach/*/vm_param.h
        .x86, .x86_64 => 4 << 10,
        .aarch64 => null,
        else => null,
    },
    .plan9 => switch (builtin.cpu.arch) {
        // 9front/sys/src/9/*/mem.h
        .x86, .x86_64 => 4 << 10,
        .thumb, .thumbeb, .arm, .armeb => 4 << 10,
        .aarch64, .aarch64_be => 4 << 10,
        .mips, .mipsel, .mips64, .mips64el => 4 << 10,
        .powerpc, .powerpcle, .powerpc64, .powerpc64le => 4 << 10,
        .sparc => 4 << 10,
        else => null,
    },
    .ps3 => switch (builtin.cpu.arch) {
        // cell/SDK_doc/en/html/C_and_C++_standard_libraries/stdlib.html
        .powerpc64 => 1 << 20, // 1 MiB
        else => null,
    },
    .ps4 => switch (builtin.cpu.arch) {
        // https://github.com/ps4dev/ps4sdk/blob/4df9d001b66ae4ec07d9a51b62d1e4c5e270eecc/include/machine/param.h#L95
        .x86, .x86_64 => 4 << 10,
        else => null,
    },
    .ps5 => switch (builtin.cpu.arch) {
        // https://github.com/PS5Dev/PS5SDK/blob/a2e03a2a0231a3a3397fa6cd087a01ca6d04f273/include/machine/param.h#L95
        .x86, .x86_64 => 16 << 10,
        else => null,
    },
    .psp => switch (builtin.cpu.arch) {
        // 通过测试 sceKernel 得到的最小块分配
        .mips, .mipsel => 1 << 8, // 256
        else => null,
    },
    // system/lib/libc/musl/arch/emscripten/bits/limits.h
    .emscripten => 64 << 10,
    .linux => switch (builtin.cpu.arch) {
        // Linux/arch/*/Kconfig
        .alpha => 8 << 10,
        .arc, .arceb => 4 << 10,
        .thumb, .thumbeb, .arm, .armeb => 4 << 10,
        .aarch64, .aarch64_be => 4 << 10,
        .csky => 4 << 10,
        .hexagon => 4 << 10,
        .hppa => 4 << 10,
        .loongarch32, .loongarch64 => 4 << 10,
        .m68k => 4 << 10,
        .microblaze, .microblazeel => 4 << 10,
        .mips, .mipsel, .mips64, .mips64el => 4 << 10,
        .or1k => 8 << 10,
        .powerpc, .powerpc64, .powerpc64le, .powerpcle => 4 << 10,
        .riscv32, .riscv64 => 4 << 10,
        .s390x => 4 << 10,
        .sh, .sheb => 4 << 10,
        .sparc => 4 << 10,
        .sparc64 => 8 << 10,
        .x86, .x86_64 => 4 << 10,
        .xtensa, .xtensaeb => 4 << 10,
        else => null,
    },
    .freestanding, .other => switch (builtin.cpu.arch) {
        .wasm32, .wasm64 => 64 << 10,
        .x86, .x86_64 => 4 << 10,
        .aarch64, .aarch64_be => 4 << 10,
        else => null,
    },
    else => null,
};

const page_size_max_default: ?usize = switch (builtin.os.tag) {
    .driverkit, .ios, .maccatalyst, .macos, .tvos, .visionos, .watchos => switch (builtin.cpu.arch) {
        .x86_64 => 4 << 10,
        .aarch64 => 16 << 10,
        else => null,
    },
    .windows => switch (builtin.cpu.arch) {
        // -- <https://devblogs.microsoft.com/oldnewthing/20210510-00/?p=105200>
        .x86, .x86_64 => 4 << 10,
        // SuperH => 4 << 10,
        .mips, .mipsel, .mips64, .mips64el => 4 << 10,
        .powerpc, .powerpcle, .powerpc64, .powerpc64le => 4 << 10,
        // DEC Alpha => 8 << 10,
        // Itanium => 8 << 10,
        .thumb, .thumbeb, .arm, .armeb, .aarch64, .aarch64_be => 4 << 10,
        else => null,
    },
    .wasi => switch (builtin.cpu.arch) {
        .wasm32, .wasm64 => 64 << 10,
        else => null,
    },
    // https://github.com/tianocore/edk2/blob/b158dad150bf02879668f72ce306445250838201/MdePkg/Include/Uefi/UefiBaseType.h#L180-L187
    .uefi => 4 << 10,
    .freebsd => switch (builtin.cpu.arch) {
        // FreeBSD/sys/*
        .x86, .x86_64 => 4 << 10,
        .thumb, .thumbeb, .arm, .armeb => 4 << 10,
        .aarch64, .aarch64_be => 4 << 10,
        .powerpc, .powerpc64, .powerpc64le, .powerpcle => 4 << 10,
        .riscv32, .riscv64 => 4 << 10,
        else => null,
    },
    .netbsd => switch (builtin.cpu.arch) {
        // NetBSD/sys/arch/*
        .alpha => 8 << 10,
        .x86, .x86_64 => 4 << 10,
        .thumb, .thumbeb, .arm, .armeb => 4 << 10,
        .aarch64, .aarch64_be => 64 << 10,
        .hppa => 4 << 10,
        .mips, .mipsel, .mips64, .mips64el => 16 << 10,
        .powerpc, .powerpc64, .powerpc64le, .powerpcle => 16 << 10,
        .sh, .sheb => 4 << 10,
        .sparc => 8 << 10,
        .sparc64 => 8 << 10,
        .riscv32, .riscv64 => 4 << 10,
        .m68k => 8 << 10,
        else => null,
    },
    .dragonfly => switch (builtin.cpu.arch) {
        .x86, .x86_64 => 4 << 10,
        else => null,
    },
    .openbsd => switch (builtin.cpu.arch) {
        // OpenBSD/sys/arch/*
        .alpha => 8 << 10,
        .hppa => 4 << 10,
        .x86, .x86_64 => 4 << 10,
        .thumb, .thumbeb, .arm, .armeb, .aarch64, .aarch64_be => 4 << 10,
        .m88k => 4 << 10,
        .mips64, .mips64el => 16 << 10,
        .powerpc, .powerpc64, .powerpc64le, .powerpcle => 4 << 10,
        .riscv64 => 4 << 10,
        .sh, .sheb => 4 << 10,
        .sparc64 => 8 << 10,
        else => null,
    },
    .illumos => switch (builtin.cpu.arch) {
        // src/uts/*/sys/machparam.h
        .x86, .x86_64 => 4 << 10,
        .sparc, .sparc64 => 8 << 10,
        else => null,
    },
    .fuchsia => switch (builtin.cpu.arch) {
        // fuchsia/kernel/arch/*/include/arch/defines.h
        .x86_64 => 4 << 10,
        .aarch64, .aarch64_be => 4 << 10,
        .riscv64 => 4 << 10,
        else => null,
    },
    // https://github.com/SerenityOS/serenity/blob/62b938b798dc009605b5df8a71145942fc53808b/Kernel/API/POSIX/sys/limits.h#L11-L13
    .serenity => 4 << 10,
    .haiku => switch (builtin.cpu.arch) {
        // haiku/headers/posix/arch/*/limits.h
        .thumb, .thumbeb, .arm, .armeb => 4 << 10,
        .aarch64, .aarch64_be => 4 << 10,
        .m68k => 4 << 10,
        .mips, .mipsel, .mips64, .mips64el => 4 << 10,
        .powerpc, .powerpc64, .powerpc64le, .powerpcle => 4 << 10,
        .riscv64 => 4 << 10,
        .sparc64 => 8 << 10,
        .x86, .x86_64 => 4 << 10,
        else => null,
    },
    .hurd => switch (builtin.cpu.arch) {
        // gnumach/*/include/mach/*/vm_param.h
        .x86, .x86_64 => 4 << 10,
        .aarch64 => null,
        else => null,
    },
    .plan9 => switch (builtin.cpu.arch) {
        // 9front/sys/src/9/*/mem.h
        .x86, .x86_64 => 4 << 10,
        .thumb, .thumbeb, .arm, .armeb => 4 << 10,
        .aarch64, .aarch64_be => 64 << 10,
        .mips, .mipsel, .mips64, .mips64el => 16 << 10,
        .powerpc, .powerpcle, .powerpc64, .powerpc64le => 4 << 10,
        .sparc => 4 << 10,
        else => null,
    },
    .ps3 => switch (builtin.cpu.arch) {
        // cell/SDK_doc/en/html/C_and_C++_standard_libraries/stdlib.html
        .powerpc64 => 1 << 20, // 1 MiB
        else => null,
    },
    .ps4 => switch (builtin.cpu.arch) {
        // https://github.com/ps4dev/ps4sdk/blob/4df9d001b66ae4ec07d9a51b62d1e4c5e270eecc/include/machine/param.h#L95
        .x86, .x86_64 => 4 << 10,
        else => null,
    },
    .ps5 => switch (builtin.cpu.arch) {
        // https://github.com/PS5Dev/PS5SDK/blob/a2e03a2a0231a3a3397fa6cd087a01ca6d04f273/include/machine/param.h#L95
        .x86, .x86_64 => 16 << 10,
        else => null,
    },
    .psp => switch (builtin.cpu.arch) {
        // 通过测试 sceKernel 得到的最小块分配
        .mips, .mipsel => 1 << 8, // 256
        else => null,
    },
    // system/lib/libc/musl/arch/emscripten/bits/limits.h
    .emscripten => 64 << 10,
    .linux => switch (builtin.cpu.arch) {
        // Linux/arch/*/Kconfig
        .alpha => 8 << 10,
        .arc, .arceb => 16 << 10,
        .thumb, .thumbeb, .arm, .armeb => 4 << 10,
        .aarch64, .aarch64_be => 64 << 10,
        .csky => 4 << 10,
        .hexagon => 256 << 10,
        .hppa => 64 << 10,
        .loongarch32, .loongarch64 => 64 << 10,
        .m68k => 8 << 10,
        .microblaze, .microblazeel => 4 << 10,
        .mips, .mipsel, .mips64, .mips64el => 64 << 10,
        .or1k => 8 << 10,
        .powerpc, .powerpc64, .powerpc64le, .powerpcle => 256 << 10,
        .riscv32, .riscv64 => 4 << 10,
        .s390x => 4 << 10,
        .sh, .sheb => 64 << 10,
        .sparc => 4 << 10,
        .sparc64 => 8 << 10,
        .x86, .x86_64 => 4 << 10,
        .xtensa, .xtensaeb => 4 << 10,
        else => null,
    },
    .freestanding => switch (builtin.cpu.arch) {
        .wasm32, .wasm64 => 64 << 10,
        else => null,
    },
    else => null,
};

test {
    _ = @import("heap/memory_pool.zig");
    _ = ArenaAllocator;
    _ = DebugAllocator(.{});
    _ = SafeAllocator;
    _ = FixedBufferAllocator;
    _ = BufferFirstAllocator;
    if (builtin.single_threaded) {
        if (builtin.cpu.arch.isWasm() or (builtin.os.tag == .linux and !builtin.link_libc)) {
            _ = brk_allocator;
        }
    } else {
        _ = smp_allocator;
    }
}