Skip to content

Instantly share code, notes, and snippets.

@mikdusan
Created November 6, 2019 20:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mikdusan/9a99082dced5f014f390e22e3d134d7c to your computer and use it in GitHub Desktop.
Save mikdusan/9a99082dced5f014f390e22e3d134d7c to your computer and use it in GitHub Desktop.
const std = @import("std");
pub fn main() !void {
var arena_object = std.heap.ArenaAllocator.init(std.heap.direct_allocator);
defer arena_object.deinit();
const arena = &arena_object.allocator;
std.debug.warn("Please enter a new title to add in the library:\n");
var buf = try std.Buffer.initSize(arena, 0);
const title = try std.io.readLine(&buf);
if (title.len >= 3) {
std.debug.warn("'{}' has been successfully added to the library.\n", title);
} else {
std.debug.warn("That title is too short.\n");
}
try buf.appendByte('\n');
const file = try std.fs.File.openWrite("books.txt");
defer file.close();
try file.write(buf.toSliceConst());
}
@mikdusan
Copy link
Author

mikdusan commented Nov 6, 2019

added comments

const std = @import("std");
  
pub fn main() !void {
    // stack variable for an arena allocator
    // this holds the arena state
    var arena_object = std.heap.ArenaAllocator.init(std.heap.direct_allocator);
    // any arena allocations are free'd at end of lexical scope (main fn)
    defer arena_object.deinit();
    // get a convenient pointer to the allocator _interface_
    const arena = &arena_object.allocator;

    // stack variable for a dynamic buffer using arena allocator
    // initialize to 0 length (empty string)
    // reminder: buf or any slices of buf are only good as long as arena lives
    var buf = try std.Buffer.initSize(arena, 0);
    std.debug.warn("Please enter a new title to add in the library:\n");
    // std io has a nice fn to read up to end-of-line and append to buf
    const title = try std.io.readLine(&buf);
    if (title.len >= 3) {
        std.debug.warn("'{}' has been successfully added to the library.\n", title);
    } else {
        std.debug.warn("That title is too short.\n");
    }

    // title is a slice so we cannot append to it
    // instead append to buf a single byte but it also supports many other ways to append
    try buf.appendByte('\n');
    const file = try std.fs.File.openWrite("books.txt");
    defer file.close();
    // now that buf has grown we can easily grab a slice of it
    // use the const variant of toSlice() slice because we're good citizens
    try file.write(buf.toSliceConst());
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment