Skip to main content

better_url/util/
normalizer.rs

1//! [`Normalizer`].
2
3use crate::prelude::*;
4
5/// A [`std::fmt::Write`] that, if fed a prefix of its input, does not allocate.
6///
7/// Used for things like [`Ipv6Host`] where detecting if an input is normalized is super complicated but always allocating is super stupid.
8/// # Examples
9/// ```
10/// use std::fmt::Write;
11/// use std::assert_matches;
12/// use std::borrow::Cow;
13///
14/// use better_url::util::*;
15///
16/// // Prefixes don't get allocated.
17///
18/// let mut normalizer = Normalizer::new("abc");
19///
20/// write!(normalizer, "a").unwrap();
21/// write!(normalizer, "b").unwrap();
22///
23/// assert_matches!(normalizer.done(), (true, Cow::Borrowed("ab")));
24///
25/// // But changes do.
26///
27/// let mut normalizer = Normalizer::new("[1::0]");
28///
29/// write!(normalizer, "[" ).unwrap();
30/// write!(normalizer, "1" ).unwrap();
31/// write!(normalizer, "::").unwrap();
32/// write!(normalizer, "]" ).unwrap();
33///
34/// assert_matches!(normalizer.done(), (true, Cow::Owned(x)) if x == "[1::]");
35/// ```
36#[derive(Debug, Clone)]
37pub struct Normalizer<'a> {
38    /// The serialization.
39    x: Cow<'a, str>,
40    /// The index to write to.
41    i: usize,
42    /// If [`Self::x`] has been changed.
43    c: bool,
44}
45
46impl<'a> Normalizer<'a> {
47    /// Make a new [`Self`].
48    pub fn new<T: Into<Self>>(value: T) -> Self {
49        value.into()
50    }
51
52    /// Truncate if needed and return the final result.
53    pub fn done(mut self) -> (bool, Cow<'a, str>) {
54        let changed = self.c || self.i != self.x.len();
55
56        unsafe {
57            self.x.truncate_unchecked(self.i);
58        }
59
60        (changed, self.x)
61    }
62
63    /// What [`Self::done`] would return, without consuming `self`.
64    pub fn current_output(&self) -> (bool, &str) {
65        let changed = self.c || self.i != self.x.len();
66
67        (changed, unsafe {self.x.get_unchecked(..self.i)})
68    }
69}
70
71impl<'a> From<Cow<'a, str>> for Normalizer<'a     > {fn from(value: Cow<'a, str>) -> Self {Self {x: value       , i: 0, c: false}}}
72impl<'a> From<&'a str     > for Normalizer<'a     > {fn from(value: &'a str     ) -> Self {Self {x: value.into(), i: 0, c: false}}}
73impl     From<String      > for Normalizer<'static> {fn from(value: String      ) -> Self {Self {x: value.into(), i: 0, c: false}}}
74
75impl<'a> std::fmt::Write for Normalizer<'a> {
76    #[inline]
77    fn write_str(&mut self, s: &str) -> Result<(), std::fmt::Error> {
78        if self.c || !unsafe {self.x.get_unchecked(self.i..)}.starts_with(s) {
79            let a = self.x.to_mut();
80
81            unsafe {
82                a.as_mut_vec().set_len(self.i);
83            }
84
85            a.push_str(s);
86
87            self.c = true;
88        }
89
90        self.i += s.len();
91
92        Ok(())
93    }
94}