]> git.lizzy.rs Git - rust.git/blob - src/librustdoc/html/url_parts_builder.rs
Make `AVG_PART_LENGTH` a power of 2
[rust.git] / src / librustdoc / html / url_parts_builder.rs
1 use std::fmt::{self, Write};
2
3 use rustc_span::Symbol;
4
5 /// A builder that allows efficiently and easily constructing the part of a URL
6 /// after the domain: `nightly/core/str/struct.Bytes.html`.
7 ///
8 /// This type is a wrapper around the final `String` buffer,
9 /// but its API is like that of a `Vec` of URL components.
10 #[derive(Debug)]
11 crate struct UrlPartsBuilder {
12     buf: String,
13 }
14
15 impl UrlPartsBuilder {
16     /// Create an empty buffer.
17     #[allow(dead_code)]
18     crate fn new() -> Self {
19         Self { buf: String::new() }
20     }
21
22     /// Create an empty buffer with capacity for the specified number of bytes.
23     fn with_capacity_bytes(count: usize) -> Self {
24         Self { buf: String::with_capacity(count) }
25     }
26
27     /// Create a buffer with one URL component.
28     ///
29     /// # Examples
30     ///
31     /// Basic usage:
32     ///
33     /// ```ignore (private-type)
34     /// let builder = UrlPartsBuilder::singleton("core");
35     /// assert_eq!(builder.finish(), "core");
36     /// ```
37     ///
38     /// Adding more components afterward.
39     ///
40     /// ```ignore (private-type)
41     /// let mut builder = UrlPartsBuilder::singleton("core");
42     /// builder.push("str");
43     /// builder.push_front("nightly");
44     /// assert_eq!(builder.finish(), "nightly/core/str");
45     /// ```
46     crate fn singleton(part: &str) -> Self {
47         Self { buf: part.to_owned() }
48     }
49
50     /// Push a component onto the buffer.
51     ///
52     /// # Examples
53     ///
54     /// Basic usage:
55     ///
56     /// ```ignore (private-type)
57     /// let mut builder = UrlPartsBuilder::new();
58     /// builder.push("core");
59     /// builder.push("str");
60     /// builder.push("struct.Bytes.html");
61     /// assert_eq!(builder.finish(), "core/str/struct.Bytes.html");
62     /// ```
63     crate fn push(&mut self, part: &str) {
64         if !self.buf.is_empty() {
65             self.buf.push('/');
66         }
67         self.buf.push_str(part);
68     }
69
70     crate fn push_fmt(&mut self, args: fmt::Arguments<'_>) {
71         if !self.buf.is_empty() {
72             self.buf.push('/');
73         }
74         self.buf.write_fmt(args).unwrap()
75     }
76
77     /// Push a component onto the front of the buffer.
78     ///
79     /// # Examples
80     ///
81     /// Basic usage:
82     ///
83     /// ```ignore (private-type)
84     /// let mut builder = UrlPartsBuilder::new();
85     /// builder.push("core");
86     /// builder.push("str");
87     /// builder.push_front("nightly");
88     /// builder.push("struct.Bytes.html");
89     /// assert_eq!(builder.finish(), "nightly/core/str/struct.Bytes.html");
90     /// ```
91     crate fn push_front(&mut self, part: &str) {
92         let is_empty = self.buf.is_empty();
93         self.buf.reserve(part.len() + if !is_empty { 1 } else { 0 });
94         self.buf.insert_str(0, part);
95         if !is_empty {
96             self.buf.insert(part.len(), '/');
97         }
98     }
99
100     /// Get the final `String` buffer.
101     crate fn finish(self) -> String {
102         self.buf
103     }
104 }
105
106 /// This is just a guess at the average length of a URL part,
107 /// used for [`String::with_capacity`] calls in the [`FromIterator`]
108 /// and [`Extend`] impls, and for [estimating item path lengths].
109 ///
110 /// The value `8` was chosen for two main reasons:
111 ///
112 /// * It seems like a good guess for the average part length.
113 /// * jemalloc's size classes are all multiples of eight,
114 ///   which means that the amount of memory it allocates will often match
115 ///   the amount requested, avoiding wasted bytes.
116 ///
117 /// [estimating item path lengths]: estimate_item_path_byte_length
118 const AVG_PART_LENGTH: usize = 8;
119
120 /// Estimate the number of bytes in an item's path, based on how many segments it has.
121 ///
122 /// **Note:** This is only to be used with, e.g., [`String::with_capacity()`];
123 /// the return value is just a rough estimate.
124 crate const fn estimate_item_path_byte_length(segment_count: usize) -> usize {
125     AVG_PART_LENGTH * segment_count
126 }
127
128 impl<'a> FromIterator<&'a str> for UrlPartsBuilder {
129     fn from_iter<T: IntoIterator<Item = &'a str>>(iter: T) -> Self {
130         let iter = iter.into_iter();
131         let mut builder = Self::with_capacity_bytes(AVG_PART_LENGTH * iter.size_hint().0);
132         iter.for_each(|part| builder.push(part));
133         builder
134     }
135 }
136
137 impl<'a> Extend<&'a str> for UrlPartsBuilder {
138     fn extend<T: IntoIterator<Item = &'a str>>(&mut self, iter: T) {
139         let iter = iter.into_iter();
140         self.buf.reserve(AVG_PART_LENGTH * iter.size_hint().0);
141         iter.for_each(|part| self.push(part));
142     }
143 }
144
145 impl FromIterator<Symbol> for UrlPartsBuilder {
146     fn from_iter<T: IntoIterator<Item = Symbol>>(iter: T) -> Self {
147         // This code has to be duplicated from the `&str` impl because of
148         // `Symbol::as_str`'s lifetimes.
149         let iter = iter.into_iter();
150         let mut builder = Self::with_capacity_bytes(AVG_PART_LENGTH * iter.size_hint().0);
151         iter.for_each(|part| builder.push(part.as_str()));
152         builder
153     }
154 }
155
156 impl Extend<Symbol> for UrlPartsBuilder {
157     fn extend<T: IntoIterator<Item = Symbol>>(&mut self, iter: T) {
158         // This code has to be duplicated from the `&str` impl because of
159         // `Symbol::as_str`'s lifetimes.
160         let iter = iter.into_iter();
161         self.buf.reserve(AVG_PART_LENGTH * iter.size_hint().0);
162         iter.for_each(|part| self.push(part.as_str()));
163     }
164 }
165
166 #[cfg(test)]
167 mod tests;