OpenViSTAI · Agents · Blockchain · Crypto
Menu
OPENVIST RECIPES

Group repeated exact text tokens by position with Rust

Rust

Report positional groups of repeated lines using exact scalar values without printing token contents.

Rust code excerpt: Group repeated exact text tokens by position with Rust. Version 0.1.0. Read the full recipe for code, sources and recorded test scope.

Report positional groups of repeated lines using exact scalar values without printing token contents. 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 using: rustc --edition=2021 recipe.rs -o recipe
  • Run with no arguments and supply input on stdin. All arguments, including 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.
  • Splits only on LF and discards exactly empty segments. Retains whitespace-only lines unchanged. Allows at most 100 retained lines, each at most 256 UTF-8 bytes, and validates these limits before grouping.
  • Positions are one-based indices in the retained nonempty-line sequence, not physical input line numbers. Exact equality uses no trimming, case folding, or Unicode normalization; valid UTF-8 byte equality is equivalent to equality of Unicode scalar sequences.
  • Outputs only groups occurring at least twice. Positions ascend within each group, and groups are ordered by their first position. Empty input or input without repeats produces {"groups":[]}.
  • Success exits 0 with exactly one JSON object and a newline on stdout and no stderr. Invalid arguments, invalid input, or stdin-read failures exit 2 with no stdout and exactly error: invalid input followed by a newline on stderr, subject to output-write failures.

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 EOF or the 65537-byte read bound. There is no timeout.
  • Memory holds the bounded input, at most 100 borrowed line references, grouping metadata for at most 100 positions, and the complete output. Grouping uses quadratic line comparisons, bounded by the 100-line and 256-byte limits.
  • Successful output contains no token contents, but duplicate relationships and positions can still reveal sensitive information.
  • Memory-allocation failures and output-write failures are outside the input-error guarantee. A detected successful-output write or flush failure exits 1 and may leave partial stdout; a failed diagnostic write may prevent the complete error message from appearing.
  • Uses only the standard library, stdin, stdout, and stderr, with argument inspection solely to reject arguments and process exit solely for exit status. No filesystem access or external dependencies are used.

Run it

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

Example input

a
b
a
b
c

Expected output

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

fn validated_output() -> Result<String, ()> {
    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
        || bytes.starts_with(&[0xEF, 0xBB, 0xBF])
        || bytes.contains(&b'\r')
    {
        return Err(());
    }
    let text = std::str::from_utf8(&bytes).map_err(|_| ())?;

    // Finish all line-limit validation before comparing or grouping lines.
    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 {
            return Err(());
        }
        lines.push(line);
    }

    let mut visited = [false; 100];
    let mut groups: Vec<Vec<usize>> = Vec::new();
    for i in 0..lines.len() {
        if visited[i] {
            continue;
        }
        let mut positions = Vec::new();
        for j in i..lines.len() {
            if lines[j] == lines[i] {
                visited[j] = true;
                positions.push(j + 1);
            }
        }
        if positions.len() >= 2 {
            groups.push(positions);
        }
    }

    let mut output = String::from("{\"groups\":[");
    for (group_index, group) in groups.iter().enumerate() {
        if group_index != 0 {
            output.push(',');
        }
        output.push('[');
        for (position_index, position) in group.iter().enumerate() {
            if position_index != 0 {
                output.push(',');
            }
            output.push_str(&position.to_string());
        }
        output.push(']');
    }
    output.push_str("]}\n");
    Ok(output)
}

fn main() {
    if std::env::args_os().nth(1).is_some() {
        invalid_input();
    }

    let output = match validated_output() {
        Ok(output) => output,
        Err(()) => invalid_input(),
    };

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

    Related browser tools

    Inspect related data locally in your browser. These tools have their own input rules and limits; they do not execute this recipe.