Which text type?
Two questions decide it: is it text or bytes, and will it change after you make it?
| Made once, never changes | Built up or changed | |
|---|---|---|
| Text, printable characters | String, the default |
DynamicString |
| Bytes, any content at all | ByteBuffer: files, wire data, dictionary keys |
DynamicByteBuffer |
Start with String. Reach for the dynamic pair only when the content really changes, and turn
it back into its immutable twin with toString() once it is done. Most text in a program is made
once and read many times, and an immutable value can be shared without anyone wondering who
changed it.
Text and bytes are different things. A String holds characters (Unicode code points), one
per position, so length() counts characters and reaching any position takes the same time. A
ByteBuffer holds bytes, which might be text in some encoding, an image, or a network packet. Move
between them at the edge of your program, once: INTO ByteBuffer encodes a String as UTF-8, and
INTO String decodes it back.
To look inside without copying, take a view. StringView and ByteBufferView borrow a window
over the owner's storage, and the search and slicing methods live there. A view borrows, so the
string or buffer it looks into must outlive it; the compiler checks that.
There is no + on text. Compose with format, as in ("$1 of $2")->format(done, total), or
build in steps with a DynamicString.
CLASS Main IMPLEMENTS TaskStarter {
METHOD start() RETURNS STATUS {
// Text that never changes is a String.
String name := "Zoë"
// Text built in steps is a DynamicString, turned into a String when it is done.
DynamicString greeting := CREATE DynamicString("Hello, ")
$? := greeting->append(name)
String done := greeting->toString()
printline(done)
// Bytes for a file, a socket or a dictionary key: convert once, at the edge.
ByteBuffer bytes := done INTO ByteBuffer
printline(("$1 characters, $2 bytes")->format(done->length(), bytes->size()))
RETURN (SUCCESS)
}
}
The last line prints 10 characters, 11 bytes: the ë is one character and two bytes of UTF-8.