capacity_builder
Builders where the code to calculate the capacity is the same as the code to write what's being built.
Overview
Sometimes you have some complex code that would be a bit of a pain to calculate the capacity of or could risk easily getting out of sync with the implementation. This crate makes keeping it in sync easier because it's the same code.
use StringBuilder;
let text = build?;
Behind the scenes it runs the closure once to compute the capacity and a second time to write the string.
Implementing faster .to_string() and std::fmt::Display
The default .to_string() implementation reuses std::fmt::Display. This is
slow because the capacity isn't set.
This crate provides a StringBuildable trait and #[derive(FastDisplay)] macro
for implementing .to_string() and std::fmt::Display using this crate.
use FastDisplay;
use StringBuildable;
use StringBuilder;
Now version.to_string() will be fast and return a string that has an accurate
capacity.
Additionally, this type can now be appended to other builders:
builder.append;
Side note: You may have noticed that no errors are necessary to surface. This is
because errors when formatting are really rare and if an error is encountered it
will store it to surface at the end and the rest of the append statements stop
formatting.
BytesBuilder
The bytes builder is similar to the StringBuilder:
use BytesBuilder;
let bytes = build?;
You can implement BytesAppendable to allow appending a struct to a builder.
;
let bytes = build
.unwrap;
assert_eq!;
Features
- The builder prevents adding owned data—only references.
- This helps to prevent accidentally allocating data multiple times in the closure.
- Errors when capacity cannot be reserved.
- For the string builder, types other than references can be provided.
- Numbers get written with the itoa crate.
Tips
- Do any necessary allocations before running the closure.
- Measure before and after using this crate to ensure you're not slower.