better_url/
parse.rs

1//! [`ParseOptions`].
2
3#[expect(unused_imports, reason = "Used in doc comments.")]
4use url::{Url, EncodingOverride, SyntaxViolation, ParseOptions, ParseError};
5
6use crate::*;
7
8/// [`url::ParseOptions`] with public fields and [`std::fmt::Debug`].
9#[derive(Clone, Copy, Default)]
10pub struct BetterParseOptions<'a> {
11    /// [`ParseOptions::base_url`].
12    pub base_url: Option<&'a Url>,
13    /// [`ParseOptions::encoding_override`].
14    pub encoding_override: EncodingOverride<'a>,
15    /// [`ParseOptions::violation_fn`].
16    pub violation_fn: Option<&'a dyn Fn(SyntaxViolation)>
17}
18
19impl<'a> BetterParseOptions<'a> {
20    /// Set [`Self::base_url`].
21    pub fn base_url(mut self, base_url: Option<&'a Url>) -> Self {
22        self.base_url = base_url;
23        self
24    }
25
26    /// Set [`Self::encoding_override`].
27    pub fn encoding_override(mut self, encoding_override: EncodingOverride<'a>) -> Self {
28        self.encoding_override = encoding_override;
29        self
30    }
31
32    /// Set [`Self::violation_fn`].
33    pub fn violation_fn(mut self, violation_fn: Option<&'a dyn Fn(SyntaxViolation)>) -> Self {
34        self.violation_fn = violation_fn;
35        self
36    }
37
38    /// Make the equivalent [`ParseOptions`], parse `input`, and convert into a [`BetterUrl`].
39    /// # Errors
40    /// If the call to [`ParseOptions::parse`] returns an error, that error is returned.
41    pub fn parse(self, input: &str) -> Result<BetterUrl, ParseError> {
42        Url::options()
43            .base_url(self.base_url)
44            .encoding_override(self.encoding_override)
45            .syntax_violation_callback(self.violation_fn)
46            .parse(input)
47            .map(Into::into)
48    }
49}
50
51impl std::fmt::Debug for BetterParseOptions<'_> {
52    fn fmt(&self, fmt: &mut std::fmt::Formatter) -> std::fmt::Result {
53        fmt.debug_struct("BetterParseOptions")
54            .field("base_url", &self.base_url)
55            .field("encoding_override", &match self.encoding_override {
56                Some(_) => "Some(_)",
57                None => "None"
58            })
59            .field("violation_fn", &match self.violation_fn {
60                Some(_) => "Some(_)",
61                None => "None"
62            })
63            .finish()
64    }
65}