Buffer

Growing buffers

This module defines buffers that grow, with a general element type.

Why?

Motoko applications expose interfaces that use fixed-size arrays of general (user-defined) elements to represent sets, sequences and maps of application-specific elements.

The Array module focuses on Motoko’s builtin arrays, whose size is each fixed. They do not permit general growth/appending, which is the focus here.

To create these arrays, and to consume them with ergonomic (imperative) code, and low API friction, developers need buffers that grow.

Define Buf<X> object type

A "buffer" is a mutable sequence that grows, either one element at a time, or one (second) buffer at time.

Buffer

Create a buffer represented internally by an mutable array.

The argument initCapacity gives the initial capacity. Under the interface, the mutable array grows by doubling when this initial capacity is exhausted.

class Buffer<X>(initCapacity : Nat)

add

Adds a single element to the buffer.

func add(elem : X)

removeLast

Removes the item that was inserted last and returns it or null if no elements had been added to the Buffer.

func removeLast() : ?X

append

Adds all elements in buffer b to this buffer.

func append(b : Buffer<X>)

size

Returns the current number of elements.

func size() : Nat

clear

Resets the buffer.

func clear()

clone

Returns a copy of this buffer.

func clone() : Buffer<X>

vals

Returns an [Iter](Iter.html#type.Iter) over the elements of this buffer.

func vals() : { next : () -> ?X }

toArray

Creates a new array containing this buffer’s elements.

func toArray() : [X]

toVarArray

Creates a mutable array containing this buffer’s elements.

func toVarArray() : [var X]

get

Gets the i-th element of this buffer. Traps if i >= count. Indexing is zero-based.

func get(i : Nat) : X

getOpt

Gets the 'i'-th element of the buffer as an option. Returns null when i >= count. Indexing is zero-based.

func getOpt(i : Nat) : ?X

put

Overwrites the current value of the i-entry of this buffer with elem. Traps if the index is out of bounds. Indexing is zero-based.

func put(i : Nat, elem : X)