OpenViSTAI · Agents · Blockchain · Crypto
Menu
OPENVIST RECIPES

Count set bits in canonical unsigned 32-bit values with Rust

Rust

Report population counts for supplied decimal integers without confusing textual digits with binary representation.

Rust code excerpt: Count set bits in canonical unsigned 32-bit values with Rust. Version 0.1.0. Read the full recipe for code, sources and recorded test scope.

Report population counts for supplied decimal integers without confusing textual digits with binary representation. 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. No Cargo or external crates are needed.
  • Run recipe without arguments, including help flags, and supply input through stdin.
  • At most 65537 bytes are read from stdin; input exceeding 65536 bytes is rejected. Input must be strict UTF-8 without a leading BOM or any CR character.
  • Only LF separates lines. Exactly empty segments are discarded; nothing is trimmed or normalized. Before numeric interpretation, retained input is limited to 100 nonempty lines of at most 256 UTF-8 bytes each.
  • Each retained line must contain canonical ASCII decimal for a u32: 0 through 4294967295, without signs, whitespace or leading zeroes except the single digit 0.
  • After complete validation, successful output is exactly one JSON object followed by a newline, with binary population counts in input order. Empty input or input containing only LF characters produces {"ones":[]}. Success exits 0 with no stderr.
  • Invalid arguments, invalid input and stdin-read failures exit 2 without stdout and attempt to write exactly error: invalid input followed by a newline to stderr. Diagnostics never contain 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

  • Stdin can block while waiting for bytes or EOF. An input of exactly 65536 bytes requires EOF to establish that no additional byte exists.
  • Memory use is bounded in terms of input: at most 65537 input bytes, up to 100 borrowed line references and 100 counts, and at most 311 bytes of successful JSON text. Allocator capacity, temporary formatting storage and standard I/O buffering add overhead.
  • Successful output can be sensitive: it reveals each retained value's population count, their order and the number of retained values.
  • 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. A failed stderr write can prevent the complete error diagnostic from appearing.

Run it

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

Example input

0
1
3
8
4294967295

Expected output

{"ones":[0,1,2,1,32]}
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 stderr = io::stderr();
    let mut err = stderr.lock();
    let _ = err.write_all(b"error: invalid input\n");
    let _ = err.flush();
    std::process::exit(2);
}

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

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

    // Enforce all retained-line limits before interpreting any numbers.
    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 counts = Vec::with_capacity(lines.len());
    for line in lines {
        let bytes = line.as_bytes();
        if bytes.len() > 1 && bytes[0] == b'0' {
            return Err(());
        }
        let mut value = 0u32;
        for &byte in bytes {
            if !byte.is_ascii_digit() {
                return Err(());
            }
            value = value.checked_mul(10)
                .and_then(|v| v.checked_add(u32::from(byte - b'0')))
                .ok_or(())?;
        }
        counts.push(value.count_ones());
    }

    let mut output = String::from("{\"ones\":[");
    for (index, count) in counts.iter().enumerate() {
        if index != 0 {
            output.push(',');
        }
        output.push_str(&count.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 out = stdout.lock();
    if out.write_all(output.as_bytes()).is_err() || out.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.