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 fixed. Arrays 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 can employ Buffer objects.

Define Buf<X> object type

A "Buffer" is a mutable sequence that can be extended by a single element or the contents of another buffer.

Buffer

class Buffer<X>(initCapacity : Nat)

Create a stateful buffer class encapsulating a mutable array.

The argument initCapacity determines its initial capacity. The underlying mutable array grows by doubling when its current capacity is exceeded.

add

func add(elem : X)

Adds a single element to the buffer.

removeLast

func removeLast() : ?X

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

append

func append(b : Buffer<X>)

Adds all elements in buffer b to this buffer.

size

func size() : Nat

Returns the current number of elements.

clear

func clear()

Resets the buffer.

clone

func clone() : Buffer<X>

Returns a copy of this buffer.

vals

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

Returns an Iter over the elements of this buffer.

toArray

func toArray() : [X]

Creates a new array containing this buffer’s elements.

toVarArray

func toVarArray() : [var X]

Creates a mutable array containing this buffer’s elements.

get

func get(i : Nat) : X

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

getOpt

func getOpt(i : Nat) : ?X

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

put

func put(i : Nat, elem : X)

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.