1use crate::{error::MalformedReason, EditXMLError};
2
3#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
4#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
5#[cfg_attr(feature = "serde", serde(rename_all = "lowercase"))]
6pub enum StandaloneValue {
7 Yes,
8 #[default]
9 No,
10}
11impl StandaloneValue {
12 pub fn as_str(&self) -> &'static str {
13 match self {
14 StandaloneValue::Yes => "yes",
15 StandaloneValue::No => "no",
16 }
17 }
18 pub fn as_bytes(&self) -> &'static [u8] {
19 match self {
20 StandaloneValue::Yes => b"yes",
21 StandaloneValue::No => b"no",
22 }
23 }
24 pub fn is_standalone(&self) -> bool {
25 match self {
26 StandaloneValue::Yes => true,
27 StandaloneValue::No => false,
28 }
29 }
30}
31impl TryFrom<&[u8]> for StandaloneValue {
32 type Error = EditXMLError;
33 fn try_from(value: &[u8]) -> Result<Self, Self::Error> {
34 let value = String::from_utf8(value.to_vec())?.to_lowercase();
35 match value.as_str() {
36 "yes" => Ok(StandaloneValue::Yes),
37 "no" => Ok(StandaloneValue::No),
38 _ => Err(MalformedReason::InvalidStandAloneValue.into()),
39 }
40 }
41}
42impl TryFrom<&str> for StandaloneValue {
43 type Error = EditXMLError;
44 fn try_from(value: &str) -> Result<Self, Self::Error> {
45 let value = value.to_lowercase();
46 match value.as_str() {
47 "yes" => Ok(StandaloneValue::Yes),
48 "no" => Ok(StandaloneValue::No),
49 _ => Err(MalformedReason::InvalidStandAloneValue.into()),
50 }
51 }
52}
53impl std::fmt::Display for StandaloneValue {
54 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
55 write!(f, "{}", self.as_str())
56 }
57}
58
59#[cfg(test)]
60mod tests {
61 use super::*;
62 #[test]
63 fn test_standalone_value() {
64 let yes = StandaloneValue::Yes;
65 let no = StandaloneValue::No;
66 assert_eq!(yes.as_str(), "yes");
67 assert_eq!(no.as_str(), "no");
68 assert_eq!(yes.as_bytes(), b"yes");
69 assert_eq!(no.as_bytes(), b"no");
70 assert!(yes.is_standalone());
71 assert!(!no.is_standalone());
72 let yes_str = "yes";
73 let no_str = "no";
74 assert_eq!(
75 StandaloneValue::try_from(yes_str).unwrap(),
76 StandaloneValue::Yes
77 );
78 assert_eq!(
79 StandaloneValue::try_from(no_str).unwrap(),
80 StandaloneValue::No
81 );
82 }
83}