OpenViSTAI · Agents · Blockchain · Crypto
Menu
OPENVIST RECIPES

Partition bounded integers by parity with Rust

Rust

Separate even and odd values while preserving order and duplicates within each partition.

Rust code excerpt: Partition bounded integers by parity with Rust. Version 0.1.0. Read the full recipe for code, sources and recorded test scope.

Separate even and odd values while preserving order and duplicates within each partition. 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 arguments, supplying 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. Before parsing values or partitioning, enforces at most 100 retained lines and at most 256 UTF-8 bytes per retained line. Nothing is trimmed or normalized.
  • Accepts only canonical ASCII decimal integers from 0 through 1000000, with no signs, whitespace, or leading zeroes except the single digit 0.
  • Validates the complete input before constructing successful output. Emits exactly one compact JSON object followed by a newline, with even and odd arrays preserving input order and duplicates. Zero is even; empty input produces {"even":[],"odd":[]}.
  • Success exits 0 without 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 failure limitations below.
  • Uses only the standard library, permitted explicit imports, argument inspection solely to reject arguments, and process exit solely 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 more bytes or EOF. For oversized input, only the first 65537 bytes need be consumed.
  • Memory use is O(B + N), where B is the bounded input byte count and N is the number of retained values. It stores the input buffer, at most 100 borrowed line references, at most 100 integers, and the bounded output string; allocator capacity and runtime overhead are additional.
  • Successful output contains every accepted numeric value, including duplicates, and may expose sensitive data.
  • Memory-allocation failures and output-write failures are outside the input-error guarantee. Successful-output write or flush failures exit 1 and may leave partial stdout. A stderr-write failure can prevent delivery of the required error diagnostic.

Run it

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

Example input

3
2
0
3
4

Expected output

{"even":[2,0,4],"odd":[3,3]}
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 prepare_output() -> Result<String, ()> {
    let stdin = io::stdin();
    let mut reader = stdin.lock().take(65_537);
    let mut bytes = Vec::new();
    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 bytes.starts_with(&[0xEF, 0xBB, 0xBF]) || text.contains('\r') {
        return Err(());
    }

    // Establish every line-count and line-length limit before parsing values.
    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 values = Vec::new();
    for line in lines {
        let digits = line.as_bytes();
        if digits.len() > 1 && digits[0] == b'0' {
            return Err(());
        }
        let mut value = 0u32;
        for &digit in digits {
            if !digit.is_ascii_digit() {
                return Err(());
            }
            value = value.checked_mul(10)
                .and_then(|v| v.checked_add(u32::from(digit - b'0')))
                .ok_or(())?;
            if value > 1_000_000 {
                return Err(());
            }
        }
        values.push(value);
    }

    // All input is now validated. Scan in input order for each partition.
    let mut output = String::from("{\"even\":[");
    for parity in 0..2u32 {
        if parity == 1 {
            output.push_str("],\"odd\":[");
        }
        let mut first = true;
        for &value in &values {
            if value % 2 == parity {
                if !first {
                    output.push(',');
                }
                first = false;
                output.push_str(&value.to_string());
            }
        }
    }
    output.push_str("]}\n");
    Ok(output)
}

fn main() {
    if std::env::args_os().skip(1).next().is_some() {
        invalid_input();
    }
    let output = match prepare_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 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.