aboutsummaryrefslogtreecommitdiff
path: root/src/encoding/uri.rs
blob: b1a1282b2c033cb1ac866af3887a56fdf0f4f59c (plain)
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
use anyhow::anyhow;
use std::{fmt::Display, str::FromStr};

#[derive(Debug, Clone)]
pub struct Uri {
    pub protocol: String,
    pub localpart: Option<String>,
    pub addr: String,
    pub params: String,
}

impl Display for Uri {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let Self {
            protocol,
            localpart,
            addr,
            params,
        } = self;
        write!(
            f,
            "{protocol}:{}{addr}{}",
            if let Some(localpart) = localpart {
                format!("{localpart}@")
            } else {
                "".to_string()
            },
            if params.is_empty() {
                "".to_string()
            } else {
                format!(";{params}")
            }
        )?;
        Ok(())
    }
}
impl FromStr for Uri {
    type Err = anyhow::Error;
    fn from_str(s: &str) -> Result<Self, Self::Err> {
        let (pr, s) = s.split_once(":").ok_or(anyhow!("protocol sep"))?;
        let (lp, s) = s.split_once("@").unwrap_or(("", s));
        let (addr, params) = s.split_once(";").unwrap_or((s, ""));

        Ok(Self {
            addr: addr.to_owned(),
            localpart: if lp.is_empty() {
                None
            } else {
                Some(lp.to_string())
            },
            params: params.to_string(),
            protocol: pr.to_string(),
        })
    }
}