Strings and Collections
The standard library supplies owned strings and heap-backed containers. Their APIs follow Rock’s ownership model: shared methods inspect without taking ownership, mutable methods require an exclusive borrow, and consuming transformations move elements into a new result. The prelude exports String, Vec, HashMap, Box, Arc, and Option; specialized string search helpers are imported explicitly below.
String and &Str
&Str is a borrowed string slice. String owns a null-terminated heap buffer. Construct an owner when data must outlive the expression that supplied the slice, and keep a slice when a function only needs to inspect text.
describe: &Str -> String
describe = value -> String::from value
main = !->
name = "Rock"
owned = describe name
empty = String::new!
number = 42.show!
copy = owned.clone!
length = owned.len!
view = owned.as_str!
combined = owned.concat number
message = "Hello, " + "Rock" + "!"
empty.len!.println!
%println copy, "\n", length, "\n", view, "\n", combined, "\n", message
The output is 0, Rock, 4, Rock, Rock42, and Hello, Rock! on separate lines. String::from converts through the From trait, while String::new! constructs an empty string; len! reads a byte count and as_str! borrows a string view. clone! makes a second owner. owned.concat number borrows its receiver owned, consumes the argument number, and returns a new owner. Because owned remains alive, view can still be printed after concatenation. The + implementations cover String and &Str combinations and also return a new String.
Both string types contain valid UTF-8. Char is a 32-bit Unicode scalar value, and converting it to String encodes one to four UTF-8 bytes. Lengths and search offsets count bytes, not Unicode scalars or displayed characters. Strings can contain embedded NUL bytes; their stored length includes these bytes, and println! prints the whole string. C functions that consume null-terminated strings still stop at the first NUL.
Borrowed strings also expose len!, is_empty!, and as_bytes! directly:
main = !->
text = "aé🦀"
text.len!.println!
"".is_empty!.println!
bytes = text.as_bytes!
bytes.len!.println!
bytes[0].println!
This prints 7, true, 7, and 97. The byte view borrows the same storage without allocating or copying; keep its source alive while using it.
Raw sequence pointers
For low-level interoperation, arrays and slices expose as_ptr!, and mutable arrays and slices expose as_mut_ptr!. These methods point into the original storage, including the start of a subslice; they do not copy elements. Prefer ordinary indexing unless a raw pointer is needed, and use an unsafe block to dereference one:
main = !->
mut values = [10, 20]
before = values.as_ptr!
(unsafe *before).println!
ptr = values.as_mut_ptr!
unsafe *ptr = 42
values[0].println!
text = "Rock"
text_ptr = text.as_ptr!
(unsafe *text_ptr).println!
This prints 10, 42, and 82. Do not dereference a pointer from an empty sequence, use it after its backing storage is destroyed or moved, or access outside the sequence bounds. The &Str.as_ptr! method likewise exposes UTF-8 bytes; it does not promise a null-terminated string.
UTF-8 range indexing
Use a borrowed range to select text from either &Str or String:
main = !->
text = "aé中🦀z"
owned = String::from text
(&text[1..3]).println!
(&owned[3..6]).println!
(&text[6..=9]).println!
(&owned[..1]).println!
(&text[10..]).println!
(&owned[..]).println!
(&text[11..11]).len!.println!
The output is é, 中, 🦀, a, z, aé中🦀z, and 0. start..end excludes end; start..=end includes that byte, so the checked end boundary is end + 1. The forms ..end, ..=end, start.., and .. work too. Empty slices at valid boundaries, including the end of a string, are allowed.
The operation borrows the original text without allocating. The owner must remain alive while the slice is used. Negative offsets, reversed or out-of-bounds ranges, and endpoints inside a multi-byte encoding terminate the program with an error, just as invalid collection indexes do. For example, byte offset 2 in the text above is inside é; it is not a valid slice boundary. str_is_char_boundary text, offset checks a byte boundary without terminating.
String indexing uses the standard library’s Index Range implementations. There is no integer Index or mutable IndexMut implementation for strings: arbitrary byte mutation could invalidate UTF-8. Borrow bytes explicitly when byte-level inspection is intended.
Unicode scalar access
str_char_at and String::char_at return Option Char using a zero-based scalar index. A negative index or an index past the last scalar returns None.
main = !->
text = "aé中🦀"
owned = String::from text
str_char_at text, 1 .println!
owned.char_at 3 .println!
owned.char_at 4 .println!
String::from '中' .len!.println!
bytes = owned.as_bytes!
bytes[1].println!
str_is_char_boundary text, 2 .println!
This prints Some(é), Some(🦀), None, 3, 195, and false. Scalar lookup scans from the beginning, so its cost grows with the requested index. Byte-range slicing and boundary checks take constant time. Integer-to-Char casts accept only Unicode scalars (0..=0x10FFFF, excluding surrogates 0xD800..=0xDFFF) and trap for invalid values before narrowing.
A scalar is not necessarily a whole displayed character: a letter followed by a combining accent consists of two scalars. These APIs do not perform grapheme segmentation, normalization, or locale-sensitive comparison.
Iterating over UTF-8 text
Both &Str and String provide chars! and char_indices!. They create small borrowing cursors without allocating a collection. chars! yields Char values; char_indices! yields (I64, Char) pairs whose first component is the character’s starting byte offset.
main = !->
text = String::from "aé🦀"
for_each text.chars!, (!.println!)
for (offset, ch) in text.char_indices!
%println offset, "\n", ch
text.println!
The first traversal prints a, é, and 🦀 on separate lines. The second prints offsets 0, 1, and 3, each followed by its character on the next line. The final line prints aé🦀: traversal borrowed the owner rather than consuming it. Keep the owner alive while a cursor exists.
Each call creates a fresh cursor. Advancing through the entire text takes linear time in its byte length, and break stops decoding immediately. To advance manually, use next! on a mutable cursor; it returns Option Char or Option (I64, Char) and remains exhausted after reaching the end:
main = !->
mut cursor = "é🦀".chars!
cursor.next!.println!
for ch in cursor
ch.println!
mut empty = "".chars!
empty.next!.println!
This prints Some(é), 🦀, and None. The loop consumes the remaining cursor state, starting after é. Chars and CharIndices implement FoldableValue, so manual advancement, folding, for_each, and for..in share the same UTF-8 decoder. As with char_at, the items are Unicode scalars, not grapheme clusters.
Validating bytes
Use String::from_utf8 for input that might not be UTF-8. It returns Some String after validation and copying, or None for invalid bytes. Validation rejects incomplete sequences, unexpected continuation bytes, overlong encodings, surrogates, and values beyond U+10FFFF.
main = !->
valid = [195 as U8, 169 as U8]
invalid = [255 as U8]
String::from_utf8 (&valid) .println!
String::from_utf8 (&invalid) .println!
is_utf8 (&invalid) .println!
This prints Some(é), None, and false. is_utf8 validates without allocating. String::from also accepts byte slices but terminates with invalid UTF-8 when validation fails; prefer from_utf8 for recoverable input errors. The unsafe String::from_c_str requires a readable null-terminated allocation and also validates its bytes. Raw borrowed-string construction in unsafe code must uphold UTF-8 validity and the lifetime of its backing allocation.
String methods
Borrowed strings (&Str) carry the searching, splitting, trimming and parsing methods; String offers the same methods by forwarding to its contents. Offsets and lengths are in bytes. Methods that return &Str borrow from the original text, while methods that return String or Vec String allocate new strings.
main = !->
line = " name = Rock "
trimmed = line.trim!
trimmed.println!
(trimmed.starts_with "name").println!
(trimmed.find "=").println!
match trimmed.split_once " = "
Some pair =>
pair.0.println!
pair.1.to_uppercase!.println!
None => "no separator".println!
words = "red green blue".split_whitespace!
(words.join ", ").println!
("1,2,,3".split ",").len!.println!
("a-b-c".replace "-", "+").println!
("42".parse_i64!).println!
("4x".parse_i64!).println!
This prints name = Rock, true, Some(5), name, ROCK, red, green, blue, 4, a+b+c, Some(42) and None, each on its own line.
| Purpose | Methods |
|---|---|
| Searching | contains, find, rfind, starts_with, ends_with, matches_count |
| Splitting | split, splitn, split_once, rsplit_once, lines, split_whitespace; Vec String has join |
| Borrowed pieces | trim, trim_start, trim_end, strip_prefix, strip_suffix, substr |
| New strings | replace, replacen, repeat, to_uppercase, to_lowercase, to_string |
| Counting and comparing | char_count, eq_ignore_ascii_case, < and the other comparisons on String |
| Parsing | parse_i64, parse_f64, parse_bool, each returning an Option; try_into returns a Result with the reason, such as "4x".try_into! giving Err(InvalidDigit) for an I64 |
find and rfind return a byte offset. split keeps empty pieces, and an empty separator yields the whole text as a single piece. substr start, len returns None when the range is out of bounds or cuts a character in half. to_uppercase and to_lowercase only change ASCII letters for now.
A String can also be built in place. These methods need a mutable binding:
main = !->
mut text = String::with_capacity 16
text.push_str "Rock"
text.push '!'
text.insert_str 0, "Hello, "
text.println!
text.pop!.println!
text.truncate 5
text.println!
text.clear!
text.len!.println!
This prints Hello, Rock!, Some(!), Hello and 0. truncate and insert_str take byte offsets and stop the program when the offset is not on a character boundary.
Char has classification helpers: is_whitespace (Unicode), plus the ASCII-only is_digit, is_alphabetic, is_alphanumeric, is_uppercase, is_lowercase, to_ascii_uppercase, to_ascii_lowercase, to_digit radix and len_utf8.
byte_at reads one byte from a byte slice and terminates on an out-of-range index.
Vec T
Vec T is a growable owned sequence. A mutable receiver method requires a mutable binding. get returns Option &T for a checked lookup; set replaces an existing element; swap_remove removes an element by moving the last element into its position.
main = !->
mut values = Vec::new!
values.push 10
values.push 20
values.push 30
view = values.as_slice!
view.println!
values.set 1, 99
match values.get 1
Option::Some value => value.println!
Option::None => -1 .println!
match values.swap_remove 0
Option::Some value => value.println!
Option::None => -1 .println!
values.len!.println!
The output is [10, 20, 30], 99, 10, and 2. as_slice! borrows the vector, so do not keep that borrow live across push, set, or swap_remove. swap_remove does not preserve order: after removing index 0, the old final element occupies that position.
Consuming and borrowing transformations
The callback type tells you whether an operation moves elements or borrows them. map, filter, and filter_map consume the source; map_ref, for_each, and retain borrow elements while processing them. try_map consumes the source and stops at the first Result::Err.
main = !->
mut source = Vec::new!
source.push 1
source.push 2
source.push 3
mapped = source.map (+ 1)
mut borrowed_source = Vec::new!
borrowed_source.push 4
borrowed_source.push 5
references = borrowed_source.map_ref (+ 1)
borrowed_source.for_each (!.println!)
mut filtered_source = Vec::new!
filtered_source.push 1
filtered_source.push 2
filtered_source.push 3
filtered = filtered_source.filter (% 2 == 0)
mut retained_source = Vec::new!
retained_source.push 1
retained_source.push 2
retained_source.push 3
retained_source.retain (% 2 == 0)
mut optional_source = Vec::new!
optional_source.push -1
optional_source.push 2
optional_source.push 3
positives = optional_source.filter_map value ->
if value > 0
then Option::Some value
else Option::None
mut checked_source = Vec::new!
checked_source.push 4
checked_source.push 5
checked = checked_source.try_map value ->
if value >= 0
then Result::Ok value
else Result::Err 1
%println mapped, "\n", references, "\n", filtered, "\n", retained_source, "\n", positives
checked.unwrap_or Vec::new! .println!
The first map moves source, while map_ref leaves borrowed_source available after the callback. The output is 4, 5, [2, 3, 4], [5, 6], [2], [2], [2, 3], and [4, 5] on separate lines; the first two lines come from for_each. try_map returns Ok here. If a callback returns Err 1, later source elements are not mapped and the original source is consumed.
map_ref and retain pass shared references to their callbacks. Their operator sections still work: (+ 1) means value -> value + 1, and (% 2 == 0) means value -> value % 2 == 0. The integer + and % implementations use shared receivers, and method lookup adjusts the borrowed left operand to select them. No explicit *value is needed; the parameter remains &I64. See operators on borrowed values.
The concrete methods above are the supported everyday Vec surface. Higher-kinded traversal interfaces are still evolving and are intentionally not expanded here. Vec has no Applicative or Monad implementation: choosing Cartesian application would require cloning, while choosing zipped application would not have list-monad semantics.
HashMap K, V
HashMap K, V requires Hash and Eq for keys. The current map supports construction, length, insertion, checked lookup, and key containment.
main = !->
mut scores = HashMap::new!
scores.insert 10, 100
scores.insert 20, 200
ten = 10
twenty = 20
thirty = 30
scores.contains_key &ten .println!
scores.contains_key &thirty .println!
match scores.get &ten
Option::Some score => score.println!
Option::None => -1 .println!
match scores.get &twenty
Option::Some score => score.println!
Option::None => -1 .println!
scores.len!.println!
The output is true, false, 100, 200, and 2. ten, twenty, and thirty are borrowed as probe keys, so the caller retains ownership. The implementation uses open addressing and grows near a 75 percent load factor. Removal, iteration, entry APIs, and configurable hashers are not currently public.
Box T
Box::new moves one value into a single owned heap allocation. as_ref! borrows it, as_mut! permits mutation through a mutable binding, and Deref forwards * access. Boxing is useful for stable indirection or recursive ownership; it is not a default replacement for a local value.
struct Point
< x: I64
< y: I64
main = !->
point = Point
x: 3
y: 4
mut boxed = Box::new point
mutable_view = boxed.as_mut!
mutable_view.x = 5
view = boxed.as_ref!
%println view.x, "\n", view.y
(*boxed).x.println!
The output is 5, 4, and 5 on separate lines. point is moved into boxed; as_mut! changes the owned value through an exclusive borrow, as_ref! creates a shared view, and *boxed uses Deref. The box drops its value and allocation when boxed leaves scope.
Querying a value’s size
sizeof borrows a value and returns the byte size of its type as an I64. It does not move or drop the value, and the result includes any padding required by the target’s layout. The type must implement Sized.
struct Point
< x: I64
< y: I64
main = !->
point = Point
x: 3
y: 4
(sizeof &point).println!
%println point.x, "\n", point.y
On a 64-bit target, the output is 16, 3, and 4 on separate lines. The shared borrow leaves point available for later use. sizeof measures the value’s representation, not any separately allocated memory it owns; for example, measuring a vector does not include its element buffer.
When allocating storage before a value exists, use sizeof_pointee with a typed raw pointer. The pointer supplies the type; the function does not read memory, so a null pointer is sufficient:
struct Point
< x: I64
< y: I64
main = !->
pointer = 0 as *Point
(sizeof_pointee pointer).println!
This prints 16 on a 64-bit target without dereferencing pointer. To measure the pointer itself instead, use sizeof &pointer. Both functions are available through the prelude and through std::mem.
Arc T
Arc::new creates atomic shared ownership. clone! increments the reference count, but Arc does not make the contained value mutable. Combine it with Mutex T when multiple owners must update shared state.
main = !->
state = Arc::new String::from "shared"
worker_copy = state.clone!
*state .println!
*worker_copy .println!
The output is shared twice. Both Arc values point at the same owned string; dropping the final owner releases the allocation. A mutable String cannot be obtained from an Arc String without a separate synchronization design.
Current resource limits
Regression tests cover Vec and HashMap element cleanup during destruction, replacement, and growth. Zero-sized Vec elements and HashMap keys or values are still rejected on insertion. Treat the prototype’s resource behavior as an explicit current limit, not as a production boundary for long-running memory-heavy programs.