解答18: 標準ライブラリ

概要

Zigの豊富な標準ライブラリを活用して、ファイル処理、JSON設定管理、ロギングシステム、テキスト処理ツールの実装について学びます。

解答のポイント

1. std.fs

// ファイルの読み書き
const file = try std.fs.cwd().openFile("path.txt", .{});
defer file.close();

const content = try file.readToEndAlloc(allocator, 1024 * 1024);
defer allocator.free(content);

2. std.json

// JSONのパース
const parsed = try std.json.parseFromSlice(
    AppConfig,
    allocator,
    json_str,
    .{}
);
defer parsed.deinit();

// JSON文字列化
var buf = std.ArrayList(u8).init(allocator);
defer buf.deinit();
try std.json.stringify(config, .{}, buf.writer());

3. std.log

// ロギング
std.log.info("Application started", .{});
std.log.err("Failed: {s}", .{err});

4. std.mem

// 文字列操作
const index = std.mem.indexOf(u8, text, "pattern");
const split = std.mem.split(u8, text, "\n");

実装例: ファイル処理

pub fn readFileContent(
    allocator: std.mem.Allocator,
    path: []const u8
) ![]u8 {
    const file = try std.fs.cwd().openFile(path, .{});
    defer file.close();
    
    return try file.readToEndAlloc(allocator, 10 * 1024 * 1024);
}

pub fn writeFileContent(path: []const u8, content: []const u8) !void {
    const file = try std.fs.cwd().createFile(path, .{});
    defer file.close();
    
    try file.writeAll(content);
}

よくある間違い

ファイルクローズの忘れ

// 間違い
const file = try std.fs.cwd().openFile("path", .{});
// closeを忘れている

// 正しい
const file = try std.fs.cwd().openFile("path", .{});
defer file.close();

アロケータの不一致

// 間違い
const data = try allocator1.alloc(u8, 100);
allocator2.free(data);  // 違うアロケータ!

// 正しい
const data = try allocator1.alloc(u8, 100);
allocator1.free(data);

発展課題

  • HTTPサーバーの実装
  • マークダウンパーサー
  • データベースクライアント
  • コマンドラインパーサー
  • 圧縮/解凍ツール

まとめ

Zigの標準ライブラリは、実用的なアプリケーション開発に必要な機能を提供します。シンプルで一貫性のあるAPIが特徴です。