From d8ab28bbaba52e2c9f30aad2cc9812bd8a44becf Mon Sep 17 00:00:00 2001 From: Irene Knapp Date: Mon, 30 Nov 2020 22:06:13 -0800 Subject: Day 1! --- lib/src/error.rs | 37 ++++++++++++++++++++++++------------- lib/src/lib.rs | 26 ++++++++++++++++++++++++++ 2 files changed, 50 insertions(+), 13 deletions(-) (limited to 'lib') diff --git a/lib/src/error.rs b/lib/src/error.rs index cd4a760..216df78 100644 --- a/lib/src/error.rs +++ b/lib/src/error.rs @@ -1,30 +1,41 @@ #[derive(Debug)] pub enum Error { - IO(std::io::Error), + IO(std::io::Error), + Parse, } impl std::error::Error for Error { } impl std::fmt::Display for Error { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - match self { - Error::IO(e) => e.fmt(f), - } + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self { + Error::IO(e) => e.fmt(f), + Error::Parse => f.write_str("Parse error"), } + } } impl std::cmp::PartialEq for Error { - fn eq(&self, other: &Self) -> bool { - match (self, other) { - (Error::IO(_), Error::IO(_)) => - false, - } + fn eq(&self, other: &Self) -> bool { + match (self, other) { + (Error::IO(_), Error::IO(_)) => + false, + (Error::Parse, Error::Parse) => + true, + _ => + false, } + } } impl From for Error { - fn from(e: std::io::Error) -> Error { - Error::IO(e) - } + fn from(e: std::io::Error) -> Error { + Error::IO(e) + } } +impl From for Error { + fn from(_: std::num::ParseIntError) -> Error { + Error::Parse + } +} diff --git a/lib/src/lib.rs b/lib/src/lib.rs index b198f10..4b4b679 100644 --- a/lib/src/lib.rs +++ b/lib/src/lib.rs @@ -3,9 +3,35 @@ pub mod prelude; pub use crate::prelude::Result; +use std::fs::File; +use std::io::BufReader; +use std::io::prelude::*; + pub fn greeting() -> Result<()> { println!("Hello, Irenes!"); Ok(()) } + +pub fn read_int_file(filename: &str) -> Result> { + let file = File::open(filename)?; + let mut reader = BufReader::new(file); + let mut buffer = String::new(); + + let mut input: Vec = Vec::new(); + loop { + reader.read_line(&mut buffer)?; + if buffer.len() == 0 { + break; + } + + let item = buffer.trim().parse::()?; + + buffer.clear(); + + input.push(item); + } + + Ok(input) +} -- cgit 1.4.1