From 00c6b35ef3c979f184319807d2346e1abff5a50d Mon Sep 17 00:00:00 2001 From: PlexSheep Date: Mon, 13 May 2024 16:26:35 +0200 Subject: [PATCH] feat: allow reading numbers from stdin #1 --- src/main.rs | 30 +++++++++++++++++++++++++++++- 1 file changed, 29 insertions(+), 1 deletion(-) diff --git a/src/main.rs b/src/main.rs index 1aa0470..1071e10 100644 --- a/src/main.rs +++ b/src/main.rs @@ -3,13 +3,41 @@ //! This binary should just take any amount of numbers and print them out formatted to some other //! system. +use std::io::Read; +use std::process::exit; + use clap::Parser; mod format; use format::*; fn main() { - let options = FormatOptions::parse(); + // try to read from stdin first, appending the numbers we read to the FormatOptions + let mut args: Vec = std::env::args_os() + .map(|x| x.into_string().unwrap()) + .collect(); + let mut stdin_nums = Vec::new(); + match std::io::stdin().lock().read_to_end(&mut stdin_nums) { + Ok(_) => { + let whole: String = match String::from_utf8(stdin_nums) { + Ok(r) => r, + Err(e) => { + eprintln!("stdin for this program only accepts text: {e:#?}"); + exit(1); + } + }; + let whole = whole.replace('\n', ""); + for s in whole.split(' ') { + args.push(s.to_string()); + } + } + Err(e) => { + eprintln!("could not read from stdin: {e:#?}"); + exit(2); + } + }; + + let options = FormatOptions::parse_from(args); let mut out: Vec = Vec::new();