A lightweight Rust utility for reading input from stdin or a file path, designed for seamless integration with clap's derive API.
- Simple API: Just parse
"-"for stdin or any path for file input - Clap Integration: Implements
FromStrfor direct use as a clap argument type - Zero Configuration: Works out of the box with sensible defaults
- Lightweight: Minimal dependencies
Add this to your Cargo.toml:
[dependencies]
take_bytes = "0.1"The clap feature is enabled by default. To use without clap:
[dependencies]
take_bytes = { version = "0.1", default-features = false }use clap::Parser;
use take_bytes::TakeBytes;
#[derive(Parser)]
struct Cli {
/// Input file or "-" for stdin
#[arg(default_value = "-")]
input: TakeBytes,
}
fn main() -> Result<(), Box<dyn std::error::Error>> {
let cli = Cli::parse();
// Read as bytes
let bytes = cli.input.try_into_bytes()?;
println!("Read {} bytes", bytes.len());
Ok(())
}use take_bytes::TakeBytes;
use std::path::PathBuf;
// Read from stdin
let stdin_input = TakeBytes::stdin();
// Read from a file
let file_input = TakeBytes::file(PathBuf::from("input.txt"));
// Parse from string (like clap does)
let input: TakeBytes = "-".parse()?;use take_bytes::{TakeBytes, read_as_bytes, decode_utf8_string};
let input: TakeBytes = "file.txt".parse()?;
// Read as raw bytes
let bytes = read_as_bytes(input)?;
// Or decode as UTF-8 string
let input: TakeBytes = "file.txt".parse()?;
let text = decode_utf8_string(input)?;The classic Unix pattern of accepting input from either a file or stdin:
# Read from a file
myapp input.txt
# Read from stdin
cat input.txt | myapp -
# Read from stdin (default)
echo "hello" | myappMIT License - see LICENSE for details.