Module

std::vector

Vector Module

Growable contiguous array backed by std::memory.

Overview

Vector<T> stores elements in a contiguous heap allocation and grows capacity geometrically (x2) when needed.

  • length is the number of initialized elements
  • capacity is the number of elements that can be stored without reallocating
  • data points to the first element (or null when empty)

Memory Layout

  Vector<T>
  ┌──────────────┐
  │ data ────────┼──────► ┌───┬───┬───┬───┬───┬───┬───┬───┐
  │ length: 5    │        │ 0 │ 1 │ 2 │ 3 │ 4 │   │   │   │
  │ capacity: 8  │        └───┴───┴───┴───┴───┴───┴───┴───┘
  └──────────────┘        ◄── initialized ──►◄─ reserved ─►

Growth Strategy

When push() is called and length == capacity, the vector doubles its backing storage (or allocates 1 slot if currently empty):

  push() when length == capacity
  ┌──────────────────────────────────────────────────────────────────────┐
  │ old capacity = N                                                     │
  │ new capacity = max(1, N * 2)                                         │
  │ reallocate buffer to new capacity                                    │
  └──────────────────────────────────────────────────────────────────────┘

  Example:
    cap=0 → push → cap=1
    cap=1 → push → cap=2
    cap=2 → push → cap=4
    cap=4 → push → cap=8

Higher-Order Methods

Vector provides callback-based operations for functional-style iteration, filtering, transformation, and aggregation:

Method Signature Description
forEach (&T) -> void Iterate elements by immutable ref
forEachMut (&mut T) -> void Iterate elements by mutable ref
filter (&T) -> booleanVector<T> Keep matching elements
any (&T) -> booleanboolean Short-circuit existential check
all (&T) -> booleanboolean Short-circuit universal check
findIndex (&T) -> booleanOption<u64> Index of first match
count (&T) -> booleanu64 Count matching elements
reduce (T, &T) -> TOption<T> Fold without initial value
sort (&T, &T) -> i32 In-place insertion sort
map<U> (&T) -> UVector<U> Transform each element
fold<U> U, (U, &T) -> UU Fold with initial value

All callbacks are @noescape: the closure must not outlive the method call.

Safety Notes

This container performs manual memory management and raw pointer writes. It does not run element destructors automatically.

The vector implements Drop and will automatically release its backing storage when it goes out of scope.

Example

import Vector from "std::vector";
import String from "std::string";
import Io from "std::io";

function main(): i32 {
  let mut values: Vector<i32> = Vector::new<i32>();
  values.push(10);
  values.push(20);
  values.push(30);

  // Functional-style: double every even element, then sum
  let sum: i32 = values
    .filter((x: &i32): boolean -> { return *x % 2 == 0; })
    .map<i32>((x: &i32): i32 -> { return *x * 2; })
    .fold<i32>(0, (acc: i32, x: &i32): i32 -> { return acc + *x; });

  // Vector is automatically dropped here
  return 0;
}

Records

record Vector<T>

Growable contiguous array of T.

Example

import Vector from "std::vector";

function main(): i32 {
  let mut values: Vector<i32> = Vector::new<i32>();
  values.push(1);
  values.push(2);
  // Vector is automatically dropped here
  return 0;
}
Members
data: *mut T

Pointer to the backing storage (or null when empty).

length(&self): u64

Returns the current number of elements.

Example

import Vector from "std::vector";

let mut v: Vector<i32> = Vector::new<i32>();
v.push(10);
let len: u64 = v.length();
capacity(&self): u64

Returns the currently reserved capacity.

Example

import Vector from "std::vector";

let v: Vector<i32> = Vector::new<i32>(8);
let cap: u64 = v.capacity();
static init(capacity: u64): Vector<T>

Compatibility alias for Vector::new(capacity).

static init(capacity: u64): Vector<T>

Compatibility alias for Vector::new(capacity).

static new(capacity: u64): Vector<T>

Creates an empty vector with preallocated capacity elements.

Example

import Vector from "std::vector";

