~jplatte/turbo.fish

ref: 51d23ade5228c689a7fb992ad8c3fe6b260b0fe1 turbo.fish/src/reverse_turbofish.rs -rw-r--r-- 1.0 KiB View raw
51d23ade — Jonas Platte Fix reverse links 10 months ago
                                                                                
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
use std::fmt;

use rocket::{
    http::{
        impl_from_uri_param_identity,
        uri::{Formatter, Path, UriDisplay},
        RawStr,
    },
    request::FromParam,
};

pub struct ReverseTurboFish(String);

impl ReverseTurboFish {
    pub fn new(guts: String) -> ReverseTurboFish {
        ReverseTurboFish(guts)
    }

    pub fn gut(self) -> String {
        self.0
    }
}

impl<'a> FromParam<'a> for ReverseTurboFish {
    type Error = &'a RawStr;

    fn from_param(param: &'a RawStr) -> Result<Self, Self::Error> {
        let param_cow = param.percent_decode().map_err(|_| param)?;
        let (front, rest) = param_cow.split_at(1);
        let (mid, back) = rest.split_at(rest.len() - 3);

        if front == "<" && back == ">::" {
            Ok(ReverseTurboFish(mid.to_owned()))
        } else {
            Err(param)
        }
    }
}

impl UriDisplay<Path> for ReverseTurboFish {
    fn fmt(&self, f: &mut Formatter<Path>) -> fmt::Result {
        f.write_value(&format!("<{}>::", self.0))
    }
}

impl_from_uri_param_identity!([Path] ReverseTurboFish);