OpenViSTAI · Agents · Blockchain · Crypto
Menu
OPENVIST RECIPES

Compute signed deltas between adjacent integers with Rust

Rust

Measure consecutive changes with subtraction in a signed type so decreases remain negative.

Rust code excerpt: Compute signed deltas between adjacent integers with Rust. Version 0.1.0. Read the full recipe for code, sources and recorded test scope.

Measure consecutive changes with subtraction in a signed type so decreases remain negative. 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 without any arguments, including help flags, and supply input through stdin.
  • Uses only the standard library, with an explicit std::io import. No Cargo, crates, filesystem access, networking, subprocesses, unsafe code or dynamic loading.
  • 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, rejects more than 100 retained lines or any retained line exceeding 256 UTF-8 bytes. Does not trim, normalize, group or deduplicate.
  • Accepts only canonical ASCII decimal integers from 0 through 1000000: no signs, spaces or leading zeroes except the spelling 0.
  • Computes each adjacent difference as an i64 subtraction, preserving negative decreases. Empty input and a single value produce {"deltas":[]}.
  • Success exits 0 and writes exactly one JSON object followed by a newline, with no stderr. 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 limitations below.

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. The byte bound is not a timeout.
  • Memory stores at most 65537 input bytes, 100 retained-line references, 100 i64 values and a small output string. There are at most 99 deltas, each in -1000000..1000000; successful output is at most 904 bytes. Allocation capacities and runtime overhead are additional.
  • Successful output reveals the number of adjacent pairs and their signed changes, which may be sensitive. Error diagnostics do not disclose input values.
  • Memory-allocation failures and stdout/stderr write or flush failures are outside the input-error guarantee. Output failures can leave partial output; detected stdout failures exit 2 without an additional diagnostic.

Run it

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

Example input

5
2
2
9

Expected output

{"deltas":[-3,0,7]}
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::{Read, Write};

fn invalid() -> ! {
    let stderr = std::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 stdin = std::io::stdin();
    let mut reader = stdin.lock().take(65_537);
    let mut input = Vec::new();
    if reader.read_to_end(&mut input).is_err() {
        invalid();
    }
    if input.len() > 65_536 {
        invalid();
    }

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

    // Enforce every retained-line limit before classifying any value.
    let mut lines = 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 values: Vec<i64> = Vec::with_capacity(lines.len());
    for line in lines {
        let bytes = line.as_bytes();
        if bytes.len() > 1 && bytes[0] == b'0' {
            invalid();
        }

        let mut value: i64 = 0;
        for &byte in bytes {
            if !byte.is_ascii_digit() {
                invalid();
            }
            // The previous value is at most 1,000,000, so this cannot overflow.
            value = value * 10 + i64::from(byte - b'0');
            if value > 1_000_000 {
                invalid();
            }
        }
        values.push(value);
    }

    // No successful stdout is emitted until all input has been validated.
    let mut output = String::from("{\"deltas\":[");
    for (index, pair) in values.windows(2).enumerate() {
        if index != 0 {
            output.push(',');
        }
        let delta: i64 = pair[1] - pair[0];
        output.push_str(&delta.to_string());
    }
    output.push_str("]}\n");

    let stdout = std::io::stdout();
    let mut out = stdout.lock();
    if out.write_all(output.as_bytes()).is_err() || out.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 19 supplementary cases are executed in pinned, offline Rust 1.99.0 containers. These checks do not establish exhaustive correctness or behavior on other versions.