From 00c6b35ef3c979f184319807d2346e1abff5a50d Mon Sep 17 00:00:00 2001 From: PlexSheep Date: Mon, 13 May 2024 16:26:35 +0200 Subject: [PATCH 1/2] 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(); -- 2.40.1 From 585bb41a9d1baf45b596cd511fba7fe4584a5a54 Mon Sep 17 00:00:00 2001 From: PlexSheep Date: Mon, 13 May 2024 16:29:17 +0200 Subject: [PATCH 2/2] refactor: split at whitespace #1 #15 --- src/main.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/main.rs b/src/main.rs index 1071e10..342c755 100644 --- a/src/main.rs +++ b/src/main.rs @@ -26,8 +26,8 @@ fn main() { exit(1); } }; - let whole = whole.replace('\n', ""); - for s in whole.split(' ') { + let split = whole.split_whitespace(); + for s in split { args.push(s.to_string()); } } -- 2.40.1