跳转到内容

std.testing.FailingAllocator

标准库Zig 0.17.0官方原文
源码std/testing/FailingAllocator.zig

第 1 行

在 N 次分配后失败的分配器,可用于确认 内存不足的情况是否得到正确处理。

字段

alloc_index: usize
resize_index: usize
internal_allocator: mem.Allocator
allocated_bytes: usize
freed_bytes: usize
allocations: usize
deallocations: usize
stack_addresses: [num_stack_frames]usize
has_induced_failure: bool
fail_index: usize
resize_fail_index: usize

std.testing.FailingAllocator.alloc

函数

第 58 行

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

参数

ctx: *anyopaque
len: usize
alignment: mem.Alignment
return_address: usize

std.testing.FailingAllocator.allocator

函数

第 46 行

pub fn allocator(self: *FailingAllocator) mem.Allocator

参数

std.testing.FailingAllocator.Config

容器

第 21 行

字段

fail_index: usize = std.math.maxInt(usize)

此分配器预期可成功执行的分配次数。 再下一次分配将失败。

resize_fail_index: usize = std.math.maxInt(usize)

此分配器预期成功调整大小的次数。下一次调整将失败。

std.testing.FailingAllocator.FailingAllocator

别名

第 5 行

别名目标 std.testing.FailingAllocator

std.testing.FailingAllocator.free

函数

第 121 行

fn free( ctx: *anyopaque, old_mem: []u8, alignment: mem.Alignment, ra: usize, ) void

参数

ctx: *anyopaque
old_mem: []u8
alignment: mem.Alignment
ra: usize

std.testing.FailingAllocator.getStackTrace

函数

第 134 行

仅在 has_induced_failure == true 时有效

pub fn getStackTrace(self: *FailingAllocator) std.debug.StackTrace

参数

std.testing.FailingAllocator.init

函数

第 30 行

pub fn init(internal_allocator: mem.Allocator, config: Config) FailingAllocator

参数

internal_allocator: mem.Allocator
config: Config

std.testing.FailingAllocator.mem

别名

第 4 行

别名目标 std.mem

std.testing.FailingAllocator.num_stack_frames

常量

第 19 行

std.testing.FailingAllocator.remap

函数

第 102 行

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

参数

ctx: *anyopaque
memory: []u8
alignment: mem.Alignment
new_len: usize
ra: usize

std.testing.FailingAllocator.resize

函数

第 81 行

fn resize( ctx: *anyopaque, memory: []u8, alignment: mem.Alignment, new_len: usize, ra: usize, ) bool

参数

ctx: *anyopaque
memory: []u8
alignment: mem.Alignment
new_len: usize
ra: usize

std.testing.FailingAllocator.std

别名

第 3 行

别名目标 std

源码

std/testing/FailingAllocator.zig

//! 在 N 次分配后失败的分配器,可用于确认
//! 内存不足的情况是否得到正确处理。
const std = @import("../std.zig");
const mem = std.mem;
const FailingAllocator = @This();

alloc_index: usize,
resize_index: usize,
internal_allocator: mem.Allocator,
allocated_bytes: usize,
freed_bytes: usize,
allocations: usize,
deallocations: usize,
stack_addresses: [num_stack_frames]usize,
has_induced_failure: bool,
fail_index: usize,
resize_fail_index: usize,

const num_stack_frames = if (std.debug.sys_can_stack_trace) 16 else 0;

pub const Config = struct {
    /// 此分配器预期可成功执行的分配次数。
    /// 再下一次分配将失败。
    fail_index: usize = std.math.maxInt(usize),

    /// 此分配器预期成功调整大小的次数。下一次调整将失败。
    resize_fail_index: usize = std.math.maxInt(usize),
};

pub fn init(internal_allocator: mem.Allocator, config: Config) FailingAllocator {
    return FailingAllocator{
        .internal_allocator = internal_allocator,
        .alloc_index = 0,
        .resize_index = 0,
        .allocated_bytes = 0,
        .freed_bytes = 0,
        .allocations = 0,
        .deallocations = 0,
        .stack_addresses = undefined,
        .has_induced_failure = false,
        .fail_index = config.fail_index,
        .resize_fail_index = config.resize_fail_index,
    };
}

pub fn allocator(self: *FailingAllocator) mem.Allocator {
    return .{
        .ptr = self,
        .vtable = &.{
            .alloc = alloc,
            .resize = resize,
            .remap = remap,
            .free = free,
        },
    };
}

