From 68f70707b0d04e5429f0c16d71ca329a9d4a9557 Mon Sep 17 00:00:00 2001 From: "Aode (Lion)" Date: Mon, 18 Oct 2021 18:54:14 -0500 Subject: [PATCH] Implement Error for PathError --- src/lib.rs | 30 ++++++++++++++++++++++++++---- 1 file changed, 26 insertions(+), 4 deletions(-) diff --git a/src/lib.rs b/src/lib.rs index 40bd46f..1080771 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -17,7 +17,11 @@ pub struct Path { } #[derive(Debug)] -pub struct PathError; +pub enum PathError { + Format, + Length, + Range, +} impl Inner { fn next(&mut self) -> Vec { @@ -66,7 +70,7 @@ impl Path { let inner = bytes .chunks(2) .map(|chunk| { - let be_bytes: [u8; 2] = chunk.try_into().map_err(|_| PathError)?; + let be_bytes: [u8; 2] = chunk.try_into().map_err(|_| PathError::Length)?; Ok(u16::from_be_bytes(be_bytes)) }) .collect::>()?; @@ -91,12 +95,12 @@ impl Path { } if inner.len().saturating_sub(1) != inner[0].into() { - return Err(PathError); + return Err(PathError::Format); } for elem in inner.iter() { if *elem > 999 { - return Err(PathError); + return Err(PathError::Range); } } @@ -118,3 +122,21 @@ impl Path { .collect() } } + +impl std::fmt::Display for PathError { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self { + PathError::Format => { + write!(f, "Invalid path format") + } + PathError::Length => { + write!(f, "Invalid segment length") + } + PathError::Range => { + write!(f, "Invalid segment format") + } + } + } +} + +impl std::error::Error for PathError {}