OpenViSTAI · Agents · Blockchain · Crypto
Menu
OPENVIST RECIPES

Count literal equals signs per text line with Rust

Rust

Measure delimiter occurrences without interpreting quoted values or assignment syntax.

Rust code excerpt: Count literal equals signs per text line with Rust. Version 0.1.0. Read the full recipe for code, sources and recorded test scope.

Measure delimiter occurrences without interpreting quoted values or assignment syntax. Work only with supplied input; this does not contact external services or modify input.

Before you start

  • Save the code as recipe.rs. Compile with Rust 1.99.0 using: rustc --edition=2021 recipe.rs -o recipe
  • Run recipe with input supplied through stdin and no CLI arguments. 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 character, including CRLF line endings.
  • Splits only at LF and discards exactly empty segments. Retains whitespace-only segments unchanged. Before counting, validates that there are at most 100 retained lines and that each contains at most 256 UTF-8 bytes.
  • Counts every literal U+003D equals sign in retained-line order, including occurrences inside quoted text. Performs no trimming, normalization, grouping, deduplication, or assignment parsing.
  • Success exits 0, emits exactly one JSON object followed by a newline, and emits no stderr. Empty input or input containing only LF characters produces {"counts":[]}.
  • 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 failure limitations below. Diagnostics never include input values.
  • Uses only the standard library, with explicit std::io imports. The only environment/process calls are std::env::args_os for argument rejection and std::process::exit for exit status.

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 may block while waiting for data or EOF. Accepted input requires EOF; oversized input is rejected once the 65537th byte is read.
  • Application storage includes a fixed 65537-byte input buffer, references to at most 100 retained lines, and a small output string. Overall application memory is O(input bound + retained-line count), plus standard-library buffering and allocator overhead.
  • Line lengths are measured in UTF-8 bytes, not Unicode characters. Only a BOM at the beginning of the entire input is rejected as a BOM; later U+FEFF characters are ordinary text.
  • Successful output reveals retained-line counts and per-line equals-sign frequencies, which may be sensitive even though original text is not printed.
  • Memory-allocation failures and output-write failures are outside the input-error guarantee. A detected stdout write or flush failure exits 2 without an added diagnostic and may leave partial stdout. Stderr failures may prevent delivery of the required error message.

Run it

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

Example input

a=b
x==y
plain

Expected output

{"counts":[1,2,0]}
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 mut stderr = io::stderr().lock();
    let _ = stderr.write_all(b"error: invalid input\n");
    let _ = stderr.flush();
    std::process::exit(2);
}

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

    let mut buffer = [0u8; 65_537];
    let mut used = 0usize;
    {
        let mut stdin = io::stdin().lock();
        loop {
            match stdin.read(&mut buffer[used..]) {
                Ok(0) => break,
                Ok(n) => {
                    used += n;
                    if used > 65_536 {
                        invalid();
                    }
                }
                Err(e) if e.kind() == io::ErrorKind::Interrupted => continue,
                Err(_) => invalid(),
            }
        }
    }

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

    // Validate every retained line before counting any equals signs.
    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("{\"counts\":[");
    for (index, line) in lines.iter().enumerate() {
        if index != 0 {
            output.push(',');
        }
        let count = line.bytes().filter(|&byte| byte == b'=').count();
        output.push_str(&count.to_string());
    }
    output.push_str("]}\n");

    let mut stdout = io::stdout().lock();
    if stdout.write_all(output.as_bytes()).is_err() || stdout.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.