Skip to content

Commit 58edfb4

Browse files
committed
perf: reduce string resizing
1 parent a44aa36 commit 58edfb4

1 file changed

Lines changed: 31 additions & 5 deletions

File tree

src/reporter/progress_report.rs

Lines changed: 31 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -13,20 +13,46 @@ pub struct ProgressReport<Size: size::Size> {
1313
}
1414

1515
impl<Size: size::Size + Into<u64>> ProgressReport<Size> {
16-
/// Print progress to stderr.
17-
pub const TEXT: fn(Self) = |report| {
16+
/// Maximum extend by which the progress text may extend.
17+
///
18+
/// This constant is used as capacity in [`Self::TEXT`] to prevent
19+
/// performance penalty from string resizing.
20+
///
21+
/// The value of this function is made correct by a unit test.
22+
const TEXT_MAX_LEN: usize = 145;
23+
24+
/// Create a text to be used in [`Self::TEXT`].
25+
fn text(self) -> String {
1826
let ProgressReport {
1927
items,
2028
total,
2129
errors,
22-
} = report;
23-
let mut text = String::new();
30+
} = self;
31+
let mut text = String::with_capacity(Self::TEXT_MAX_LEN);
2432
let total: u64 = total.into();
2533
write!(text, "\r(scanned {items}, total {total}").unwrap();
2634
if errors != 0 {
2735
write!(text, ", erred {errors}").unwrap();
2836
}
2937
text.push(')');
30-
GLOBAL_STATUS_BOARD.temporary_message(&text);
38+
text
39+
}
40+
41+
/// Print progress to stderr.
42+
pub const TEXT: fn(Self) = |report| {
43+
GLOBAL_STATUS_BOARD.temporary_message(&report.text());
3144
};
3245
}
46+
47+
#[test]
48+
fn text_max_len() {
49+
use crate::size::Bytes;
50+
let correct_value = ProgressReport::<Bytes> {
51+
items: u64::MAX,
52+
total: u64::MAX.into(),
53+
errors: u64::MAX,
54+
}
55+
.text()
56+
.len();
57+
assert_eq!(ProgressReport::<Bytes>::TEXT_MAX_LEN, correct_value);
58+
}

0 commit comments

Comments
 (0)