RefSliceIterator

public struct RefSliceIterator[T] { /* private fields */ }

Forward iterator yielding SHARED REFERENCES (&T) to contiguous elements in place — no copies, no clones. The by-reference sibling of ArraySliceIterator; surfaced as Array.refs().

Invalidation

Holds a raw pointer into the underlying buffer. Mutating the source collection's STRUCTURE while iterating (append/realloc, removal) invalidates the cursor and any yielded reference — the same contract as every pointer-backed iterator, met through references here.

Representation

A Pointer[T] cursor and an Int64 countdown.

Initializers

public init(ptr: Pointer[T], remaining: Int64)

Builds an iterator from a starting pointer and remaining count.

ImplementsIterator

Associated Types

type Item = &T
type TargetIterator = Self

Methods

public mutating func all(where: (Item) -> Bool) -> Bool

True if every element satisfies predicate. Stops at the first failure. True for an empty iterator (vacuous truth).

Examples

[2, 4, 6].iter().all { it % 2 == 0 }; // true [2, 3, 4].iter().all { it % 2 == 0 }; // false (stops at 3) [].iter().all { false }; // true (empty)
public mutating func any(where: (Item) -> Bool) -> Bool

True if any element satisfies predicate. Stops at the first match. False for an empty iterator.

Examples

[1, 2, 3, 4].iter().any { it > 3 }; // true (stops at 4) [1, 2, 3].iter().any { it > 10 }; // false [].iter().any { true }; // false
public func chain[Other](Other) -> ChainIterator[Self, Other] where Other: Iterator, Other.Item == Item

Yields all of self, then all of other. Both must produce the same Item type.

Examples

[1, 2].iter().chain([3, 4].iter()).collect(); // [1, 2, 3, 4]
public consuming func collect() -> Array[Item]

Drains the iterator into an Array[Item]. Eager and O(n). Use at the end of an adapter chain to materialise the result.

Examples

[1, 2, 3].iter().filter { it > 1 }.collect(); // [2, 3] (1..5).iter().map { it * it }.collect(); // [1, 4, 9, 16]
public func compactMap[T]() -> FilterMapIterator[Self, T] where Item == Optional[T]

Drops Nones and unwraps Somes — the identity-transform special case of filterMap. Available when the iterator already yields optionals.

Examples

let xs: [Int64?] = [.Some(1), .None, .Some(2), .None, .Some(3)]; xs.iter().compactMap().collect(); // [1, 2, 3]
public mutating func contains(Item) -> Bool

True if any element equals element. Short-circuits.

Examples

[1, 2, 3].iter().contains(2); // true [1, 2, 3].iter().contains(5); // false
public consuming func count() -> Int64

Counts the elements by walking the whole iterator. O(n) — for types that already know their length, prefer ExactSizeIterator.remaining.

Examples

[1, 2, 3, 4, 5].iter().filter { it % 2 == 0 }.count(); // 2
public func cycle() -> CycleIterator[Self]

Restarts iteration from the beginning whenever the inner iterator is exhausted, producing an infinite sequence. Always combine with take (or another short-circuiting consumer) — otherwise the result is unbounded.

Examples

[1, 2, 3].iter().cycle().take(7).collect(); // [1, 2, 3, 1, 2, 3, 1]
public func enumerate() -> EnumerateIterator[Self]

Pairs each element with its zero-based position.

Examples

for (i, item) in arr.iter().enumerate() { print("Index \{i}: \{item}") };
public func filter(where: consuming (Item) -> Bool) -> FilterIterator[Self]

Yields only elements where predicate returns true. Lazy — elements are tested as they're pulled.

Examples

[1, 2, 3, 4, 5].iter().filter { it % 2 == 0 }.collect(); // [2, 4]
public func filterMap[U](as: consuming (Item) -> U?) -> FilterMapIterator[Self, U]

Combined map + filter — transform returns Optional[U]; None values are skipped. Use over map(...).filter(...) when the transform itself decides whether the element belongs.

Examples

["1", "two", "3"].iter() .filterMap { Int64.parse(it) } .collect(); // [1, 3]
public mutating func first(where: (Item) -> Bool) -> Item?

First element matching predicate, or None. Stops at the first match.

Examples

[1, 2, 3, 4, 5].iter().first { it > 3 }; // Some(4) [1, 2, 3].iter().first { it > 10 }; // None
public mutating func firstIndex(where: (Item) -> Bool) -> Int64?

Index of the first element matching predicate, or None.

Examples

["a", "b", "c"].iter().firstIndex(where: { it == "b" }); // Some(1) [1, 2, 3].iter().firstIndex(where: { it > 10 }); // None
public func flatMap[U](as: consuming (Item) -> U) -> FlatMapIterator[Self, U] where U: Iterator

Maps each element to an iterator and concatenates the results. The monadic bind for iterators.

Examples

