]> git.lizzy.rs Git - rust.git/commitdiff
Estimate path length instead of hardcoding 64 bytes
authorNoah Lev <camelidcamel@gmail.com>
Mon, 10 Jan 2022 20:23:58 +0000 (12:23 -0800)
committerNoah Lev <camelidcamel@gmail.com>
Fri, 14 Jan 2022 20:05:35 +0000 (12:05 -0800)
src/librustdoc/html/format.rs
src/librustdoc/html/url_parts_builder.rs

index 342c15855d2144e2deb8edb3558af10bdf45583e..8571a6a137f5101687d769642177c6a60df46c59 100644 (file)
@@ -30,6 +30,7 @@
 use crate::html::escape::Escape;
 use crate::html::render::Context;
 
 use crate::html::escape::Escape;
 use crate::html::render::Context;
 
+use super::url_parts_builder::estimate_item_path_byte_length;
 use super::url_parts_builder::UrlPartsBuilder;
 
 crate trait Print {
 use super::url_parts_builder::UrlPartsBuilder;
 
 crate trait Print {
@@ -505,8 +506,7 @@ fn print<'a, 'tcx: 'a>(
 
 // Panics if `syms` is empty.
 crate fn join_with_double_colon(syms: &[Symbol]) -> String {
 
 // Panics if `syms` is empty.
 crate fn join_with_double_colon(syms: &[Symbol]) -> String {
-    // 64 bytes covers 99.9%+ of cases.
-    let mut s = String::with_capacity(64);
+    let mut s = String::with_capacity(estimate_item_path_byte_length(syms.len()));
     s.push_str(&syms[0].as_str());
     for sym in &syms[1..] {
         s.push_str("::");
     s.push_str(&syms[0].as_str());
     for sym in &syms[1..] {
         s.push_str("::");
index 5c1557078aa8080842f1c5975d666056ae328f49..26cebe8c72beaa78e289b17ffc6e7877ea517b8e 100644 (file)
@@ -110,6 +110,14 @@ fn with_capacity_bytes(count: usize) -> Self {
 /// This is intentionally on the lower end to avoid overallocating.
 const AVG_PART_LENGTH: usize = 5;
 
 /// This is intentionally on the lower end to avoid overallocating.
 const AVG_PART_LENGTH: usize = 5;
 
+/// Estimate the number of bytes in an item's path, based on how many segments it has.
+///
+/// **Note:** This is only to be used with, e.g., [`String::with_capacity()`];
+/// the return value is just a rough estimate.
+crate const fn estimate_item_path_byte_length(segment_count: usize) -> usize {
+    AVG_PART_LENGTH * segment_count
+}
+
 impl<'a> FromIterator<&'a str> for UrlPartsBuilder {
     fn from_iter<T: IntoIterator<Item = &'a str>>(iter: T) -> Self {
         let iter = iter.into_iter();
 impl<'a> FromIterator<&'a str> for UrlPartsBuilder {
     fn from_iter<T: IntoIterator<Item = &'a str>>(iter: T) -> Self {
         let iter = iter.into_iter();