标准内存分配接口。
字段
ptr: *anyopaque指向分配器实现的类型擦除的指针。
比较此字段可能导致非法行为,因为在分配器实现没有
关联状态的情况下,此字段可能被设为 undefined。
vtable: *const VTable
AllocatorbuiltinstdassertmathmemAlignmentSliceAbsorbSentinelErrorLog2AlignVTablenoAllocnoResizenoRemapnoFreerawAllocrawResizerawRemaprawFreecreatealignedCreatecreateAdvancedWithRetAddrdestroyallocallocWithOptionsallocWithOptionsRetAddrAllocWithOptionsPayloadallocSentinelalignedAllocallocAdvancedWithRetAddrallocWithSizeAndAlignmentallocBytesAlignedresizeremapreallocreallocAdvancedfreedupedupeSentinelprintprintSentinelfailingunreachableResizeunreachableRemapunreachableFree
std.mem.Allocator.AbsorbSentinel
别名
std.mem.Allocator.alignedAlloc
函数
pub fn alignedAlloc( self: Allocator, comptime T: type, comptime alignment: ?Alignment, n: usize, ) Error![]align(if (alignment) |a| a.toByteUnits() else @alignOf(T)) T
参数
错误
- OutOfMemory
std.mem.Allocator.alignedCreate
函数
pub fn alignedCreate( self: Allocator, comptime T: type, comptime alignment: ?Alignment, ) Error!*align(if (alignment) |a| a.toByteUnits() else @alignOf(T)) T
参数
错误
- OutOfMemory
std.mem.Allocator.Alignment
别名
别名目标 std.mem.Alignment
std.mem.Allocator.alloc
函数
分配包含 n 个 T 类型项目的数组,将全部
项目设为 undefined。根据 Allocator
实现,内存不再需要时可能必须调用 free,
以避免资源泄漏。若
Allocator 的实现未知,正确代码
应在使用结束后调用 free。
分配单个项目参见 create。
pub fn alloc(self: Allocator, comptime T: type, n: usize) Error![]T
参数
错误
- OutOfMemory
std.mem.Allocator.allocAdvancedWithRetAddr
函数
pub inline fn allocAdvancedWithRetAddr( self: Allocator, comptime T: type, comptime alignment: ?Alignment, n: usize, return_address: usize, ) Error![]align(if (alignment) |a| a.toByteUnits() else @alignOf(T)) T
参数
错误
- OutOfMemory
std.mem.Allocator.Allocator
别名
别名目标 std.mem.Allocator
std.mem.Allocator.allocBytesAligned
函数
pub fn allocBytesAligned( self: Allocator, comptime alignment: Alignment, byte_count: usize, return_address: usize, ) Error![*]align(alignment.toByteUnits()) u8
参数
错误
- OutOfMemory
std.mem.Allocator.allocSentinel
函数
分配包含 n + 1 个 T 类型项目的数组,将前 n
个项目设为 undefined,最后一个设为 sentinel。根据
Allocator 的实现,内存不再需要时可能必须调用 free,
以避免资源泄漏。若
Allocator 的实现未知,正确代码
应在使用结束后调用 free。
分配单个项目参见 create。
pub fn allocSentinel( self: Allocator, comptime Elem: type, n: usize, comptime sentinel: Elem, ) Error![:sentinel]Elem
参数
错误
- OutOfMemory
std.mem.Allocator.allocWithOptions
函数
pub fn allocWithOptions( self: Allocator, comptime Elem: type, n: usize, comptime optional_alignment: ?Alignment, comptime optional_sentinel: ?Elem, ) Error!AllocWithOptionsPayload(Elem, optional_alignment, optional_sentinel)
参数
self: Allocator
Elem: type
n: usize
optional_alignment: ?Alignmentnull 表示自然对齐
optional_sentinel: ?Elem
错误
- OutOfMemory
std.mem.Allocator.AllocWithOptionsPayload
类型函数
fn AllocWithOptionsPayload(comptime Elem: type, comptime alignment: ?Alignment, comptime sentinel: ?Elem) type
参数
std.mem.Allocator.allocWithOptionsRetAddr
函数
pub fn allocWithOptionsRetAddr( self: Allocator, comptime Elem: type, n: usize, comptime optional_alignment: ?Alignment, comptime optional_sentinel: ?Elem, return_address: usize, ) Error!AllocWithOptionsPayload(Elem, optional_alignment, optional_sentinel)
参数
self: Allocator
Elem: type
n: usize
optional_alignment: ?Alignmentnull 表示自然对齐
optional_sentinel: ?Elem
return_address: usize
错误
- OutOfMemory
std.mem.Allocator.allocWithSizeAndAlignment
函数
fn allocWithSizeAndAlignment( self: Allocator, comptime size: usize, comptime alignment: Alignment, n: usize, return_address: usize, ) Error![*]align(alignment.toByteUnits()) u8
参数
错误
- OutOfMemory
std.mem.Allocator.assert
别名
别名目标 std.debug.assert
std.mem.Allocator.builtin
常量
std.mem.Allocator.create
函数
返回指向未定义内存的指针。
使用 destroy 释放该内存。
pub fn create(a: Allocator, comptime T: type) Error!*T
参数
a: Allocator
T: type
错误
- OutOfMemory
std.mem.Allocator.createAdvancedWithRetAddr
函数
pub inline fn createAdvancedWithRetAddr( self: Allocator, comptime T: type, comptime alignment: ?Alignment, return_address: usize, ) Error!*align(if (alignment) |a| a.toByteUnits() else @alignOf(T)) T
参数
错误
- OutOfMemory
std.mem.Allocator.destroy
函数
ptr 应为 create 的返回值,
或具有相同地址及对齐属性。
pub fn destroy(self: Allocator, ptr: anytype) void
参数
self: Allocator
std.mem.Allocator.dupe
函数
将 m 复制到新分配的内存。调用方拥有该内存。
pub fn dupe(allocator: Allocator, comptime T: type, m: []const T) Error![]T
参数
错误
- OutOfMemory
std.mem.Allocator.dupeSentinel
函数
将 m 复制到新分配的内存,并添加哨兵终止元素。调用方拥有该内存。
pub fn dupeSentinel( allocator: Allocator, comptime T: type, m: []const T, comptime sentinel: T, ) Error![:sentinel]T
参数
错误
- OutOfMemory
std.mem.Allocator.Error
错误集合
错误
- OutOfMemory
std.mem.Allocator.failing
常量
始终分配失败的分配器。
Allocator
std.mem.Allocator.free
函数
pub fn free(self: Allocator, memory: anytype) void
参数
self: Allocator
std.mem.Allocator.Log2Align
类型
std.mem.Allocator.math
别名
别名目标 std.math
std.mem.Allocator.mem
别名
别名目标 std.mem
std.mem.Allocator.noAlloc
函数
pub fn noAlloc( self: *anyopaque, len: usize, alignment: Alignment, ret_addr: usize, ) ?[*]u8
参数
std.mem.Allocator.noFree
函数
pub fn noFree( self: *anyopaque, memory: []u8, alignment: Alignment, ret_addr: usize, ) void
参数
std.mem.Allocator.noRemap
函数
pub fn noRemap( self: *anyopaque, memory: []u8, alignment: Alignment, new_len: usize, ret_addr: usize, ) ?[*]u8
参数
std.mem.Allocator.noResize
函数
pub fn noResize( self: *anyopaque, memory: []u8, alignment: Alignment, new_len: usize, ret_addr: usize, ) bool
参数
std.mem.Allocator.print
函数
分配格式化字符串,成功时返回该字符串。
返回的切片可用 free 释放。若使用 arena 式分配器,
例如 std.heap.ArenaAllocator,则无需调用
free。
pub fn print(a: Allocator, comptime format: []const u8, args: anytype) Error![]u8
参数
a: Allocator
format: []const u8
错误
- OutOfMemory
用法示例
test print {
const x: i32 = -1;
const y: []const u8 = "hi";
const a = std.testing.allocator;
const s = try print(a, "{d}={s}", .{ x, y });
defer free(a, s);
try std.testing.expectEqualStrings("-1=hi", s);
}
std.mem.Allocator.printSentinel
函数
类似 print,但返回的切片具有指定哨兵。
返回的切片可用 free 释放。如果使用 arena 风格的分配器,
例如 std.heap.ArenaAllocator,则无需调用 free。
如果将返回切片强制转换为不含哨兵的切片,
再传给 free,则发生非法行为。
pub fn printSentinel( a: Allocator, comptime format: []const u8, args: anytype, comptime sentinel: u8, ) Allocator.Error![:sentinel]u8
参数
错误
- OutOfMemory
用法示例
test printSentinel {
const x: i32 = -1;
const y: []const u8 = "hi";
const a = std.testing.allocator;
const s = try printSentinel(a, "{d}={s}", .{ x, y }, 0);
defer free(a, s);
try std.testing.expectEqualStrings("-1=hi", s);
try std.testing.expectEqual(0, s[s.len]);
}
std.mem.Allocator.rawAlloc
函数
此函数仅应从 Allocator 的
实现内部调用。
pub inline fn rawAlloc(a: Allocator, len: usize, alignment: Alignment, ret_addr: usize) ?[*]u8
参数
std.mem.Allocator.rawFree
函数
此函数仅应从 Allocator 的
实现内部调用。
pub inline fn rawFree(a: Allocator, memory: []u8, alignment: Alignment, ret_addr: usize) void
参数
std.mem.Allocator.rawRemap
函数
此函数仅应从 Allocator 的
实现内部调用。
pub inline fn rawRemap(a: Allocator, memory: []u8, alignment: Alignment, new_len: usize, ret_addr: usize) ?[*]u8
参数
std.mem.Allocator.rawResize
函数
此函数仅应从 Allocator 的
实现内部调用。
pub inline fn rawResize(a: Allocator, memory: []u8, alignment: Alignment, new_len: usize, ret_addr: usize) bool
参数
std.mem.Allocator.realloc
函数
此函数为现有分配请求新的大小,可以比原分配更大、更小,或保持不变。
结果是由 new_n 个元素组成的数组,元素类型与现有分配相同。
若 new_n 为 0,则等同于 free,并且始终成功。
old_mem 可以为零长度,此时执行新的分配。
与以下函数不同,此函数只会因内存不足而失败:
pub fn realloc(self: Allocator, old_mem: anytype, new_n: usize) Error!Slice(AbsorbSentinel(@TypeOf(old_mem)))
参数
self: Allocator
new_n: usize
错误
- OutOfMemory
std.mem.Allocator.reallocAdvanced
函数
pub fn reallocAdvanced( self: Allocator, old_mem: anytype, new_n: usize, return_address: usize, ) Error!Slice(AbsorbSentinel(@TypeOf(old_mem)))
参数
错误
- OutOfMemory
std.mem.Allocator.remap
函数
请求修改分配的大小,允许重定位。
返回非 null 值表示调整大小成功。分配的地址可能保持不变,也可能已被重定位。无论哪种情况,分配的新大小均为 new_len。返回 null 表示此次调整等同于分配新内存、从旧内存复制字节,然后释放旧内存。在这种情况下,由调用方执行这些操作效率更高。
allocation 可以为空切片,此时返回 null;但若 new_len 同样为 0,则返回 allocation。
new_len 可以为零,此时释放该分配。
若分配元素的类型大小为零字节,则将 allocation.len 设置为 new_len。
pub fn remap(self: Allocator, allocation: anytype, new_len: usize) ?Slice(AbsorbSentinel(@TypeOf(allocation)))
参数
self: Allocator
new_len: usize
std.mem.Allocator.resize
函数
请求修改分配大小。
保证不移动指针,但分配器
实现可以通过返回 false 拒绝调整请求。
allocation 可以为空切片,此时返回 false;
但若 new_len 也为 0,则返回 true。
new_len 可以为零,此时释放该分配。
pub fn resize(self: Allocator, allocation: anytype, new_len: usize) bool
参数
self: Allocator
new_len: usize
std.mem.Allocator.Slice
别名
别名目标 std.meta.Slice
std.mem.Allocator.std
别名
别名目标 std
std.mem.Allocator.unreachableFree
函数
fn unreachableFree( self: *anyopaque, memory: []u8, alignment: Alignment, ret_addr: usize, ) void
参数
std.mem.Allocator.unreachableRemap
函数
fn unreachableRemap( self: *anyopaque, memory: []u8, alignment: Alignment, new_len: usize, ret_addr: usize, ) ?[*]u8
参数
std.mem.Allocator.unreachableResize
函数
fn unreachableResize( self: *anyopaque, memory: []u8, alignment: Alignment, new_len: usize, ret_addr: usize, ) bool
参数
std.mem.Allocator.VTable
容器
字段
alloc: *const fn (*anyopaque, len: usize, alignment: Alignment, ret_addr: usize) ?[*]u8返回指向 len 字节、满足指定 alignment 的指针,或返回
null 表示分配失败。
new_len 必须大于零。
可选的 ret_addr 表示分配调用栈中的
第一个返回地址。如果值为 0,则表示
未提供返回地址。
resize: *const fn (*anyopaque, memory: []u8, alignment: Alignment, new_len: usize, ret_addr: usize) bool尝试在原地扩大或缩小内存。
memory.len 必须等于最近一次成功
调用 alloc、resize 或 remap 所请求的长度。alignment 必须
等于最初调用 alloc 时作为 alignment
参数传入的值。
结果为 true 表示调整大小成功,
分配地址不变,大小变为 new_len。结果为 false
表示只有将分配移动到其他地址
才能完成调整。
new_len 必须大于零。
可选的 ret_addr 用于提供分配调用栈中的
首个返回地址。值为 0 表示
未提供返回地址。
remap: *const fn (*anyopaque, memory: []u8, alignment: Alignment, new_len: usize, ret_addr: usize) ?[*]u8尝试扩展或收缩内存,允许重定位。
memory.len 必须等于最近一次成功调用
alloc、resize 或 remap 时请求的长度。alignment 必须
等于作为 alignment 参数传入最初
alloc 调用的值。
返回非 null 值表示调整大小成功。
分配可能保持原地址,也可能已重定位。不论哪种
情况,分配大小现为 new_len。返回 null 表示
此次调整等同于重新分配内存、
从旧内存复制字节,再释放旧内存。
此时由调用方执行复制更高效。
new_len 必须大于零。
ret_addr 可选地提供分配调用栈的
第一个返回地址。若其值为 0,表示未提供
返回地址。
free: *const fn (*anyopaque, memory: []u8, alignment: Alignment, ret_addr: usize) void
源码
std/mem/Allocator.zig
//! 标准内存分配接口。
const Allocator = @This();
const builtin = @import("builtin");
const std = @import("../std.zig");
const assert = std.debug.assert;
const math = std.math;
const mem = std.mem;
const Alignment = std.mem.Alignment;
const Slice = std.meta.Slice;
const AbsorbSentinel = std.meta.AbsorbSentinel;
pub const Error = error{OutOfMemory};
pub const Log2Align = math.Log2Int(usize);
/// 指向分配器实现的类型擦除的指针。
///
/// 比较此字段可能导致非法行为,因为在分配器实现没有
/// 关联状态的情况下,此字段可能被设为 `undefined`。
///
ptr: *anyopaque,
vtable: *const VTable,
pub const VTable = struct {
/// 返回指向 `len` 字节、满足指定 `alignment` 的指针,或返回
/// `null` 表示分配失败。
///
/// `new_len` 必须大于零。
///
/// 可选的 `ret_addr` 表示分配调用栈中的
/// 第一个返回地址。如果值为 `0`,则表示
/// 未提供返回地址。
alloc: *const fn (*anyopaque, len: usize, alignment: Alignment, ret_addr: usize) ?[*]u8,
/// 尝试在原地扩大或缩小内存。
///
/// `memory.len` 必须等于最近一次成功
/// 调用 `alloc`、`resize` 或 `remap` 所请求的长度。`alignment` 必须
/// 等于最初调用 `alloc` 时作为 `alignment`
/// 参数传入的值。
///
/// 结果为 `true` 表示调整大小成功,
/// 分配地址不变,大小变为 `new_len`。结果为 `false`
/// 表示只有将分配移动到其他地址
/// 才能完成调整。
///
/// `new_len` 必须大于零。
///
/// 可选的 `ret_addr` 用于提供分配调用栈中的
/// 首个返回地址。值为 `0` 表示
/// 未提供返回地址。
resize: *const fn (*anyopaque, memory: []u8, alignment: Alignment, new_len: usize, ret_addr: usize) bool,
/// 尝试扩展或收缩内存,允许重定位。
///
/// `memory.len` 必须等于最近一次成功调用
/// `alloc`、`resize` 或 `remap` 时请求的长度。`alignment` 必须
/// 等于作为 `alignment` 参数传入最初
/// `alloc` 调用的值。
///
/// 返回非 `null` 值表示调整大小成功。
/// 分配可能保持原地址,也可能已重定位。不论哪种
/// 情况,分配大小现为 `new_len`。返回 `null` 表示
/// 此次调整等同于重新分配内存、
/// 从旧内存复制字节,再释放旧内存。
/// 此时由调用方执行复制更高效。
///
/// `new_len` 必须大于零。
///
/// `ret_addr` 可选地提供分配调用栈的
/// 第一个返回地址。若其值为 `0`,表示未提供
/// 返回地址。
remap: *const fn (*anyopaque, memory: []u8, alignment: Alignment, new_len: usize, ret_addr: usize) ?[*]u8,
/// 释放一段内存,并使其失效。
///
/// `memory.len` 必须等于最近一次成功调用 `alloc`、`resize` 或 `remap` 时请求的长度。
/// `alignment` 必须等于原始 `alignment` 参数的值,该参数传给最初的 `alloc` 调用。
///
/// 可选参数 `ret_addr` 提供分配调用栈的第一个返回地址。若值为 `0`,表示未提供返回地址。
///
///
///
///
free: *const fn (*anyopaque, memory: []u8, alignment: Alignment, ret_addr: usize) void,
};
pub fn noAlloc(
self: *anyopaque,
len: usize,
alignment: Alignment,
ret_addr: usize,
) ?[*]u8 {
_ = self;
_ = len;
_ = alignment;
_ = ret_addr;
return null;
}
pub fn noResize(
self: *anyopaque,
memory: []u8,
alignment: Alignment,
new_len: usize,
ret_addr: usize,
) bool {
_ = self;
_ = memory;
_ = alignment;
_ = new_len;
_ = ret_addr;
return false;
}
pub fn noRemap(
self: *anyopaque,
memory: []u8,
alignment: Alignment,
new_len: usize,
ret_addr: usize,
) ?[*]u8 {
_ = self;
_ = memory;
_ = alignment;
_ = new_len;
_ = ret_addr;
return null;
}
pub fn noFree(
self: *anyopaque,
memory: []u8,
alignment: Alignment,
ret_addr: usize,
) void {
_ = self;
_ = memory;
_ = alignment;
_ = ret_addr;
}
/// 此函数仅应从 `Allocator` 的
/// 实现内部调用。
pub inline fn rawAlloc(a: Allocator, len: usize, alignment: Alignment, ret_addr: usize) ?[*]u8 {
return a.vtable.alloc(a.ptr, len, alignment, ret_addr);
}
/// 此函数仅应从 `Allocator` 的
/// 实现内部调用。
pub inline fn rawResize(a: Allocator, memory: []u8, alignment: Alignment, new_len: usize, ret_addr: usize) bool {
return a.vtable.resize(a.ptr, memory, alignment, new_len, ret_addr);
}
/// 此函数仅应从 `Allocator` 的
/// 实现内部调用。
pub inline fn rawRemap(a: Allocator, memory: []u8, alignment: Alignment, new_len: usize, ret_addr: usize) ?[*]u8 {
return a.vtable.remap(a.ptr, memory, alignment, new_len, ret_addr);
}
/// 此函数仅应从 `Allocator` 的
/// 实现内部调用。
pub inline fn rawFree(a: Allocator, memory: []u8, alignment: Alignment, ret_addr: usize) void {
return a.vtable.free(a.ptr, memory, alignment, ret_addr);
}
/// 返回指向未定义内存的指针。
/// 使用 `destroy` 释放该内存。
pub fn create(a: Allocator, comptime T: type) Error!*T {
return a.createAdvancedWithRetAddr(T, null, @returnAddress());
}
pub fn alignedCreate(
self: Allocator,
comptime T: type,
/// null 表示自然对齐
comptime alignment: ?Alignment,
) Error!*align(if (alignment) |a| a.toByteUnits() else @alignOf(T)) T {
return self.createAdvancedWithRetAddr(T, alignment, @returnAddress());
}
pub inline fn createAdvancedWithRetAddr(
self: Allocator,
comptime T: type,
/// null 表示自然对齐
comptime alignment: ?Alignment,
return_address: usize,
) Error!*align(if (alignment) |a| a.toByteUnits() else @alignOf(T)) T {
if (@sizeOf(T) == 0) {
const ptr = comptime std.mem.alignBackward(usize, math.maxInt(usize), @alignOf(T));
return @ptrFromInt(ptr);
}
const a: Alignment = alignment orelse comptime .of(T);
const ptr: *align(a.toByteUnits()) T = @ptrCast(try self.allocBytesAligned(a, @sizeOf(T), return_address));
return ptr;
}
/// `ptr` 应为 `create` 的返回值,
/// 或具有相同地址及对齐属性。
pub fn destroy(self: Allocator, ptr: anytype) void {
const info = @typeInfo(@TypeOf(ptr)).pointer;
if (info.size != .one) @compileError("ptr must be a single item pointer");
const T = info.child;
if (@sizeOf(T) == 0) return;
const non_const_ptr = @as([*]u8, @ptrCast(@constCast(ptr)));
self.rawFree(
non_const_ptr[0..@sizeOf(T)],
.fromByteUnits(info.attrs.@"align" orelse @alignOf(T)),
@returnAddress(),
);
}
/// 分配包含 `n` 个 `T` 类型项目的数组,将全部
/// 项目设为 `undefined`。根据 Allocator
/// 实现,内存不再需要时可能必须调用 `free`,
/// 以避免资源泄漏。若
/// `Allocator` 的实现未知,正确代码
/// 应在使用结束后调用 `free`。
///
/// 分配单个项目参见 `create`。
pub fn alloc(self: Allocator, comptime T: type, n: usize) Error![]T {
return self.allocAdvancedWithRetAddr(T, null, n, @returnAddress());
}
pub fn allocWithOptions(
self: Allocator,
comptime Elem: type,
n: usize,
/// null 表示自然对齐
comptime optional_alignment: ?Alignment,
comptime optional_sentinel: ?Elem,
) Error!AllocWithOptionsPayload(Elem, optional_alignment, optional_sentinel) {
return self.allocWithOptionsRetAddr(Elem, n, optional_alignment, optional_sentinel, @returnAddress());
}
pub fn allocWithOptionsRetAddr(
self: Allocator,
comptime Elem: type,
n: usize,
/// null 表示自然对齐
comptime optional_alignment: ?Alignment,
comptime optional_sentinel: ?Elem,
return_address: usize,
) Error!AllocWithOptionsPayload(Elem, optional_alignment, optional_sentinel) {
if (optional_sentinel) |sentinel| {
const ptr = try self.allocAdvancedWithRetAddr(Elem, optional_alignment, n + 1, return_address);
ptr[n] = sentinel;
return ptr[0..n :sentinel];
} else {
return self.allocAdvancedWithRetAddr(Elem, optional_alignment, n, return_address);
}
}
fn AllocWithOptionsPayload(comptime Elem: type, comptime alignment: ?Alignment, comptime sentinel: ?Elem) type {
if (sentinel) |s| {
return [:s]align(if (alignment) |a| a.toByteUnits() else @alignOf(Elem)) Elem;
} else {
return []align(if (alignment) |a| a.toByteUnits() else @alignOf(Elem)) Elem;
}
}
/// 分配包含 `n + 1` 个 `T` 类型项目的数组,将前 `n`
/// 个项目设为 `undefined`,最后一个设为 `sentinel`。根据
/// Allocator 的实现,内存不再需要时可能必须调用 `free`,
/// 以避免资源泄漏。若
/// `Allocator` 的实现未知,正确代码
/// 应在使用结束后调用 `free`。
///
/// 分配单个项目参见 `create`。
pub fn allocSentinel(
self: Allocator,
comptime Elem: type,
n: usize,
comptime sentinel: Elem,
) Error![:sentinel]Elem {
return self.allocWithOptionsRetAddr(Elem, n, null, sentinel, @returnAddress());
}
pub fn alignedAlloc(
self: Allocator,
comptime T: type,
/// null 表示自然对齐
comptime alignment: ?Alignment,
n: usize,
) Error![]align(if (alignment) |a| a.toByteUnits() else @alignOf(T)) T {
return self.allocAdvancedWithRetAddr(T, alignment, n, @returnAddress());
}
pub inline fn allocAdvancedWithRetAddr(
self: Allocator,
comptime T: type,
/// null 表示自然对齐
comptime alignment: ?Alignment,
n: usize,
return_address: usize,
) Error![]align(if (alignment) |a| a.toByteUnits() else @alignOf(T)) T {
const a: Alignment = alignment orelse comptime .of(T);
const ptr: [*]align(a.toByteUnits()) T = @ptrCast(try self.allocWithSizeAndAlignment(@sizeOf(T), a, n, return_address));
return ptr[0..n];
}
fn allocWithSizeAndAlignment(
self: Allocator,
comptime size: usize,
comptime alignment: Alignment,
n: usize,
return_address: usize,
) Error![*]align(alignment.toByteUnits()) u8 {
const byte_count = math.mul(usize, size, n) catch return error.OutOfMemory;
return self.allocBytesAligned(alignment, byte_count, return_address);
}
pub fn allocBytesAligned(
self: Allocator,
comptime alignment: Alignment,
byte_count: usize,
return_address: usize,
) Error![*]align(alignment.toByteUnits()) u8 {
if (byte_count == 0) {
const ptr = comptime alignment.backward(math.maxInt(usize));
return @as([*]align(alignment.toByteUnits()) u8, @ptrFromInt(ptr));
}
const byte_ptr = self.rawAlloc(byte_count, alignment, return_address) orelse return error.OutOfMemory;
@memset(byte_ptr[0..byte_count], undefined);
return @alignCast(byte_ptr);
}
/// 请求修改分配大小。
///
/// 保证不移动指针,但分配器
/// 实现可以通过返回 `false` 拒绝调整请求。
///
/// `allocation` 可以为空切片,此时返回 `false`;
/// 但若 `new_len` 也为 0,则返回 `true`。
///
/// `new_len` 可以为零,此时释放该分配。
pub fn resize(self: Allocator, allocation: anytype, new_len: usize) bool {
const slice_info = @typeInfo(@TypeOf(allocation)).pointer;
const T = if (slice_info.size != .slice) comptime T: {
assert(slice_info.size == .one);
break :T @typeInfo(slice_info.child).array.child;
} else slice_info.child;
if (new_len == 0) {
self.free(allocation);
return true;
}
if (allocation.len == 0) {
return false;
}
const old_memory: []u8 = @ptrCast(@constCast(mem.absorbSentinel(allocation)));
const new_len_bytes = math.mul(usize, @sizeOf(T), new_len) catch return false;
return self.rawResize(
old_memory,
.fromByteUnits(slice_info.attrs.@"align" orelse @alignOf(T)),
new_len_bytes,
@returnAddress(),
);
}
/// 请求修改分配的大小,允许重定位。
///
/// 返回非 `null` 值表示调整大小成功。分配的地址可能保持不变,也可能已被重定位。无论哪种情况,分配的新大小均为 `new_len`。返回 `null` 表示此次调整等同于分配新内存、从旧内存复制字节,然后释放旧内存。在这种情况下,由调用方执行这些操作效率更高。
///
/// `allocation` 可以为空切片,此时返回 `null`;但若 `new_len` 同样为 0,则返回 `allocation`。
///
/// `new_len` 可以为零,此时释放该分配。
///
/// 若分配元素的类型大小为零字节,则将 `allocation.len` 设置为 `new_len`。
///
///
///
///
///
///
///
pub fn remap(self: Allocator, allocation: anytype, new_len: usize) ?Slice(AbsorbSentinel(@TypeOf(allocation))) {
const slice_info = @typeInfo(@TypeOf(allocation)).pointer;
const T = if (slice_info.size != .slice) comptime T: {
assert(slice_info.size == .one);
break :T @typeInfo(slice_info.child).array.child;
} else slice_info.child;
if (new_len == 0) {
self.free(allocation);
return allocation[0..0];
}
if (allocation.len == 0) {
return null;
}
if (@sizeOf(T) == 0) {
var new_memory = allocation;
new_memory.len = new_len;
return new_memory;
}
const old_memory: []u8 = @ptrCast(@constCast(mem.absorbSentinel(allocation)));
const new_len_bytes = math.mul(usize, @sizeOf(T), new_len) catch return null;
const new_ptr = self.rawRemap(
old_memory,
.fromByteUnits(slice_info.attrs.@"align" orelse @alignOf(T)),
new_len_bytes,
@returnAddress(),
) orelse return null;
return @ptrCast(@alignCast(new_ptr[0..new_len_bytes]));
}
/// 此函数为现有分配请求新的大小,可以比原分配更大、更小,或保持不变。
/// 结果是由 `new_n` 个元素组成的数组,元素类型与现有分配相同。
///
/// 若 `new_n` 为 0,则等同于 `free`,并且始终成功。
///
/// `old_mem` 可以为零长度,此时执行新的分配。
///
/// 与以下函数不同,此函数只会因内存不足而失败:
/// * `remap`:返回 `null`,若 `Allocator` 的实现无法比调用者自行重新分配更高效地完成操作。
/// * `resize`:返回 `false`,若 `Allocator` 的实现无法在不移动分配的情况下调整大小。
///
///
///
///
pub fn realloc(self: Allocator, old_mem: anytype, new_n: usize) Error!Slice(AbsorbSentinel(@TypeOf(old_mem))) {
return self.reallocAdvanced(old_mem, new_n, @returnAddress());
}
pub fn reallocAdvanced(
self: Allocator,
old_mem: anytype,
new_n: usize,
return_address: usize,
) Error!Slice(AbsorbSentinel(@TypeOf(old_mem))) {
const slice_info = @typeInfo(@TypeOf(old_mem)).pointer;
const T = if (slice_info.size != .slice) comptime T: {
assert(slice_info.size == .one);
break :T @typeInfo(slice_info.child).array.child;
} else slice_info.child;
if (old_mem.len == 0) {
return self.allocAdvancedWithRetAddr(T, .fromByteUnitsOptional(slice_info.attrs.@"align"), new_n, return_address);
}
if (new_n == 0) {
self.free(old_mem);
const alignment = slice_info.attrs.@"align" orelse @alignOf(T);
const addr = comptime std.mem.alignBackward(usize, math.maxInt(usize), alignment);
const ptr: *align(alignment) [0]T = @ptrFromInt(addr);
return ptr;
}
const old_byte_slice: []u8 = @ptrCast(@constCast(mem.absorbSentinel(old_mem)));
const byte_count = math.mul(usize, @sizeOf(T), new_n) catch return error.OutOfMemory;
// 注意:不能将缩小后的内存设为 undefined,因为 realloc 失败时不应修改内存
if (self.rawRemap(old_byte_slice, .fromByteUnits(slice_info.attrs.@"align" orelse @alignOf(T)), byte_count, return_address)) |p| {
return @ptrCast(@alignCast(p[0..byte_count]));
}
const new_mem = self.rawAlloc(byte_count, .fromByteUnits(slice_info.attrs.@"align" orelse @alignOf(T)), return_address) orelse
return error.OutOfMemory;
const copy_len = @min(byte_count, old_byte_slice.len);
@memcpy(new_mem[0..copy_len], old_byte_slice[0..copy_len]);
@memset(old_byte_slice, undefined);
self.rawFree(old_byte_slice, .fromByteUnits(slice_info.attrs.@"align" orelse @alignOf(T)), return_address);
return @ptrCast(@alignCast(new_mem[0..byte_count]));
}
/// 释放由 `alloc` 分配的数组。
/// 若内存长度为 0,free 为空操作。
/// 释放单个元素时,参见 `destroy`。
pub fn free(self: Allocator, memory: anytype) void {
const slice_info = @typeInfo(@TypeOf(memory)).pointer;
if (slice_info.size != .slice) {
comptime assert(slice_info.size == .one and @typeInfo(slice_info.child) == .array);
}
const bytes: []u8 = @ptrCast(@constCast(mem.absorbSentinel(memory)));
if (bytes.len == 0) return;
@memset(bytes, undefined);
self.rawFree(bytes, .fromByteUnits(slice_info.attrs.@"align" orelse @alignOf(slice_info.child)), @returnAddress());
}
/// 将 `m` 复制到新分配的内存。调用方拥有该内存。
pub fn dupe(allocator: Allocator, comptime T: type, m: []const T) Error![]T {
const new_buf = try allocator.alloc(T, m.len);
@memcpy(new_buf, m);
return new_buf;
}
/// 将 `m` 复制到新分配的内存,并添加哨兵终止元素。调用方拥有该内存。
pub fn dupeSentinel(
allocator: Allocator,
comptime T: type,
m: []const T,
comptime sentinel: T,
) Error![:sentinel]T {
const new_buf = try allocator.alloc(T, m.len + 1);
@memcpy(new_buf[0..m.len], m);
new_buf[m.len] = sentinel;
return new_buf[0..m.len :sentinel];
}
/// 分配格式化字符串,成功时返回该字符串。
///
/// 返回的切片可用 `free` 释放。若使用 arena 式分配器,
/// 例如 `std.heap.ArenaAllocator`,则无需调用
/// `free`。
///
/// 参见 `std.Io.Writer.print`。
pub fn print(a: Allocator, comptime format: []const u8, args: anytype) Error![]u8 {
var aw = try std.Io.Writer.Allocating.initCapacity(a, format.len);
defer aw.deinit();
aw.writer.print(format, args) catch |err| switch (err) {
error.WriteFailed => return error.OutOfMemory,
};
return aw.toOwnedSlice();
}
test print {
const x: i32 = -1;
const y: []const u8 = "hi";
const a = std.testing.allocator;
const s = try print(a, "{d}={s}", .{ x, y });
defer free(a, s);
try std.testing.expectEqualStrings("-1=hi", s);
}
/// 类似 `print`,但返回的切片具有指定哨兵。
///
/// 返回的切片可用 `free` 释放。如果使用 arena 风格的分配器,
/// 例如 `std.heap.ArenaAllocator`,则无需调用 `free`。
/// 如果将返回切片强制转换为不含哨兵的切片,
/// 再传给 `free`,则发生非法行为。
pub fn printSentinel(
a: Allocator,
comptime format: []const u8,
args: anytype,
comptime sentinel: u8,
) Allocator.Error![:sentinel]u8 {
var aw = try std.Io.Writer.Allocating.initCapacity(a, format.len);
defer aw.deinit();
aw.writer.print(format, args) catch |err| switch (err) {
error.WriteFailed => return error.OutOfMemory,
};
return aw.toOwnedSliceSentinel(sentinel);
}
test printSentinel {
const x: i32 = -1;
const y: []const u8 = "hi";
const a = std.testing.allocator;
const s = try printSentinel(a, "{d}={s}", .{ x, y }, 0);
defer free(a, s);
try std.testing.expectEqualStrings("-1=hi", s);
try std.testing.expectEqual(0, s[s.len]);
}
/// 始终分配失败的分配器。
pub const failing: Allocator = .{
.ptr = undefined,
.vtable = &.{
.alloc = noAlloc,
.resize = unreachableResize,
.remap = unreachableRemap,
.free = unreachableFree,
},
};
fn unreachableResize(
self: *anyopaque,
memory: []u8,
alignment: Alignment,
new_len: usize,
ret_addr: usize,
) bool {
_ = self;
_ = memory;
_ = alignment;
_ = new_len;
_ = ret_addr;
unreachable;
}
fn unreachableRemap(
self: *anyopaque,
memory: []u8,
alignment: Alignment,
new_len: usize,
ret_addr: usize,
) ?[*]u8 {
_ = self;
_ = memory;
_ = alignment;
_ = new_len;
_ = ret_addr;
unreachable;
}
fn unreachableFree(
self: *anyopaque,
memory: []u8,
alignment: Alignment,
ret_addr: usize,
) void {
_ = self;
_ = memory;
_ = alignment;
_ = ret_addr;
unreachable;
}
test failing {
const f: Allocator = .failing;
try std.testing.expectError(error.OutOfMemory, f.alloc(u8, 123));
// 预期超大分配在实现层面失败,而不是在接口层面失败。
try std.testing.expectError(error.OutOfMemory, f.alloc(u8, std.math.maxInt(usize)));
try std.testing.expectError(error.OutOfMemory, f.allocSentinel(u8, std.math.maxInt(usize) - 1, 0));
}
test "free single-pointer to array" {
const allocator = std.testing.allocator;
{
const allocation = try allocator.alloc(u32, 128);
allocation[127] = 0;
const ptr: *[127:0]u32 = allocation[0..127 :0];
allocator.free(ptr);
}
{
const allocation = try allocator.alloc(u32, 128);
allocation[127] = 0;
const ptr: *[127:0]u32 = allocation[0..127 :0];
if (allocator.resize(ptr, 16)) {
allocator.free(ptr[0..16]);
} else allocator.free(ptr);
}
{
const allocation = try allocator.alloc(u32, 128);
allocation[127] = 0;
const ptr: *[127:0]u32 = allocation[0..127 :0];
if (allocator.remap(ptr, 16)) |new| {
allocator.free(new);
} else allocator.free(ptr);
}
{
const allocation = try allocator.alloc(u32, 128);
allocation[127] = 0;
const ptr: *[127:0]u32 = allocation[0..127 :0];
if (allocator.realloc(ptr, 16)) |new| {
allocator.free(new);
} else |_| {
allocator.free(allocation);
}
}
}