OpenViSTAI · Agents · Blockchain · Crypto
Menu
OPENVIST RECIPES

Check literal bracket nesting in text lines with Rust

Rust

Validate matched round square and curly brackets while treating all other scalars as ordinary text.

Rust code excerpt: Check literal bracket nesting in text lines with Rust. Version 0.1.0. Read the full recipe for code, sources and recorded test scope.

Validate matched round square and curly brackets while treating all other scalars as ordinary text. Work only with supplied input; this does not contact external services or modify input.

Before you start

  • Save as recipe.rs. Compile with Rust 1.99.0 using: rustc --edition=2021 recipe.rs -o recipe
  • Run with no arguments, supplying text on stdin: ./recipe < input.txt. All arguments, including help flags, are rejected.
  • Reads at most 65537 bytes from stdin and rejects input exceeding 65536 bytes. Requires strict UTF-8, rejects a leading UTF-8 BOM, and rejects every CR, including CRLF.
  • Splits only on LF and discards exactly empty segments. Whitespace-only segments remain. Before bracket classification, rejects more than 100 retained lines or any retained line exceeding 256 UTF-8 bytes. No trimming, normalization, grouping, or deduplication occurs.
  • Checks each retained line independently with a stack for (), [] and {}. Every other Unicode scalar is ordinary text, including quotes, backslashes, and any non-leading BOM. Wrong closers and unmatched brackets produce false.
  • Success exits 0 and writes exactly one JSON object followed by LF, with no stderr. Empty input or input containing only LF characters produces {"balanced":[]}.
  • Invalid arguments, invalid input, and stdin-read failures exit 2 without stdout and report exactly error: invalid input followed by LF on stderr, subject to the allocation and output-failure limitations below. Diagnostics never contain input values.

Build and check

  1. Save the example as recipe.rs.
  2. Compile with Rust 1.99.0 using rustc --edition=2021 recipe.rs -o recipe.
  3. Prepare UTF-8 input.txt following the documented operation-specific conventions.
  4. Run ./recipe < input.txt.
  5. Inspect the JSON result. Exit 2 with exactly error: invalid input followed by a newline on stderr and no stdout identifies rejected input or stdin-read failure. Output-write failures may also exit nonzero, without that diagnostic and potentially after partial stdout; these are outside the input-error guarantee.

Limits to understand

  • Stdin can block while waiting for data or EOF. No timeout is provided. The read bound limits bytes consumed, not elapsed time.
  • Memory use is bounded by the input buffer holding at most 65537 bytes, references to at most 100 lines, a temporary stack of at most 256 characters, and the small JSON output buffer. Allocator capacity and standard-library I/O buffering add overhead.
  • Successful output does not reproduce line text, but reveals the number and order of retained lines and their bracket-balance results; treat that information as potentially sensitive.
  • Memory-allocation failures and stdout/stderr write or flush failures are outside the input-error guarantee. An output failure may leave partial output or prevent the diagnostic from being delivered; detected stdout failures exit 2.
  • Uses only the standard library, stdin, stdout, and stderr. Argument inspection is used only to reject arguments, and process exit is used only to set status. No filesystem, networking, subprocess, dynamic-loading, or unsafe operations are used.
  • This checks literal brackets, not programming-language syntax or quoted-string semantics.

Run it

rustc --edition=2021 recipe.rs -o recipe
./recipe < input.txt

Example input

([])
([)]
plain

Expected output

{"balanced":[true,false,true]}
INSPECT THE SCRIPT

Inspect, copy and run the documented checks.

This browser preview builds code locally. It does not contact an API or run the code.

Default example ready.

Rust example
use std::io::{self, Read, Write};

fn invalid() -> ! {
    let stderr = io::stderr();
    let mut err = stderr.lock();
    let _ = err.write_all(b"error: invalid input\n");
    let _ = err.flush();
    std::process::exit(2);
}

fn balanced(line: &str) -> bool {
    let mut stack: Vec<char> = Vec::new();
    for ch in line.chars() {
        match ch {
            '(' | '[' | '{' => stack.push(ch),
            ')' | ']' | '}' => {
                let expected = match ch {
                    ')' => '(',
                    ']' => '[',
                    '}' => '{',
                    _ => unreachable!(),
                };
                if stack.pop() != Some(expected) {
                    return false;
                }
            }
            _ => {}
        }
    }
    stack.is_empty()
}

fn main() {
    if std::env::args_os().skip(1).next().is_some() {
        invalid();
    }

    let mut input = Vec::new();
    {
        let stdin = io::stdin();
        let mut reader = stdin.lock().take(65_537);
        if reader.read_to_end(&mut input).is_err() {
            invalid();
        }
    }
    if input.len() > 65_536 {
        invalid();
    }

    let text = match std::str::from_utf8(&input) {
        Ok(text) => text,
        Err(_) => invalid(),
    };
    if text.starts_with('\u{feff}') || text.contains('\r') {
        invalid();
    }

    // Validate every retained line before classifying any line.
    let mut lines: Vec<&str> = Vec::new();
    for line in text.split('\n') {
        if line.is_empty() {
            continue;
        }
        if line.len() > 256 || lines.len() >= 100 {
            invalid();
        }
        lines.push(line);
    }

    let mut output = String::from("{\"balanced\":[");
    for (index, line) in lines.iter().enumerate() {
        if index != 0 {
            output.push(',');
        }
        output.push_str(if balanced(line) { "true" } else { "false" });
    }
    output.push_str("]}\n");

    let stdout = io::stdout();
    let mut out = stdout.lock();
    if out.write_all(output.as_bytes()).is_err() || out.flush().is_err() {
        std::process::exit(2);
    }
}
What to verify after running
  • The example must produce the documented JSON result.
  • Empty stdin must produce the documented empty result.
  • Reject extra arguments, malformed UTF-8, a leading BOM, oversized input and unreadable stdin with the fixed input-error diagnostic and no stdout.

Request or format preview

Illustrative preview. No provider response, price or balance is fetched.

Change a setting to inspect the preview.

Official sources and related profiles

    Code license: MIT. Keep the license notice with your copy.

    Example version 0.1.0 · Documentation reviewed 2026-10-14.

    Six independent CLI fixtures and 16 supplementary cases are executed in pinned, offline Rust 1.99.0 containers. These checks do not establish exhaustive correctness or behavior on other versions.