Skip to content
المشاريع

حول

Spec-first Rust port of TOON (a token-efficient data format): deterministic JSON<->TOON conversion with strict validation and streaming support

أدوات التطوير

كيف تُقاس هذه الأرقام

ما يمكنك فعله

  • Spec-first parity - Matches the reference behavior, not a re-interpretation
  • Streaming decode - Process large TOON inputs without full buffering
  • Deterministic output - Stable diffs, reproducible pipelines
  • Token efficiency - Delimiters + key folding to minimize tokens

النمو المقاس للنجوم

خلال 24 ساعة
جارٍ جمع السجل
خلال 7 أيام
جارٍ جمع السجل
خلال 15 يومًا
جارٍ جمع السجل
خلال شهر
جارٍ جمع السجل

تغيّر صافي النجوم خلال فترات متداخلة، وليس مجموعًا يوميًا. تبقى القياسات المفقودة فارغة. النجوم تقيس الاهتمام لا جودة البرمجيات.

README.md

الأصل

toon - TOON Rust

toon - TOON Rust: Spec-first Rust port of the TOON reference implementation

License: MIT Rust TOON Spec

Spec-first Rust port of TOON with deterministic output, strict validation, and token-efficiency options.

Credit: This is a Rust port of the original TOON TypeScript implementation by the toon-format team. The format specification is maintained at toon-format/spec.

Quick Install

curl -fsSL "https://raw.githubusercontent.com/Dicklesworthstone/toon_rust/main/install.sh?$(date +%s)" | bash

The installer verifies each archive's SHA256 checksum. Install minisign to verify release authenticity, or pass --require-minisign to require it:

curl -fsSL https://raw.githubusercontent.com/Dicklesworthstone/toon_rust/main/install.sh \
  | bash -s -- --version 0.3.0 --require-minisign

Use --dest DIR for an isolated installation. Download scratch and any previous binary are retained so a failed download or verification can be inspected.

Or build from source:

cargo install --git https://github.com/Dicklesworthstone/toon_rust

Works on Linux, macOS, and Windows.


TL;DR

The Problem

The official TOON implementation is TypeScript/JavaScript. If you want a small, fast, native binary that runs without Node and supports streaming and strict validation, you need a Rust port that matches the spec exactly.

The Solution

toon is a spec-first Rust implementation with streaming decode, deterministic output, and TOON-specific optimizations (delimiters, key folding, path expansion).

Why Use toon?

Feature Why it matters
Spec-first parity Matches the reference behavior, not a re-interpretation
Streaming decode Process large TOON inputs without full buffering
Deterministic output Stable diffs, reproducible pipelines
Token efficiency Delimiters + key folding to minimize tokens
Native binary No runtime dependency on Node

What is TOON?

TOON (Token-Optimized Object Notation) is a human-readable data serialization format designed specifically for LLM token efficiency. Where JSON uses braces, brackets, quotes, and colons liberally, TOON uses indentation and contextual structure to convey the same information with significantly fewer tokens.

The Token Problem

When working with LLMs, every token counts:

  • Cost: API pricing is per-token
  • Context window: More data = less room for conversation
  • Latency: Fewer tokens = faster responses

JSON is notoriously token-inefficient. A simple object like {"name": "Alice", "age": 30} requires quotes around every key, colons, commas, and braces. TOON represents the same data as:

name: Alice
age: 30

TOON Format at a Glance

# Primitives - just the value
Hello World
42
true
null

# Objects - indented key-value pairs
user:
  id: 1
  name: Alice
  email: [email protected]

# Arrays - count in brackets, items indented with dash
tags[3]: red,green,blue

# Tabular arrays - header declares fields, rows are CSV-like
users[3]{id,name,active}:
  1,Alice,true
  2,Bob,false
  3,Carol,true

# Key folding (--key-folding safe) - chains of single-key objects collapse
config.database:
  host: localhost
  port: 5432

Token Savings in Practice

Data Type JSON Tokens TOON Tokens Savings
Simple object (5 fields) ~25 ~15 40%
Array of 10 strings ~35 ~15 57%
Tabular data (100 rows, 5 cols) ~1500 ~600 60%
Nested config (3 levels) ~80 ~40 50%

The savings compound with data size. A 100KB JSON API response might compress to 40KB in TOON, saving thousands of tokens per request.


Quick Example

CLI Usage

# Encode JSON to TOON
echo '{"users":[{"id":1,"name":"Alice"},{"id":2,"name":"Bob"}]}' | toon --encode

# Output:
# users[2]{id,name}:
#   1,Alice
#   2,Bob

# Decode TOON back to JSON
echo 'users[2]{id,name}:
  1,Alice
  2,Bob' | toon --decode

# Output (2-space JSON by default; --json-indent 0 prints compact JSON):
# {
#   "users": [
#     {
#       "id": 1,
#       "name": "Alice"
#     },
#     {
#       "id": 2,
#       "name": "Bob"
#     }
#   ]
# }

# File-based with auto-detection
toon data.json -o data.toon    # .json -> encode
toon data.toon -o data.json    # .toon -> decode

# Show token estimates (stderr, after an empty line; either direction)
echo '{"users":[{"id":1,"name":"Alice","role":"admin"},{"id":2,"name":"Bob","role":"user"},{"id":3,"name":"Carol","role":"user"}]}' | toon --encode --stats
# users[3]{id,name,role}:
#   1,Alice,admin
#   2,Bob,user
#   3,Carol,user
#
# Token estimates: ~31 (JSON) → ~14 (TOON)
# Saved ~17 tokens (-54.8%)

