OpenViSTAI · Agents · Blockchain · Crypto
Menu
OPENVIST RECIPES

Classify fixed-width six-digit ASCII codes with Rust

Rust

Validate a width-sensitive decimal code convention while preserving the meaning of leading zeroes.

Rust code excerpt: Classify fixed-width six-digit ASCII codes with Rust. Version 0.1.0. Read the full recipe for code, sources and recorded test scope.

Validate a width-sensitive decimal code convention while preserving the meaning of leading zeroes. Work only with supplied input; this does not contact external services or modify input.

Before you start

  • Save as recipe.rs and compile using Rust 1.99.0: rustc --edition=2021 recipe.rs -o recipe
  • Run recipe with input supplied on stdin and no CLI arguments. Help flags are rejected.
  • Reads at most 65537 bytes and rejects input exceeding 65536 bytes. Requires strict UTF-8, rejects a leading UTF-8 BOM, and rejects every CR byte, including CRLF.
  • Splits only on LF and discards exactly empty segments. Retains at most 100 nonempty lines, each at most 256 UTF-8 bytes. All limits are enforced before classification; no trimming, normalization, grouping or deduplication occurs.
  • Each retained line produces one boolean, in input order. Only exactly six ASCII digits are valid. Leading zeroes are preserved and accepted; no numeric parsing occurs. Other spellings within the input limits produce false.
  • Success exits 0, emits exactly one JSON object of the form {"valid":[boolean,...]} followed by a newline, and writes no stderr. Empty input or only LF characters produces {"valid":[]}.
  • Invalid arguments, invalid input and stdin-read failures exit 2 with no stdout and exactly error: invalid input followed by a newline on stderr, subject to the output-write limitation below. Diagnostics do not 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

  • Memory use is bounded by a 65537-byte input buffer, storage for at most 100 borrowed line references, a JSON output buffer of at most 612 bytes, and standard I/O and allocation overhead.
  • Stdin can block while waiting for input or EOF. There is no timeout. Reading stops and rejects immediately once 65537 bytes have been obtained.
  • Successful output can be sensitive: it reveals the number and ordering of retained lines and their validity classifications, although it does not echo their contents.
  • Memory-allocation failures and output-write failures are outside the input-error guarantee. A detected stdout write or flush failure exits 1 and may leave partial stdout; stderr failures can prevent delivery of the complete error diagnostic.
  • Uses only the standard library, stdin, stdout and stderr, plus argument inspection solely to reject arguments and process exit solely to set status. No filesystem, network, subprocess or dynamic-loading access is used.

Run it

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

Example input

000000
123456
12345
1234567

Expected output

{"valid":[true,true,false,false]}
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};
use std::str;

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 main() {
    if std::env::args_os().skip(1).next().is_some() {
        invalid();
    }

    let mut buffer = vec![0u8; 65537];
    let mut used = 0usize;
    {
        let stdin = io::stdin();
        let mut input = stdin.lock();
        while used < buffer.len() {
            match input.read(&mut buffer[used..]) {
                Ok(0) => break,
                Ok(n) => used += n,
                Err(e) if e.kind() == io::ErrorKind::Interrupted => continue,
                Err(_) => invalid(),
            }
        }
    }
    if used > 65536 {
        invalid();
    }

    let text = match str::from_utf8(&buffer[..used]) {
        Ok(text) => text,
        Err(_) => invalid(),
    };
    if text.starts_with('\u{feff}') || text.as_bytes().contains(&b'\r') {
        invalid();
    }

    let mut lines: Vec<&str> = Vec::with_capacity(100);
    for line in text.split('\n') {
        if line.is_empty() {
            continue;
        }
        if line.len() > 256 || lines.len() >= 100 {
            invalid();
        }
        lines.push(line);
    }

    // All input validation is complete before classification or output.
    let mut output = String::with_capacity(612);
    output.push_str("{\"valid\":[");
    for (index, line) in lines.iter().enumerate() {
        if index != 0 {
            output.push(',');
        }
        let bytes = line.as_bytes();
        let valid = bytes.len() == 6 && bytes.iter().all(|b| b.is_ascii_digit());
        output.push_str(if valid { "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(1);
    }
}
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.