Packages

TOON (Token-Oriented Object Notation) encoder/decoder - a compact, token-efficient format for LLM input

Current section

Files

Jump to
toon_codec src toon_codec@encode@writer.erl
Raw

src/toon_codec@encode@writer.erl

-module(toon_codec@encode@writer).
-compile([no_auto_import, nowarn_unused_vars, nowarn_unused_function, nowarn_nomatch, inline]).
-define(FILEPATH, "src/toon_codec/encode/writer.gleam").
-export([new/1, push/3, to_string/1, is_empty/1, line_count/1]).
-export_type([writer/0]).
-if(?OTP_RELEASE >= 27).
-define(MODULEDOC(Str), -moduledoc(Str)).
-define(DOC(Str), -doc(Str)).
-else.
-define(MODULEDOC(Str), -compile([])).
-define(DOC(Str), -compile([])).
-endif.
?MODULEDOC(
" Line writer for building TOON output with proper indentation.\n"
"\n"
" This internal module provides an opaque Writer type that accumulates\n"
" lines with automatic indentation formatting.\n"
" Opaque type for building lines with indentation.\n"
" Create a new writer with the specified indentation size.\n"
"\n"
" ## Examples\n"
"\n"
" ```gleam\n"
" let writer = new(2)\n"
" ```\n"
" Add a line at the specified depth.\n"
"\n"
" The depth is multiplied by indent_size to calculate the indentation.\n"
"\n"
" ## Examples\n"
"\n"
" ```gleam\n"
" let writer = new(2)\n"
" let writer = push(writer, 0, \"name: Alice\")\n"
" let writer = push(writer, 1, \"id: 123\")\n"
" ```\n"
" Convert the writer to a final string output.\n"
"\n"
" Lines are reversed (since they were accumulated in reverse order)\n"
" and joined with newlines. No trailing newline is added.\n"
"\n"
" ## Examples\n"
"\n"
" ```gleam\n"
" let writer = new(2)\n"
" let writer = push(writer, 0, \"name: Alice\")\n"
" let writer = push(writer, 1, \"id: 123\")\n"
" to_string(writer)\n"
" // -> \"name: Alice\\n id: 123\"\n"
" ```\n"
" Check if the writer is empty (has no lines).\n"
" Get the number of lines in the writer.\n"
).
-opaque writer() :: {writer, integer(), list(binary())}.
-file("src/toon_codec/encode/writer.gleam", 52).
-spec new(integer()) -> writer().
new(Indent_size) ->
{writer, Indent_size, []}.
-file("src/toon_codec/encode/writer.gleam", 56).
-spec push(writer(), integer(), binary()) -> writer().
push(Writer, Depth, Line) ->
Indent = gleam@string:repeat(
<<" "/utf8>>,
Depth * erlang:element(2, Writer)
),
Formatted_line = <<Indent/binary, Line/binary>>,
{writer,
erlang:element(2, Writer),
[Formatted_line | erlang:element(3, Writer)]}.
-file("src/toon_codec/encode/writer.gleam", 62).
-spec to_string(writer()) -> binary().
to_string(Writer) ->
_pipe = erlang:element(3, Writer),
_pipe@1 = lists:reverse(_pipe),
gleam@string:join(_pipe@1, <<"\n"/utf8>>).
-file("src/toon_codec/encode/writer.gleam", 68).
-spec is_empty(writer()) -> boolean().
is_empty(Writer) ->
gleam@list:is_empty(erlang:element(3, Writer)).
-file("src/toon_codec/encode/writer.gleam", 72).
-spec line_count(writer()) -> integer().
line_count(Writer) ->
erlang:length(erlang:element(3, Writer)).