OpenViSTAI · Agents · Blockchain · Crypto
Menu
OPENVIST RECIPES

Compute bounded integer prefix sums with Rust

Rust

Accumulate each numeric prefix in input order using a representation wide enough for the maximum total.

Rust code excerpt: Compute bounded integer prefix sums with Rust. Version 0.1.0. Read the full recipe for code, sources and recorded test scope.

Accumulate each numeric prefix in input order using a representation wide enough for the maximum total. 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 ./recipe with input supplied through stdin. No CLI arguments are accepted, including help flags. Only the standard library is used.
  • 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. Before numeric classification, enforces at most 100 nonempty lines and at most 256 UTF-8 bytes per retained line. No trimming, normalization, sorting, or deduplication occurs.
  • Each retained line must be canonical ASCII decimal in 0..1000000, without signs, spaces, or leading zeroes except for 0 itself.
  • Accumulates prefixes in input order using u64. The maximum total is 100000000. Empty input or input containing only LF characters produces {"sums":[]}.
  • After complete validation, success writes exactly one JSON object followed by a newline, writes no stderr, and exits 0.
  • Invalid arguments, invalid input, or stdin-read failures produce no stdout, attempt to write exactly error: invalid input followed by a newline to stderr, and exit 2. Diagnostics never include 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 O(B + L + J), where B is the bounded input buffer, L is at most 100 retained-line references and prefix sums, and J is the small generated JSON string. Allocator capacity and standard I/O buffering add overhead.
  • Stdin can block while awaiting more data or EOF. The read cap prevents consuming more than 65537 bytes but does not impose a time limit.
  • Successful output contains every prefix sum and can reveal the original values through differences; treat it as sensitive when the input is sensitive.
  • Memory-allocation failures and output-write failures, including stderr-write failures, are outside the input-error guarantee. A stdout-write failure can leave partial output; the program exits 2 without adding a diagnostic.
  • The program reads only stdin and writes only stdout/stderr. It performs no filesystem access, networking, subprocess execution, or dynamic loading.

Run it

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

Example input

2
0
3
1

Expected output

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

fn prepare_output() -> Result<String, ()> {
    if std::env::args_os().nth(1).is_some() {
        return Err(());
    }

    let mut input = Vec::new();
    io::stdin()
        .lock()
        .take(65537)
        .read_to_end(&mut input)
        .map_err(|_| ())?;
    if input.len() > 65536 {
        return Err(());
    }

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

    // Enforce all retained-line limits before numeric classification.
    let mut lines = 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 sums: Vec<u64> = Vec::with_capacity(lines.len());
    let mut total: u64 = 0;
    for line in lines {
        let bytes = line.as_bytes();
        if bytes.len() > 1 && bytes[0] == b'0' {
            return Err(());
        }

        let mut value: u64 = 0;
        for &byte in bytes {
            if !(b'0'..=b'9').contains(&byte) {
                return Err(());
            }
            value = value * 10 + u64::from(byte - b'0');
            if value > 1_000_000 {
                return Err(());
            }
        }
        total += value;
        sums.push(total);
    }

    // Construct output only after every input value has been validated.
    let mut output = String::from("{\"sums\":[");
    for (index, sum) in sums.iter().enumerate() {
        if index != 0 {
            output.push(',');
        }
        output.push_str(&sum.to_string());
    }
    output.push_str("]}\n");
    Ok(output)
}

fn main() {
    let output = match prepare_output() {
        Ok(output) => output,
        Err(()) => invalid_input(),
    };

    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 18 supplementary cases are executed in pinned, offline Rust 1.99.0 containers. These checks do not establish exhaustive correctness or behavior on other versions.