dysk_cli/
order.rs

1use {
2    std::{
3        fmt,
4        str::FromStr,
5    },
6};
7
8/// one of the two sorting directions
9#[derive(Debug, Clone, Copy, PartialEq)]
10pub enum Order {
11    Asc,
12    Desc,
13}
14
15
16#[derive(Debug)]
17pub struct ParseOrderError {
18    /// the string which couldn't be parsed
19    pub raw: String,
20}
21impl ParseOrderError {
22    pub fn new<S: Into<String>>(s: S) -> Self {
23        Self { raw: s.into() }
24    }
25}
26impl fmt::Display for ParseOrderError {
27    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
28        write!(f, "{:?} can't be parsed as a sort order. Use 'asc' or 'desc' (or nothing)", self.raw)
29    }
30}
31impl std::error::Error for ParseOrderError {}
32
33impl FromStr for Order {
34    type Err = ParseOrderError;
35    fn from_str(s: &str) -> Result<Self, ParseOrderError> {
36        let s = s.to_lowercase();
37        match s.as_ref() {
38            "a" | "asc" => Ok(Self::Asc),
39            "d" | "desc" => Ok(Self::Desc),
40            _ => Err(ParseOrderError::new(s))
41        }
42    }
43}