String v0.1.0

Source
An immutable, heap-allocated string.

Package: Text

Struct

struct String {
    data:   *char8;
    length: uint;
}

A String owns the block of length bytes behind data and never writes to it again: every transformation below returns a fresh String and leaves the receiver untouched. The fields are an implementation detail — read them with Data and Length.

The bytes are not terminated by a null, and length counts bytes rather than characters, so a multi-byte UTF-8 sequence counts for more than one.

Ownership

Assignment copies the struct, not the block, so two String values can name the same allocation. Take Clone when both of them have to be freed, and pass each one to Free exactly once. The empty String owns no block, which is why New allocates nothing and Free can be called on anything this package returns.

Because each transformation allocates, + in a loop is a chain of allocations. Accumulate with a StringBuilder instead.

Methods

Construction

MethodDescription
NewCreates an empty string, without allocating.
FromCreates a string by copying a literal or a buffer.
CloneReturns an independent copy, with its own block.
FreeReleases the block the string owns.

Accessors

MethodDescription
DataThe pointer to the underlying bytes.
LengthThe length in bytes.
IsEmptyWhether the string holds no bytes.
AtThe byte at an index.

Comparison

MethodDescription
EqualsWhether two strings hold the same bytes. Also == and !=.
MethodDescription
StartsWithWhether the string opens with a prefix.
EndsWithWhether the string closes with a suffix.
IndexOfThe offset of the first match, or -1.
ContainsWhether a substring occurs anywhere.

Transformation

Each returns a new String and leaves the receiver unchanged.

MethodDescription
+Joins two strings, or a string and a literal.
SubstringA copy of the bytes in a range.
ToUpperA copy with ASCII letters uppercased.
ToLowerA copy with ASCII letters lowercased.
TrimA copy with surrounding whitespace dropped.
RepeatA copy of the contents laid down N times.

Example

import Io::PrintLine;
import Text::String;

func Main() -> int {
    var greeting = String::From("Hello, Rux!");
    var needle = String::From("Rux");

    PrintLine(greeting.Length());        // 11
    PrintLine(greeting.Contains(needle)); // true
    PrintLine(greeting.IndexOf(needle));  // 7

    var shout = greeting.ToUpper(); // "HELLO, RUX!"

    shout.Free();
    needle.Free();
    greeting.Free();
    return 0;
}

See also

  • Text — the package overview
  • StringBuilder — build a string without allocating on every step