1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117

mod machine_data {


use serde::de::{Deserializer, Deserialize, Error as SerdeError};
use serde::ser::{Serializer, Serialize};
use self::super::super::Error;
use bidir_map::BidirMap;
use std::str::FromStr;
use unicase::UniCase;
use std::fmt;


lazy_static! {
    static ref NAME_ORDER_MAP: BidirMap<UniCase<&'static str>, MachineDataKind> = bidir_map!{
        UniCase::new("JSON") => MachineDataKind::Json,
    };

    static ref ERROR_WHER: String = String::from_utf8(NAME_ORDER_MAP.first_col()
            .enumerate()
            .map(|(i, v)| (i == NAME_ORDER_MAP.len() - 1, v))
            .fold((true, "expected ".as_bytes().to_vec()), |(first, mut acc), (last, el)| {
                if !first {
                    if NAME_ORDER_MAP.len() != 2 {
                        acc.extend(b",");
                    }
                    acc.extend(b" ");
                    if last {
                        acc.extend(b"or ");
                    }
                }

                acc.extend(b"\"");
                acc.extend(el.as_bytes());
                acc.extend(b"\"");

                (false, acc)
            })
            .1)
        .unwrap();
}


/// A specifier of machine data format.
#[derive(Debug, Copy, Clone, Hash, PartialEq, Eq, PartialOrd, Ord)]
pub enum MachineDataKind {
    /// JSON with all the data except content in it
    Json,
}

impl MachineDataKind {
    /// Get a machine data specifier corresponding to the specified string.
    ///
    /// The string repr of any variant is its name, case-insensitive.
    ///
    /// # Examples
    ///
    /// ```
    /// # use bloguen::ops::MachineDataKind;
    /// assert_eq!(MachineDataKind::from("JsoN"), Some(MachineDataKind::Json));
    /// ```
    pub fn from(s: &str) -> Option<MachineDataKind> {
        NAME_ORDER_MAP.get_by_first(&UniCase::new(s)).map(|&k| k)
    }

    /// Get a human-readable name of this machine data specifier.
    ///
    /// This is re-`from()`able to self.
    ///
    /// # Examples
    ///
    /// ```
    /// # use bloguen::ops::MachineDataKind;
    /// assert_eq!(MachineDataKind::Json.name(), "JSON");
    /// ```
    pub fn name(&self) -> &'static str {
        NAME_ORDER_MAP.get_by_second(&self).unwrap()
    }
}

impl FromStr for MachineDataKind {
    type Err = Error;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        MachineDataKind::from(s).ok_or_else(|| {
            Error::Parse {
                tp: "machine data specifier",
                wher: ERROR_WHER[..].into(),
                more: format!("\"{}\" invalid", s).into(),
            }
        })
    }
}

impl<'de> Deserialize<'de> for MachineDataKind {
    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
        MachineDataKind::from_str(<&'de str>::deserialize(deserializer)?).map_err(|e| {
            let buf = e.to_string();
            D::Error::custom(&buf[..buf.len() - 1]) // Drop dot
        })
    }
}

impl Serialize for MachineDataKind {
    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        serializer.serialize_str(self.name())
    }
}

impl fmt::Display for MachineDataKind {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        self.name().fmt(f)
    }
}


}