use core::{error, fmt, ops, str};
use alloc::string::{String, ToString};
#[derive(Debug)]
pub struct ParseIcalVersionError(
String,
);
impl fmt::Display for ParseIcalVersionError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "Cannot parse iCalendar version `{}`", self.0)
}
}
impl error::Error for ParseIcalVersionError {}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum IcalVersion {
V1_0,
V2_0,
}
impl str::FromStr for IcalVersion {
type Err = ParseIcalVersionError;
fn from_str(version: &str) -> Result<Self, Self::Err> {
match version {
"1.0" => Ok(Self::V1_0),
"2.0" => Ok(Self::V2_0),
_ => Err(ParseIcalVersionError(version.to_string())),
}
}
}
impl ops::Deref for IcalVersion {
type Target = str;
fn deref(&self) -> &Self::Target {
match self {
Self::V1_0 => "1.0",
Self::V2_0 => "2.0",
}
}
}
#[cfg(test)]
mod tests {
use alloc::string::ToString;
use crate::version::IcalVersion;
#[test]
fn maps_known_wire_strings_both_ways() {
assert_eq!("1.0".parse().ok(), Some(IcalVersion::V1_0));
assert_eq!(IcalVersion::V2_0.to_string(), "2.0");
assert_eq!(&*IcalVersion::V2_0, "2.0");
}
#[test]
fn rejects_unknown_versions() {
let error = "5.0".parse::<IcalVersion>().unwrap_err();
assert!(error.to_string().contains("5.0"));
}
}