Growing buffers

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


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.


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)


Adds a single element to the buffer.

func add(elem : X)


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

func removeLast() : ?X


Adds all elements in buffer b to this buffer.

func append(b : Buffer<X>)


Returns the current number of elements.

func size() : Nat


Resets the buffer.

func clear()


Returns a copy of this buffer.

func clone() : Buffer<X>


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

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


Creates a new array containing this buffer’s elements.

func toArray() : [X]


Creates a mutable array containing this buffer’s elements.

func toVarArray() : [var X]


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

func get(i : Nat) : X


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


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)