Learning Zig from the official language reference.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

42 lines
1.8 KiB

const std = @import("std");
const mem = std.mem;
const Allocator = mem.Allocator;
const testing = std.testing;
// Choosing an allocator:
// 1. For libraries, accept a *Allocator parameter, and allow the clients to chooise their preferred allocator.
// 2. If using/linking libc, probably choose std.heap.c_allocator.
// 3. If the upper bound of the amount of memory needed is known at comptime, prefer a std.heap.FixedBufferAllocator or the
// std.heap.ThreadSafeFixedBufferAllocator.
// 4. If memory needs to be allocated upfront and then released all in one go, prefer std.heap.ArenaAllocator with the std.heap.page_allocator.
// 5. If same as above, but there is a cyclical pattern of usage, use the std.heap.ArenaAllocator.
// 6. For tests which need to ensure that OOM is handled correctly, , use std.testing.FailingAllocator.
// 7. For general tests, use std.testing.allocator.
// 8. Finally, use the std.heap.GeneralPurposeAllocator.
// 9. If needed, use the Allocator interface to create a custom allocator.
test "FixedBufferAllocator" {
var buffer: [100]u8 = undefined; // stack memory, so free is not needed
const allocator = &std.heap.FixedBufferAllocator.init(&buffer).allocator;
const result = try concat(allocator, "foo", "bar");
testing.expect(mem.eql(u8, result, "foobar"));
fn concat(allocator: *Allocator, first: []const u8, second: []const u8) ![]u8 {
const result = try allocator.alloc(u8, first.len + second.len);
mem.copy(u8, result, first);
mem.copy(u8, result[first.len..], second);
return result;
test "ArenaAllocator with page_allocator" {
var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator);
defer arena.deinit();
const allocator = &arena.allocator;
const ptr = try allocator.create(i32);
ptr.* = 42;
testing.expectEqual(ptr.*, 42);
testing.expectEqual(@TypeOf(ptr), *i32);