Skip to main content

reqtls/url/
param.rs

1use super::error::UrlError;
2use crate::coder;
3use std::fmt::{Display, Formatter};
4use crate::error::RlsResult;
5
6#[derive(Debug, Clone)]
7pub struct Param {
8    name: String,
9    ///编码后的值
10    value: String,
11}
12
13impl Default for Param {
14    fn default() -> Self {
15        Param {
16            name: "".to_string(),
17            value: "".to_string(),
18        }
19    }
20}
21
22impl Param {
23    pub fn new_param(name: impl ToString, value: impl AsRef<str>) -> Param {
24        Param {
25            name: name.to_string(),
26            value: coder::url_encode(value),
27        }
28    }
29
30    pub fn name(&self) -> &str {
31        &self.name
32    }
33
34    pub fn value_raw(&self) -> &str { &self.value }
35
36    pub fn value(&self) -> RlsResult<String> {
37        coder::url_decode(&self.value).or(Err(UrlError::InvalidParamEncoded.into()))
38    }
39
40    pub fn into_value(self) -> RlsResult<String> {
41        coder::url_decode(&self.value).or(Err(UrlError::InvalidParamEncoded.into()))
42    }
43
44    pub fn set_value(&mut self, value: impl AsRef<str>) {
45        self.value = coder::url_encode(value);
46    }
47
48    pub fn is_empty(&self) -> bool {
49        self.name.is_empty() && self.value.is_empty()
50    }
51
52    pub fn len(&self) -> usize {
53        self.name.len() + 1 + self.value.len()
54    }
55}
56
57impl Display for Param {
58    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
59        let res = format!("{}={}", self.name, self.value);
60        f.write_str(&res)
61    }
62}
63
64impl TryFrom<&str> for Param {
65    type Error = UrlError;
66    fn try_from(value: &str) -> Result<Self, Self::Error> {
67        let mut items = value.split("=");
68        let name = items.next().ok_or(UrlError::MissingParamName)?.to_string();
69        let value = items.collect::<Vec<_>>().join("=");
70        Ok(Param {
71            name,
72            value,
73        })
74    }
75}
76
77impl TryFrom<String> for Param {
78    type Error = UrlError;
79    fn try_from(value: String) -> Result<Self, Self::Error> {
80        Param::try_from(value.as_str())
81    }
82}