[[1, 2], [3, 4], [5]].iter() .flatMap { it.iter() } .collect(); // [1, 2, 3, 4, 5] // Conditional expand — drop odd, double even [1, 2, 3].iter() .flatMap { if it % 2 == 0 { [it, it].iter() } else { [].iter() } } .collect(); // [2, 2]
public func flatten() -> FlattenIterator[Self]

Concatenates the inner iterators into one flat stream. Each inner iterator is fully drained before moving to the next. The already-have-iterators counterpart of flatMap.

Examples

let nested = [[1, 2], [3, 4], [5]].iter().map { it.iter() }; nested.flatten().collect(); // [1, 2, 3, 4, 5]
public consuming func fold[Acc](from: Acc, by: (Acc, Item) -> Acc) -> Acc

Left fold — start at initial and walk left to right, applying combine(acc, element). Returns initial for an empty iterator.

Examples

[1, 2, 3, 4].iter().fold(from: 0) { (acc, x) in acc + x }; // 10 [1, 2, 3].iter().fold(from: 1) { (acc, x) in acc * x }; // 6 [].iter().fold(from: 42) { (acc, x) in acc + x }; // 42
public consuming func forEach((Item) -> ())

Calls action on every element, discarding return values. Use tryForEach if you need to short-circuit on failure.

Examples

[1, 2, 3].iter().forEach { print(it) };
public func fuse() -> FusedIterator[Self]

Locks None once seen — protects against iterators that aren't fused (i.e. that may produce more elements after returning None once). After the first None, this adapter returns None forever.

public func inspect(consuming (Item) -> ()) -> InspectIterator[Self]

Calls inspector on each element as it flows through, leaving the value otherwise untouched. Useful for logging or instrumenting an adapter chain mid-pipeline.

Examples

[1, 2, 3].iter() .inspect { print("before filter: \{it}") } .filter { it > 1 } .inspect { print("after filter: \{it}") } .collect();
public func intersperse(with: Item) -> IntersperseIterator[Self]

Inserts separator between consecutive elements. Empty inputs stay empty; single-element inputs get no separator.

Examples

[1, 2, 3].iter().intersperse(with: 0).collect(); // [1, 0, 2, 0, 3]
public func intersperseWith(with: consuming () -> Item) -> IntersperseWithIterator[Self]

Like intersperse, but builds each separator on demand by calling separator(). Use when the separator is expensive or needs to vary by call.

Examples

var counter = 0; [1, 2, 3].iter() .intersperseWith { counter += 1; counter * 10 } .collect(); // [1, 10, 2, 20, 3]
public consuming func isSorted() -> Bool

True if elements come out in ascending order. True for empty or single-element iterators (vacuous). Short-circuits on the first out-of-order pair.

Examples

[1, 2, 3, 4, 5].iter().isSorted(); // true [1, 3, 2, 4, 5].iter().isSorted(); // false [1, 1, 2, 2, 3].iter().isSorted(); // true (equal allowed)
public consuming func isSortedDescending() -> Bool

True if elements come out in descending order. Mirror of isSorted.

func iter() -> Self

Returns self. The blanket conformance pivot — iterators are iterables.

public consuming func last() -> Item?

Last element, or None if empty. Consumes the entire iterator — O(n) even for sequences whose last element is cheap to address directly.

public func map[U](as: consuming (Item) -> U) -> MapIterator[Self, U]

Applies transform to each element. Lazy — the function only fires when the downstream pulls a value.

Examples

[1, 2, 3].iter().map { it * 2 }.collect(); // [2, 4, 6] ["hi", "yo"].iter().map { it.count }.collect(); // [2, 2]
public consuming func max() -> Item?

Largest element, or None for an empty iterator. Ties go to the first occurrence.

public consuming func min() -> Item?

Smallest element, or None for an empty iterator. Ties go to the first occurrence.

Examples

[3, 1, 4, 1, 5].iter().min(); // Some(1) [].iter().min(); // None
public mutating func next() -> Optional[&T]

Yields a reference to the next element in place, or .None when the count reaches zero.

public mutating func nth(Int64) -> Item?

Returns the element at index n (zero-based), consuming everything up to and including it. None if n is past the end.

Examples

[10, 20, 30, 40].iter().nth(2); // Some(30) [10, 20].iter().nth(5); // None [10, 20, 30].iter().nth(0); // Some(10)
public func peekable() -> PeekableIterator[Self]

Wraps self so you can look at the next element without consuming it.

Examples

var it = [1, 2, 3].iter().peekable(); it.peek(); // Some(1) — no consumption it.peek(); // Some(1) — still it.next(); // Some(1) — now consumed it.peek(); // Some(2)
public consuming func product() -> Item

Product of every element. Returns Item.one for an empty iterator.

Examples

