weave.lp

The structure of this file is quite similar to that of tangle.zig, only differing in terms of which functions are used to transform the input data.

*:

(License)

(Imports)

pub fn main() !u8 {
    (IO initialization)

    (Allocator initialization)

    (Read file from stdin)

    (Split into lines)

    (Generate text)

    (Write to stdout)

    return 0;
}

License:

// Copyright 2022 DistressNetwork┬░ <uplink@distress.network>
// This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not distributed with this file, You can obtain one at https://mozilla.org/MPL/2.0/.

First we import the other files containing the core functions.

Imports:

const std = @import("std");
const data = @import("data.zig");
const log = @import("log.zig").log;

const Allocator = std.mem.Allocator;

Within the main procedure, we first initialize the stdin and stdout interfaces.

IO initialization:

const stdin = std.io.getStdIn();
const stdout = std.io.getStdOut();

We then initialize the allocator, deferring its deinitialization to the end of the process. Since the overall memory usage pattern is one in which all resources may be freed at once, the arena allocator is the most appropriate choice for this program.

Allocator initialization:

var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator);
var alloc = arena.allocator();
defer arena.deinit();

The input file is then read from stdin. In the case of input exceeding the maximum permitted file size, the program may report the error and exit normally. All other errors which may be returned are memory allocation failures and should thus yield control to the panic handler.

Read file from stdin:

const input = stdin.reader().readAllAlloc(alloc, data.input_max) catch |err| switch (err) {
    error.StreamTooLong => {
        log(.err, "input too large (maximum {})", .{std.fmt.fmtIntSizeBin(data.input_max)});
        return 1;
    },
    else => |e| return e,
};

We then pass the input into the line splitting function, creating an array of strings.

Split into lines:

const lines = try data.split_lines(input, alloc);

The text file is then generated. This entails searching for the configuration declarations, which may fail and thus return an error. Logging such errors is handled by the function itself, and thus the errors are handled here solely by exiting.

Generate text:

const text = data.textgen(lines, alloc) catch |err| switch (err) {
    error.NotFound => {
        return 1;
    },
    else => |e| return e,
};

Finally, the lines of the text file are written to stdout, separated by newlines.

Write to stdout:

for (text) |line| {
    try stdout.writer().print("{s}\n", .{line});
}