Select Git revision
Forked from
orestis.malaspin / rust-101
Source project has a limited visibility.
io.rs 5.85 KiB
use std::{
fs::File,
io::{BufReader, Read, Write},
};
// ANCHOR: use_clap
use clap::{value_parser, Arg, Command, Parser};
// ANCHOR_END: use_clap
// ANCHOR: consts
const COMMAND: &str = "cli";
const AUTHOR: &str = "Orestis Malaspinas";
const VERSION: &str = "0.1.0";
// ANCHOR_END: consts
use crate::something_or_nothing::find_min;
// ANCHOR: read_from_urandom
fn read_from_urandom(count: usize) -> Result<Vec<i32>, String> {
// ANCHOR: open
let file = File::open("/dev/urandom").map_err(|_| "Could not open /dev/urandom")?;
// ANCHOR_END: open
// ANCHOR: read
let mut buf_reader = BufReader::new(file);
let mut numbers = vec![0; count * 4];
buf_reader
.read_exact(&mut numbers)
.map_err(|_| "Could not read numbers")?;
// ANCHOR_END: read
// ANCHOR: convert_to_i32
Ok(numbers
.chunks(4)
.map(|i| i32::from_be_bytes(i.try_into().unwrap()))
.collect::<Vec<_>>())
// ANCHOR_END: convert_to_i32
}
// ANCHOR_END: read_from_urandom
// ANCHOR: write_to_file
fn write_to_file(output: &str, numbers: &[i32]) -> Result<(), String> {
// ANCHOR: create
let mut file = File::create(output).map_err(|_| format!("Failed to create {output}"))?;
// ANCHOR_END: create
// ANCHOR: write
writeln!(file, "Among the Somethings in the list:")
.map_err(|_| "Failed to write header into file.")?;
for n in numbers {
write!(file, "{n} ").map_err(|_| format!("Failed to write {n} into file."))?;
}
writeln!(file,).map_err(|_| "Failed to write carriage return into file.")?;
writeln!(file, "{}", find_min(numbers).to_string())
.map_err(|_| "Failed to write minimum value into file.")?;
// ANCHOR_END: write
Ok(())
}
// ANCHOR_END: write_to_file
/// Reads i32 from the command line and returns a [Vec] containing
/// these numbers. Returns errors when the parsing fails.
pub fn read_command_line_builder() -> Result<(), String> {
// ANCHOR: matches
let matches =
// ANCHOR: new_command
Command::new(COMMAND)
.author(AUTHOR)
.version(VERSION)
// ANCHOR_END: new_command
// ANCHOR: new_args
.arg(
Arg::new("numbers") // id