wallabag_api/types/
format.rs

1// Copyright 2018 Samuel Walladge <samuel@swalladge.net>
2// SPDX-License-Identifier: Apache-2.0 OR MIT
3
4use std::fmt;
5
6/// Use to represent a format to export to.
7#[derive(Debug, Clone, Copy, PartialEq, Eq)]
8pub enum Format {
9    XML,
10    JSON,
11    TXT,
12    CSV,
13    PDF,
14    EPUB,
15    MOBI,
16}
17
18impl fmt::Display for Format {
19    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
20        use self::Format::*;
21        write!(
22            f,
23            "{}",
24            match self {
25                XML => "xml",
26                JSON => "json",
27                TXT => "txt",
28                CSV => "csv",
29                PDF => "pdf",
30                EPUB => "epub",
31                MOBI => "mobi",
32            }
33        )
34    }
35}
36
37impl Format {
38    /// Create a `Format` from a str. Case-insensitive. Returns `None` if could
39    /// not determine format.
40    ///
41    /// ```
42    /// # use wallabag_api::types::Format;
43    /// assert_eq!(Format::try_from("json").unwrap(), Format::JSON);
44    /// ```
45    pub fn try_from(s: &str) -> Option<Self> {
46        use self::Format::*;
47        match s.to_lowercase().as_ref() {
48            "xml" => Some(XML),
49            "json" => Some(JSON),
50            "txt" => Some(TXT),
51            "csv" => Some(CSV),
52            "pdf" => Some(PDF),
53            "epub" => Some(EPUB),
54            "mobi" => Some(MOBI),
55            _ => None,
56        }
57    }
58}
59
60#[cfg(test)]
61mod tests {
62    use super::*;
63
64    #[test]
65    fn test_create_format_from_str() {
66        assert_eq!(Format::try_from("csv"), Some(Format::CSV));
67        assert_eq!(Format::try_from("Csv"), Some(Format::CSV));
68        assert_eq!(Format::try_from("EPUB"), Some(Format::EPUB));
69        assert_eq!(Format::try_from("EPUB_"), None);
70        assert_eq!(Format::try_from("wat"), None);
71        assert_eq!(Format::try_from(""), None);
72    }
73}