1 use crate::result::FResult; 2 use crate::FendError; 3 use crate::{Deserialize, Serialize}; 4 use std::fmt; 5 use std::io; 6 7 #[derive(Copy, Clone, Eq, PartialEq)] 8 pub(crate) struct Day(u8); 9 10 impl Day { value(self) -> u811 pub(crate) fn value(self) -> u8 { 12 self.0 13 } 14 new(day: u8) -> Self15 pub(crate) fn new(day: u8) -> Self { 16 assert!(day != 0 && day < 32, "day value {day} is out of range"); 17 Self(day) 18 } 19 serialize(self, write: &mut impl io::Write) -> FResult<()>20 pub(crate) fn serialize(self, write: &mut impl io::Write) -> FResult<()> { 21 self.value().serialize(write)?; 22 Ok(()) 23 } 24 deserialize(read: &mut impl io::Read) -> FResult<Self>25 pub(crate) fn deserialize(read: &mut impl io::Read) -> FResult<Self> { 26 let n = u8::deserialize(read)?; 27 if n == 0 || n >= 32 { 28 return Err(FendError::DeserializationError); 29 } 30 Ok(Self::new(n)) 31 } 32 } 33 34 impl fmt::Debug for Day { fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result35 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { 36 write!(f, "{}", self.0) 37 } 38 } 39 40 impl fmt::Display for Day { fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result41 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { 42 write!(f, "{}", self.0) 43 } 44 } 45 46 #[cfg(test)] 47 mod tests { 48 use super::*; 49 50 #[test] 51 #[should_panic(expected = "day value 0 is out of range")] day_0()52 fn day_0() { 53 Day::new(0); 54 } 55 56 #[test] 57 #[should_panic(expected = "day value 32 is out of range")] day_32()58 fn day_32() { 59 Day::new(32); 60 } 61 62 #[test] day_to_string()63 fn day_to_string() { 64 assert_eq!(Day::new(1).to_string(), "1"); 65 } 66 } 67