let v: Vector<i32> = Vector::new<i32>(16);
static new(capacity: u64): Vector<T>

Creates an empty vector with preallocated capacity elements.

Example

import Vector from "std::vector";

let v: Vector<i32> = Vector::new<i32>(16);
all(&self, predicate: fn(&T) -> boolean): boolean

Returns true if predicate returns true for every element.

Short-circuits: stops iterating as soon as a non-match is found. Returns true for an empty vector (vacuous truth).

Arguments

  • predicate - Callback that receives &T and returns true/false.

Example

import Vector from "std::vector";

let mut v: Vector<i32> = Vector::new<i32>();
v.push(2);
v.push(4);
v.push(6);

let allEven: boolean = v.all((x: &i32): boolean -> { return *x % 2 == 0; });
// allEven == true

v.push(7);
let stillAllEven: boolean = v.all((x: &i32): boolean -> { return *x % 2 == 0; });
// stillAllEven == false (stops at 7)
any(&self, predicate: fn(&T) -> boolean): boolean

Returns true if predicate returns true for at least one element.

Short-circuits: stops iterating as soon as a match is found. Returns false for an empty vector.

Arguments

  • predicate - Callback that receives &T and returns true/false.

Example

import Vector from "std::vector";

let mut v: Vector<i32> = Vector::new<i32>();
v.push(1);
v.push(3);
v.push(5);

let hasEven: boolean = v.any((x: &i32): boolean -> { return *x % 2 == 0; });
// hasEven == false

v.push(4);
let hasEven2: boolean = v.any((x: &i32): boolean -> { return *x % 2 == 0; });
// hasEven2 == true (stops at 4, never checks beyond)
asMutPtr(&mut self): *mut T

Returns the backing pointer as mutable raw pointer.

Example

import Vector from "std::vector";

let mut v: Vector<i32> = Vector::new<i32>();
v.push(10);
let ptr: *mut i32 = v.asMutPtr();
asPtr(&self): *T

Returns the backing pointer as immutable raw pointer.

Example

import Vector from "std::vector";

let mut v: Vector<i32> = Vector::new<i32>();
v.push(10);
let ptr: *i32 = v.asPtr();
capacity(&self): u64

Returns the currently reserved capacity.

Example

import Vector from "std::vector";

let v: Vector<i32> = Vector::new<i32>(8);
let cap: u64 = v.capacity();
clear(&mut self): void

Removes all logical elements without releasing capacity.

Example

import Vector from "std::vector";

let mut v: Vector<i32> = Vector::new<i32>();
v.push(1);
v.push(2);
v.clear();
count(&self, predicate: fn(&T) -> boolean): u64

Returns the number of elements for which predicate returns true.

Always iterates the entire vector.

Arguments

  • predicate - Callback that receives &T and returns true/false.

Returns

The count of matching elements (0 if none match or the vector is empty).

Example

import Vector from "std::vector";

let mut v: Vector<i32> = Vector::new<i32>();
v.push(1);
v.push(2);
v.push(3);
v.push(4);

let numEvens: u64 = v.count((x: &i32): boolean -> { return *x % 2 == 0; });
// numEvens == 2
drop(&mut self): void

Releases the backing storage and resets length/capacity to zero.

Called automatically when the vector goes out of scope via @implements(Drop). Can also be called manually to release resources early.

dropElements(&mut self): void
filter(&self, predicate: fn(&T) -> boolean): Vector<T>

Returns a new vector containing only elements for which predicate returns true.

Elements are copied into the result; the original vector is unchanged. Order is preserved.

Arguments

  • predicate - Callback that receives &T and returns true to keep the element, false to discard it.

Returns

A new Vector<T> containing only the matching elements. The caller owns the returned vector.

Example

import Vector from "std::vector";

let mut v: Vector<i32> = Vector::new<i32>();
v.push(1);
v.push(2);
v.push(3);
v.push(4);

let evens: Vector<i32> = v.filter((x: &i32): boolean -> {
  return *x % 2 == 0;
});
// evens is [2, 4]
findIndex(&self, predicate: fn(&T) -> boolean): Option<u64>

