liveBook · Manning

String buffer

As explained in Refactoring to Rust

A string buffer is a memory region that stores the character data of a growable string together with its current length and capacity.

A string buffer stores a growable string’s character data in heap memory alongside its current length and capacity. Mutating the buffer avoids copying the entire string until new data exceeds its capacity. section 2.4.1

The buffer’s two size measures determine when allocation is needed:

  • Length counts the valid elements currently stored. section 2.4.1
  • Capacity counts how many elements fit before growth requires reallocation. section 2.4.1
  • When capacity is exceeded, the buffer obtains larger storage and copies its data; growth strategy is not guaranteed. section 2.4.1

Building ten million dots

A mutable Rust String can receive one dot per loop iteration. String::with_capacity(10_000_000) reserves space in advance, reducing allocation opportunities while preserving the resulting string.

How Refactoring to Rust covers it

How deep it goes
Defines length, capacity, and reallocation, but does not specify a particular buffer-growth strategy.
Examples
Demonstrates repeated dot appends, preallocated Rust strings, and conversions between String values and string references.
What it assumes
Assumes basic loops and strings while teaching buffer length, capacity, mutation, and reallocation.
What you can do after
Build it from scratch by mutating strings and reserving capacity for expected data.
How it connects
Connects string buffers with mutable strings, heap allocation, capacity, reallocation, and string references.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Refactoring to Rust. The section links point to the parts of the book it draws on.