String Sharing
The terminal-text layer uses one shared storage model for
String and
StringView.
Overview
String references one shared impl::StringData object and an IndexRange
describing the visible sub-range inside that storage.
This gives us:
cheap copies of
Stringcheap slices via
substr()a read-only
StringViewthat points at the same storage
Detach Rules
All read-only operations use the shared storage directly.
Every mutating String API detaches first when one of these conditions is true:
the backing storage is shared with another string or view
the current string represents only a sub-range of the backing storage
Detaching materializes only the currently visible range into a fresh impl::StringData instance.
After that, the mutating operation works on a unique contiguous buffer again.
Thread Safety
Implicit sharing is thread-safe:
concurrent reads of shared copies are safe
mutating one copied instance is safe because it detaches first
mutating the same
Stringobject from multiple threads is not thread safe.
Design Notes
StringView intentionally stays read-only. It shares the exact same storage representation as String
but only exposes read-only methods and return StringView instances.