Returns the index of the first element for which predicate returns true, or Option::NONE if no element matches.

Short-circuits: stops iterating at the first match.

Arguments

  • predicate - Callback that receives &T and returns true/false.

Returns

Option::SOME(index) for the first matching element, or Option::NONE.

Example

import Vector from "std::vector";
import Option from "std::option";

let mut v: Vector<i32> = Vector::new<i32>();
v.push(10);
v.push(20);
v.push(30);

let idx: Option<u64> = v.findIndex((x: &i32): boolean -> { return *x == 20; });
// idx == Option::SOME(1)

let missing: Option<u64> = v.findIndex((x: &i32): boolean -> { return *x == 99; });
// missing == Option::NONE
fold(&self, initial: U, f: fn(U, &T) -> U): U

Folds the vector left-to-right starting from an explicit initial value.

The accumulator starts at initial. For each element, f is called with (accumulator, &element), and its return value becomes the new accumulator. The final accumulator is returned.

Type Parameters

  • U - The type of the accumulator and the return value. Can differ from T.

Arguments

  • initial - Starting value for the accumulator.
  • f - Callback that combines the accumulator with each element.

Returns

The final accumulated value. Returns initial unchanged if the vector is empty.

Example

import Vector from "std::vector";

let mut v: Vector<i32> = Vector::new<i32>();
v.push(1);
v.push(2);
v.push(3);

// Sum with explicit initial value
let sum: i32 = v.fold<i32>(0, (acc: i32, x: &i32): i32 -> {
  return acc + *x;
});
// sum == 6

// Count elements as u64 (different accumulator type)
let count: u64 = v.fold<u64>(0, (acc: u64, _x: &i32): u64 -> {
  return acc + 1;
});
// count == 3

See Also

Use reduce when the accumulator type is the same as T and you want to use the first element as the initial value.

forEach(&self, f: fn(&T) -> void): void

Calls f with an immutable reference to each element, in order.

The callback receives &T (immutable reference), so the vector cannot be modified during iteration.

Arguments

  • f - Callback invoked once per element with &T.

Example

import Vector from "std::vector";
import Io from "std::io";

let mut v: Vector<i32> = Vector::new<i32>();
v.push(10);
v.push(20);
v.push(30);

// Print each element
v.forEach((x: &i32): void -> {
  Io::printI32(*x);
});
// Output: 10 20 30
forEachMut(&mut self, f: fn(&mut T) -> void): void

Calls f with a mutable reference to each element, in order.

The callback receives &mut T, allowing in-place modification of every element without allocating a new vector.

Arguments

  • f - Callback invoked once per element with &mut T.

Example

import Vector from "std::vector";

let mut v: Vector<i32> = Vector::new<i32>();
v.push(1);
v.push(2);
v.push(3);

// Double every element in-place
v.forEachMut((x: &mut i32): void -> {
  *x = *x * 2;
});
// v is now [2, 4, 6]
get(&self, index: u64): Option<&T>

Returns an immutable reference to index, if it exists.

Example

import Vector from "std::vector";
import Option from "std::option";

let mut v: Vector<i32> = Vector::new<i32>();
v.push(9);
let item: Option<&i32> = v.get(0);
getMut(&mut self, index: u64): Option<&mut T>

Returns a mutable reference to index, if it exists.

Example

import Vector from "std::vector";
import Option from "std::option";

let mut v: Vector<i32> = Vector::new<i32>();
v.push(1);
let item: Option<&mut i32> = v.getMut(0);
grow(&mut self): void

Grows the backing storage using geometric doubling.

If capacity is 0 it becomes 1, otherwise it doubles. Allocates a new buffer (or reallocates the existing one) via Memory::allocateVector / Memory::reallocateVector.

isEmpty(&self): boolean

Returns true when length == 0.

Example

import Vector from "std::vector";

let v: Vector<i32> = Vector::new<i32>();
let empty: boolean = v.isEmpty();
length(&self): u64

Returns the current number of elements.

Example

import Vector from "std::vector";

