StringBuilder v0.1.0

Source
A growable buffer for building a string in steps.

Package: Text

Struct

struct StringBuilder {
    data:     *char8;
    length:   uint;
    capacity: uint;
}

The mutable counterpart to String. Appending to a String allocates on every step, since each transformation returns a fresh one; accumulation happens here instead. The builder keeps spare capacity and doubles it when it runs out, which is what the third field buys over a String, and what makes a run of appends cost an amortized constant rather than a reallocation each time.

The fields are an implementation detail — read them with Data, Length, and Capacity.

Ownership

A builder owns its block and has to be passed to Free exactly once, on the same terms as a String. The exception is IntoString, which hands the block over to the String it returns and leaves the builder empty and owning nothing — after that only the String has to be freed, and Free on the drained builder is a harmless no-op.

Take the result with IntoString once the builder is finished with, and with ToString when the builder has to stay usable — that one copies, and leaves both to be freed.

Methods

Construction

MethodDescription
NewCreates an empty builder, without allocating.
WithCapacityCreates an empty builder with room reserved.
FreeReleases the block the builder owns.

Accessors

MethodDescription
DataThe pointer to the bytes written so far.
LengthHow many bytes have been written.
CapacityHow many bytes fit before the block grows.
IsEmptyWhether anything has been written.

Building

MethodDescription
AppendWrites a byte, a literal, or a string.
ReserveMakes room for N more bytes.
GrowGrows the block to hold at least N bytes.
ShrinkDrops the capacity the builder is not using.
ClearForgets the contents but keeps the block.

Conversion

MethodDescription
ToStringCopies the contents out into a String.
IntoStringHands the block over to a String, without a copy.

Example

import Io::PrintLine;
import Text::{ String, StringBuilder };

func Main() -> int {
    var builder = StringBuilder::New();

    for i in 0..3 {
        builder.Append("ab");
        builder.Append(c8'-');
    }

    PrintLine(builder.Length()); // 9

    var text = builder.IntoString(); // "ab-ab-ab-", and the builder is empty
    text.Free();
    return 0;
}

See also

  • Text — the package overview
  • String — the immutable string a builder produces