fn alloc(
    ctx: *anyopaque,
    len: usize,
    alignment: mem.Alignment,
    return_address: usize,
) ?[*]u8 {
    const self: *FailingAllocator = @ptrCast(@alignCast(ctx));
    if (self.alloc_index == self.fail_index) {
        if (!self.has_induced_failure) {
            const st = std.debug.captureCurrentStackTrace(.{ .first_address = return_address }, &self.stack_addresses);
            @memset(self.stack_addresses[@min(st.return_addresses.len, self.stack_addresses.len)..], 0);
            self.has_induced_failure = true;
        }
        return null;
    }
    const result = self.internal_allocator.rawAlloc(len, alignment, return_address) orelse
        return null;
    self.allocated_bytes += len;
    self.allocations += 1;
    self.alloc_index += 1;
    return result;
}

fn resize(
    ctx: *anyopaque,
    memory: []u8,
    alignment: mem.Alignment,
    new_len: usize,
    ra: usize,
) bool {
    const self: *FailingAllocator = @ptrCast(@alignCast(ctx));
    if (self.resize_index == self.resize_fail_index)
        return false;
    if (!self.internal_allocator.rawResize(memory, alignment, new_len, ra))
        return false;
    if (new_len < memory.len) {
        self.freed_bytes += memory.len - new_len;
    } else {
        self.allocated_bytes += new_len - memory.len;
    }
    self.resize_index += 1;
    return true;
}

fn remap(
    ctx: *anyopaque,
    memory: []u8,
    alignment: mem.Alignment,
    new_len: usize,
    ra: usize,
) ?[*]u8 {
    const self: *FailingAllocator = @ptrCast(@alignCast(ctx));
    if (self.resize_index == self.resize_fail_index) return null;
    const new_ptr = self.internal_allocator.rawRemap(memory, alignment, new_len, ra) orelse return null;
    if (new_len < memory.len) {
        self.freed_bytes += memory.len - new_len;
    } else {
        self.allocated_bytes += new_len - memory.len;
    }
    self.resize_index += 1;
    return new_ptr;
}

fn free(
    ctx: *anyopaque,
    old_mem: []u8,
    alignment: mem.Alignment,
    ra: usize,
) void {
    const self: *FailingAllocator = @ptrCast(@alignCast(ctx));
    self.internal_allocator.rawFree(old_mem, alignment, ra);
    self.deallocations += 1;
    self.freed_bytes += old_mem.len;
}

/// 仅在 `has_induced_failure == true` 时有效
pub fn getStackTrace(self: *FailingAllocator) std.debug.StackTrace {
    std.debug.assert(self.has_induced_failure);
    var len: usize = 0;
    while (len < self.stack_addresses.len and self.stack_addresses[len] != 0) {
        len += 1;
    }
    return .{
        .return_addresses = self.stack_addresses[0..len],
        .skipped = if (len == self.stack_addresses.len) .unknown else .none,
    };
}

test FailingAllocator {
    // 分配时失败
    {
        var failing_allocator_state = FailingAllocator.init(std.testing.allocator, .{
            .fail_index = 2,
        });
        const failing_alloc = failing_allocator_state.allocator();

        const a = try failing_alloc.create(i32);
        defer failing_alloc.destroy(a);
        const b = try failing_alloc.create(i32);
        defer failing_alloc.destroy(b);
        try std.testing.expectError(error.OutOfMemory, failing_alloc.create(i32));
    }
    // 调整大小时失败
    {
        var failing_allocator_state = FailingAllocator.init(std.testing.allocator, .{
            .resize_fail_index = 1,
        });
        const failing_alloc = failing_allocator_state.allocator();

        const resized_slice = blk: {
            const slice = try failing_alloc.alloc(u8, 8);
            errdefer failing_alloc.free(slice);

            break :blk failing_alloc.remap(slice, 6) orelse return error.UnexpectedRemapFailure;
        };
        defer failing_alloc.free(resized_slice);

        // 从此处开始,重映射与调整大小操作应当失败
        try std.testing.expectEqual(null, failing_alloc.remap(resized_slice, 4));
        try std.testing.expectEqual(false, failing_alloc.resize(resized_slice, 4));

        // 注意:realloc 可能成功,因为它会回退为 free+alloc。
    }
}