let mut v: Vector<i32> = Vector::new<i32>();
v.push(10);
let len: u64 = v.length();
map(&self, f: fn(&T) -> U): Vector<U>

Returns a new vector by applying f to each element.

Each element is passed by immutable reference (&T). The callback returns a value of type U, which is pushed into the result vector. The result is pre-allocated to self.length() capacity.

Type Parameters

  • U - The element type of the output vector. Can be the same as T or a completely different type.

Arguments

  • f - Transformation callback from &T to U.

Returns

A new Vector<U> of the same length. The caller owns the result.

Example

import Vector from "std::vector";

let mut v: Vector<i32> = Vector::new<i32>();
v.push(1);
v.push(2);
v.push(3);

// Square each element (same type: i32 -> i32)
let squared: Vector<i32> = v.map<i32>((x: &i32): i32 -> {
  return *x * *x;
});
// squared is [1, 4, 9]

// Convert to booleans (different type: i32 -> boolean)
let isEven: Vector<boolean> = v.map<boolean>((x: &i32): boolean -> {
  return *x % 2 == 0;
});
// isEven is [false, true, false]
pop(&mut self): Option<T>

Removes and returns the last element, or Option::NONE if empty.

Example

import Vector from "std::vector";
import Option from "std::option";

let mut v: Vector<i32> = Vector::new<i32>();
v.push(7);
let x: Option<i32> = v.pop();
push(&mut self, value: T): void

Appends value at the end of the vector.

Example

import Vector from "std::vector";

let mut v: Vector<i32> = Vector::new<i32>();
v.push(42);
pushUninitialized(&mut self): *mut T
reduce(&self, f: fn(T, &T) -> T): Option<T>

Folds the vector left-to-right without an explicit initial value.

The first element is copied as the initial accumulator. Then f is called for each subsequent element with (accumulator, &element), and its return value becomes the new accumulator.

Returns Option::NONE for an empty vector.

Arguments

  • f - Callback that takes the accumulator by value and the next element by reference, and returns the updated accumulator.

Returns

Option::SOME(result) with the final accumulated value, or Option::NONE if the vector is empty.

Example

import Vector from "std::vector";
import Option from "std::option";

let mut v: Vector<i32> = Vector::new<i32>();
v.push(1);
v.push(2);
v.push(3);

// Sum all elements: 1 + 2 + 3 = 6
let sum: Option<i32> = v.reduce((acc: i32, x: &i32): i32 -> {
  return acc + *x;
});
// sum == Option::SOME(6)

// Empty vector returns NONE
let empty: Vector<i32> = Vector::new<i32>();
let result: Option<i32> = empty.reduce((acc: i32, x: &i32): i32 -> {
  return acc + *x;
});
// result == Option::NONE

See Also

Use fold<U> if you need an explicit initial value or a different return type.

set(&mut self, index: u64, value: T): boolean

Replaces the element at index.

Returns false when index is out of bounds.

sort(&mut self, compare: fn(&T, &T) -> i32): void

Sorts the vector in-place using a comparator.

Uses insertion sort, which is simple, stable, and efficient for small-to-moderate sizes. For large vectors a different algorithm may be preferable.

Arguments

  • compare - Comparator callback that receives two &T references and returns:
    • negative (< 0) if a < b
    • zero (0) if a == b
    • positive (> 0) if a > b

Stability

The sort is stable: elements that compare equal retain their original relative order.

Example

import Vector from "std::vector";

let mut v: Vector<i32> = Vector::new<i32>();
v.push(30);
v.push(10);
v.push(20);

// Sort ascending
v.sort((a: &i32, b: &i32): i32 -> { return *a - *b; });
// v is now [10, 20, 30]

// Sort descending
v.sort((a: &i32, b: &i32): i32 -> { return *b - *a; });
// v is now [30, 20, 10]
toSlice(&self): T[]

Returns a non-owning slice view over initialized elements.

The returned T[] borrows the vector storage. It does not own, copy, or extend the lifetime of the elements. Do not mutate the vector in a way that may reallocate while the slice is live.