Library Usage

For a zero-dependency library build over toon::JsonValue (no clap, no serde_json), disable default features:

[dependencies]
toon = { package = "tru", version = "0.3.0", default-features = false, features = ["lib"] }

The core also exposes toon_to_json, json_stringify, and write_json. They format the native value directly, preserving object-entry order without rebuilding a serde value tree. Use json_stringify(&value, indent) for a complete string, or write_json(&value, indent, writer) to emit borrowed data to any std::io::Write, including trait objects:

fn main() -> Result<(), Box<dyn std::error::Error>> {
    let value = toon::try_decode("count: 1\nready: true", None)?;
    assert_eq!(toon::json_stringify(&value, 0), r#"{"count":1,"ready":true}"#);

    let mut output = Vec::new();
    toon::write_json(&value, 2, &mut output)?;
    assert_eq!(toon::toon_to_json("count: 1")?, r#"{"count":1}"#);
    Ok(())
}

Indent zero selects compact JSON; positive values select spaces per level. The formatter adds no final newline and leaves flushing to the caller. The direct writer stops at the original I/O error and avoids collecting a complete output string. CLI, library, and WASM output share JSON escaping and JavaScript-compatible number text: 1.0 becomes 1, negative zero becomes 0, and exponent thresholds follow the existing CLI formatter.

For documents that should not be retained in memory, the same dependency-free build also provides write_json_from_toon(reader, options, json_indent, writer) and write_json_from_events(events, json_indent, writer). The first connects any BufRead input directly to a JSON writer; the second accepts fallible structural events. Both retain only the current line/event and open-container state. They preserve repeated object members and leave output flushing to the caller; the streaming examples below explain error handling.

To also enable serde_json::Value conversions and JSON-text input through json_to_toon without pulling in the CLI (clap), enable serde:

[dependencies]
toon = { package = "tru", version = "0.3.0", default-features = false, features = ["serde"] }
use toon::{encode, decode};
use toon::options::{EncodeOptions, KeyFoldingMode};

fn main() {
    // Simple encode
    let json: serde_json::Value = serde_json::json!({
        "user": {"id": 1, "name": "Ada"},
        "tags": ["rust", "toon"]
    });
    let toon = encode(json.clone(), None);
    println!("{toon}");

    // Encode with options
    let options = EncodeOptions {
        key_folding: Some(KeyFoldingMode::Safe),
        flatten_depth: Some(4),
        ..Default::default()
    };
    let folded = encode(json, Some(options));

    // Decode back to JsonValue
    let decoded = decode(&toon, None);
}

Performance

toon is designed for speed. The Rust implementation significantly outperforms the Node.js reference.

Encode Benchmarks (hyperfine, 10 runs)

Input Size Node.js (toon) Rust (toon) Speedup
336 B 82 ms 3 ms 27x faster
144 KB (1.5K rows) 92 ms 11 ms 8x faster
784 KB (5K rows) 105 ms 24 ms 4x faster

Decode Benchmarks

Input Size Node.js (toon) Rust (toon) Speedup
379 KB TOON 519 ms 59 ms 9x faster

Resource Comparison

Metric Node.js (toon) Rust (toon) Improvement
Startup time 66 ms 1.1 ms 60x faster
Memory (784KB encode) 68 MB 8 MB 8x less
Binary size 608 KB + Node runtime 681 KB standalone No runtime needed

Token Compression

Input Size JSON TOON Reduction
336 B 336 B 191 B 43% smaller
144 KB 144 KB 67 KB 53% smaller
784 KB 784 KB 379 KB 52% smaller

Why So Fast?

  1. Zero-copy parsing where possible
  2. Pre-allocated buffers based on input size estimation
  3. Reference-based key tracking (no string cloning in hot paths)
  4. Direct string building instead of format macros
  5. Streaming architecture - process line-by-line without buffering entire input

Design Philosophy

  1. Spec-first: The spec doc is the source of truth, not translations.
  2. Streaming by default: Encode and decode are designed for large inputs.
  3. Deterministic output: Identical inputs produce identical TOON.
  4. Minimal dependencies: Keep binaries small and fast.

Comparison

Tool Runtime Streaming Spec fidelity Notes
toon (this repo) Native Yes Target: full parity Rust port of reference
toon (reference, TS) Node Yes Yes Canonical behavior
jq + custom format Native Partial No Not TOON-compatible

Installation

One-liner install script

curl -fsSL "https://raw.githubusercontent.com/Dicklesworthstone/toon_rust/main/install.sh?$(date +%s)" | bash

Cargo (from source)

cargo install --git https://github.com/Dicklesworthstone/toon_rust

Build locally

git clone https://github.com/Dicklesworthstone/toon_rust
cd toon_rust
cargo build --release
./target/release/toon --help

Quick Start

  1. Build the binary:
    cargo build --release
    
  2. Encode:
    cat input.json | ./target/release/toon --encode
    
  3. Decode:
    cat data.toon | ./target/release/toon --decode
    

Command Reference

toon [OPTIONS] [INPUT]

Auto-detection:

  • .json -> encode
  • .toon -> decode
  • stdin defaults to encode unless --decode or --jsonl is provided

Common flags:

  • -o, --output <file> (- or omitted: stdout)
  • -e, --encode
  • -d, --decode
  • --stream: decode directly to JSON, or encode a JSON root array with --array-length
  • --array-length <n>: known root-array count for --stream encoding
  • --jsonl decodes a root TOON array into one compact JSON value per line
  • --delimiter <d>: , or comma, \t, tab or a TAB character, | or pipe
  • --indent <n>: 0 to 16; encode needs at least 1; on decode it controls TOON input indentation and the default JSON output indentation
  • --json-indent <n>: decode only, 0 to 16; overrides JSON output indentation without changing TOON parsing (0 = compact JSON)
  • --no-strict
  • --key-folding <off|safe>
  • --flatten-depth <n>
  • --expand-paths <off|safe>
  • --stats: token estimates on stderr, either direction; also works with --stream

Exit codes: 0 success, 1 conversion or I/O error (including a failed write of the output), 2 usage error.

Regular output files are written to a temporary sibling, flushed and synchronized, then replaced atomically. A failed write leaves the previous destination intact, including same-path conversions. Existing file permissions are preserved. Symlinks to regular files keep their links and stage output beside the resolved target. Stdout and special files retain direct-write behavior.

Streaming large documents

# Decode a large file without building a complete value tree
toon large.toon --stream -o large.json

# Start producing JSON while the input pipe is still open
cat large.toon | toon --decode --stream

# Produce compact JSON and token estimates while preserving the input's nested structure
toon large.toon --stream --stats --json-indent 0 -o compact.json

# Encode a JSON root array whose item count is known, retaining one record at a time
toon records.json --stream --array-length 100000 --stats -o records.toon

When decoding, --stream retains the current input line, its pending events, and open-container state. Object members are emitted in source order, including repeated names; they are not merged. Use ordinary decoding for a single JSON document with object merging or safe path expansion. --no-strict still controls TOON syntax and count validation. Use --json-indent 0 for compact JSON, or a positive value for different output spacing. --indent continues to describe the TOON input; when --json-indent is omitted, JSON output uses that same indentation as before. The output override also works with ordinary decoding, --stats, and --expand-paths safe.

When encoding, --stream --array-length N reads a JSON root array one element at a time. The known count supplies the TOON header before the input has been consumed. The root uses expanded-list layout; nested values still use canonical inline or tabular layouts and support --delimiter, --indent, --key-folding, and --flatten-depth. Each element's JSON text and parsed value must fit in memory, but the complete array is never collected. --stats also counts input and output incrementally. The actual count, closing bracket, and trailing input are validated; a mismatch is an error even with --no-strict. Use ordinary encoding when the count is unknown or when canonical root tabular layout is preferred. Streaming file output retains the same atomic replacement behavior.

For JSON Lines output, pass --jsonl to a root array. Each item is decoded with ordinary duplicate-key handling and optional safe path expansion. Every output record ends in a newline. An empty array produces an empty output file.

printf '[2]{id,user.name}:\n  1,Ada\n  2,Lin\n' | toon --jsonl --expand-paths safe
# {"id":1,"user":{"name":"Ada"}}
# {"id":2,"user":{"name":"Lin"}}

Ordinary --stats reads and validates the complete input and materializes its value before writing output, preserving ordinary encoding and decoding behavior. Both input and output estimates are counted incrementally, without retaining a complete raw input or serialized output string. Input uses a bounded reader buffer plus scratch for the current JSON number; the value tree and individual TOON lines still need to fit in memory. If parsing fails early, the remaining input is consumed so late read and UTF-8 errors retain their existing precedence. With --stream --stats, decoding retains only the current line, its pending events, open-container state, and fixed-size counter state; an error stops streaming immediately. Estimates use the same Unicode-aware heuristic in both modes and reflect the selected JSON output indentation. The statistics are printed only after conversion and output writing, flushing, and any atomic file replacement have succeeded.

A late input or validation error returns a failure status and can leave a partial JSON prefix on stdout or a special output file. Regular output files are published only after the input has been completely consumed and validated, including when input and output share a path or an existing output symlink points to the input file.


Configuration

There is no config file. All configuration is via CLI flags or library options:

use toon::options::{EncodeOptions, KeyFoldingMode};

let options = EncodeOptions {
    indent: Some(2),
    delimiter: Some(','),
    key_folding: Some(KeyFoldingMode::Safe),
    flatten_depth: Some(usize::MAX),
    replacer: None,
};

Incremental Library APIs

When encoding options come from a caller or configuration, use try_encode, try_encode_lines, or try_encode_lines_iter. They return an error for zero indentation or a delimiter other than comma, tab, or pipe, before normalization or running a replacer. try_encode_stream_events provides the same validation for structural events. The matching functions without try_ panic on invalid options, just like the non-fallible decode helpers; valid options produce the same output through either API.

Checked encoders also reject input and replacer-generated trees deeper than the decoder's 127-container nesting limit. Input conversion runs immediately, even when options are invalid, so owned JsonValue and serde_json::Value inputs can be discarded without recursive teardown. Option errors take precedence over excessive input nesting, and invalid options never invoke the replacer. Custom Into<JsonValue> implementations are responsible for their own conversion behavior. Safe path expansion checks that same limit before constructing expanded objects, including depth accumulated across several nested dotted keys.

Use encode_stream_events_iter or its checked counterpart try_encode_stream_events_iter to emit structural JSON events one at a time. They retain the unconsumed input and a stack of open containers, transferring keys and scalar strings into events without creating a complete event vector. Options, normalization, and replacers run before the iterator is returned. The collecting and asynchronous event APIs share this traversal.

Use encode_lines_iter to format TOON one line at a time, and decode_stream_iter to read lines as fallible JSON events. Both iterators stop work when dropped:

use toon::{JsonValue, decode_stream_iter, encode_lines_iter};

fn main() -> toon::error::Result<()> {
    let value = JsonValue::Object(vec![("answer".into(), JsonValue::from(42_i64))]);
    let lines = encode_lines_iter(value, None);
    for event in decode_stream_iter(lines, None) {
        println!("{:?}", event?);
    }
    Ok(())
}

For buffered files or stdin, pass the reader directly to decode_stream_from_reader. The iterator reads on demand and preserves repeated keys in source order. Drain it to validate the whole document, including array counts and trailing input. To get a JsonValue with duplicate-key resolution and optional safe dotted-path expansion, use try_decode_from_reader(reader, options). Both APIs are available in the zero-dependency core. For sources that already produce fallible UTF-8 lines, use decode_stream_from_lines.

For a root array, decode_array_items_from_reader(reader, options) yields one Result<JsonValue> per element. It handles inline arrays, tabular rows, and mixed lists. Each element uses the same duplicate-key resolution and optional safe path expansion as try_decode_from_reader. The decoder releases each element to the caller before building the next. The current input line and the largest individual element still need to fit in memory. Drain the iterator to detect a late error, including a row-count mismatch or unexpected content after the array.

For fallible UTF-8 line iterators, use toon::decode::decode_array_items_from_lines(lines, options). It resolves each element with the same duplicate-key and safe path-expansion rules, and composes directly with the item encoders without collecting the input or translating it into a buffered reader:

use toon::decode::decode_array_items_from_lines;
use toon::encode::{try_encode_array_items_lines, write_toon_from_array_items};

fn main() -> toon::error::Result<()> {
    let lines = try_encode_array_items_lines(2, [Ok(true), Ok(false)], None)?;
    let items = decode_array_items_from_lines(lines, None);
    let mut output = Vec::new();
    write_toon_from_array_items(2, items, None, &mut output)?;
    assert_eq!(output, b"[2]:\n  - true\n  - false");
    Ok(())
}

Source errors retain their original payload. The first EOF or error permanently ends iteration and releases the source. Drain the result to validate the complete array; the current line and largest element must fit in memory, and nested list items can require a lookahead line to establish their boundary.

For buffered files or stdin, write_json_from_toon performs the line adaptation and event formatting without collecting JSON chunks or a complete value. It is available in the zero-dependency core. TOON parsing options and JSON output indentation are independent:

use std::io::{BufWriter, Write};
use toon::write_json_from_toon;

fn main() -> toon::error::Result<()> {
    let mut output = BufWriter::new(std::io::stdout().lock());
    write_json_from_toon(std::io::stdin().lock(), None, 0, &mut output)?;
    output.flush()?;
    Ok(())
}

The reader accepts one leading UTF-8 BOM and handles CRLF consistently with the string decoder. Input errors retain their original I/O payload, invalid UTF-8 is reported as an input error, and the first observed EOF permanently ends the document. A buffered reader may have prefetched bytes, but the pipeline requests no further lines after an error.

Native Rust integers passed through JsonValue::from_integer (or JsonValue::from(i64)) use the reference BigInt rule. Values from −9,007,199,254,740,991 through 9,007,199,254,740,991 become JSON numbers. Larger magnitudes become quoted decimal strings, preserving every digit. JSON text and native f64 inputs continue to use binary64 number semantics.

For a native JsonValue, try_encode_lines_iter(value, options)?.write_to(writer)? writes TOON directly to a byte sink with the zero-dependency core. It writes the remaining lines and leaves flushing and any final newline to the caller.

For tables whose schema and row count are known in advance, write_toon_from_rows writes a root tabular array from a fallible row iterator without building a complete value tree. Each row supplies primitive cells in the declared column order; owned arrays, vectors, and borrowed slices are accepted. Use a buffered writer for files and stdout:

use std::io::{BufWriter, Write};
use toon::{JsonPrimitive, write_toon_from_rows};

fn main() -> toon::error::Result<()> {
    let rows = (0..3).map(|id| {
        Ok([
            JsonPrimitive::Number(f64::from(id)),
            JsonPrimitive::String(format!("row-{id}")),
        ])
    });
    let mut output = BufWriter::new(std::io::stdout().lock());
    write_toon_from_rows(&["id", "name"], 3, rows, None, &mut output)?;
    output.flush()?;
    Ok(())
}

The writer validates unique column names, encoding options, row widths, and the declared row count. At least one column is required; an empty column name is valid. It uses the same quoting, delimiters, and number normalization as the ordinary encoder. A zero-row table produces the canonical empty-array header. Folding options have no effect on flat primitive rows; replacers are rejected because they could change the promised schema or row count.

Additional retained data is proportional to the schema, one source row, and a fixed 8 KiB output buffer. Keys and string cells are escaped into that buffer without complete encoded copies. The writer checks for one extra row to validate the count, stops requesting rows after any error, and leaves flushing and a final newline to the caller. A late source, shape, count, or output error can leave a partial TOON document in the destination.

For caller-controlled consumption, try_encode_rows_lines returns an EncodeRowLines iterator of fallible TOON lines without trailing newlines. The first call yields the header without requesting a row; each later call validates and formats one row. Dropping the iterator stops source polling. Drain it completely to validate the declared count and catch late source errors. EOF and errors permanently exhaust the iterator, even if its source would otherwise resume.

The line iterator builds one complete formatted row at a time. The direct writer above keeps its fixed output buffer. Both APIs share schema, option, width, and count validation. Fallible lines compose directly with the streaming decoder:

use toon::{
    JsonPrimitive, decode_stream_from_lines, try_encode_rows_lines, write_json_from_events,
};

fn main() -> toon::error::Result<()> {
    let rows = [
        Ok([JsonPrimitive::Bool(true)]),
        Ok([JsonPrimitive::Bool(false)]),
    ];
    let lines = try_encode_rows_lines(&["active"], 2, rows, None)?;
    let mut output = Vec::new();
    write_json_from_events(decode_stream_from_lines(lines, None), 0, &mut output)?;
    assert_eq!(output, br#"[{"active":true},{"active":false}]"#);
    Ok(())
}

For nested or heterogeneous records with a known count, write_toon_from_array_items accepts a fallible source of values and retains only the current item. The root array uses expanded list form so it can start writing without inspecting later items. Nested values still use the ordinary encoder's inline, tabular, and list layouts, quoting, normalization, and optional key folding:

use toon::{JsonValue, write_toon_from_array_items};

fn main() -> toon::error::Result<()> {
    let items = [
        Ok(JsonValue::Object(vec![("name".into(), JsonValue::from("Ada"))])),
        Ok(JsonValue::Array(vec![JsonValue::from(true), JsonValue::from(false)])),
    ];
    let mut output = Vec::new();
    write_toon_from_array_items(2, items, None, &mut output)?;
    assert_eq!(output, b"[2]:\n  - name: Ada\n  - [2]: true,false");
    Ok(())
}

try_encode_array_items_lines provides the same conversion as a fallible line iterator. Its first item is the array header, without reading a source item; subsequent calls consume the current item's lines before requesting another item. Both APIs count the enclosing root array toward the nesting limit and validate the declared count, including a final lookahead for surplus items or source errors. Replacers are rejected because their root callback would require the complete array. Dropping the line iterator stops source requests; draining it checks the entire document. Late input, count, nesting, or output errors can leave partial output. The direct writer leaves flushing and any final newline to the caller.

These encoders compose with decode_array_items_from_reader for transformations that retain one decoded record at a time, in addition to the decoder's current input line. The caller must supply the resulting item count; changing the number of records requires knowing that count before the header is emitted.

With the serde feature, write_toon_from_json(reader, options, writer) converts in the other direction. It validates the complete JSON value before writing and retains that value to choose array layouts and lengths. It reads the source through a bounded buffer, retains scratch for the current numeric token, and writes one formatted TOON line at a time. Use encode_json_reader to consume those lines as an iterator. Both APIs accept one leading UTF-8 BOM. The writer leaves flushing and any final newline to the caller.

For a large JSON root array, json_array_items_from_reader(reader) yields one Result<JsonValue> at a time. It shares the JSON number normalization and duplicate-key semantics of ordinary JSON input, accepts one leading BOM, and stops when dropped. Drain the iterator to validate the array's closing bracket and the complete document. Its memory depends on the largest element's JSON text and value rather than the whole array.

If the count is known, write_toon_from_json_array(length, reader, options, writer) connects that source directly to the counted-item encoder. The root uses expanded-list layout, while nested arrays keep their canonical layouts and safe key folding remains available. The writer verifies the actual count and all trailing input before returning success. It can leave partial output on failure and does not flush or append a final newline.

use toon::write_toon_from_json_array;

let input = br#"[{"id":1},{"id":2}]"#.as_slice();
let mut output = Vec::new();
write_toon_from_json_array(2, input, None, &mut output)?;
assert_eq!(output, b"[2]:\n  - id: 1\n  - id: 2");
# Ok::<(), toon::error::ToonError>(())

JSON text inputs use JavaScript's binary64 number model across library, reader, CLI, and WebAssembly encoding. Valid numbers that overflow, such as 1e400 and -1e400, normalize to null; underflow and negative zero normalize to 0. Finite number text retains the existing round-trip parsing precision. Quoted strings and object keys are never rewritten. Malformed numeric syntax still fails. Reader diagnostics retain source byte positions after overflow normalization, and --stats counts the original input text. Ordinary valid string input uses the existing direct parser; only rejected string input is retried through the compatibility adapter.

If you already have structural events, connect them directly to a JSON output writer:

use std::io::{BufWriter, Write};
use toon::{decode_stream_iter, write_json_from_events};

fn main() -> toon::error::Result<()> {
    let lines = ["rows[2]{id}:", "  1", "  2"].map(str::to_string);
    let mut output = BufWriter::new(std::io::stdout().lock());
    write_json_from_events(decode_stream_iter(lines, None), 2, &mut output)?;
    output.flush()?;
    Ok(())
}

Both writers validate and write each event before requesting the next. Source or output errors stop processing immediately; a failed stream can leave a partial JSON prefix in its destination. The caller controls flushing and any final newline. This API preserves repeated object members in event order; use value-building decode APIs when duplicate-object merging or safe path expansion is needed.

The existing encode_lines, decode_stream_sync, and asynchronous vector-returning helpers collect their results. With --features async-stream, AsyncEncodeStream and AsyncDecodeStream expose incremental streams with cooperative scheduler handoffs, using the same encoding and decoding engines as the synchronous APIs. Their inputs are synchronous values or line iterators; they do not turn blocking input reads into asynchronous I/O.

Async encoding convenience functions convert input to JsonValue when called. Their futures yield during input validation, normalization, replacement traversal, disposal of replaced trees, and output collection. These preparation phases share a work budget so moving between phases does not restart an unbounded batch. Options are checked before normalization or any replacer callback, and the full initial input is validated before the root callback runs.

For cooperative preparation without collecting output, await AsyncEncodeStream::try_new_async(input, options) or AsyncEncodeEventStream::try_new_async(input, options), then consume the resulting stream. The synchronous new and try_new constructors still prepare input immediately. Dropping a preparation future stops later callbacks and safely discards its input and replacement trees iteratively, including unchecked trees beyond the supported depth. Checked futures return preparation errors; the matching functions without try_ panic on those errors when polled. Custom input conversion, each user callback, and formatting an individual key or scalar remain synchronous operations.

Output traversal also cooperates before a line is available. AsyncEncodeStream yields while checking primitive-array eligibility, validating tabular schemas and row cells, formatting inline-array cells and table header fields, arranging and formatting table rows, building safe-folding key indexes, and retiring those indexes and table metadata. These steps and emitted lines share a 64-step budget. The synchronous iterator drains the same state, preserving primitive, tabular, and list representations, first-row column order, and safe-folding collision checks. A table still requires complete eligibility checking before its header can be emitted. Individual keys, scalars, allocation operations, and cancellation cleanup remain synchronous; the budget bounds traversal units rather than elapsed time.

Line iterators and streams retain one complete output line until it can be returned. EncodeLines::write_to instead escapes keys and strings into a fixed 8 KiB buffer, including root and object scalars, keyed array prefixes, inline arrays, table headers, and table rows. It retains the owned input and any column-order index, plus any prefix already formatted before switching from iteration to writing. Reordered rows use the first row's field order. A writer error stops output immediately and retains its original error payload; the caller owns buffering, flushing, and any final newline.

For an asynchronous row source with a known schema and count, use toon::encode::AsyncEncodeRowStream. It accepts asupersync::stream::Stream<Item = Result<R>> where R: AsRef<[JsonPrimitive]>, so rows can own their cells or borrow slices. It emits the header without polling the source, then formats one row at a time without building a JsonValue or collecting the rows.

use asupersync::stream::{Stream, StreamExt};
use toon::encode::AsyncEncodeRowStream;
use toon::error::Result;
use toon::JsonPrimitive;

async fn encode_rows<S>(rows: S, length: usize) -> Result<()>
where
    S: Stream<Item = Result<Vec<JsonPrimitive>>>,
{
    let mut lines = AsyncEncodeRowStream::try_new(&["id", "name"], length, rows, None)?;
    while let Some(line) = lines.next().await {
        println!("{}", line?);
    }
    Ok(())
}

The row stream waits for source readiness and also yields between batches of immediately ready lines. Sources need not implement Unpin. Schema, options, quoting, and primitive normalization follow write_toon_from_rows; replacers are rejected because the schema and row count are explicit. Drain the stream to validate the final count: it polls once more after the declared last row to check for excess rows or a source error. Width, count, and source errors appear once, then the stream stays exhausted and releases its source. Dropping it also releases the source without further polling. Each item is one complete line without a newline; source polling and formatting one row remain synchronous.

For asynchronous sources of nested or heterogeneous records, use toon::encode::async_encode::AsyncEncodeArrayItemStream. Supply the declared item count and a fallible Stream whose successful values convert into JsonValue. The first line is the array header, emitted without polling the source; the current item is fully normalized and encoded before another item is requested. Sources need not be Unpin, and borrowed input values are converted only when they arrive.

It shares the synchronous counted-item encoder's explicit root list layout and option, count, quoting, normalization, and nesting rules. Preparation, rejected-item disposal, nested layout selection, and line delivery share a cooperative work budget. Custom conversion, source polling, individual scalar formatting, and cancellation destruction remain synchronous. Replacers are rejected because they can change the complete array.

The async item encoder composes directly with the semantic array decoder:

use asupersync::stream::{Stream, StreamExt};
use toon::decode::AsyncDecodeArrayStream;
use toon::encode::async_encode::AsyncEncodeArrayItemStream;
use toon::error::Result;

async fn transcode(lines: impl Stream<Item = Result<String>>, count: usize) -> Result<()> {
    let items = AsyncDecodeArrayStream::new(lines, None);
    let mut encoded = AsyncEncodeArrayItemStream::try_new(count, items, None)?;
    while let Some(line) = encoded.next().await {
        println!("{}", line?);
    }
    Ok(())
}

The pipeline retains the current decoded record and output line rather than the full array. The caller supplies the resulting count before the header is emitted. Drain the stream to verify that count, including the final source lookahead; original source errors are preserved. An error is delivered once and releases the source, while cancellation stops further polling and safely disposes of unchecked owned values.

For a nonblocking source implementing asupersync::stream::Stream<Item = Result<String>>, use toon::decode::AsyncDecodeLineStream. It waits for input readiness, emits each line's events before polling for another line, and supports sources that do not implement Unpin. Source errors propagate once and stop decoding. Dropping the decoder drops its source.

use asupersync::stream::{Stream, StreamExt};
use toon::decode::AsyncDecodeLineStream;
use toon::error::Result;

async fn consume(lines: impl Stream<Item = Result<String>>) -> Result<()> {
    let mut events = AsyncDecodeLineStream::new(lines, None);
    while let Some(event) = events.next().await {
        println!("{:?}", event?);
    }
    Ok(())
}

For a root array, toon::decode::AsyncDecodeArrayStream::new(lines, options) yields one complete Result<JsonValue> per element instead of retaining the complete array. Inline, tabular, and mixed list input have the same duplicate-key resolution and optional safe path expansion as the synchronous array-item decoder:

use asupersync::stream::{Stream, StreamExt};
use toon::decode::AsyncDecodeArrayStream;
use toon::error::Result;

async fn consume_records(lines: impl Stream<Item = Result<String>>) -> Result<()> {
    let mut records = AsyncDecodeArrayStream::new(lines, None);
    while let Some(record) = records.next().await {
        println!("{}", toon::json_stringify(&record?, 0));
    }
    Ok(())
}

Construction does not poll the source, and sources need not implement Unpin. Item attachment, duplicate merges, safe expansion, and conversion yield cooperatively before requesting another event. Source readiness is forwarded through the caller's task context. The current line and individual record must fit in memory. Drain the stream to check the declared count and trailing input: a late error cannot retract earlier records. Errors appear once; errors, EOF, and cancellation release the source and stop further polling. Individual source polls, headers, cells, allocations, and cancellation teardown still run synchronously.

toon::decode::try_decode_from_async_lines(lines, options).await builds a complete JsonValue directly from the same asynchronous source, including duplicate-object merging and optional safe path expansion. It retains the resulting value, without a separate event vector. Both async input APIs accept one UTF-8 line per item, without its newline. Wide inline arrays and tabular rows yield during cell validation and event delivery, retaining the input line and at most one decoded cell instead of a complete row of events. Validation finishes before any events from that line are exposed, so malformed rows stay atomic.

Completed array items, duplicate-object merges, and disposal of replaced values yield before the next input event is read. Array items release their private indexes promptly. After input ends, retained-index finalization, safe path expansion, object-fragment merges within expansion, obsolete-value disposal, and final JSON conversion continue yielding. The materializer shares a budget of 64 traversal steps across input events and finalization phases, so many immediately ready events also hand control back to the scheduler.

Dropping the future stops input polling and traversal. Individual source polls, headers, cells, keys, allocation operations, and destruction of retained state after cancellation still run to completion.

Encoding retains the normalized input value and checks array eligibility before emitting its header. Decoding retains open container state, bounded structural events, and the current line, including for nested objects, list arrays, and tabular arrays. A single large inline array is one line and must still fit in memory.


WebAssembly

The wasm feature builds both a Rust library and a WebAssembly module. To generate Node.js bindings and exercise the JavaScript API:

rustup target add wasm32-unknown-unknown
cargo build --locked --lib --no-default-features --features wasm \
  --target wasm32-unknown-unknown
# Use the wasm-bindgen CLI version matching Cargo.lock (currently 0.2.130).
wasm-bindgen --target nodejs --out-dir target/wasm-node \
  target/wasm32-unknown-unknown/debug/toon.wasm
node --test tests/wasm_bindings.cjs

Use --target web with wasm-bindgen for browser bindings. Exported functions accept JSON or TOON strings and return strings; conversion and option errors throw JavaScript Error objects. Optional settings use their defaults when omitted or undefined. Explicit values must have the documented type: numeric settings are finite nonnegative integers in the target's supported range, encoding indentation is positive, delimiters are exactly ,, literal TAB, or |, and folding/expansion modes are off or safe. Getter exceptions are reported rather than silently replaced by defaults.


How It Works

Encoding Algorithm

The encoder transforms JSON into TOON through a multi-phase pipeline:

JSON Input
    |
    v
[1. Normalize] - Convert serde_json::Value to internal JsonValue
    |
    v
[2. Classify] - Determine structure type for each value
    |           - Primitive: emit directly
    |           - Object: check for tabular or nested
    |           - Array: detect homogeneous, tabular, or mixed
    |
    v
[3. Fold Keys] - Apply key folding (if enabled)
    |           - Detect single-key chains: {a:{b:{c:1}}} -> a.b.c: 1
    |           - Validate no sibling conflicts
    |
    v
[4. Emit Lines] - Generate TOON output line-by-line
                - Track indentation depth
                - Format headers with counts and field lists

Tabular Array Detection

One of TOON's most powerful features is automatic tabular array formatting. The algorithm:

  1. Check if array is non-empty and all elements are objects
  2. Extract field names from the first object
  3. Verify all objects have the same set of keys (the order may differ; cells follow the first object's order)
  4. Verify all values are primitives (no nested structures)
  5. If all checks pass, emit as tabular with header
// Input
[{"id":1,"name":"Alice","active":true},{"id":2,"name":"Bob","active":false}]

// Detection: All objects, same keys [id,name,active], all primitive values
// Output (tabular format)
[2]{id,name,active}:
  1,Alice,true
  2,Bob,false

Key Folding Algorithm

Key folding collapses nested single-key objects into dotted paths:

Input: {"config":{"database":{"host":"localhost"}}}

Algorithm:
1. Start at "config", value is object with 1 key
2. Descend to "database", value is object with 1 key
3. Descend to "host", value is primitive "localhost"
4. Collect path segments: ["config", "database", "host"]
5. Join with dots: "config.database.host"
6. Emit: config.database.host: localhost

Safety checks prevent folding when:

  • A sibling key (in a list-item object: any key of that object) equals the folded path
  • A segment within the depth budget is not an identifier ([A-Za-z_][A-Za-z0-9_]*)

--flatten-depth N folds at most N segments and writes the rest of the chain nested: {"a":{"b":{"c":1}}} with --flatten-depth 2 is a.b: followed by c: 1.

Decoding Algorithm

The decoder uses an event-based streaming architecture:

TOON Input (lines)
    |
    v
[1. Scanner] - Tokenize each line
    |         - Detect indentation level
    |         - Parse key, header, value components
    |
    v
[2. Parser] - Build event stream from tokens
    |        - Track nesting via indentation stack
    |        - Emit JsonStreamEvent for each structural element
    |
    v
[3. Event Builder] - Reconstruct JSON tree
    |               - Handle ObjectStart/End, ArrayStart/End
    |               - Expand dotted paths (if enabled)
    |
    v
[4. Path Expansion] - Convert dotted keys to nested objects
                    - "a.b.c: 1" -> {"a":{"b":{"c":1}}}

Event Types

enum JsonStreamEvent {
    StartObject,
    EndObject,
    StartArray { length: usize },
    EndArray,
    Key { key: String, was_quoted: bool },
    Primitive { value: JsonPrimitive },
}

The event iterator does not retain the full input or all emitted events. Value-returning APIs build a complete result tree. The CLI also keeps this tree so repeated object keys can merge, strict conflicts are reported consistently, and optional path expansion remains correct. Its normal decode path reads lines incrementally and writes JSON directly, without additional full-input, event-vector, or serialized-output buffers. --stats counts input and output incrementally using the same conversion paths.


Architecture

           +--------------------+
           |      CLI (toon)    |
           |  args + IO + stats |
           +---------+----------+
                     |
                     v
 +-------------------+-------------------+
 |          Core Library                 |
 |  encode: normalize -> folding -> emit |
 |  decode: scan -> parse -> events      |
 +-------------------+-------------------+
                     |
                     v
          +----------+-----------+
          |  Shared Utilities    |
          |  escaping + validation|
          +----------------------+

Module Structure

src/
├── main.rs           # CLI entry point
├── lib.rs            # Public API exports
├── options.rs        # EncodeOptions, DecodeOptions
├── error.rs          # Error types
├── encode/
│   ├── mod.rs        # encode(), encode_lines()
│   ├── normalize.rs  # JSON normalization
│   ├── primitives.rs # Primitive encoding
│   ├── encoders.rs   # Object/array encoders
│   ├── folding.rs    # Key folding algorithm
│   └── replacer.rs   # Custom replacer support
├── decode/
│   ├── mod.rs        # decode(), decode_stream_sync()
│   ├── scanner.rs    # Line tokenization
│   ├── parser.rs     # Token -> event parsing
│   ├── decoders.rs   # Value reconstruction
│   ├── event_builder.rs  # Event stream builder
│   ├── expand.rs     # Path expansion
│   └── validation.rs # Strict mode validation
├── cli/
│   ├── mod.rs        # CLI orchestration
│   ├── args.rs       # clap argument definitions
│   ├── conversion.rs # Streaming encode/decode
│   ├── json_stream.rs    # Event -> JSON chunks
│   └── json_stringify.rs # JsonValue -> JSON string
└── shared/
    ├── mod.rs
    ├── constants.rs  # Format constants
    ├── string_utils.rs   # Escaping, quoting
    ├── literal_utils.rs  # Literal parsing
    └── validation.rs     # Key/value validation

Troubleshooting

Common errors and fixes:

  1. Failed to parse JSON
    Ensure your input is valid JSON. Use jq . to validate before encoding.

  2. Tabs are not allowed in indentation
    Strict mode forbids tabs. Replace leading tabs with spaces or use --no-strict.

  3. Blank lines inside list/tabular arrays
    Strict mode disallows blank lines inside array blocks.

  4. Expected N list array items, but found more
    Declared array length in header must match items in strict mode.

  5. Path expansion conflict
    When expanding dotted keys, conflicts throw in strict mode. Use --no-strict or fix the input.


Limitations

  • Collecting APIs retain their result; use the iterator/stream types for incremental consumption
  • The CLI decoder retains the value tree for duplicate-key merging and path expansion
  • Decoder nesting is limited to 127 containers; a single line still needs to fit in memory
  • WebAssembly bindings require building with --features wasm for wasm32-unknown-unknown

FAQ

Q: Is this a new format?
A: No. This is a spec-first port of TOON.

Q: Does it match the reference implementation? A: Yes. Full spec conformance verified via fixture tests. CLI flags match the TypeScript reference exactly.

Q: Does it stream?
A: The library's line/event iterators and async stream types process output incrementally, including nested arrays. The CLI writes output directly and reads TOON lines incrementally, while retaining the value tree needed for its object-merge semantics. See the memory details above.

Q: Why nightly Rust?
A: The project targets Rust 2024 with strict linting and nightly toolchain components.

Q: Can I use this as a library?
A: Yes. The encode and decode APIs are stable and spec-driven.


About Contributions

About Contributions: Please don't take this the wrong way, but I do not accept outside contributions for any of my projects. I simply don't have the mental bandwidth to review anything, and it's my name on the thing, so I'm responsible for any problems it causes; thus, the risk-reward is highly asymmetric from my perspective. I'd also have to worry about other "stakeholders," which seems unwise for tools I mostly make for myself for free. Feel free to submit issues, and even PRs if you want to illustrate a proposed fix, but know I won't merge them directly. Instead, I'll have Claude or Codex review submissions via gh and independently decide whether and how to address them. Bug reports in particular are welcome. Sorry if this offends, but I want to avoid wasted time and hurt feelings. I understand this isn't in sync with the prevailing open-source ethos that seeks community contributions, but it's the only way I can move at this velocity and keep my sanity.


License

MIT License (with OpenAI/Anthropic Rider). See LICENSE.

استكشف مشاريع مشابهة ومرتبطة

جارٍ التحميل…