String Builder

Efficient string concatenation with pre-allocated capacity

rust (1.70) 2025-11-12 string builder performance concatenation

Description

A string builder utility for efficient string construction. Pre-allocates capacity to avoid repeated allocations during concatenation.

Features

  • Pre-allocated capacity
  • Efficient appending
  • Multiple value types
  • Format support

Code

RAW
pub struct StringBuilder {    buffer: String,}impl StringBuilder {    pub fn new() -> Self {        StringBuilder {            buffer: String::new(),        }    }        pub fn with_capacity(capacity: usize) -> Self {        StringBuilder {            buffer: String::with_capacity(capacity),        }    }        pub fn append(&mut self, s: &str) -> &mut Self {        self.buffer.push_str(s);        self    }        pub fn append_char(&mut self, c: char) -> &mut Self {        self.buffer.push(c);        self    }        pub fn append_line(&mut self, s: &str) -> &mut Self {        self.buffer.push_str(s);        self.buffer.push('\n');        self    }        pub fn append_format(&mut self, format: &str, args: &[&dyn std::fmt::Display]) -> &mut Self {        // Simplified format - in real implementation, use format! macro        self.buffer.push_str(&format!("{}", format));        self    }        pub fn build(self) -> String {        self.buffer    }        pub fn len(&self) -> usize {        self.buffer.len()    }        pub fn clear(&mut self) {        self.buffer.clear();    }}impl Default for StringBuilder {    fn default() -> Self {        Self::new()    }}
RAW
use string_builder::StringBuilder;let mut builder = StringBuilder::with_capacity(100);builder    .append("Hello")    .append(" ")    .append("World")    .append_char('!')    .append_line("This is a line");let result = builder.build();println!("{}", result);

Comments

No comments yet. Be the first to comment!