http_type/http_url/impl.rs
1use crate::*;
2
3/// Implements the `std::error::Error` trait for `HttpUrlError`.
4impl std::error::Error for HttpUrlError {}
5
6/// Implements the `Display` trait for `HttpUrlError`, allowing it to be formatted as a string.
7impl Display for HttpUrlError {
8 /// Formats the `HttpUrlError` variant into a human-readable string.
9 ///
10 /// # Arguments
11 ///
12 /// - `&mut fmt::Formatter<'_>` - The formatter to write the string into.
13 ///
14 /// # Returns
15 ///
16 /// A `fmt::Result` indicating success or failure of the formatting operation.
17 #[inline(always)]
18 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
19 match self {
20 HttpUrlError::InvalidUrl => write!(f, "Invalid URL"),
21 HttpUrlError::Unknown => write!(f, "Unknown error"),
22 }
23 }
24}
25
26/// Converts a URL parse error to a `HttpUrlError`.
27///
28/// Maps URL parse errors to `InvalidUrl`.
29impl From<ParseError> for HttpUrlError {
30 /// Converts a URL parse error to a `HttpUrlError`.
31 ///
32 /// # Arguments
33 ///
34 /// - `ParseError`: The URL parse error to convert.
35 ///
36 /// # Returns
37 ///
38 /// - `HttpUrlError`: The corresponding error as `InvalidUrl`.
39 #[inline(always)]
40 fn from(_: ParseError) -> Self {
41 HttpUrlError::InvalidUrl
42 }
43}
44
45impl HttpUrlComponents {
46 /// Parses a URL string into its components.
47 ///
48 /// Extracts protocol, host, port, path, query and fragment from the URL string.
49 ///
50 /// # Arguments
51 ///
52 /// - `AsRef<str>` - The URL string to parse.
53 ///
54 /// # Returns
55 ///
56 /// - `Result<HttpUrlComponents, HttpUrlError>` - Either the parsed components or an error.
57 #[inline]
58 pub fn parse<U>(url: U) -> Result<Self, HttpUrlError>
59 where
60 U: AsRef<str>,
61 {
62 let parsed_url: Url = Url::parse(url.as_ref())?;
63 let protocol: String = parsed_url.scheme().to_string();
64 let res: Self = Self {
65 protocol,
66 host: parsed_url.host_str().map(|h| h.to_string()),
67 port: parsed_url.port(),
68 path: Some(parsed_url.path().to_string()),
69 query: parsed_url.query().map(|q| q.to_string()),
70 fragment: parsed_url.fragment().map(|f| f.to_string()),
71 };
72 Ok(res)
73 }
74}