Skip to content
Try Kata

dsa.arr

Growable arrays with checked indexing, optional access, and iteration.

All modules · Writing docstrings

import core.{Opt, GetItem, SetItem, ToBin}
import mem.{Ptr, Buf, heap}
kind Arr[T]

A growable sequence of values of type T. len counts initialized elements. Use get for optional access or brackets for access that stops on an invalid index.

let values = Arr[Int].new()
values.push(10)
values.push(20)
print(values.len)
print(values.pop().unwrap())
print(values.get(8).unwrap_or(-1))
2
20
-1

Source, line 25

buf: Buf[T]

Backing buffer. Changing it directly can violate the array’s invariants.

Source, line 27

len: Int

Number of live elements, from zero through the buffer capacity.

Source, line 29

impl Arr[@T]

Source, line 32

func new(): Arr[T]

Create an empty array with an initial capacity of four.

Source, line 34

func push(self, val: T)

Append val, growing the backing allocation when full. Mutates the array.

Source, line 44

func pop(self): Opt[T]

Remove and return the last value, or Non if empty.

Source, line 55

func get(self, index: Int): Opt[T]

Return the indexed value, or Non for a negative or out-of-range index.

Source, line 64

func set(self, index: Int, val: T): Bool

Replace an existing element. Return false without writing if the index is invalid.

let values = [10, 20]
print(values.set(1, 30))
print(values[1])
print(values.set(9, 50))
true
30
false

Source, line 84

kind ArrIter[T]

An array iterator. Avoid changing the source array while iterating.

Source, line 94

arr: Arr[T]

Array value used by this iterator.

Source, line 96

idx: Int

Index of the next element to visit.

Source, line 98

impl ArrIter[@T] as Iter[T]

Source, line 101

func next(self): Opt[T]

Yield the next element and advance, or return Non after the last element.

Source, line 103

impl Arr[@T] as GetItem[Int, T]

Source, line 113

func get_item(self, key: Int): T

Implement array[key]. Stop with an error when key is outside 0..len.

Source, line 115

impl Arr[@T] as SetItem[Int, T]

Source, line 123

func set_item(self, key: Int, val: T)

Implement array[key] = val. Stop with an error for an invalid index.

Source, line 125

impl Arr[@T] as ToIter[T]

Source, line 133

func to_iter(self): ArrIter[T]

Create an iterator starting at the first element.

Source, line 135

impl Arr[Byte] as ToBin

Source, line 140

func to_bin(self): Bin

Copy the live bytes into an immutable byte string. Available on Arr[Byte].

Source, line 142