String
A view borrows, so it can never outlive the bytes it looks at. Text that a function builds and hands back, or that must be kept after its source is gone, needs an owner. That is String: it keeps its own copy of the bytes, in memory it asked an allocator for, and gives that memory back in its destructor when the value's life ends.
Borrowed or owned
StringView | String | |
|---|---|---|
| Holds | a view of someone else's bytes | its own copy of the bytes |
| Making one | free: no copy, no allocation | copies the bytes into allocated memory |
| From bytes | FromBytes answers none if not text | FromBytes throws TextError if not text |
Copied with =? | yes — it is a small borrowed view | no — it is move-only; call Clone |
| Lives | no longer than the bytes it views | as long as the String itself |
| Cleans up | nothing to clean up | its destructor frees the memory |
Where the memory comes from
A String needs an allocator to ask for memory. Main makes the system's allocator and passes it on, and the String keeps it as an Allocator:
let allocator = SystemAllocator();
The allocator itself is the subject of the Memory part. For now it is simply where a String's bytes come from.
Returning text a function made
Reversed builds its letters in a local array, which is gone once the function returns. A view of that array would be left pointing at nothing, so the function returns a String that owns a copy:
func Reversed(allocator: Allocator, word: char8[..]) -> String throws TextError {
var letters: char8[16];
for i in 0..word.length {
letters[i] = word[word.length - 1 - i];
}
return try String::FromBytes(allocator, letters[..word.length]);
}
FromBytes checks that the bytes are text before copying them, so it throws a TextError, and Reversed passes it on with try:
TextError case | When |
|---|---|
InvalidUtf8 | FromBytes was given bytes that are not text |
NotABoundary | a position fell inside a character rather than between two |
Running out of memory is not on the list. A String that cannot get its storage ends the program, as every allocation in a string or a collection does.
The UTF-8 check is not a formality here. Reversed byte by byte, né puts the two bytes of é in the wrong order, and FromBytes throws TextError::InvalidUtf8 rather than make a String that is not text.
Main is a throwing main, func Main() throws TextError, so try passes any such error on and the program exits with status 1:
var word = try Reversed(allocator, "stressed");
PrintLine("word {}, {} bytes", word.View(), word.Length());
A String is printed through its view, word.View().
Copying with Clone
A String owns its memory, so = never copies one: two owners would release the same bytes. let copy = saved; is refused with cannot copy 'String', which owns resources. Copying is always the visible call to Clone, which makes an independent copy with storage of its own:
let saved = word.Clone();
try word.ReplaceWith(Reversed(allocator, "drawer"));
ReplaceWith gives word new text and frees its old bytes. saved has its own copy, so it is untouched: word is now reward, saved is still desserts. The try belongs to Reversed, the call inside that can throw.
Clone cannot throw — like every allocation in a String, it ends the program if memory runs out. Where that must be handled, TryClone throws the allocator's AllocError instead.
Lending a view
Whenever borrowed text is enough, a String lends out a view without copying anything:
let view = saved.View();
PrintLine("view {}, {} characters", view, view.ScalarCount());
The view is valid as long as saved is. No cleanup is written anywhere: word and saved each release their own memory at the end of Main, as the destructor lesson promised.
The program
The whole lesson is one package in the Examples repository. Its comments explain every step.
// A view borrows, so it can never outlive the bytes it looks at. Text that a function builds
// and hands back, or that must be kept after its source is gone, needs an owner. That is
// `String`: it keeps its own copy of the bytes, in memory it asked an allocator for, and gives
// that memory back in its destructor when the value's life ends.
//
// Checking that bytes are UTF-8 can fail, so the calls that make a `String` from bytes declare
// `throws TextError`. `Main` throws here too, and `try` passes any such error on. The allocator
// itself is the subject of the Memory part; for now it is simply where a String's bytes come
// from.
import Allocator::{ Allocator, SystemAllocator };
import Io::PrintLine;
import Text::{ String, TextError };
// The reversed letters exist only in this function's array, which is gone once it returns. A
// view of them would be left pointing at nothing, so the function returns a String that owns
// a copy. `FromBytes` checks the bytes are text before copying them, and that check matters
// here: reversed byte by byte, "né" puts the two bytes of `é` in the wrong order, and the
// call throws `TextError::InvalidUtf8`. The array has room for words of up to 16 bytes.
func Reversed(allocator: Allocator, word: char8[..]) -> String throws TextError {
var letters: char8[16];
for i in 0..word.length {
letters[i] = word[word.length - 1 - i];
}
return try String::FromBytes(allocator, letters[..word.length]);
}
func Main() throws TextError {
let allocator = SystemAllocator();
var word = try Reversed(allocator, "stressed");
PrintLine("word {}, {} bytes", word.View(), word.Length());
// `Clone` makes an independent copy with storage of its own. Replacing the original's text
// afterwards leaves the clone exactly as it was.
let saved = word.Clone();
try word.ReplaceWith(Reversed(allocator, "drawer"));
PrintLine("word {}", word.View());
PrintLine("saved {}", saved.View());
// A String owns its memory, so `=` never copies one: two owners would release the same
// bytes. Copying is always the visible call to `Clone`, and `move` hands the one value over:
//
// let copy = saved;
// error: cannot copy 'String', which owns resources
//
// `Clone` ends the program if memory runs out, as every allocation in a String does.
// `TryClone` throws an `AllocError` instead, for code where that must be handled.
// A String lends out a view whenever borrowed text is enough, without copying anything.
let view = saved.View();
PrintLine("view {}, {} characters", view, view.ScalarCount());
// No cleanup is written: `word` and `saved` each release their own memory at the end of
// `Main`, as the Destructor lesson promised.
}
Besides Io, its Rux.toml lists Allocator and Text under [Dependencies].
Run it
cd Examples/Text/String
rux run
word desserts, 8 bytes
word reward
saved desserts
view desserts, 8 characters
Common mistakes
Try it yourself
- Reverse
"né"and handle the error withtry … catchinstead of passing it on, printing a message of your own. - Make a
Stringfrom a view withString::FromView(allocator, view). - Use
Substring(start, end)to copy the first four bytes ofsavedinto a newString. - Compare
wordandsavedwithEquals, before and afterReplaceWith.
Learn more
- Text in the API reference
- String view — the borrowed form a
Stringlends out - Destructor and Custom copy — how a
Stringfrees its memory, and why it is copied withClone - Allocator — where the memory comes from