zig-alloc - 課題
概要
Zigのアロケータシステムを理解し、カスタムアロケータを実装する課題です。
マンダトリーパート
必須要件
- 固定バッファアロケータの実装
alloc、free、resize を実装- アリーナアロケータの実装
- ログ付きアロケータラッパーの実装
インターフェース
const std = @import("std");
pub const FixedBufferAllocator = struct {
buffer: []u8,
end_index: usize,
pub fn init(buffer: []u8) FixedBufferAllocator {
// 実装
}
pub fn allocator(self: *FixedBufferAllocator) std.mem.Allocator {
// 実装
}
};
pub const ArenaAllocator = struct {
child_allocator: std.mem.Allocator,
// ...
pub fn init(child_allocator: std.mem.Allocator) ArenaAllocator {
// 実装
}
pub fn deinit(self: *ArenaAllocator) void {
// 実装
}
pub fn allocator(self: *ArenaAllocator) std.mem.Allocator {
// 実装
}
};
使用例
var buffer: [1024]u8 = undefined;
var fba = FixedBufferAllocator.init(&buffer);
const allocator = fba.allocator();
const slice = try allocator.alloc(u8, 100);
defer allocator.free(slice);
ボーナスパート
ボーナス1: プールアロケータ
- 固定サイズのオブジェクト用アロケータ
- O(1)のalloc/free
ボーナス2: スレッドセーフアロケータ
- mutexを使用したスレッドセーフなラッパー
ボーナス3: メモリ使用統計
- ピークメモリ使用量の追跡
- アロケーション回数のカウント
src/allocators.zig- アロケータ実装src/main.zig- デモプログラムbuild.zig- ビルド設定README.md- 使用方法- 標準ライブラリの
std.heapは使用可能 - サードパーティライブラリは使用不可
@cImportは使用不可