1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
//! 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;
}