An arena allocator gives its allocations a shared lifetime: recipe and ingredient strings can remain valid for as long as their recipe book object. section 5.3.2
Listing 5.4 Giving the recipe book blank pages to fill
const std = @import("std");
const Allocator = std.mem.Allocator;
const RecipeId = enum (c_int) { _ };
const RecipeBook = struct {
const Recipe = struct {
name: [:0]const u8,
author: [:0]const u8,
instructions: [:0]const u8,
};
const Ingredient = struct {
recipe_id: RecipeId,
quantity: [:0]const u8,
name: [:0]const u8,
};
string_arena: std.heap.ArenaAllocator,
recipes: std.AutoHashMapUnmanaged(RecipeId, Recipe),
ingredients: std.ArrayList(Ingredient),
fn init(ally: Allocator) RecipeBook { #1
return .{
.string_arena = .init(ally),
.recipes = .empty,
.ingredients = .empty,
};
}
fn deinit(self: *RecipeBook, ally: Allocator) void { #2
self.string_arena.deinit(); #3
self.recipes.deinit(ally); #3
self.ingredients.deinit(ally); #3
}
};
The recipe book structure pairs a string arena with its recipe and ingredient data. section 5.3.2








