#[inline]
pub fn string_with_capacity(estimated_size: usize) -> String {
String::with_capacity(estimated_size)
}
pub fn join_with_capacity(
parts: &[&str],
separator: &str,
estimated_part_size: usize,
) -> String {
let total_capacity = parts.len() * estimated_part_size + (parts.len() * separator.len());
let mut result = String::with_capacity(total_capacity);
for (i, part) in parts.iter().enumerate() {
if i > 0 {
result.push_str(separator);
}
result.push_str(part);
}
result
}
#[inline]
pub const fn estimate_csv_row_capacity(num_cols: usize) -> usize {
num_cols * 11
}
#[inline]
pub const fn estimate_json_array_capacity(
num_rows: usize,
num_cols: usize,
avg_cell_size: usize,
) -> usize {
let cell_capacity = (avg_cell_size + 3) * num_cols;
let row_capacity = cell_capacity + 3;
row_capacity * num_rows + 2
}
pub trait StringBuilder {
fn from_iter_with_capacity<I>(iter: I, estimated_capacity: usize) -> Self
where
I: IntoIterator<Item = String>;
}
impl StringBuilder for String {
fn from_iter_with_capacity<I>(iter: I, estimated_capacity: usize) -> Self
where
I: IntoIterator<Item = String>,
{
let mut result = String::with_capacity(estimated_capacity);
for s in iter {
result.push_str(&s);
}
result
}
}
#[inline]
pub fn join_cell_reference(col: &str, row: usize) -> String {
let mut result = String::with_capacity(col.len() + 4);
result.push_str(col);
result.push_str(&row.to_string());
result
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_join_with_capacity() {
let parts = vec!["hello", "world", "test"];
let result = join_with_capacity(&parts, ", ", 5);
assert_eq!(result, "hello, world, test");
}
#[test]
fn test_join_cell_reference() {
assert_eq!(join_cell_reference("A", 1), "A1");
assert_eq!(join_cell_reference("AB", 123), "AB123");
}
#[test]
fn test_estimates() {
assert_eq!(estimate_csv_row_capacity(5), 55);
assert_eq!(estimate_json_array_capacity(10, 3, 10), (10 * 3 * 13) + 32);
}
#[test]
fn test_string_builder() {
let parts = vec!["a".to_string(), "b".to_string(), "c".to_string()];
let result = String::from_iter_with_capacity(parts.into_iter(), 10);
assert_eq!(result, "abc");
}
}