mirror of
https://github.com/chylex/Advent-of-Code.git
synced 2025-07-30 09:59:05 +02:00
Refactor Rust error utility
This commit is contained in:
parent
f8bc38182f
commit
7eef7e4ae3
@ -38,14 +38,14 @@ impl PasswordRule {
|
||||
}
|
||||
|
||||
impl FromStr for PasswordRule {
|
||||
type Err = GenericError<'static>;
|
||||
type Err = GenericError;
|
||||
|
||||
fn from_str(s: &str) -> Result<Self, Self::Err> {
|
||||
let (s_range, s_rest) = s.split_once(' ').ok_or(GenericError::new("Missing space."))?;
|
||||
let (s_min, s_max) = s_range.split_once('-').ok_or(GenericError::new("Missing dash in the left part of the input."))?;
|
||||
let (s_char, s_password) = s_rest.split_once(": ").ok_or(GenericError::new("Missing colon followed by space in the right part of the input."))?;
|
||||
|
||||
return Ok(PasswordRule {
|
||||
Ok(PasswordRule {
|
||||
left_value: s_min.parse::<usize>().map_err(|_| GenericError::new("Cannot parse first number."))?,
|
||||
right_value: s_max.parse::<usize>().map_err(|_| GenericError::new("Cannot parse second number."))?,
|
||||
required_char: s_char.to_string(),
|
||||
|
@ -1,5 +1,5 @@
|
||||
use std::error::Error;
|
||||
use std::fmt::{Display, Formatter};
|
||||
use std::fmt::{Debug, Display, Formatter};
|
||||
use std::fs::File;
|
||||
use std::io;
|
||||
use std::io::{BufRead, BufReader};
|
||||
@ -14,21 +14,26 @@ pub fn parse_input_lines<T : FromStr>() -> Result<Vec<T>, Box<dyn Error>> where
|
||||
return read_input_lines()?.iter().map(|line| line.parse::<T>()).collect::<Result<Vec<T>, T::Err>>().map_err(Into::into);
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct GenericError<'a> {
|
||||
pub message: &'a str
|
||||
pub struct GenericError {
|
||||
pub message: String
|
||||
}
|
||||
|
||||
impl<'a> GenericError<'a> {
|
||||
pub fn new(message: &'a str) -> GenericError<'a> {
|
||||
GenericError { message }
|
||||
impl GenericError {
|
||||
pub fn new(message: impl Into<String>) -> GenericError {
|
||||
GenericError { message: message.into() }
|
||||
}
|
||||
}
|
||||
|
||||
impl Display for GenericError<'_> {
|
||||
impl Display for GenericError {
|
||||
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
|
||||
write!(f, "Parse error: {}", self.message)
|
||||
}
|
||||
}
|
||||
|
||||
impl Error for GenericError<'_> {}
|
||||
impl Debug for GenericError {
|
||||
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
|
||||
Display::fmt(self, f)
|
||||
}
|
||||
}
|
||||
|
||||
impl Error for GenericError {}
|
||||
|
Loading…
Reference in New Issue
Block a user