# Copyable examples

Complete code for the [Flatzz README](../README.md). The examples use Zig 0.17.0
and the actual `Rocket` module generated from the schema below.

## 1. Serialize and read back

[README](../README.md#1-serialize-and-read-back) ·
[Runnable source and tests](../example/readme/main.zig)

`serialize(allocator, .{})` returns an owner. `std.testing.allocator` detects leaked
storage when this test runs; `deinit` releases it after all borrowed views are finished.

```zig
test "1. serialize and read back" {
    const allocator = std.testing.allocator;
    const rocket: Rocket = .{
        .id = 7,
        .fuel = 80,
        .pilot = "Ziguana",
        .payload = &.{ 1, 2, 3 },
    };
    const result = try rocket.serialize(allocator, .{});
    defer result.deinit(allocator);

    try Rocket.verify(result.bytes, .{});
    const view = try Rocket.read(result.bytes);
    try std.testing.expectEqual(@as(u32, 7), view.id);
    try std.testing.expectEqual(@as(f32, 80), view.fuel);
    try std.testing.expectEqualStrings("Ziguana", view.pilot.?);
    try std.testing.expectEqual(@as(u8, 1), try view.payload.?.get(0));
}
```

## 2. Use caller-owned storage

[View illustration](../README.md#2-use-caller-owned-storage) ·
[Runnable source and tests](../example/readme/main.zig)

No allocator is passed to this path. The returned frame borrows a suffix of the
usable storage. `capacityFor` derives a conservative bound from the complete
native value at comptime; it is not the frame length. The pointer checks show
that the string is borrowed from the frame. Scalars are decoded by value, and
vector elements are read lazily with `get`.

```zig
test "2. use caller-owned storage" {
    const rocket: Rocket = .{
        .id = 7,
        .fuel = 80,
        .pilot = "Ziguana",
        .payload = &.{ 1, 2, 3 },
    };
    const capacity = comptime flatzz.storage.capacityFor(Rocket.Schema, rocket, .{});
    var storage: [capacity]u8 align(flatzz.storage_alignment) = undefined;
    const bytes = try rocket.serialize(&storage, .{});

    try Rocket.verify(bytes, .{});
    const view = try Rocket.read(bytes);
    try std.testing.expectEqualStrings("Ziguana", view.pilot.?);
    try std.testing.expectEqual(@as(f32, 80), view.fuel);
    try std.testing.expectEqual(@as(u8, 3), try view.payload.?.get(2));

    const pilot_start = @intFromPtr(view.pilot.?.ptr);
    const frame_start = @intFromPtr(bytes.ptr);
    try std.testing.expect(pilot_start >= frame_start);
    try std.testing.expect(pilot_start + view.pilot.?.len <= frame_start + bytes.len);
}
```

## 3. From FBS to generated Zig

[View illustration](../README.md#3-from-fbs-to-generated-zig) ·
[Schema file](../example/readme/rocket.fbs)

The illustration abbreviates the generated declarations. This is the full schema:

```fbs
table Rocket {
  id:uint;
  fuel:float = 100;
  pilot:string;
  payload:[ubyte];
}
root_type Rocket;
```

The compiler produces the following complete module. Build-time generation is the
source of truth; the application uses its native fields and schema operations.

```zig
// Generated by flatzz --zig. Do not edit.
// Wire IDs and layouts come from reflection metadata, never the native ABI.
// Strings and views borrow their buffer; builders use caller-owned storage.
const runtime = @import("flatzz");
const types = @This();
pub const Rocket = struct {
    id: u32 = fields.id.default,
    fuel: f32 = fields.fuel.default,
    pilot: ?[]const u8 = null,
    payload: ?[]const u8 = null,
    pub const fields = .{
        .id = runtime.ScalarField(u32, 0, 0),
        .fuel = runtime.ScalarField(f32, 1, @bitCast(@as(u32, 1120403456))),
        .pilot = runtime.ReferenceField(2, .string, .{}),
        .payload = runtime.ReferenceField(3, .{
            .vector = runtime.ScalarCodec(u8),
        }, .{}),
    };
    pub const Schema = runtime.Schema(@This(), fields);
    pub const Field = Schema.Field;
    pub const View = Schema.View;
    pub const serialize = Schema.serialize;
    pub const read = Schema.read;
    pub const update = Schema.update;
    pub const borrowMutable = Schema.borrowMutable;
    pub const verify = Schema.verify;
    pub const WriteOptions = runtime.WriteOptions;
};
```

The `fuel` descriptor preserves the FBS default `100` as its exact `f32` bit
pattern. `id` is an external schema field name. The generated wire metadata,
not native Zig struct layout, defines the FlatBuffer representation.

## 4. Read and edit existing bytes

[README](../README.md#4-read-and-edit-existing-bytes) ·
[Runnable source and tests](../example/readme/main.zig)

This example creates a frame to stand in for received bytes. Verify untrusted
input before using schema views; keep it unchanged during verification. `read`
alone performs local access checks and is not a substitute for `verify`.

The scalar in `before` remains `80` after mutation, while its borrowed pilot
string observes the new seven-byte name. An unequal-length replacement fails
without changing the field.

```zig
test "4. read and edit existing bytes" {
    const rocket: Rocket = .{
        .id = 7,
        .fuel = 80,
        .pilot = "Ziguana",
        .payload = &.{ 1, 2, 3 },
    };
    const capacity = comptime flatzz.storage.capacityFor(Rocket.Schema, rocket, .{});
    var storage: [capacity]u8 align(flatzz.storage_alignment) = undefined;
    const bytes = try rocket.serialize(&storage, .{});
    try Rocket.verify(bytes, .{});
    const before = try Rocket.read(bytes);

    try std.testing.expect(try Rocket.update(bytes, .fuel, 79));
    try std.testing.expect(try Rocket.update(bytes, .pilot, "Pilot01"));
    try Rocket.verify(bytes, .{});
    const after = try Rocket.read(bytes);

    try std.testing.expectEqual(@as(f32, 80), before.fuel);
    try std.testing.expectEqual(@as(f32, 79), after.fuel);
    try std.testing.expectEqualStrings("Pilot01", after.pilot.?);
    try std.testing.expectEqualStrings("Pilot01", before.pilot.?);
    try std.testing.expectError(error.LengthMismatch, Rocket.update(bytes, .pilot, "short"));
    try std.testing.expectEqualStrings("Pilot01", (try Rocket.read(bytes)).pilot.?);
}
```

For nested struct mutation, see `Reading.borrowMutable(bytes, .location)` in the
[generated Reading example](../example/generated/main.zig). `borrowMutable` is
for structured fields, not scalar or string replacement. Mutable vector views
preserve their element codec's access rules; scalar elements remain copied values.

## Complete runner

[Source](../example/readme/main.zig) · [Schema](../example/readme/rocket.fbs)

The build imports `flatzz` and the generated `rocket` module. This complete
program allocates a frame, prints its fields, then uses fixed storage for a
receive/read/edit/print flow. The receive step uses locally serialized bytes;
there is no networking or mapping hidden in the example.

```zig
//! Generate Rocket from rocket.fbs, serialize it, and edit existing bytes.
//! Run with `zig build run-readme`; `zig build test` checks the copyable examples.

const std = @import("std");
const flatzz = @import("flatzz");
const generated = @import("rocket");

const Rocket = generated.Rocket;

/// Print a borrowed view while its backing storage is still alive.
fn printRocket(output: *std.Io.Writer, label: []const u8, view: Rocket.View) !void {
    const pilot = view.pilot orelse return error.MissingPilot;
    const payload = view.payload orelse return error.MissingPayload;
    try output.print("{s}: id={d}, fuel={d}, pilot={s}, payload[0]={d}\n", .{
        label, view.id, view.fuel, pilot, try payload.get(0),
    });
}

/// Create an owned frame, then receive and edit a separate caller-owned frame.
pub fn main(init: std.process.Init) !void {
    const rocket: Rocket = .{
        .id = 7,
        .fuel = 80,
        .pilot = "Ziguana",
        .payload = &.{ 1, 2, 3 },
    };
    var output: std.Io.Writer.Allocating = .init(init.gpa);
    defer output.deinit();

    const result = try rocket.serialize(init.gpa, .{});
    defer result.deinit(init.gpa);
    try Rocket.verify(result.bytes, .{});
    try printRocket(&output.writer, "allocated", try Rocket.read(result.bytes));

    const capacity = comptime flatzz.storage.capacityFor(Rocket.Schema, rocket, .{});
    var storage: [capacity]u8 align(flatzz.storage_alignment) = undefined;
    const bytes = try rocket.serialize(&storage, .{});
    try Rocket.verify(bytes, .{});
    try printRocket(&output.writer, "received", try Rocket.read(bytes));
    if (!try Rocket.update(bytes, .fuel, 79)) return error.MissingFuel;
    if (!try Rocket.update(bytes, .pilot, "Pilot01")) return error.MissingPilot;
    try Rocket.verify(bytes, .{});
    try printRocket(&output.writer, "edited", try Rocket.read(bytes));
    try std.Io.File.stdout().writeStreamingAll(init.io, output.written());
}
```
