OpenViSTAI · Agents · Blockchain · Crypto
Menu
OPENVIST RECIPES

Count consecutive runs of equal text lines with Rust

Rust

Summarize consecutive repetition lengths without merging occurrences separated by another token.

Rust code excerpt: Count consecutive runs of equal text lines with Rust. Version 0.1.0. Read the full recipe for code, sources and recorded test scope.

Summarize consecutive repetition lengths without merging occurrences separated by another token. Work only with supplied input; this does not contact external services or modify input.

Before you start

  • Save as recipe.rs and compile with Rust 1.99.0: rustc --edition=2021 recipe.rs -o recipe
  • Run recipe with input supplied on stdin and no 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, including CRLF.
  • Splits only on LF and discards exactly empty segments. Whitespace-only lines remain. Retains at most 100 nonempty lines, each at most 256 UTF-8 bytes, validating these limits before grouping.
  • Compares retained lines exactly, without trimming or normalization. Discarded empty segments do not interrupt runs; different retained lines do. Empty input produces {"runs":[]}.
  • After complete validation, success writes exactly one JSON object followed by a newline, writes no stderr, and exits 0.
  • Invalid arguments, invalid input, and stdin-read failures produce no stdout, write exactly error: invalid input followed by a newline to stderr, and exit 2, subject to the failure limitations below.
  • Uses only the standard library, permitted imports, stdin/stdout/stderr, argument inspection for rejection, and process exit for 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 can block while waiting for data or EOF. No timeout is imposed.
  • Memory includes a 65537-byte input buffer, capacity for 100 borrowed line references and 100 run lengths, a small JSON buffer, and standard I/O and allocator overhead. Retained line text is not copied.
  • Successful output omits line contents but reveals run lengths and repetition structure; treat it as potentially sensitive.
  • 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 output. Failure to write stderr can prevent delivery of the prescribed diagnostic.

Run it

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

Example input

a
a
b
a

Expected output

{"runs":[2,1,1]}
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 prepare_output() -> Result<String, ()> {
    if std::env::args_os().nth(1).is_some() {
        return Err(());
    }

    let stdin = io::stdin();
    let mut reader = stdin.lock().take(65_537);
    let mut bytes = Vec::with_capacity(65_537);
    reader.read_to_end(&mut bytes).map_err(|_| ())?;
    if bytes.len() > 65_536 {
        return Err(());
    }

    let text = std::str::from_utf8(&bytes).map_err(|_| ())?;
    if text.starts_with('\u{feff}') || text.contains('\r') {
        return Err(());
    }

    // Validate every retained line before comparing or grouping any lines.
    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 {
            return Err(());
        }
        lines.push(line);
    }

    let mut runs: Vec<usize> = Vec::with_capacity(100);
    let mut previous: Option<&str> = None;
    let mut length = 0usize;
    for line in lines {
        if previous == Some(line) {
            length += 1;
        } else {
            if length != 0 {
                runs.push(length);
            }
            previous = Some(line);
            length = 1;
        }
    }
    if length != 0 {
        runs.push(length);
    }

    let mut output = String::with_capacity(512);
    output.push_str("{\"runs\":[");
    for (index, length) in runs.iter().enumerate() {
        if index != 0 {
            output.push(',');
        }
        output.push_str(&length.to_string());
    }
    output.push_str("]}\n");
    Ok(output)
}

fn main() {
    match prepare_output() {
        Ok(output) => {
            let stdout = io::stdout();
            let mut writer = stdout.lock();
            if writer.write_all(output.as_bytes())
                .and_then(|_| writer.flush())
                .is_err()
            {
                std::process::exit(1);
            }
        }
        Err(()) => {
            let stderr = io::stderr();
            let mut writer = stderr.lock();
            let _ = writer.write_all(b"error: invalid input\n");
            let _ = writer.flush();
            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.