~ knotless Search/
↑↓ move↵ open⇧↵ all results

zat.dev/zat

atproto utils for zig · mirror of https://tangled.org/zat.dev/zat

0
0
55 lines · 2.3 KB Raw History
//! write a STAR archive, read it back, and see a truncated one refused.
//!
//! run: zig build example-write-a-star-archive

const std = @import("std");
const zat = @import("zat");

pub fn main(init: std.process.Init) !void {
    const allocator = init.gpa;

    // a STAR archive is a metadata map, then key/value pairs, then an end byte
    var out: std.Io.Writer.Allocating = .init(allocator);
    defer out.deinit();
    const metadata: zat.cbor.Value = .{ .map = &.{
        .{ .key = "$type", .value = .{ .text = "com.example.greetings" } },
    } };
    // ordered_keys refuses a key that doesn't sort after the one before it,
    // which repository archives require
    const options: zat.star.Writer.Options = .{ .ordered_keys = true };
    var writer = try zat.star.Writer.init(allocator, &out.writer, metadata, options);
    defer writer.deinit();
    try writer.writePair("greeting/en", "hello");
    try writer.writePair("greeting/es", "hola");
    try writer.writePair("greeting/fr", "bonjour");
    try writer.finish(); // writes the end byte
    const archive = out.written();
    std.debug.print("wrote {d} bytes\n", .{archive.len});

    // read it back: the metadata first, then each pair in order
    var input: std.Io.Reader = .fixed(archive);
    var reader = try zat.star.Reader.init(allocator, &input, .{});
    defer reader.deinit();
    std.debug.print("$type: {s}\n", .{reader.metadata.getString("$type").?});
    var value: [64]u8 = undefined;
    while (try reader.next()) |entry| {
        if (entry.value_len > value.len) return error.ValueTooLong;
        const n = try reader.readValue(value[0..@intCast(entry.value_len)]);
        std.debug.print("{s} = {s}\n", .{ entry.key, value[0..n] });
    }

    // drop the last byte: the archive is now cut off, and reading it fails
    // instead of quietly returning fewer pairs
    var cut: std.Io.Reader = .fixed(archive[0 .. archive.len - 1]);
    var truncated = try zat.star.Reader.init(allocator, &cut, .{});
    defer truncated.deinit();
    var pairs: usize = 0;
    while (truncated.next() catch |err| {
        std.debug.print("truncated archive: error.{t} after {d} pairs\n", .{ err, pairs });
        return;
    }) |entry| {
        _ = try truncated.readValue(value[0..@intCast(entry.value_len)]);
        pairs += 1;
    }
    return error.TruncationNotDetected;
}