[1, 2, 3, 4, 5].iter().product(); // 120 (1..=5).iter().product(); // 120 (5!) [].iter().product(); // 1
public consuming func reduce(by: (Item, Item) -> Item) -> Item?

Like fold, but seeds the accumulator with the first element instead of taking an explicit initial. Returns None for an empty iterator.

Examples

[1, 2, 3, 4].iter().reduce { (a, b) in a + b }; // Some(10) [5].iter().reduce { (a, b) in a + b }; // Some(5) [].iter().reduce { (a, b) in a + b }; // None
public func scan[Acc](from: Acc, by: consuming (Acc, Item) -> Acc) -> ScanIterator[Self, Acc]

Like fold, but yields each intermediate accumulator value instead of just the final one. Useful for prefix sums, running products, and any "carry state along" pattern.

Examples

// Running sum [1, 2, 3, 4].iter() .scan(from: 0) { (acc, x) in acc + x } .collect(); // [1, 3, 6, 10]
public func skip(Int64) -> SkipIterator[Self]

Drops the first count elements, then yields the rest.

Examples

[1, 2, 3, 4, 5].iter().skip(2).collect(); // [3, 4, 5] [1, 2].iter().skip(10).collect(); // []
public func skipWhile(where: consuming (Item) -> Bool) -> SkipWhileIterator[Self]

Drops elements while predicate is true, then yields every remaining element (including ones that would also satisfy the predicate). Mirror of takeWhile.

Examples

[1, 2, 3, 4, 1, 2].iter() .skipWhile { it < 3 } .collect(); // [3, 4, 1, 2]
public consuming func sorted() -> Array[Item]

Collects into an Array[Item], sorted ascending. Eager and O(n log n) — calls Array.sort(by:) after collect().

Examples

[3, 1, 4, 1, 5].iter().sorted(); // [1, 1, 3, 4, 5] [3, 1, 2].iter().filter { it > 1 }.sorted(); // [2, 3]
public func stepBy(Int64) -> StepByIterator[Self]

Yields every n-th element, starting at the first. n == 0 is undefined (the adapter will spin forever).

Examples

[0, 1, 2, 3, 4, 5, 6].iter().stepBy(2).collect(); // [0, 2, 4, 6]
public consuming func sum() -> Item

Sum of every element. Returns Item.zero for an empty iterator.

Examples

[1, 2, 3, 4, 5].iter().sum(); // 15 [1.5, 2.5, 3.0].iter().sum(); // 7.0 [].iter().sum(); // 0
public func take(Int64) -> TakeIterator[Self]

Yields at most the first count elements; stops early even if more are available.

Examples

[1, 2, 3, 4, 5].iter().take(3).collect(); // [1, 2, 3] [1, 2].iter().take(10).collect(); // [1, 2]
public func takeWhile(where: consuming (Item) -> Bool) -> TakeWhileIterator[Self]

Yields elements until predicate first returns false, then stops. The "first failing" element is not yielded.

Examples

[1, 2, 3, 4, 1, 2].iter() .takeWhile { it < 4 } .collect(); // [1, 2, 3]
public mutating func tryFold[Acc, E](from: Acc, by: (Acc, Item) -> Result[Acc, E]) -> Result[Acc, E]

Fold with early exit on Err. The combine returns Result; the first Err halts iteration and is returned. If everything succeeds, returns Ok(final accumulator).

Examples

// Stop the moment a parse fails ["1", "2", "3"].iter() .tryFold(from: 0) { (acc, s) in match Int64.parse(s) { .Some(n) => .Ok(acc + n), .None => .Err("parse error") } }; // Ok(6) ["1", "bad", "3"].iter() .tryFold(from: 0) { (acc, s) in match Int64.parse(s) { .Some(n) => .Ok(acc + n), .None => .Err("parse error") } }; // Err("parse error")
public mutating func tryForEach[E](consuming (Item) -> Result[(), E]) -> Result[(), E]

forEach with early exit on Err. Mirror of tryFold for the "do something with each element" shape.

Examples

files.iter().tryForEach { (path) in File.delete(path) // Result[(), IoError] }; // stops on first failure
public consuming func unzip[A, B]() -> (Array[A], Array[B]) where Item == (A, B)

Splits an iterator of pairs into two parallel arrays. Inverse of zip.

Examples

let pairs = [(1, "a"), (2, "b"), (3, "c")]; let (nums, strs) = pairs.iter().unzip(); // nums = [1, 2, 3], strs = ["a", "b", "c"]
public func zip[Other](Other) -> ZipIterator[Self, Other] where Other: Iterator

Pairs elements from self and other. Stops as soon as either side runs out.

Examples

let names = ["Alice", "Bob", "Charlie"]; let ages = [30, 25, 35]; names.iter().zip(ages.iter()).collect(); // [("Alice", 30), ("Bob", 25), ("Charlie", 35)]

Defined in lang/std/memory/pointer.ks