zig-alloc - 課題

概要

Zigのアロケータシステムを理解し、カスタムアロケータを実装する課題です。

マンダトリーパート

必須要件

  • 固定バッファアロケータの実装
- 事前に確保したバッファからメモリを割り当てる - allocfreeresize を実装

  • アリーナアロケータの実装
- 連続したメモリブロックを管理 - 一括解放のみをサポート

  • ログ付きアロケータラッパーの実装
- 既存のアロケータをラップ - 全てのアロケーション操作をログ出力

インターフェース

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 は使用不可