# Kestrel — Full Documentation # Standard Library ## std.collections ### struct Array ```kestrel public struct Array[T] { /* private fields */ } ``` A dynamic, growable, contiguous-buffer array with copy-on-write storage. `Array[T]` is the standard ordered-collection type. It supports constant-time random access, amortized constant-time `append`, and arbitrary-position insert/remove via shifting. Storage is shared between copies until one of them mutates, at which point that copy lazily clones the buffer (see "Memory Model" below). For non-owning views over an existing buffer use `ArraySlice[T]`; for fixed-size or set-like collections see `ArraySlice[T]`, `Set`, or `Dictionary`. # Examples ``` let evens = [2, 4, 6, 8]; var names = Array[String](); names.append("Alice"); names.append("Bob"); let copy = names; // O(1) — shares storage with `names` names.append("Carol"); // O(1) clone happens here, `copy` is unchanged for n in names.iter() { ... } let pivot = names.partition(by: { (n) in n.count > 3 }); ``` # Indexing The default subscript `arr(i)` panics on out-of-bounds. Variants exist for every common policy: `arr(checked: i)` returns `T?`, `arr(unchecked: i)` skips the bounds check (UB on OOB), `arr(wrapped: i)` wraps with modulo (and supports negative indices), and `arr(clamped: i)` clamps to `[0, count-1]`. Range arguments use the same labels — `arr(0..<3)`, `arr(checked: r)`, `arr(unchecked: r)`, `arr(clamped: r)` — dispatched through the unified `SeqIndex[T]`, `SeqClampable[T]`, and `SeqWrappable[T]` protocols. `Int64` and range types share each label; the result type varies (`T?` vs `ArraySlice[T]` for `clamped:`). # Capacity & Reallocation `count` is the number of elements; `capacity` is how many can fit without reallocating. When `append` would exceed capacity the buffer doubles (starting from 4 if previously zero). Use `reserveCapacity(minimumCapacity:)` to pre-allocate, and `shrinkToFit()` to release excess. # Representation Holds a single `CowBox[ArrayStorage[T]]` field. The storage is a `(ptr, len, cap)` triple over a heap-allocated buffer. # Memory Model Reference-counted storage with copy-on-write *value* semantics. Copying an `Array` is O(1) and shares the buffer; the next mutation on a shared `Array` triggers `makeUnique()`, which deep-clones the buffer so the mutation is invisible to other copies. The user-visible behavior is indistinguishable from deep-copying on assignment. # Guarantees - Elements are stored contiguously and are accessible via `asPointer()` for FFI; the pointer is invalidated by any mutation that may reallocate. - `count <= capacity` always. - Iteration order is insertion order. - Operations marked O(1) are amortized; growth is geometric. #### initializer Array Literal ```kestrel public init(arrayLiteral: LiteralSlice[T]) ``` Creates an array containing every element of the supplied literal slice. Allocates a buffer sized exactly to the literal's element count (so `capacity == count` after construction) and copies the elements over. An empty slice yields an empty unallocated array. Panics if allocation fails. # Examples ``` // Triggered by the array-literal syntax: let arr: Array[Int64] = [10, 20, 30]; ``` #### initializer Empty ```kestrel public init() ``` Creates an empty array with no allocation. Capacity starts at zero; the first `append` allocates a small buffer (currently 4 elements). Use `init(capacity:)` if you can pre-size to avoid the early growth steps. # Examples ``` var arr = Array[Int64](); arr.count; // 0 arr.capacity; // 0 ``` #### initializer From Generator ```kestrel public init(of: Int64, generatedBy: (Int64) -> T) ``` Creates an array of `count` elements computed by a per-index closure. Allocates exactly `count` slots and invokes `gen(i)` once for each `i` in `0..= 1000 — no reallocation for first 1000 appends ``` #### function append ```kestrel public mutating func append(consuming T) ``` Appends `element` to the end of the array. Amortized O(1). Triggers a reallocation (and COW if storage is shared) when `count == capacity`. For appending many elements, `reserveCapacity(...)` first to avoid intermediate growths; for adding multiple elements at once see `append(contentsOf:)` or `append(from:)`. # Examples ``` var arr = [1, 2]; arr.append(3); // [1, 2, 3] ``` #### function append ```kestrel public mutating func append[__opaque_0](contentsOf: __opaque_0) where __opaque_0: Slice[T] ``` Appends every element of `other` to the end of this array. Reserves the exact required capacity in one growth step then copies the elements over, so it's faster than calling `append` in a loop. Sharing semantics: `other` is read-only here, but if `self` shares storage with anything else, COW fires once at the start. See also `append(from:)` for arbitrary iterable sources. # Examples ``` var arr = [1, 2]; arr.append(contentsOf: [3, 4]); // [1, 2, 3, 4] arr.append(contentsOf: []); // [1, 2, 3, 4] — no-op ``` #### function append ```kestrel public mutating func append[I](from: I) where I: Iterable, I.Item == T ``` Appends every element produced by an arbitrary iterable. Drains the iterable via `append`, so capacity grows geometrically rather than to an exact target — for sized sources like another `Array`, prefer `append(contentsOf:)`. # Examples ``` var arr = [1, 2]; arr.append(from: 3..<6); // [1, 2, 3, 4, 5] ``` #### field capacity ```kestrel public var capacity: Int64 { get } ``` The number of elements the buffer can hold without reallocating. #### function clear ```kestrel public mutating func clear() ``` Removes every element from the array, leaving capacity untouched. O(1). The buffer is kept so subsequent appends don't reallocate — if you want the memory back, follow with `shrinkToFit()`. # Examples ``` var arr = [1, 2, 3]; arr.clear(); // arr is [] arr.capacity; // unchanged ``` #### function dedup ```kestrel public mutating func dedup() ``` Removes runs of consecutive equal elements, in place. Only adjacent duplicates collapse — non-adjacent equal values are kept. To deduplicate globally, `sort()` first or, for `Hashable` elements, use the `unique()` / `removeDuplicates()` extension methods. The non-mutating variant is `deduped()`. # Examples ``` var arr = [1, 1, 2, 2, 2, 3, 1, 1]; arr.dedup(); // [1, 2, 3, 1] — trailing 1s survive (not adjacent to first run) ``` #### function deduped ```kestrel public func deduped() -> Array[T] ``` Returns a new array with consecutive duplicates removed; original is unchanged. Non-mutating mirror of `dedup()`. Same caveat: only adjacent duplicates collapse. # Examples ``` [1, 1, 2, 2, 3].deduped(); // [1, 2, 3] [1, 2, 1, 2].deduped(); // [1, 2, 1, 2] — none are adjacent ``` #### function flatten ```kestrel public func flatten() -> Array[T.Item] ``` Concatenates each element's iterator into a single `Array[T.Item]`. Drains every inner iterator in order. Empty inner sequences disappear without affecting the surrounding ones. Element type of the result is `T.Item`, the inner iterable's item type. # Examples ``` let nested = [[1, 2], [3, 4], [5]]; nested.flatten(); // [1, 2, 3, 4, 5] let mixed = [[1], [], [2, 3]]; mixed.flatten(); // [1, 2, 3] ``` #### function insert ```kestrel public mutating func insert(T, at: Int64) ``` Inserts `element` at `index`, shifting later elements right by one. O(n) in the number of elements after `index`. `index == count` behaves like `append`. Triggers COW and may reallocate. For bulk insertion at one location, prefer `replaceSubrange(i.. count`. # Examples ``` var arr = [1, 3]; arr.insert(2, at: 1); // [1, 2, 3] arr.insert(0, at: 0); // [0, 1, 2, 3] arr.insert(4, at: 4); // [0, 1, 2, 3, 4] — append-equivalent arr.insert(9, at: 99); // PANIC ``` #### function joined ```kestrel public func joined(String) -> String ``` Concatenates each element's string representation, separated by `separator`. Each element is rendered with its `format()` method using default `FormatOptions`. The default `separator` is empty (raw concatenation). Empty arrays produce `""`. For the bracketed debug form (`"[1, 2, 3]"`), use `format()` directly. # Examples ``` [1, 2, 3].joined(", "); // "1, 2, 3" [1, 2, 3].joined(); // "123" ["a", "b"].joined("-"); // "a-b" [].joined(", "); // "" ``` #### function partition ```kestrel public mutating func partition(by: (T) -> Bool) -> Int64 ``` Reorders elements in place so that all matching elements come before all non-matching elements; returns the partition point. The returned index is the count of matching elements (and the index of the first non-matching one). This is an *unstable* partition — relative order within each side is not preserved. For a stable, allocating variant that returns two arrays, use `partitioned(by:)`. # Examples ``` var arr = [1, 2, 3, 4, 5]; let pivot = arr.partition(by: { (x) in x % 2 == 0 }); // arr might be [2, 4, 3, 1, 5] (or another valid permutation) // pivot == 2 — first two elements satisfy the predicate ``` #### function partitioned ```kestrel public func partitioned(by: (T) -> Bool) -> (Array[T], Array[T]) ``` Returns two new arrays: elements matching `predicate` first, then elements that don't. Stable: relative order within each side is preserved. Allocates two new arrays — use `partition(by:)` for an in-place, unstable reordering that avoids the allocation. # Examples ``` let (evens, odds) = [1, 2, 3, 4, 5].partitioned(by: { (x) in x % 2 == 0 }); // evens = [2, 4] // odds = [1, 3, 5] ``` #### function pop ```kestrel public mutating func pop() -> T? ``` Removes and returns the last element, or `None` if the array is empty. O(1). Capacity is retained for reuse — only `len` is decremented. The mirror operation `popFirst()` is O(n) because it must shift the remainder. To inspect the last element without removing, use `last()`. # Examples ``` var arr = [1, 2, 3]; arr.pop(); // Some(3), arr is [1, 2] arr.pop(); // Some(2), arr is [1] arr.pop(); // Some(1), arr is [] arr.pop(); // None, arr is still [] ``` #### function popFirst ```kestrel public mutating func popFirst() -> T? ``` Removes and returns the first element, or `None` if the array is empty. O(n) — every following element shifts left by one. If you can tolerate it, `pop()` from the back is O(1). For inspection without removal, use `first()`. # Examples ``` var arr = [1, 2, 3]; arr.popFirst(); // Some(1), arr is [2, 3] arr.popFirst(); // Some(2), arr is [3] ``` #### function remove ```kestrel public mutating func remove(at: Int64) -> T ``` Removes and returns the element at `index`, shifting later elements left. O(n - index). Capacity is retained. For removing many elements at once, prefer `removeSubrange(range:)`. To remove the *first* element by *value* see the `Equatable` extension's `remove(element:)`. # Errors Panics with `"Array.remove: index out of bounds"` if `index < 0` or `index >= count`. # Examples ``` var arr = [1, 2, 3, 4]; arr.remove(at: 1); // returns 2; arr is [1, 3, 4] arr.remove(at: 9); // PANIC ``` #### function remove ```kestrel public mutating func remove(T) -> Bool ``` Removes the first element equal to `element`. Returns whether a removal occurred. Performs `firstIndex(of:)` then `remove(at:)`. To strip every occurrence in one pass, use `removeAll(element:)`. # Examples ``` var arr = [1, 2, 3, 2]; arr.remove(2); // true; arr is [1, 3, 2] arr.remove(5); // false; arr unchanged ``` #### function removeAll ```kestrel public mutating func removeAll(where: (T) -> Bool) ``` Removes every element for which `predicate` returns true. The inverse of `retain(where:)` — implemented as `retain` over the negated predicate. O(n), stable. # Examples ``` var arr = [1, 2, 3, 4, 5]; arr.removeAll(where: { (x) in x % 2 == 0 }); // [1, 3, 5] var names = ["Alice", "", "Bob", ""]; names.removeAll(where: { (s) in s.isEmpty }); // ["Alice", "Bob"] ``` #### function removeAll ```kestrel public mutating func removeAll(T) ``` Removes every element equal to `element`. Implemented as `retain` with a negated equality predicate — O(n), single pass, stable. To remove only the first occurrence use `remove(element:)`. # Examples ``` var arr = [1, 2, 3, 2, 4, 2]; arr.removeAll(2); // [1, 3, 4] ``` #### function removeDuplicates ```kestrel public mutating func removeDuplicates() ``` Removes every duplicate in place, keeping the first occurrence. Implemented by replacing storage with the result of `unique()`, so the same O(n²) caveat applies. The non-mutating mirror is `unique()`. # Examples ``` var arr = [1, 2, 1, 3, 2]; arr.removeDuplicates(); // [1, 2, 3] ``` #### function removeSubrange ```kestrel public mutating func removeSubrange[R](R) where R: SeqRange ``` Removes every element in `range`, shifting later elements left. O(count - range.end + range.length). Empty ranges are no-ops. Capacity is retained — call `shrinkToFit()` to release it. For "remove these and put others back" use `replaceSubrange(...)`. # Errors Panics with `"Array.removeSubrange: range out of bounds"` if `range.start < 0`, `range.end > count`, or `range.start > range.end`. # Examples ``` var arr = [1, 2, 3, 4, 5]; arr.removeSubrange(1..<4); // arr is [1, 5] arr.removeSubrange(0..<0); // no-op ``` #### function replaceSubrange ```kestrel public mutating func replaceSubrange[R](R, with: Array[T]) where R: SeqRange ``` Replaces the elements in `range` with the elements of `replacement`. `replacement.count` need not equal the range length — the array shrinks or grows accordingly, shifting the trailing elements once. Use `range == i.. count`, or `range.start > range.end`. # Examples ``` var arr = [1, 2, 3, 4, 5]; arr.replaceSubrange(1..<4, with: [20, 30]); // [1, 20, 30, 5] arr.replaceSubrange(1..<1, with: [9, 9]); // insert: [1, 9, 9, 20, 30, 5] arr.replaceSubrange(0..<2, with: Array[Int64]()); // remove: [9, 20, 30, 5] ``` #### function reserveCapacity ```kestrel public mutating func reserveCapacity(Int64) ``` Reserves enough capacity to hold at least `minimumCapacity` elements. A no-op when capacity already suffices. The actual capacity after the call may exceed the request because growth rounds up via the doubling policy. Pair with bulk inserts to skip intermediate reallocations. The opposite operation is `shrinkToFit()`. # Examples ``` var arr = Array[Int64](); arr.reserveCapacity(1000); for i in 0..<1000 { arr.append(i); // no reallocations } ``` #### function retain ```kestrel public mutating func retain(where: (T) -> Bool) ``` Keeps only elements for which `predicate` returns true; removes the rest in place. O(n), single pass, stable (relative order preserved). The mirror operation is `removeAll(where:)`. For a copy instead of an in-place edit, use `iter().filter(...).collect()`. # Examples ``` var arr = [1, 2, 3, 4, 5]; arr.retain(where: { (x) in x % 2 == 0 }); // [2, 4] ``` #### function reverse ```kestrel public mutating func reverse() ``` Reverses the order of elements in place. O(n). Triggers COW. For a non-mutating variant returning a new array, use `reversed()`. # Examples ``` var arr = [1, 2, 3]; arr.reverse(); // [3, 2, 1] ``` #### function rotate ```kestrel public mutating func rotate(by: Int64) ``` Rotates the elements in place by `amount` positions to the left. Implemented with the three-reversal algorithm — O(n) time, O(1) extra space. Negative `amount` rotates right; the actual rotation is `amount mod count`, so very large amounts wrap. A no-op when `count <= 1` or the normalized amount is zero. # Examples ``` var arr = [1, 2, 3, 4, 5]; arr.rotate(by: 2); // [3, 4, 5, 1, 2] arr.rotate(by: -1); // [2, 3, 4, 5, 1] arr.rotate(by: 7); // same as rotate(by: 2) for count == 5 ``` #### function shrinkToFit ```kestrel public mutating func shrinkToFit() ``` Releases unused capacity by reallocating to fit `count` exactly. Useful after a bulk removal or when you've finished building a large array. A no-op when `capacity == count`. For an empty array, fully deallocates the buffer (capacity drops to 0). Triggers COW. # Examples ``` var arr = Array[Int64](capacity: 1000); arr.append(1); arr.shrinkToFit(); // capacity reduced to 1 arr.clear(); arr.shrinkToFit(); // capacity reduced to 0, buffer freed ``` #### function shuffle ```kestrel public mutating func shuffle[__opaque_0](using: __opaque_0) where __opaque_0: RandomNumberGenerator ``` Shuffles the array in place using `rng`. Uses the Fisher-Yates algorithm — every permutation is equally likely, given a uniform RNG. Passing the same seeded `rng` produces a deterministic shuffle, which is the usual reason to reach for this overload over the no-arg `shuffle()`. # Examples ``` var arr = [1, 2, 3, 4, 5]; var rng = Lcg64(seed: 42); arr.shuffle(using: rng); // deterministic for the seed ``` #### function shuffle ```kestrel public mutating func shuffle() ``` Shuffles the array in place using a fresh default RNG. Convenience over `shuffle(using:)`. The result is non-deterministic across calls — pass an explicit `Lcg64(seed: ...)` (or other `RandomNumberGenerator`) when you need reproducibility. # Examples ``` var arr = [1, 2, 3, 4, 5]; arr.shuffle(); // e.g. [3, 1, 5, 2, 4] ``` #### function shuffled ```kestrel public func shuffled[__opaque_0](using: __opaque_0) -> Array[T] where __opaque_0: RandomNumberGenerator ``` Returns a new array shuffled with `rng`. The original is unchanged. The non-mutating mirror of `shuffle(using:)`. Internally clones via COW (cheap until the next mutation) and shuffles the copy. # Examples ``` let arr = [1, 2, 3, 4, 5]; var rng = Lcg64(seed: 42); let result = arr.shuffled(using: rng); // arr is still [1, 2, 3, 4, 5] ``` #### function shuffled ```kestrel public func shuffled() -> Array[T] ``` Returns a new array shuffled with a default RNG. Original unchanged. Convenience over `shuffled(using:)`. Non-deterministic between calls. # Examples ``` let arr = [1, 2, 3, 4, 5]; let shuffled = arr.shuffled(); // e.g. [4, 2, 5, 1, 3] // arr is still [1, 2, 3, 4, 5] ``` #### function sort ```kestrel public mutating func sort() ``` Sorts the array in ascending order using the natural `<` ordering. Uses introsort — O(n log n) worst-case. For descending or custom orderings pass a comparator to `sort(by:)`. Non-mutating variant: `sorted()`. # Examples ``` var arr = [3, 1, 4, 1, 5]; arr.sort(); // [1, 1, 3, 4, 5] ``` #### function sort ```kestrel public mutating func sort(by: (T, T) -> Bool) ``` Sorts the array in place using a `<`-style comparator. The comparator returns `true` when its first argument should come before the second. Uses introsort — quicksort with heapsort fallback when recursion exceeds 2·log₂(n), and insertion sort for partitions ≤ 16 elements. O(n log n) worst-case. Pass a reversed comparator for descending order. # Examples ``` var arr = [1, 5, 3, 2, 4]; arr.sort(by: { (a, b) in a > b }); // [5, 4, 3, 2, 1] descending ``` #### function sort ```kestrel public mutating func sort[K](byKey: (T) -> K) where K: Comparable ``` Sorts the array in place by an extracted `Comparable` key. # Examples ``` var people = [Person("Alice", 30), Person("Bob", 25)]; people.sort(byKey: { (p) in p.age }); ``` #### function sorted ```kestrel public func sorted(by: (T, T) -> Bool) -> Array[T] ``` Returns a new array sorted by a custom comparator. Original unchanged. # Examples ``` let arr = [3, 1, 2]; let desc = arr.sorted(by: { (a, b) in a > b }); // [3, 2, 1] ``` #### function sorted ```kestrel public func sorted[K](byKey: (T) -> K) -> Array[T] where K: Comparable ``` Returns a new array sorted by an extracted `Comparable` key; original unchanged. # Examples ``` let words = ["hi", "hello", "hey"]; let byLen = words.sorted(byKey: { (w) in w.count }); ``` #### function swap ```kestrel public mutating func swap(at: Int64, with: Int64) ``` Swaps the elements at indices `i` and `j` in place. O(1). A no-op when `i == j`. Triggers COW. # Errors Panics with `"Array.swap: index out of bounds"` if either index is `< 0` or `>= count`. # Examples ``` var arr = [1, 2, 3]; arr.swap(at: 0, with: 2); // [3, 2, 1] arr.swap(at: 1, with: 1); // [3, 2, 1] — no-op arr.swap(at: 0, with: 9); // PANIC ``` **Slice** #### function all ```kestrel public func all(where: (T) -> Bool) -> Bool ``` `true` when every element satisfies `predicate`. O(n). Short-circuits on the first failure. Vacuously true for empty collections. # Examples ``` [2, 4, 6].all(where: { it % 2 == 0 }); // true [2, 3, 6].all(where: { it % 2 == 0 }); // false ``` #### function any ```kestrel public func any(where: (T) -> Bool) -> Bool ``` `true` when at least one element satisfies `predicate`. O(n). Short-circuits on the first match. Always `false` for empty collections. # Examples ``` [1, 2, 3].any(where: { it > 2 }); // true [1, 2, 3].any(where: { it > 5 }); // false ``` #### function asPointer ```kestrel public func asPointer() -> Pointer[T] ``` Pointer to the first element. The pointer aliases the collection's buffer; do not outlive the source or mutate through it. # Safety Reading past `count` is undefined behavior. #### function asSlice ```kestrel public func asSlice() -> ArraySlice[T] ``` Slice protocol kernel — borrows the array's buffer as an ArraySlice. #### function binarySearch ```kestrel public func binarySearch(T) -> Int64? ``` Binary search for `element`. Returns its index or `None`. O(log n). When duplicates exist, which index is returned is unspecified. # Safety The collection must be sorted in ascending order. Calling on unsorted data won't crash but may produce false negatives. # Examples ``` [1, 2, 3, 4, 5].binarySearch(3); // Some(2) [1, 2, 3, 4, 5].binarySearch(6); // None ``` #### function chunks ```kestrel public func chunks(of: Int64) -> ChunksView[T] ``` Multi-pass lazy view over non-overlapping `size`-sized chunks. The trailing chunk may be shorter than `size`. Multi-pass: query `count`, index with `view.get(i)`, and iterate repeatedly without re-creating the view. # Errors Panics if `size <= 0`. # Examples ``` let v = [1, 2, 3, 4, 5].chunks(of: 2); v.count; // 3 v.get(2); // ArraySlice[5] for c in v { ... } ``` #### function compactMap ```kestrel public func compactMap[U]((T) -> Optional[U]) -> Array[U] ``` Maps every element through `transform`, dropping `.None` results. O(n). # Examples ``` ["1", "x", "3"].compactMap { Int64.parse(it) }; // [1, 3] ``` #### function contains ```kestrel public func contains(T) -> Bool ``` `true` if the collection contains `element`. O(n). Linear scan; short-circuits on the first match. # Examples ``` [1, 2, 3].contains(2); // true [1, 2, 3].contains(5); // false ``` #### field count ```kestrel public var count: Int64 { get } ``` Element count. O(1). # Examples ``` [1, 2, 3].count; // 3 [].count; // 0 ``` #### function countItems ```kestrel public func countItems(where: (T) -> Bool) -> Int64 ``` Number of elements for which `predicate` is true. O(n). # Examples ``` [1, 2, 3, 4, 5].countItems(where: { it % 2 == 0 }); // 2 ``` #### function drop ```kestrel public func drop(first: Int64) -> ArraySlice[T] ``` Returns a slice with the first `count` elements skipped. O(1). Complement of `prefix`. # Errors Panics if `count > self.count`. # Examples ``` [1, 2, 3, 4, 5].drop(first: 2); // ArraySlice[3, 4, 5] ``` #### function ends ```kestrel public func ends[__opaque_0](with: __opaque_0) -> Bool where __opaque_0: Slice[T] ``` `true` if the trailing elements match `suffix`. O(k) where k is the suffix length. Accepts any `Slice[T]` conformer. # Examples ``` [1, 2, 3].ends(with: [2, 3]); // true [1, 2, 3].ends(with: [1, 2]); // false [1, 2, 3].ends(with: []); // true (vacuous) ``` #### function ensureUnique ```kestrel public mutating func ensureUnique() ``` COW write barrier — deep-copies storage if shared. #### function filter ```kestrel public func filter(where: (T) -> Bool) -> Array[T] ``` Returns a new array containing every element matching `predicate`. O(n). Result size is unknown; uses geometric growth. # Examples ``` [1, 2, 3, 4].filter(where: { it % 2 == 0 }); // [2, 4] ``` #### function first ```kestrel public func first() -> T? ``` First element, or `.None` for an empty collection. O(1). Read-only — to remove the first element from an `Array`, use `popFirst()`. # Examples ``` [1, 2, 3].first(); // Some(1) [].first(); // None ``` #### function firstIndex ```kestrel public func firstIndex(where: (T) -> Bool) -> Int64? ``` Index of the first element matching `predicate`, or `None`. O(n). Short-circuits on the first match. For value-based search on `Equatable` collections, use `firstIndex(of:)`. # Examples ``` [1, 2, 3, 4, 5].firstIndex(where: { it > 3 }); // Some(3) [1, 2, 3].firstIndex(where: { it > 10 }); // None ``` #### function flatMap ```kestrel public func flatMap[U]((T) -> Array[U]) -> Array[U] ``` Maps every element through `transform` and concatenates the results into one flat array. O(n + total_output). # Examples ``` [1, 2, 3].flatMap { [it, it * 10] }; // [1, 10, 2, 20, 3, 30] ``` #### function format ```kestrel public func format(into: mutating StringBuilder, FormatOptions) ``` Renders as `"[e1, e2, ...]"`. Empty collections render as `"[]"`. # Examples ``` [1, 2, 3].format(); // "[1, 2, 3]" [].format(); // "[]" ``` #### field indices ```kestrel public var indices: Range[Int64] { get } ``` Half-open range `0.. Bool ``` Element-wise equality. O(n). Short-circuits on the first mismatch. Order matters. # Examples ``` [1, 2, 3].isEqual(to: [1, 2, 3]); // true [1, 2, 3].isEqual(to: [3, 2, 1]); // false ``` #### function isSorted ```kestrel public func isSorted() -> Bool ``` `true` if elements are in non-decreasing order. O(n). Equal adjacent elements are allowed. Empty and single-element collections are vacuously sorted. # Examples ``` [1, 2, 3].isSorted(); // true [1, 3, 2].isSorted(); // false [1, 1, 1].isSorted(); // true [].isSorted(); // true ``` #### function isValidIndex ```kestrel public func isValidIndex(Int64) -> Bool ``` `true` if `index` is in `[0, count)`. # Examples ``` [10, 20, 30].isValidIndex(2); // true [10, 20, 30].isValidIndex(3); // false [10, 20, 30].isValidIndex(-1); // false ``` #### function iter ```kestrel public func iter() -> ArraySliceIterator[T] ``` Forward iterator over the elements. # Examples ``` for item in [1, 2, 3] { ... } ``` #### function last ```kestrel public func last() -> T? ``` Last element, or `.None` for an empty collection. O(1). Read-only — to remove the last element from an `Array`, use `pop()`. # Examples ``` [1, 2, 3].last(); // Some(3) [].last(); // None ``` #### function lastIndex ```kestrel public func lastIndex(where: (T) -> Bool) -> Int64? ``` Index of the last element matching `predicate`, or `None`. O(n). Scans from the back; short-circuits on the first match. # Examples ``` [1, 2, 3, 2, 1].lastIndex(where: { it == 2 }); // Some(3) ``` #### function map ```kestrel public func map[U]((T) -> U) -> Array[U] ``` Maps every element through `transform` into a new array. O(n). Pre-sizes the result buffer to `self.count`, so no growth steps. For the lazy version that fuses into a chain, use `iter().map { ... }`. # Examples ``` [1, 2, 3].map { it * 2 }; // [2, 4, 6] [1, 2, 3].map { it.format() }; // ["1", "2", "3"] ``` #### function max ```kestrel public func max() -> T? ``` Largest element, or `None` if empty. O(n). Ties go to the first occurrence. # Examples ``` [3, 1, 4].max(); // Some(4) [].max(); // None ``` #### function min ```kestrel public func min() -> T? ``` Smallest element, or `None` if empty. O(n). Ties go to the first occurrence. # Examples ``` [3, 1, 4].min(); // Some(1) [].min(); // None ``` #### function prefix ```kestrel public func prefix(Int64) -> ArraySlice[T] ``` Returns a slice over the first `count` elements. O(1). # Errors Panics if `count > self.count`. # Examples ``` [1, 2, 3, 4, 5].prefix(3); // ArraySlice[1, 2, 3] [1, 2].prefix(0); // empty slice ``` #### function reversed ```kestrel public func reversed() -> ReversedView[T] ``` Multi-pass lazy reversed view. Iterates back-to-front and supports indexed access in O(1). # Examples ``` let v = [1, 2, 3].reversed(); v.first(); // Some(3) v.toArray(); // [3, 2, 1] — eager copy ``` #### function sorted ```kestrel public func sorted() -> Array[T] ``` Returns a new sorted array; original unchanged. O(n log n). # Examples ``` let arr = [3, 1, 4, 1, 5]; arr.sorted(); // [1, 1, 3, 4, 5] // arr is still [3, 1, 4, 1, 5] ``` #### function split ```kestrel public func split(where: (T) -> Bool) -> ArraySplitWhereView[T] ``` Multi-pass lazy view over the segments produced by splitting at each element matching `predicate`. Matching elements are dropped. # Examples ``` let v = [1, -1, 2, 3, -1, 4].split(where: { it < 0 }); for seg in v { ... } ``` #### function starts ```kestrel public func starts[__opaque_0](with: __opaque_0) -> Bool where __opaque_0: Slice[T] ``` `true` if the leading elements match `prefix`. O(k) where k is the prefix length. Accepts any `Slice[T]` conformer. # Examples ``` [1, 2, 3].starts(with: [1, 2]); // true [1, 2, 3].starts(with: [2, 3]); // false [1, 2, 3].starts(with: []); // true (vacuous) ``` #### subscript subscript ```kestrel public subscript[I](I) -> I.SeqOutput { get set } ``` #### function suffix ```kestrel public func suffix(Int64) -> ArraySlice[T] ``` Returns a slice over the last `count` elements. O(1). # Errors Panics if `count > self.count`. # Examples ``` [1, 2, 3, 4, 5].suffix(2); // ArraySlice[4, 5] ``` #### function unique ```kestrel public func unique() -> Array[T] ``` Returns a new array with duplicates removed, preserving first-occurrence order. O(n²). For the mutating variant on `Array`, see `removeDuplicates()`. # Examples ``` [1, 2, 1, 3, 2, 4].unique(); // [1, 2, 3, 4] ``` #### function windows ```kestrel public func windows(of: Int64) -> WindowsView[T] ``` Multi-pass lazy view over overlapping `size`-sized sliding windows. Adjacent windows overlap by `size - 1` elements. Empty when the source has fewer than `size` elements. # Errors Panics if `size <= 0`. # Examples ``` let v = [1, 2, 3, 4].windows(of: 2); v.count; // 3 for w in v { ... } ``` **Iterable** #### typealias Item ```kestrel type Item = T ``` `Iterable` element type — the element produced by `iter().next()`. #### typealias TargetIterator ```kestrel type TargetIterator = ArraySliceIterator[T] ``` `Iterable` iterator type — the concrete iterator returned by `iter()`. #### function iter ```kestrel public func iter() -> ArraySliceIterator[T] ``` Returns a forward iterator over the array's elements. **ExpressibleByArrayLiteral** #### initializer Array Literal ```kestrel init(arrayLiteral: LiteralSlice[Element]) ``` Builds an instance from a literal slice of elements. **_ExpressibleByArrayLiteral** #### typealias Element ```kestrel type Element = T ``` Pattern-matching element type — used by `ArrayMatchable` for `[a, b, ..rest]` patterns. #### typealias Element ```kestrel type Element = T ``` `ArrayMatchable` element type — what the pattern bindings extract. #### initializer Literal Bridge ```kestrel init(_arrayLiteralPointer: consuming lang.ptr[Element], _arrayLiteralCount: consuming lang.i64) ``` Compiler-emitted init taking a raw pointer and count. Both params are `consuming`: the compiler hands ownership of the stack buffer's address (and the count) over to the implementation, which stores them in its own storage. This convention is what the MIR lowering's structural predicate looks for — implementations that deviate will be silently skipped during literal lowering. **Cloneable** #### function clone ```kestrel public func clone() -> Array[T] ``` Returns an `Array[T]` sharing the same storage; the deep copy is deferred until either side mutates. O(1) — just bumps the storage `CowBox`'s refcount. The first mutation on either the original or the clone triggers `makeUnique()`, which deep-copies the buffer so the two arrays diverge. # Examples ``` let a = [1, 2, 3]; var b = a.clone(); // O(1), shares storage b.append(4); // b deep-copies here; a is unchanged ``` **Defaultable** #### initializer Default ```kestrel init() ``` Builds the default-valued instance. **Equatable** #### typealias Output ```kestrel type Output = Bool ``` #### function equal ```kestrel public func equal(to: Self) -> Bool ``` Bridges `Equal.equal(to:)` to `Equatable.isEqual(to:)`. #### function isEqual ```kestrel func isEqual(to: Self) -> Bool ``` Returns `true` iff `self` and `other` are considered equal. Should be reflexive, symmetric, and transitive — `Hashable` requires equal values to hash equal, so don't drift from those laws. #### function notEqual ```kestrel public func notEqual(to: Self) -> Bool ``` Default `!=`: delegates to `==` so there's a single source of truth. **ArrayMatchable** #### typealias Element ```kestrel type Element ``` #### function matchGet ```kestrel public func matchGet(Int64) -> T ``` Pattern-matcher hook reading the element at `index` (no bounds check). # Safety The matcher only calls this with indices it has already validated against `matchLength()`, so the unchecked read is safe in that context. #### function matchLength ```kestrel public func matchLength() -> Int64 ``` Pattern-matcher hook returning the array's `count`. Used by the matcher to decide whether the scrutinee has enough elements for a fixed-arity pattern. #### function matchSlice ```kestrel public func matchSlice(Int64, Int64) -> ArraySlice[T] ``` Pattern-matcher hook returning the half-open `[from, to)` slice. Used to bind `..rest` segments. The matcher guarantees the indices are in range. ### struct ArrayBuilder ```kestrel public struct ArrayBuilder[T] { /* private fields */ } ``` Write-only buffer for efficient array construction. No COW, no `RcBox`, no `isUnique` checks — every append writes directly through the pointer. `build()` transfers ownership of the buffer into a new `Array[T]` without copying. The builder resets to empty and can be reused. # Examples ``` var b = ArrayBuilder[Int64](capacity: 3); b.append(1); b.append(2); b.append(3); let arr = b.build(); // [1, 2, 3], zero-copy ``` # Representation `(ptr: Pointer[T], len: Int64, cap: Int64)`. # Memory Model Owns its buffer directly — no reference counting during construction. `build()` donates the buffer to an `Array[T]` and leaves the builder empty. `deinit` frees the buffer if `build()` was never called. #### initializer Empty ```kestrel public init() ``` Creates an empty builder with no allocation. #### initializer With Capacity ```kestrel public init(capacity: Int64) ``` Creates an empty builder with at least `capacity` elements preallocated. #### function append ```kestrel public mutating func append(T) ``` Appends a single element. #### function append ```kestrel public mutating func append(contentsOf: ArraySlice[T]) ``` Appends every element of `slice`. #### function append ```kestrel public mutating func append[I](from: I) where I: Iterable, I.Item == T ``` Appends every element produced by `iterable`. #### function build ```kestrel public mutating func build() -> Array[T] ``` Transfers the buffer into a new `Array[T]` without copying. The builder resets to empty and can be reused. #### field capacity ```kestrel public var capacity: Int64 { get } ``` Allocated capacity in elements. #### function clear ```kestrel public mutating func clear() ``` Resets length to zero, keeping the allocated buffer for reuse. #### field count ```kestrel public var count: Int64 { get } ``` Number of elements written so far. #### field isEmpty ```kestrel public var isEmpty: Bool { get } ``` True when nothing has been written. ### struct ArraySplitIterator ```kestrel public struct ArraySplitIterator[T] where T: Equatable { /* private fields */ } ``` #### initializer init ```kestrel public init(ptr: Pointer[T], remaining: Int64, separator: T, done: Bool) ``` **Iterator** #### typealias Item ```kestrel type Item = ArraySlice[T] ``` #### typealias TargetIterator ```kestrel type TargetIterator = Self ``` #### function all ```kestrel 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) ``` #### function any ```kestrel 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 ``` #### function chain ```kestrel 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] ``` #### function collect ```kestrel 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] ``` #### function compactMap ```kestrel public func compactMap[T]() -> FilterMapIterator[Self, T] where Item == Optional[T] ``` Drops `None`s and unwraps `Some`s — 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] ``` #### function contains ```kestrel 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 ``` #### function count ```kestrel 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 ``` #### function cycle ```kestrel 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] ``` #### function enumerate ```kestrel 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}") }; ``` #### function filter ```kestrel public func filter(where: (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] ``` #### function filterMap ```kestrel public func filterMap[U](as: (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] ``` #### function first ```kestrel 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 ``` #### function firstIndex ```kestrel 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 ``` #### function flatMap ```kestrel public func flatMap[U](as: (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] ``` #### function flatten ```kestrel 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] ``` #### function fold ```kestrel 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 ``` #### function forEach ```kestrel 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) }; ``` #### function fuse ```kestrel 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. #### function inspect ```kestrel public func inspect((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(); ``` #### function intersperse ```kestrel 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] ``` #### function intersperseWith ```kestrel public func intersperseWith(with: () -> 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] ``` #### function isSorted ```kestrel 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) ``` #### function isSortedDescending ```kestrel public consuming func isSortedDescending() -> Bool ``` True if elements come out in descending order. Mirror of `isSorted`. #### function iter ```kestrel func iter() -> Self ``` Returns `self`. The blanket conformance pivot — iterators *are* iterables. #### function last ```kestrel 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. #### function map ```kestrel public func map[U](as: (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] ``` #### function max ```kestrel public consuming func max() -> Item? ``` Largest element, or `None` for an empty iterator. Ties go to the first occurrence. #### function min ```kestrel 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 ``` #### function next ```kestrel public mutating func next() -> Optional[ArraySlice[T]] ``` #### function nth ```kestrel 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) ``` #### function peekable ```kestrel 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) ``` #### function product ```kestrel 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 ``` #### function reduce ```kestrel 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 ``` #### function scan ```kestrel public func scan[Acc](from: Acc, by: (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] ``` #### function skip ```kestrel 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(); // [] ``` #### function skipWhile ```kestrel public func skipWhile(where: (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] ``` #### function sorted ```kestrel 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] ``` #### function stepBy ```kestrel 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] ``` #### function sum ```kestrel 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 ``` #### function take ```kestrel 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] ``` #### function takeWhile ```kestrel public func takeWhile(where: (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] ``` #### function tryFold ```kestrel 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") ``` #### function tryForEach ```kestrel public mutating func tryForEach[E]((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 ``` #### function unzip ```kestrel 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"] ``` #### function zip ```kestrel 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)] ``` ### struct ArraySplitView ```kestrel public struct ArraySplitView[T] where T: Equatable { /* private fields */ } ``` Multi-pass lazy view over the segments produced by splitting on each occurrence of a separator value. (Named `ArraySplitView` to avoid collision with `std.text.SplitView`.) #### field count ```kestrel public var count: Int64 { get } ``` #### initializer init ```kestrel public init(slice: ArraySlice[T], separator: T) ``` #### field isEmpty ```kestrel public var isEmpty: Bool { get } ``` #### function toArray ```kestrel public func toArray() -> Array[ArraySlice[T]] ``` **Iterable** #### typealias Item ```kestrel type Item = ArraySlice[T] ``` #### typealias TargetIterator ```kestrel type TargetIterator = ArraySplitIterator[T] ``` #### function iter ```kestrel public func iter() -> ArraySplitIterator[T] ``` ### struct ArraySplitWhereIterator ```kestrel public struct ArraySplitWhereIterator[T] { /* private fields */ } ``` #### initializer init ```kestrel public init(ptr: Pointer[T], remaining: Int64, predicate: (T) -> Bool, done: Bool) ``` **Iterator** #### typealias Item ```kestrel type Item = ArraySlice[T] ``` #### typealias TargetIterator ```kestrel type TargetIterator = Self ``` #### function all ```kestrel 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) ``` #### function any ```kestrel 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 ``` #### function chain ```kestrel 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] ``` #### function collect ```kestrel 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] ``` #### function compactMap ```kestrel public func compactMap[T]() -> FilterMapIterator[Self, T] where Item == Optional[T] ``` Drops `None`s and unwraps `Some`s — 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] ``` #### function contains ```kestrel 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 ``` #### function count ```kestrel 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 ``` #### function cycle ```kestrel 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] ``` #### function enumerate ```kestrel 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}") }; ``` #### function filter ```kestrel public func filter(where: (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] ``` #### function filterMap ```kestrel public func filterMap[U](as: (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] ``` #### function first ```kestrel 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 ``` #### function firstIndex ```kestrel 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 ``` #### function flatMap ```kestrel public func flatMap[U](as: (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] ``` #### function flatten ```kestrel 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] ``` #### function fold ```kestrel 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 ``` #### function forEach ```kestrel 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) }; ``` #### function fuse ```kestrel 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. #### function inspect ```kestrel public func inspect((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(); ``` #### function intersperse ```kestrel 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] ``` #### function intersperseWith ```kestrel public func intersperseWith(with: () -> 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] ``` #### function isSorted ```kestrel 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) ``` #### function isSortedDescending ```kestrel public consuming func isSortedDescending() -> Bool ``` True if elements come out in descending order. Mirror of `isSorted`. #### function iter ```kestrel func iter() -> Self ``` Returns `self`. The blanket conformance pivot — iterators *are* iterables. #### function last ```kestrel 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. #### function map ```kestrel public func map[U](as: (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] ``` #### function max ```kestrel public consuming func max() -> Item? ``` Largest element, or `None` for an empty iterator. Ties go to the first occurrence. #### function min ```kestrel 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 ``` #### function next ```kestrel public mutating func next() -> Optional[ArraySlice[T]] ``` #### function nth ```kestrel 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) ``` #### function peekable ```kestrel 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) ``` #### function product ```kestrel 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 ``` #### function reduce ```kestrel 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 ``` #### function scan ```kestrel public func scan[Acc](from: Acc, by: (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] ``` #### function skip ```kestrel 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(); // [] ``` #### function skipWhile ```kestrel public func skipWhile(where: (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] ``` #### function sorted ```kestrel 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] ``` #### function stepBy ```kestrel 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] ``` #### function sum ```kestrel 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 ``` #### function take ```kestrel 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] ``` #### function takeWhile ```kestrel public func takeWhile(where: (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] ``` #### function tryFold ```kestrel 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") ``` #### function tryForEach ```kestrel public mutating func tryForEach[E]((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 ``` #### function unzip ```kestrel 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"] ``` #### function zip ```kestrel 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)] ``` ### struct ArraySplitWhereView ```kestrel public struct ArraySplitWhereView[T] { /* private fields */ } ``` Multi-pass lazy view over the segments produced by splitting on each element matching a predicate. No `Equatable` requirement. (Named `ArraySplitWhereView` to avoid collision with `std.text.SplitWhereView`.) #### field count ```kestrel public var count: Int64 { get } ``` #### initializer init ```kestrel public init(slice: ArraySlice[T], predicate: (T) -> Bool) ``` #### field isEmpty ```kestrel public var isEmpty: Bool { get } ``` #### function toArray ```kestrel public func toArray() -> Array[ArraySlice[T]] ``` **Iterable** #### typealias Item ```kestrel type Item = ArraySlice[T] ``` #### typealias TargetIterator ```kestrel type TargetIterator = ArraySplitWhereIterator[T] ``` #### function iter ```kestrel public func iter() -> ArraySplitWhereIterator[T] ``` ### typealias ArrayTypeOperator ```kestrel public type ArrayTypeOperator[T] = Array[T] ``` Compiler-recognized type alias that lets `[T]` desugar to `Array[T]`. Allows annotations like `let xs: [Int64] = [1, 2, 3]` instead of requiring the user to spell out `Array[Int64]`. Not intended for direct use — the parser inserts it automatically when it sees the `[T]` shorthand in a type position. # Examples ``` let xs: [Int64] = [1, 2, 3]; // same as: Array[Int64] func sum(of values: [Float]) -> Float { ... } ``` ### struct ChunksIterator ```kestrel public struct ChunksIterator[T] { /* private fields */ } ``` #### initializer init ```kestrel public init(ptr: Pointer[T], remaining: Int64, chunkSize: Int64) ``` **Iterator** #### typealias Item ```kestrel type Item = ArraySlice[T] ``` #### typealias TargetIterator ```kestrel type TargetIterator = Self ``` #### function all ```kestrel 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) ``` #### function any ```kestrel 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 ``` #### function chain ```kestrel 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] ``` #### function collect ```kestrel 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] ``` #### function compactMap ```kestrel public func compactMap[T]() -> FilterMapIterator[Self, T] where Item == Optional[T] ``` Drops `None`s and unwraps `Some`s — 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] ``` #### function contains ```kestrel 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 ``` #### function count ```kestrel 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 ``` #### function cycle ```kestrel 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] ``` #### function enumerate ```kestrel 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}") }; ``` #### function filter ```kestrel public func filter(where: (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] ``` #### function filterMap ```kestrel public func filterMap[U](as: (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] ``` #### function first ```kestrel 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 ``` #### function firstIndex ```kestrel 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 ``` #### function flatMap ```kestrel public func flatMap[U](as: (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] ``` #### function flatten ```kestrel 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] ``` #### function fold ```kestrel 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 ``` #### function forEach ```kestrel 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) }; ``` #### function fuse ```kestrel 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. #### function inspect ```kestrel public func inspect((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(); ``` #### function intersperse ```kestrel 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] ``` #### function intersperseWith ```kestrel public func intersperseWith(with: () -> 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] ``` #### function isSorted ```kestrel 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) ``` #### function isSortedDescending ```kestrel public consuming func isSortedDescending() -> Bool ``` True if elements come out in descending order. Mirror of `isSorted`. #### function iter ```kestrel func iter() -> Self ``` Returns `self`. The blanket conformance pivot — iterators *are* iterables. #### function last ```kestrel 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. #### function map ```kestrel public func map[U](as: (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] ``` #### function max ```kestrel public consuming func max() -> Item? ``` Largest element, or `None` for an empty iterator. Ties go to the first occurrence. #### function min ```kestrel 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 ``` #### function next ```kestrel public mutating func next() -> Optional[ArraySlice[T]] ``` #### function nth ```kestrel 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) ``` #### function peekable ```kestrel 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) ``` #### function product ```kestrel 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 ``` #### function reduce ```kestrel 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 ``` #### function scan ```kestrel public func scan[Acc](from: Acc, by: (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] ``` #### function skip ```kestrel 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(); // [] ``` #### function skipWhile ```kestrel public func skipWhile(where: (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] ``` #### function sorted ```kestrel 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] ``` #### function stepBy ```kestrel 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] ``` #### function sum ```kestrel 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 ``` #### function take ```kestrel 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] ``` #### function takeWhile ```kestrel public func takeWhile(where: (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] ``` #### function tryFold ```kestrel 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") ``` #### function tryForEach ```kestrel public mutating func tryForEach[E]((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 ``` #### function unzip ```kestrel 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"] ``` #### function zip ```kestrel 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)] ``` ### struct ChunksView ```kestrel public struct ChunksView[T] { /* private fields */ } ``` Multi-pass lazy view over non-overlapping `chunkSize`-sized `ArraySlice[T]` segments. #### field count ```kestrel public var count: Int64 { get } ``` #### field first ```kestrel public var first: Optional[ArraySlice[T]] { get } ``` #### initializer init ```kestrel public init(slice: ArraySlice[T], chunkSize: Int64) ``` #### field isEmpty ```kestrel public var isEmpty: Bool { get } ``` #### field last ```kestrel public var last: Optional[ArraySlice[T]] { get } ``` #### subscript subscript ```kestrel public subscript(Int64) -> ArraySlice[T] { get } ``` #### function toArray ```kestrel public func toArray() -> Array[ArraySlice[T]] ``` **Iterable** #### typealias Item ```kestrel type Item = ArraySlice[T] ``` #### typealias TargetIterator ```kestrel type TargetIterator = ChunksIterator[T] ``` #### function iter ```kestrel public func iter() -> ChunksIterator[T] ``` ### struct DefaultHasher ```kestrel public struct DefaultHasher { /* private fields */ } ``` The standard `Hasher` implementation, backed by a wyhash-derived per-byte mixer. Used by `Dictionary` and `Set` whenever the user doesn't pick a specific hasher. Each byte folds into a 64-bit running state via `state = (state ^ byte) * MULT`; `finish()` runs Murmur3's fmix64 finalizer to scramble the result so every input bit avalanches across the output. **Not adversarially safe.** The mixer is unkeyed, so an attacker who can choose keys can craft collisions. For HashDoS resistance, swap in a keyed hasher (planned: `SipHasher13`) by spelling out `Dictionary[K, V, SipHasher13]` directly. For non-adversarial workloads — internal IDs, parser symbols, config values — this hasher is faster and has better distribution than FNV-1a. # Examples ``` var h = DefaultHasher(); "hello".hash(into: h); let hash = h.finish(); // 64-bit hash of "hello" // Used implicitly through the dictionary type alias: let d: [String: Int64] = ["a": 1]; // DefaultHasher under the hood ``` # Algorithm Initialization seeds `state` with the wyhash secret `0x9e3779b97f4a7c15` (the "golden ratio" constant SplitMix64 uses). Each byte updates the state with `state = (state ^ byte) * 0x100000001b3`, which combines wyhash's mixing constant with FNV-1a's prime so every bit of the byte propagates across the 64-bit state. `finish()` runs Murmur3's `fmix64` finalizer (xor-shift-multiply twice) so consecutive integer keys produce non-clustered hashes. # Representation One `UInt64` field, `state`, holding the running digest. #### initializer Empty ```kestrel public init() ``` Creates a fresh hasher seeded with the SplitMix64 golden-ratio constant `0x9e3779b97f4a7c15`. The same input fed to two new hashers always produces the same `finish()` value — this hasher is deterministic across runs (no random seeding). **Hasher** #### function finish ```kestrel public mutating func finish() -> UInt64 ``` Returns the finalized 64-bit digest. Runs Murmur3's `fmix64` finalizer over the running state — two rounds of xor-shift-multiply that avalanche every input bit across the output. Consecutive integer keys (a common bucket query pattern) emerge well-distributed despite the simple mixer, which would otherwise leak the input's low-bit regularity into the bucket index. `finish()` mutates `state`; calling it twice on the same hasher is undefined — construct a fresh `DefaultHasher()` per logical hash. #### function write ```kestrel public mutating func write(ArraySlice[UInt8]) ``` Folds every byte of `bytes` into the running hash state. May be called any number of times before `finish()`; the result is identical to having received all the bytes in a single call. Safe to call with an empty slice (no-op). # Examples ``` var h = DefaultHasher(); h.write(bytes: "hello".utf8Bytes()); h.write(bytes: " world".utf8Bytes()); // Equivalent to a single write of "hello world".utf8Bytes() ``` **Defaultable** #### initializer Default ```kestrel init() ``` Builds the default-valued instance. ### struct Deque ```kestrel public struct Deque[T] { /* private fields */ } ``` A double-ended queue backed by a ring buffer with copy-on-write storage. O(1) amortized `pushBack`/`pushFront`/`popBack`/`popFront` and O(1) random access by index. Storage is shared between copies until one mutates, at which point the COW barrier fires. # Examples ``` var d = Deque[Int64](); d.pushBack(1); d.pushFront(0); d.pushBack(2); d.popFront(); // .Some(0) d.popBack(); // .Some(2) ``` # Representation Holds a `CowBox[DequeStorage[T]]`. The storage is a `(ptr, len, cap, head)` quad over a heap-allocated ring buffer. # Memory Model Reference-counted storage with copy-on-write value semantics via `CowBox`. Copying a `Deque` is O(1); the first mutation on a shared copy triggers a deep clone that linearizes the ring buffer. # Guarantees - `pushBack`/`pushFront` are O(1) amortized; growth is geometric. - `popBack`/`popFront` are O(1). - Subscript access is O(1). - Iteration order is front-to-back. #### initializer Empty ```kestrel public init() ``` Creates an empty deque with no allocation. No heap memory is allocated until the first `pushBack` or `pushFront`. Use `Deque(capacity:)` to pre-allocate when the expected size is known. # Examples ``` var d = Deque[Int64](); d.isEmpty; // true ``` #### initializer From Iterable ```kestrel public init[I](from: I) where I: Iterable, I.Item == T ``` Creates a deque by collecting every element from an iterable. Elements are appended via `pushBack`, so iteration order of the source is preserved as front-to-back order in the deque. # Examples ``` let d = Deque[Int64](from: 1..<5); d.count; // 4 d.first(); // .Some(1) d.last(); // .Some(4) ``` #### subscript Indexed ```kestrel subscript(Int64) -> T { get set } ``` O(1) random access by logical index. Logical index 0 is the front element, `count - 1` is the back. The ring-buffer offset is computed internally. Both get and set are O(1). # Errors Panics with `"Deque: index out of bounds"` when `index < 0` or `index >= count`. # Examples ``` var d = Deque[Int64](from: [10, 20, 30]); d(0); // 10 d(2); // 30 d(1) = 99; d(1); // 99 ``` #### initializer With Capacity ```kestrel public init(capacity: Int64) ``` Creates an empty deque with at least `capacity` slots reserved. Allocates a ring buffer that can hold `capacity` elements before needing to grow. Passing 0 is equivalent to `Deque()`. # Examples ``` var d = Deque[Int64](capacity: 100); d.count; // 0 d.capacity; // 100 ``` #### function asSlices ```kestrel public func asSlices() -> (ArraySlice[T], ArraySlice[T]) ``` Returns the two contiguous slices that make up the ring buffer. If the buffer doesn't wrap, the first slice contains all elements and the second is empty. If it wraps, the first slice covers head-to-end and the second covers start-to-tail. Useful for bulk operations that need pointer-contiguous access without copying. # Examples ``` var d = Deque[Int64](from: [1, 2, 3]); let (a, b) = d.asSlices(); // non-wrapping: a contains all 3 elements, b is empty ``` #### field capacity ```kestrel public var capacity: Int64 { get } ``` Number of elements the buffer can hold without reallocating. The deque automatically grows when `count` exceeds `capacity`, so this is mainly useful for pre-sizing via `reserveCapacity()`. # Examples ``` var d = Deque[Int64](capacity: 16); d.capacity; // 16 ``` #### function clear ```kestrel public mutating func clear() ``` Removes all elements, retaining allocated capacity. After calling `clear()`, `count` is 0 and `head` resets to 0, but the buffer stays allocated so subsequent pushes avoid reallocation. # Examples ``` var d = Deque[Int64](from: [1, 2, 3]); d.clear(); d.isEmpty; // true ``` #### field count ```kestrel public var count: Int64 { get } ``` Number of elements in the deque. # Examples ``` let d = Deque[Int64](from: [1, 2, 3]); d.count; // 3 ``` #### function first ```kestrel public func first() -> T? ``` Returns the front element without removing it, or `.None` if empty. O(1). The removing counterpart is `popFront()`. # Examples ``` let d = Deque[Int64](from: [10, 20, 30]); d.first(); // .Some(10) Deque[Int64]().first(); // .None ``` #### field isEmpty ```kestrel public var isEmpty: Bool { get } ``` True when the deque contains no elements. # Examples ``` Deque[Int64]().isEmpty; // true Deque[Int64](from: [1]).isEmpty; // false ``` #### function last ```kestrel public func last() -> T? ``` Returns the back element without removing it, or `.None` if empty. O(1). The removing counterpart is `popBack()`. # Examples ``` let d = Deque[Int64](from: [10, 20, 30]); d.last(); // .Some(30) Deque[Int64]().last(); // .None ``` #### function popBack ```kestrel public mutating func popBack() -> T? ``` Removes and returns the back element, or `.None` if empty. O(1). Retracts the logical tail by one slot. The non-removing mirror is `last()`. The front-end counterpart is `popFront()`. # Examples ``` var d = Deque[Int64](from: [1, 2, 3]); d.popBack(); // .Some(3) d.popBack(); // .Some(2) d.popBack(); // .Some(1) d.popBack(); // .None ``` #### function popFront ```kestrel public mutating func popFront() -> T? ``` Removes and returns the front element, or `.None` if empty. O(1). Advances the ring-buffer head by one slot. The non-removing mirror is `first()`. The back-end counterpart is `popBack()`. # Examples ``` var d = Deque[Int64](from: [1, 2, 3]); d.popFront(); // .Some(1) d.popFront(); // .Some(2) d.popFront(); // .Some(3) d.popFront(); // .None ``` #### function pushBack ```kestrel public mutating func pushBack(T) ``` Appends `element` to the back of the deque. O(1) amortized. Grows the ring buffer geometrically when full. The counterpart for the front end is `pushFront`. # Examples ``` var d = Deque[Int64](); d.pushBack(1); d.pushBack(2); d.popFront(); // .Some(1) ``` #### function pushFront ```kestrel public mutating func pushFront(T) ``` Prepends `element` to the front of the deque. O(1) amortized. Grows the ring buffer geometrically when full. The counterpart for the back end is `pushBack`. # Examples ``` var d = Deque[Int64](); d.pushFront(1); d.pushFront(0); d.popFront(); // .Some(0) ``` #### function reserveCapacity ```kestrel public mutating func reserveCapacity(minimumCapacity: Int64) ``` Ensures the buffer can hold at least `capacity` elements without reallocating. If the current capacity already meets or exceeds `capacity`, this is a no-op. Otherwise the ring buffer is reallocated and linearized. Useful before a burst of `pushBack`/`pushFront` calls when the final size is known in advance. # Examples ``` var d = Deque[Int64](); d.reserveCapacity(minimumCapacity: 100); ``` **Iterable** #### typealias Item ```kestrel type Item = T ``` `Iterable` element type. #### typealias TargetIterator ```kestrel type TargetIterator = DequeIterator[T] ``` `Iterable` iterator type. #### function iter ```kestrel public func iter() -> DequeIterator[T] ``` Returns an iterator that yields elements front-to-back. The iterator walks the ring buffer from `head` through `count` elements, wrapping around the buffer boundary transparently. # Examples ``` var d = Deque[Int64](from: [10, 20, 30]); for x in d { // yields 10, 20, 30 } ``` **Cloneable** #### function clone ```kestrel public func clone() -> Deque[T] ``` Returns a shallow copy of this deque. O(1). The `CowBox` storage is shared until either copy mutates, at which point the COW barrier fires a deep clone that linearizes the ring buffer. # Examples ``` let d = Deque[Int64](from: [1, 2, 3]); var d2 = d.clone(); d2.pushBack(4); d.count; // 3 -- original unchanged d2.count; // 4 ``` ### struct DequeIterator ```kestrel public struct DequeIterator[T] { /* private fields */ } ``` Iterator over a `Deque[T]`, walking the ring buffer from head through `remaining` elements. Created by `Deque.iter()`. Yields elements front-to-back, wrapping around the ring buffer boundary transparently. # Representation Holds a raw pointer into the deque's ring buffer, the buffer capacity, the current physical position, and a remaining-element count. Does not own the storage. #### initializer From Fields ```kestrel public init(ptr: Pointer[T], cap: Int64, pos: Int64, remaining: Int64) ``` Constructs an iterator from the ring buffer's raw state. Called internally by `Deque.iter()`. **Iterator** #### typealias Item ```kestrel type Item = T ``` `Iterator` element type. #### typealias TargetIterator ```kestrel type TargetIterator = Self ``` #### function all ```kestrel 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) ``` #### function any ```kestrel 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 ``` #### function chain ```kestrel 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] ``` #### function collect ```kestrel 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] ``` #### function compactMap ```kestrel public func compactMap[T]() -> FilterMapIterator[Self, T] where Item == Optional[T] ``` Drops `None`s and unwraps `Some`s — 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] ``` #### function contains ```kestrel 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 ``` #### function count ```kestrel 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 ``` #### function cycle ```kestrel 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] ``` #### function enumerate ```kestrel 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}") }; ``` #### function filter ```kestrel public func filter(where: (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] ``` #### function filterMap ```kestrel public func filterMap[U](as: (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] ``` #### function first ```kestrel 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 ``` #### function firstIndex ```kestrel 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 ``` #### function flatMap ```kestrel public func flatMap[U](as: (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] ``` #### function flatten ```kestrel 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] ``` #### function fold ```kestrel 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 ``` #### function forEach ```kestrel 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) }; ``` #### function fuse ```kestrel 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. #### function inspect ```kestrel public func inspect((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(); ``` #### function intersperse ```kestrel 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] ``` #### function intersperseWith ```kestrel public func intersperseWith(with: () -> 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] ``` #### function isSorted ```kestrel 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) ``` #### function isSortedDescending ```kestrel public consuming func isSortedDescending() -> Bool ``` True if elements come out in descending order. Mirror of `isSorted`. #### function iter ```kestrel func iter() -> Self ``` Returns `self`. The blanket conformance pivot — iterators *are* iterables. #### function last ```kestrel 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. #### function map ```kestrel public func map[U](as: (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] ``` #### function max ```kestrel public consuming func max() -> Item? ``` Largest element, or `None` for an empty iterator. Ties go to the first occurrence. #### function min ```kestrel 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 ``` #### function next ```kestrel public mutating func next() -> T? ``` Advances the iterator and returns the next element, or `.None` when all elements have been consumed. Handles the ring-buffer wrap-around: when `pos` reaches `cap` it resets to 0. # Examples ``` var d = Deque[Int64](from: [10, 20]); var it = d.iter(); it.next(); // .Some(10) it.next(); // .Some(20) it.next(); // .None ``` #### function nth ```kestrel 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) ``` #### function peekable ```kestrel 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) ``` #### function product ```kestrel 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 ``` #### function reduce ```kestrel 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 ``` #### function scan ```kestrel public func scan[Acc](from: Acc, by: (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] ``` #### function skip ```kestrel 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(); // [] ``` #### function skipWhile ```kestrel public func skipWhile(where: (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] ``` #### function sorted ```kestrel 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] ``` #### function stepBy ```kestrel 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] ``` #### function sum ```kestrel 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 ``` #### function take ```kestrel 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] ``` #### function takeWhile ```kestrel public func takeWhile(where: (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] ``` #### function tryFold ```kestrel 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") ``` #### function tryForEach ```kestrel public mutating func tryForEach[E]((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 ``` #### function unzip ```kestrel 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"] ``` #### function zip ```kestrel 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)] ``` ### struct Dictionary ```kestrel public struct Dictionary[K, V, H = DefaultHasher] where K: Hashable, H: Hasher, H: Defaultable { /* private fields */ } ``` An unordered hash map keyed by any `K: Hashable`, parameterized over the hasher type `H` (defaults to `DefaultHasher`). Uses open addressing with linear probing and a 75% load-factor threshold for resizes; capacity always grows to the next power of two. Storage is reference-counted with copy-on-write, so copying a `Dictionary` is O(1) and only the next mutation pays for the deep clone. Iteration order is unspecified and may change between versions or after any mutation. For ordered alternatives consider keeping an ordered key list separately; for set-only behavior see `Set`. # Examples ``` var ages: [String: Int64] = [:]; ages("Alice") = 30; ages("Bob") = 25; ages("Alice"); // Some(30) ages("Carol", default: 0); // 0 for (name, age) in ages.iter() { ... } let sum = ages.values.iter().sum(); ``` # Hashing The hash for each key is cached in its bucket so resizes don't recompute it. Replacing the hasher (`H`) lets you swap in `SipHasher`, `FxHasher`, etc.; the default is `DefaultHasher` and resolves through the `[K: V]` shorthand. # Capacity & Reallocation `count` is live entries; `capacity` is total slots. The table resizes (doubling capacity, starting from 8) once `count` reaches 75% of `capacity`. Use `reserveCapacity(...)` to pre-grow and `shrinkToFit()` to release excess. # Representation One field: an `RcBox[DictionaryStorage[K, V, H]]` holding `(buckets, len, cap)` over a heap bucket array. # Memory Model Reference-counted storage with copy-on-write *value* semantics. Copying a `Dictionary` is O(1) and shares the bucket array; the next mutation on a shared dictionary triggers `makeUnique()`, which deep-clones via `DictionaryStorage.clone()` so the mutation is invisible to other copies. # Guarantees - Every key satisfies `K: Hashable`. The cached hash is computed once per insert and reused on resize. - `count <= capacity * 3 / 4` after every mutation (the resize threshold). - Removing a key leaves a `.Deleted` tombstone; lookups still work but tombstones reduce effective capacity until the next resize. - Iteration order is **not** specified. #### initializer Dictionary Literal ```kestrel public init(dictionaryLiteral: std.memory.LiteralSlice[(K, V)]) ``` Creates a dictionary by inserting every `(K, V)` pair from a literal slice in order. Last-write-wins on duplicate keys (same as `init(from:)`). An empty literal yields an empty unallocated dictionary. # Examples ``` // Triggered by the dictionary-literal syntax: let dict: [String: Int64] = ["a": 1, "b": 2]; ``` #### initializer Empty ```kestrel public init() ``` Creates an empty dictionary with no allocation. Capacity starts at zero; the first insert allocates the smallest bucket array (currently 8 slots). For pre-sized creation use `init(capacity:)`. # Examples ``` var d = Dictionary[String, Int64](); d.count; // 0 d.capacity; // 0 ``` #### initializer From Pairs ```kestrel public init[I](from: I) where I: Iterable, I.Item == (K, V) ``` Creates a dictionary by inserting every `(key, value)` pair produced by an iterable. Last write wins for duplicate keys. For a panic-on-duplicate variant use `init(uniquePairs:)`. Capacity grows geometrically as inserts arrive — for sized sources, follow up with `shrinkToFit()` if memory matters. # Examples ``` let pairs = [("a", 1), ("b", 2)]; let dict = Dictionary(from: pairs); // ["a": 1, "b": 2] let dups = Dictionary(from: [("a", 1), ("a", 2)]); // ["a": 2] — later wins ``` #### initializer Grouping ```kestrel public init[I, E](grouping: I, by: (E) -> K) where I: Iterable, I.Item == E, V == Array[E] ``` Buckets each element of an iterable into an array under the key derived from `keyFunc`. The value type is constrained to `Array[E]`: each bucket accumulates the elements that mapped to it, in insertion order within that bucket. Useful for building "index-by" tables from a flat collection. The `keyFunc` runs once per element. # Examples ``` let words = ["apple", "apricot", "banana", "blueberry"]; let grouped = Dictionary(grouping: words) { (w) in w.chars.first().unwrap() }; // ["a": ["apple", "apricot"], "b": ["banana", "blueberry"]] let nums = [1, 2, 3, 4, 5]; let parity = Dictionary(grouping: nums) { (n) in n % 2 }; // [0: [2, 4], 1: [1, 3, 5]] ``` #### initializer Literal Bridge ```kestrel public init(consuming lang.ptr[(K, V)], consuming lang.i64) ``` Compiler-emitted bridge for `[k: v, ...]` literals. Not called by user code directly — the parser lowers literal expressions into a `(ptr, count)` pair which this constructor wraps in a `LiteralSlice` and forwards to `init(dictionaryLiteral:)`. # Safety The compiler guarantees `_dictionaryLiteralPointer` points to exactly `_dictionaryLiteralCount` initialized `(K, V)` pairs. #### subscript Lookup ```kestrel public subscript(K) -> V? { get set } ``` Reads the value for `key` (or `None` if absent), or assigns to insert/remove the entry. The assignment form treats `Some(v)` as insert/update and `None` as delete — so `dict(k) = None` is the inline form of `dict.remove(k)`. For a non-`Optional` getter use `dict(key, default: ...)` or `dict(unwrap: key)`. # Examples ``` var dict = ["a": 1, "b": 2]; dict("a"); // Some(1) dict("z"); // None dict("c") = 3; // inserts "c": 3 dict("a") = None; // removes "a" ``` #### initializer Unique Keys ```kestrel public init[I](uniquePairs: I) where I: Iterable, I.Item == (K, V) ``` Creates a dictionary from key-value pairs, panicking on any duplicate key. Use this when duplicate keys would indicate a bug in upstream data; for last-write-wins semantics use `init(from:)`. Each pair triggers a `contains` check before insertion, so it's slower than `init(from:)` for large inputs. # Errors Panics with `"Dictionary(uniquePairs:): duplicate key"` the first time `pairs` yields a key already in the dictionary. # Examples ``` let dict = Dictionary(uniquePairs: [("a", 1), ("b", 2)]); Dictionary(uniquePairs: [("a", 1), ("a", 2)]); // PANIC: Dictionary(uniquePairs:): duplicate key ``` #### subscript Unwrap ```kestrel public subscript(unwrap: K) -> V { get set } ``` Reads or writes the value for `key`, panicking on the read when the key is absent. Use when you've already verified the key exists (or when its absence indicates a bug). The setter is equivalent to `insert(key, newValue)` and never panics. For a non-panicking read use `dict(key)` or `dict(key, default: ...)`. # Errors Read panics with `"Dictionary subscript(unwrap:): key not found"` when the key is absent. # Examples ``` let dict = ["a": 1, "b": 2]; dict(unwrap: "a"); // 1 dict(unwrap: "z"); // PANIC: key not found ``` #### initializer With Capacity ```kestrel public init(capacity: Int64) ``` Creates an empty dictionary sized to hold at least the requested number of entries without resizing. The actual allocated capacity is the next power of two `>= capacity` (minimum 8). A non-positive `capacity` behaves like `init()` (no allocation). Panics on allocation failure. # Examples ``` var d = Dictionary[String, Int64](capacity: 100); d.capacity; // 128 (next power of two) d.count; // 0 ``` #### subscript With Default ```kestrel public subscript(K, default: V) -> V { get } ``` Reads the value for `key`, falling back to `defaultValue` when the key is absent. Read-only and *non-inserting* — the default value is returned but never stored. To upsert with a default, use `upsert(...)` or `update(...)`. # Examples ``` let dict = ["a": 1, "b": 2]; dict("a", default: 0); // 1 dict("z", default: 0); // 0 dict("z"); // still None — default wasn't stored ``` #### function all ```kestrel public func all(where: (K, V) -> Bool) -> Bool ``` `true` when every entry satisfies `predicate(key, value)` (vacuously true for empty). Short-circuits on the first failure. Dual of `any(where:)`. # Examples ``` ["a": 2, "b": 4].all { (k, v) in v % 2 == 0 }; // true ["a": 1, "b": 2].all { (k, v) in v % 2 == 0 }; // false [:].all { (k, v) in false }; // true (vacuous) ``` #### function allKeys ```kestrel public func allKeys(of: V) -> Array[K] ``` Returns every key whose value equals `value`. O(capacity), allocates an `Array[K]`. Result order matches bucket layout and is therefore unspecified. Empty array if no matches. # Examples ``` ["a": 1, "b": 2, "c": 1].allKeys(of: 1); // ["a", "c"] — order unspecified ["a": 1].allKeys(of: 99); // [] ``` #### function any ```kestrel public func any(where: (K, V) -> Bool) -> Bool ``` `true` when at least one entry satisfies `predicate(key, value)`. Alias for `contains(where:)` — the two names exist so predicate-style code reads naturally regardless of context. Short-circuits on the first match. # Examples ``` ["a": 1, "b": 5].any { (k, v) in v > 3 }; // true [:].any { (k, v) in true }; // false (empty) ``` #### field capacity ```kestrel public var capacity: Int64 { get } ``` Total slots in the bucket array — always `>= count`. Read-only. Resizes (doubling) trigger when `count` reaches 75% of `capacity`. Tombstones count against the threshold even though they don't count toward `count`. The actual value after `init(capacity:)` rounds up to the next power of two. # Examples ``` let d = Dictionary[String, Int64](capacity: 100); d.capacity; // 128 ``` #### function clear ```kestrel public mutating func clear() ``` Removes every entry, leaving the bucket array allocated and reset to all-`.Empty`. O(capacity). The buffer is kept so subsequent inserts don't reallocate; follow with `shrinkToFit()` to release it. # Examples ``` var dict = ["a": 1, "b": 2]; dict.clear(); // dict = [:] dict.capacity; // unchanged ``` #### function compactMapValues ```kestrel public func compactMapValues[U]((V) -> U?) -> Dictionary[K, U, H] ``` Returns a new dictionary with each value run through `transform`; entries whose `transform(value)` is `None` are dropped. Useful for parse-or-skip patterns. The result is unsized at construction (since the final count isn't known until the pass completes); for fixed transforms that always succeed, `mapValues(...)` avoids the allocation policy difference. # Examples ``` let dict = ["a": "1", "b": "two", "c": "3"]; let parsed = dict.compactMapValues { (s) in Int64.parse(s) }; // ["a": 1, "c": 3] — "two" failed to parse ``` #### function contains ```kestrel public func contains(K) -> Bool ``` `true` if `key` is present in the dictionary. Wraps `findEntry`. For value-based search use the `V: Equatable` extension's `containsValue(value:)`. # Examples ``` ["a": 1, "b": 2].contains("a"); // true ["a": 1, "b": 2].contains("z"); // false ``` #### function contains ```kestrel public func contains(where: (K, V) -> Bool) -> Bool ``` `true` if any entry satisfies `predicate(key, value)`. Linear scan; short-circuits on the first match. `false` for empty dictionaries. The aliased shape `any(satisfy:)` exists for symmetry with `Array`. # Examples ``` ["a": 1, "b": 5].contains { (k, v) in v > 3 }; // true ["a": 1, "b": 2].contains { (k, v) in v > 3 }; // false ``` #### function containsValue ```kestrel public func containsValue(V) -> Bool ``` `true` if any entry's value equals `value`. O(capacity) — every bucket is inspected because the dictionary is keyed on `K`, not `V`. For `O(1)` checks against a small set of values, build a `Set[V]` instead. # Examples ``` ["a": 1, "b": 2].containsValue(2); // true ["a": 1, "b": 2].containsValue(5); // false ``` #### field count ```kestrel public var count: Int64 { get } ``` Number of live (`.Occupied`) entries. Read-only; O(1). Excludes tombstones — `count` only reflects what `iter()`/`contains(...)` would see. # Examples ``` ["a": 1, "b": 2].count; // 2 [:].count; // 0 ``` #### function countItems ```kestrel public func countItems(where: (K, V) -> Bool) -> Int64 ``` Returns the number of entries for which `predicate(key, value)` is true. Linear scan, no short-circuit. For just a presence check use `any(where:)`; for a yes/no on every entry, `all(where:)`. # Examples ``` ["a": 1, "b": 2, "c": 3].countItems { (k, v) in v > 1 }; // 2 [:].countItems { (k, v) in true }; // 0 ``` #### function deepClone ```kestrel public func deepClone() -> Dictionary[K, V, H] ``` Returns a fully-detached copy of the dictionary, with no shared storage. Walks every bucket and re-inserts the live entries into a freshly-sized table. Use over `clone()` when you specifically want to avoid the lazy COW share — for example, before passing the copy to another thread or system that might race with further mutations. # Examples ``` let a = ["x": [1, 2, 3]]; let b = a.deepClone(); // fully independent copy ``` #### function filter ```kestrel public func filter(where: (K, V) -> Bool) -> Dictionary[K, V, H] ``` Returns a new dictionary containing only entries for which `predicate(key, value)` is true. Non-mutating mirror of `retain(where:)`. Allocates a fresh dictionary; for in-place filtering use `retain` or `removeAll(where:)`. # Examples ``` let dict = ["a": 1, "b": 2, "c": 3]; let big = dict.filter { (k, v) in v > 1 }; // ["b": 2, "c": 3] ``` #### function first ```kestrel public func first(where: (K, V) -> Bool) -> (K, V)? ``` Returns *some* entry matching `predicate(key, value)`, or `None`. "First" is determined by bucket order, which is hash-dependent and unspecified — treat the result as arbitrary among matching entries. Short-circuits on the first match. # Examples ``` let dict = ["a": 1, "b": 5, "c": 3]; dict.first { (k, v) in v > 2 }; // Some entry with v > 2 dict.first { (k, v) in v > 99 }; // None ``` #### function firstKey ```kestrel public func firstKey(of: V) -> K? ``` Returns *some* key mapping to `value`, or `None`. O(capacity); short-circuits on the first match. "First" is determined by bucket order and is unspecified — for an exhaustive list use `allKeys(of:)`. # Examples ``` ["a": 1, "b": 2].firstKey(of: 2); // Some("b") ["a": 1, "b": 2].firstKey(of: 5); // None ``` #### function insert ```kestrel public mutating func insert(K, V) -> V? ``` Inserts `(key, value)`, replacing any existing entry for `key`, and returns the old value (or `None`) on update. Triggers `ensureCapacity()` and may resize before the insert lands. The cached hash is computed once here. For transform-based updates see `update(...)` and `upsert(...)`. # Examples ``` var dict = ["a": 1]; dict.insert("b", 2); // None; dict = ["a": 1, "b": 2] dict.insert("a", 9); // Some(1); dict = ["a": 9, "b": 2] ``` #### field isEmpty ```kestrel public var isEmpty: Bool { get } ``` `true` when the dictionary holds no live entries; equivalent to `count == 0`. Reads more naturally than the comparison. # Examples ``` [:].isEmpty; // true ["a": 1].isEmpty; // false ``` #### field keys ```kestrel public var keys: KeysView[K, V] { get } ``` Lazy view of the dictionary's keys, iterable in unspecified order. Constructing the view is O(1) — it shares the bucket pointer and skips empty/deleted slots during iteration. The view is invalidated by any mutation that may reallocate (insertion past the load threshold, `reserveCapacity`, `shrinkToFit`). # Examples ``` let dict = ["a": 1, "b": 2, "c": 3]; for key in dict.keys { print(key) } let keyArray = Array(from: dict.keys); ``` #### function mapValues ```kestrel public func mapValues[U]((V) -> U) -> Dictionary[K, U, H] ``` Returns a new dictionary with each value run through `transform`, keys unchanged. Pre-sized to `self.capacity` so the first build avoids resizing. The result's value type can change (`V → U`); for a version that drops `None` results see `compactMapValues(...)`. # Examples ``` let dict = ["a": 1, "b": 2]; let doubled = dict.mapValues { (v) in v * 2 }; // ["a": 2, "b": 4] ``` #### function merge ```kestrel public mutating func merge(Dictionary[K, V, H], uniquingKeysWith: (V, V) -> V) ``` Merges every entry of `other` into `self`, calling `combine` to resolve key collisions. `combine(existing, incoming)` is invoked exactly once per collision — pick one, return both summed, or use `(_, new)` for last-write-wins. New keys are inserted directly. For a non-mutating variant use `merging(...)`. # Examples ``` var a = ["x": 1, "y": 2]; let b = ["y": 20, "z": 30]; a.merge(b) { (old, new) in old + new }; // a == ["x": 1, "y": 22, "z": 30] ``` #### function merge ```kestrel public mutating func merge[I](from: I, uniquingKeysWith: (V, V) -> V) where I: Iterable, I.Item == (K, V) ``` Merges every `(key, value)` pair from an arbitrary iterable into `self`, calling `combine` on collisions. Same semantics as `merge(...)` but accepts any iterable of pairs — useful for arrays of tuples, generator output, or streamed sources. # Examples ``` var dict = ["a": 1]; dict.merge(from: [("b", 2), ("c", 3)]) { (_, new) in new }; // dict == ["a": 1, "b": 2, "c": 3] ``` #### function merging ```kestrel public func merging(Dictionary[K, V, H], uniquingKeysWith: (V, V) -> V) -> Dictionary[K, V, H] ``` Returns a new dictionary that is `self` merged with `other`, resolving collisions via `combine`. Non-mutating mirror of `merge(...)`. Internally clones via COW (cheap until the next mutation) and merges into the copy. # Examples ``` let a = ["x": 1, "y": 2]; let b = ["y": 20, "z": 30]; let merged = a.merging(b) { (_, new) in new }; // merged == ["x": 1, "y": 20, "z": 30] // a is unchanged ``` #### function remove ```kestrel public mutating func remove(K) -> V? ``` Removes `key` and returns its value, or `None` if absent. Replaces the bucket with a `.Deleted` tombstone so existing probe chains stay intact. Tombstones are reclaimed by the next resize. Triggers COW only when an entry is actually removed. # Examples ``` var dict = ["a": 1, "b": 2]; dict.remove("a"); // Some(1); dict = ["b": 2] dict.remove("z"); // None; dict unchanged ``` #### function removeAll ```kestrel public mutating func removeAll(where: (K, V) -> Bool) ``` Removes every entry for which `predicate(key, value)` is true. Inverse of `retain(where:)`; implemented as `retain` over the negated predicate. Same tombstone caveat applies — consider `shrinkToFit()` after large removals. # Examples ``` var dict = ["a": 1, "b": 2, "c": 3]; dict.removeAll { (k, v) in v < 2 }; // ["b": 2, "c": 3] ``` #### function reserveCapacity ```kestrel public mutating func reserveCapacity(Int64) ``` Grows the bucket array so at least `minimumCapacity` entries fit without resizing. No-op when current capacity already suffices. The actual new capacity rounds up to the next power of two and accounts for the 75% load factor (so target = `nextPowerOfTwo(min * 4 / 3)`). The opposite operation is `shrinkToFit()`. # Examples ``` var dict = Dictionary[String, Int64](); dict.reserveCapacity(1000); // No reallocations for the first ~750 inserts. ``` #### function retain ```kestrel public mutating func retain(where: (K, V) -> Bool) ``` Keeps only entries for which `predicate(key, value)` is true. Two-pass implementation: collects keys to remove, then deletes them. Each removal leaves a tombstone — call `shrinkToFit()` afterwards if you've removed a large fraction. The mirror is `removeAll(where:)`. # Examples ``` var dict = ["a": 1, "b": 2, "c": 3]; dict.retain { (k, v) in v > 1 }; // ["b": 2, "c": 3] ``` #### function shrinkToFit ```kestrel public mutating func shrinkToFit() ``` Reduces capacity to the smallest power of two that still satisfies the load factor for the current `count`. Frees excess memory and reclaims tombstone space (the resize rebuilds the table without them). Empty dictionaries fall through to `clear()`. No-op when the table is already at the minimum acceptable capacity. # Examples ``` var dict = Dictionary[String, Int64](capacity: 1000); dict("a") = 1; dict.shrinkToFit(); // capacity drops from 1024 to 8 ``` #### function sumValues ```kestrel public func sumValues() -> V ``` Returns the sum of every value, starting from `V()` (the default-constructed zero). Empty dictionaries return `V()` — for `Int64` that's `0`, for `String` that's `""`, etc. Linear in `count`. # Examples ``` ["a": 1, "b": 2, "c": 3].sumValues(); // 6 [:].sumValues(); // 0 — V's default ``` #### function update ```kestrel public mutating func update(K, with: (V) -> V) -> Bool ``` Applies `transform` to the existing value for `key` and writes the result back; returns whether the key was found. No-op when the key is absent — for "update or insert" semantics use `upsert(...)`. Internally re-uses `insert(...)`, so the hash is recomputed. # Examples ``` var dict = ["a": 1, "b": 2]; dict.update("a") { (v) in v * 10 }; // true; dict("a") == Some(10) dict.update("z") { (v) in v * 10 }; // false; dict unchanged ``` #### function upsert ```kestrel public mutating func upsert(K, default: V, with: (V) -> V) ``` Inserts `transform(defaultValue)` for a new key, or `transform(existing)` for an existing one. The classic "increment-or-set-to-1" pattern. `defaultValue` is passed through `transform` even on the insert path, so the same closure handles both branches uniformly. For the no-insert variant see `update(...)`. # Examples ``` var counts: [String: Int64] = [:]; counts.upsert("apple", default: 0) { (n) in n + 1 }; counts.upsert("apple", default: 0) { (n) in n + 1 }; counts("apple"); // Some(2) ``` #### field values ```kestrel public var values: ValuesView[K, V] { get } ``` Lazy view of the dictionary's values, iterable in unspecified order. Same iteration order as `keys` — the two views walk the buckets in lockstep, so `zip(dict.keys, dict.values)` yields pairs equivalent to `dict.iter()`. Invalidated by any mutation that may reallocate. # Examples ``` let dict = ["a": 1, "b": 2, "c": 3]; for value in dict.values { print(value) } let sum = dict.values.iter().sum(); // 6 ``` **Iterable** #### typealias Item ```kestrel type Item = (K, V) ``` `Iterable` element type — a `(key, value)` tuple. #### typealias TargetIterator ```kestrel type TargetIterator = DictionaryIterator[K, V] ``` Concrete iterator type returned by `iter()`. #### function iter ```kestrel public func iter() -> DictionaryIterator[K, V] ``` Returns a `DictionaryIterator[K, V]` over the live entries. Order is unspecified and may change between mutations. The iterator borrows the bucket array; do not mutate the dictionary while iterating. For key- or value-only iteration, use `keys.iter()` / `values.iter()`. # Examples ``` for (k, v) in dict.iter() { ... } let entries = Array(from: dict.iter()); ``` **Cloneable** #### function clone ```kestrel public func clone() -> Dictionary[K, V, H] ``` Returns a `Dictionary` sharing the same storage; the deep copy is deferred until either side mutates. O(1) — just bumps the storage `RcBox`'s refcount. The first mutation on either side triggers `makeUnique()`, which deep-clones via `DictionaryStorage.clone()`. For an immediate deep copy use `deepClone()` (defined in the unconditional extension below). # Examples ``` let a: [String: Int64] = ["x": 1]; var b = a.clone(); // O(1), shares storage b("y") = 2; // b deep-copies here; a is unchanged ``` **Equatable** #### typealias Output ```kestrel type Output = Bool ``` #### function equal ```kestrel public func equal(to: Self) -> Bool ``` Bridges `Equal.equal(to:)` to `Equatable.isEqual(to:)`. #### function isEqual ```kestrel public func isEqual(to: Dictionary[K, V, H]) -> Bool ``` Order-independent equality: dictionaries are equal iff they have the same `count` and every key in `self` is present in `other` with an equal value. Short-circuits on the first mismatch. Insertion order does not matter — only the multiset of `(key, value)` pairs does. # Examples ``` ["a": 1, "b": 2].isEqual(to: ["b": 2, "a": 1]); // true ["a": 1].isEqual(to: ["a": 2]); // false ["a": 1].isEqual(to: [:]); // false ``` #### function notEqual ```kestrel public func notEqual(to: Self) -> Bool ``` Default `!=`: delegates to `==` so there's a single source of truth. **Formattable** #### function format ```kestrel public func format(into: mutating StringBuilder, FormatOptions) ``` Renders the dictionary as `"{" + entries.joined(", ") + "}"`, passing `options` to each key and value's `format`. # Examples ``` ["a": 1, "b": 2].format(); // "{a: 1, b: 2}" — order unspecified Dictionary[String, Int64]().format(); // "{}" "\{["a": 1, "b": 2]}"; // "{a: 1, b: 2}" via interpolation ``` #### function formatted ```kestrel public func formatted(FormatOptions) -> String ``` Returns this value rendered as a `String`. Convenience wrapper: creates a `StringBuilder`, calls `format(into:)`, and returns the built string. Uses a distinct name to avoid overload-resolution ambiguity with `format(into:)`. **_ExpressibleByDictionaryLiteral** #### typealias Key ```kestrel type Key = K ``` Key type for the literal protocol — matches `K`. #### initializer Literal Bridge ```kestrel init(consuming lang.ptr[(Key, Value)], consuming lang.i64) ``` Compiler-emitted init taking a raw `(Key, Value)` pointer and count. Both params are `consuming` for the same reason as the array bridge: the compiler hands ownership of the stack buffer to the implementation. MIR lowering matches on the unwrapped param shape, so an impl that deviates from this convention will be skipped during literal lowering. #### typealias Value ```kestrel type Value = V ``` Value type for the literal protocol — matches `V`. **ExpressibleByDictionaryLiteral** #### initializer Dictionary Literal ```kestrel init(dictionaryLiteral: LiteralSlice[(Key, Value)]) ``` Builds an instance from a literal slice of key-value pairs. **Defaultable** #### initializer Default ```kestrel init() ``` Builds the default-valued instance. ### struct DictionaryIterator ```kestrel public struct DictionaryIterator[K, V] { /* private fields */ } ``` Single-pass forward iterator over the `(key, value)` entries of a `Dictionary[K, V, H]`. Produced by `Dictionary.iter()`. Walks the bucket array once, skipping `.Empty` and `.Deleted` slots, and yields each occupied entry as a tuple. Iteration order matches bucket layout, which depends on the hash and probe sequence — treat it as unspecified. For key- or value-only views see `KeysIterator` and `ValuesIterator`. # Examples ``` let dict = ["a": 1, "b": 2]; var it = dict.iter(); it.next(); // Some(("a", 1)) — order is unspecified it.next(); // Some(("b", 2)) it.next(); // None ``` # Representation A `(buckets, capacity, index)` triple — pointer to the bucket array, total slots, and the current scan position. # Memory Model Value type. The pointer aliases dictionary storage; do not retain an iterator across mutations of the source dictionary. #### initializer From Buckets ```kestrel init(buckets: Pointer[Bucket[K, V]], capacity: Int64) ``` Constructs an iterator over a raw bucket pointer of the given capacity. Prefer `Dictionary.iter()` over calling this directly. The pointer must outlive the iterator. # Safety `buckets` must point to at least `capacity` initialized `Bucket[K, V]` slots and remain valid for the iterator's lifetime. **Iterator** #### typealias Item ```kestrel type Item = (K, V) ``` Element type yielded by `next()` — a `(key, value)` tuple. #### typealias TargetIterator ```kestrel type TargetIterator = Self ``` #### function all ```kestrel 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) ``` #### function any ```kestrel 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 ``` #### function chain ```kestrel 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] ``` #### function collect ```kestrel 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] ``` #### function compactMap ```kestrel public func compactMap[T]() -> FilterMapIterator[Self, T] where Item == Optional[T] ``` Drops `None`s and unwraps `Some`s — 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] ``` #### function contains ```kestrel 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 ``` #### function count ```kestrel 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 ``` #### function cycle ```kestrel 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] ``` #### function enumerate ```kestrel 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}") }; ``` #### function filter ```kestrel public func filter(where: (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] ``` #### function filterMap ```kestrel public func filterMap[U](as: (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] ``` #### function first ```kestrel 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 ``` #### function firstIndex ```kestrel 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 ``` #### function flatMap ```kestrel public func flatMap[U](as: (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] ``` #### function flatten ```kestrel 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] ``` #### function fold ```kestrel 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 ``` #### function forEach ```kestrel 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) }; ``` #### function fuse ```kestrel 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. #### function inspect ```kestrel public func inspect((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(); ``` #### function intersperse ```kestrel 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] ``` #### function intersperseWith ```kestrel public func intersperseWith(with: () -> 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] ``` #### function isSorted ```kestrel 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) ``` #### function isSortedDescending ```kestrel public consuming func isSortedDescending() -> Bool ``` True if elements come out in descending order. Mirror of `isSorted`. #### function iter ```kestrel func iter() -> Self ``` Returns `self`. The blanket conformance pivot — iterators *are* iterables. #### function last ```kestrel 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. #### function map ```kestrel public func map[U](as: (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] ``` #### function max ```kestrel public consuming func max() -> Item? ``` Largest element, or `None` for an empty iterator. Ties go to the first occurrence. #### function min ```kestrel 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 ``` #### function next ```kestrel public mutating func next() -> (K, V)? ``` Advances the scan to the next occupied slot and returns its entry, or `None` when no more remain. Skips `.Empty` and `.Deleted` slots silently. Once `None` is returned the iterator stays exhausted. # Examples ``` var it = ["a": 1].iter(); it.next(); // Some(("a", 1)) it.next(); // None ``` #### function nth ```kestrel 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) ``` #### function peekable ```kestrel 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) ``` #### function product ```kestrel 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 ``` #### function reduce ```kestrel 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 ``` #### function scan ```kestrel public func scan[Acc](from: Acc, by: (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] ``` #### function skip ```kestrel 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(); // [] ``` #### function skipWhile ```kestrel public func skipWhile(where: (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] ``` #### function sorted ```kestrel 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] ``` #### function stepBy ```kestrel 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] ``` #### function sum ```kestrel 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 ``` #### function take ```kestrel 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] ``` #### function takeWhile ```kestrel public func takeWhile(where: (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] ``` #### function tryFold ```kestrel 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") ``` #### function tryForEach ```kestrel public mutating func tryForEach[E]((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 ``` #### function unzip ```kestrel 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"] ``` #### function zip ```kestrel 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)] ``` ### typealias DictionaryTypeOperator ```kestrel public type DictionaryTypeOperator[K, V] = Dictionary[K, V, DefaultHasher] ``` Compiler-recognized type alias that lets `[K: V]` desugar to `Dictionary[K, V, DefaultHasher]`. Allows annotations like `let m: [String: Int64] = [:]` instead of requiring the user to spell out `Dictionary[String, Int64]`. The hasher is fixed to `DefaultHasher`; for custom hashers, write the `Dictionary[...]` form explicitly. # Examples ``` let counts: [String: Int64] = [:]; func tally(of words: [String: Int64]) -> Int64 { ... } ``` ### struct Heap ```kestrel public struct Heap[T] where T: Comparable { /* private fields */ } ``` Binary min-heap backed by `Array[T]`. O(log n) `push`/`pop`, O(1) `peek` at the minimum element. Builds from an existing array in O(n) via Floyd's heapify. Iteration yields elements in storage order (NOT sorted order). # Examples ``` var h = Heap[Int64](); h.push(5); h.push(1); h.push(3); h.peek(); // .Some(1) h.pop(); // .Some(1) h.pop(); // .Some(3) ``` # Representation A single `Array[T]` field in standard binary-heap layout: the minimum lives at index 0, children of node `i` are at `2i + 1` and `2i + 2`. # Memory Model Delegates storage to `Array[T]`, inheriting its COW value semantics. Copying a `Heap` is O(1); the first mutation on a shared copy triggers the array's copy-on-write barrier. # Guarantees - `peek()` always returns the minimum element. - After `pop()`, the next-smallest element becomes the new minimum. - Iteration order is unspecified (internal heap layout). #### initializer Empty ```kestrel public init() ``` Creates an empty min-heap with no allocation. No heap memory is allocated until the first `push`. Use `Heap(capacity:)` to pre-allocate when the expected size is known. # Examples ``` var h = Heap[Int64](); h.isEmpty; // true ``` #### initializer From Data ```kestrel init(data: Array[T]) ``` Internal constructor that wraps an existing array as the heap's backing store. Used by `clone()` to avoid a redundant heapify. #### initializer From Iterable ```kestrel public init[I](from: I) where I: Iterable, I.Item == T ``` Builds a min-heap by collecting elements then heapifying in O(n). All elements are first appended to the backing array, then Floyd's algorithm establishes the heap invariant in a single bottom-up pass. This is faster than pushing elements one at a time (O(n) vs O(n log n)). # Examples ``` let h = Heap(from: [5, 3, 1, 4, 2]); h.peek(); // .Some(1) h.count; // 5 ``` #### initializer With Capacity ```kestrel public init(capacity: Int64) ``` Creates an empty min-heap with at least `capacity` slots reserved. Pre-allocates the backing array so that up to `capacity` elements can be pushed without triggering a reallocation. # Examples ``` var h = Heap[Int64](capacity: 100); h.count; // 0 ``` #### function clear ```kestrel public mutating func clear() ``` Removes all elements, retaining allocated capacity. After calling `clear()`, `count` is 0 but the backing array keeps its buffer so subsequent `push` calls avoid reallocation. # Examples ``` var h = Heap(from: [3, 1, 2]); h.clear(); h.isEmpty; // true ``` #### field count ```kestrel public var count: Int64 { get } ``` Number of elements in the heap. # Examples ``` let h = Heap(from: [3, 1, 2]); h.count; // 3 ``` #### field isEmpty ```kestrel public var isEmpty: Bool { get } ``` True when the heap contains no elements. # Examples ``` Heap[Int64]().isEmpty; // true Heap(from: [1]).isEmpty; // false ``` #### function peek ```kestrel public func peek() -> T? ``` Returns the minimum element without removing it. O(1). Returns `.None` on an empty heap. The removing counterpart is `pop()`. # Examples ``` let h = Heap(from: [3, 1, 2]); h.peek(); // .Some(1) Heap[Int64]().peek(); // .None ``` #### function pop ```kestrel public mutating func pop() -> T? ``` Removes and returns the minimum element, or `.None` if empty. O(log n). Swaps the root with the last element, removes the last, then sifts the new root down to restore the heap invariant. The non-removing mirror is `peek()`. # Examples ``` var h = Heap(from: [3, 1, 2]); h.pop(); // .Some(1) h.pop(); // .Some(2) h.pop(); // .Some(3) h.pop(); // .None ``` #### function push ```kestrel public mutating func push(T) ``` Inserts `element`, maintaining the min-heap invariant. O(log n). The element is appended to the backing array then sifted up to restore the heap property. Amortized O(log n) because the array may occasionally grow its buffer. # Examples ``` var h = Heap[Int64](); h.push(3); h.push(1); h.peek(); // .Some(1) ``` #### function reserveCapacity ```kestrel public mutating func reserveCapacity(minimumCapacity: Int64) ``` Ensures the backing array can hold at least `capacity` elements without reallocating. If the current capacity already meets or exceeds `capacity`, this is a no-op. Otherwise the backing array grows to accommodate the requested number of slots. # Examples ``` var h = Heap[Int64](); h.reserveCapacity(minimumCapacity: 100); ``` **Iterable** #### typealias Item ```kestrel type Item = T ``` `Iterable` element type. #### typealias TargetIterator ```kestrel type TargetIterator = ArraySliceIterator[T] ``` `Iterable` iterator type — reuses the backing array's iterator. #### function iter ```kestrel public func iter() -> ArraySliceIterator[T] ``` Returns an iterator over elements in storage order (NOT sorted). The iteration order reflects the internal heap layout, not the sorted order. To consume elements smallest-first, use `pop()` in a loop instead. # Examples ``` let h = Heap(from: [5, 3, 1]); var iter = h.iter(); // yields elements in heap-array order, not 1, 3, 5 ``` **Cloneable** #### function clone ```kestrel public func clone() -> Heap[T] ``` Returns a shallow copy of this heap. O(1). The backing array's copy-on-write semantics mean the actual deep copy is deferred until the first mutation on either the original or the clone. # Examples ``` let h = Heap(from: [3, 1, 2]); var h2 = h.clone(); h2.push(0); h.peek(); // .Some(1) -- original unchanged h2.peek(); // .Some(0) ``` ### struct KeysIterator ```kestrel public struct KeysIterator[K, V] where K: Hashable { /* private fields */ } ``` Single-pass iterator yielding only the keys of a dictionary. Wraps a `DictionaryIterator[K, V]` and discards the value half of each entry. Order matches the underlying entry iteration and is unspecified. # Examples ``` var it = ["a": 1, "b": 2].keys.iter(); it.next(); // Some("a") — order unspecified it.next(); // Some("b") it.next(); // None ``` # Representation Wraps a `DictionaryIterator[K, V]`. # Memory Model Value type. Aliases dictionary storage; do not retain across mutations. #### initializer From Dict ```kestrel public init(dictIter: DictionaryIterator[K, V]) ``` Wraps a `DictionaryIterator` to yield only its keys. Prefer `KeysView.iter()` over calling this directly. **Iterator** #### typealias Item ```kestrel type Item = K ``` Element type yielded by `next()` — `K`. #### typealias TargetIterator ```kestrel type TargetIterator = Self ``` #### function all ```kestrel 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) ``` #### function any ```kestrel 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 ``` #### function chain ```kestrel 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] ``` #### function collect ```kestrel 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] ``` #### function compactMap ```kestrel public func compactMap[T]() -> FilterMapIterator[Self, T] where Item == Optional[T] ``` Drops `None`s and unwraps `Some`s — 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] ``` #### function contains ```kestrel 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 ``` #### function count ```kestrel 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 ``` #### function cycle ```kestrel 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] ``` #### function enumerate ```kestrel 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}") }; ``` #### function filter ```kestrel public func filter(where: (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] ``` #### function filterMap ```kestrel public func filterMap[U](as: (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] ``` #### function first ```kestrel 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 ``` #### function firstIndex ```kestrel 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 ``` #### function flatMap ```kestrel public func flatMap[U](as: (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] ``` #### function flatten ```kestrel 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] ``` #### function fold ```kestrel 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 ``` #### function forEach ```kestrel 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) }; ``` #### function fuse ```kestrel 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. #### function inspect ```kestrel public func inspect((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(); ``` #### function intersperse ```kestrel 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] ``` #### function intersperseWith ```kestrel public func intersperseWith(with: () -> 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] ``` #### function isSorted ```kestrel 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) ``` #### function isSortedDescending ```kestrel public consuming func isSortedDescending() -> Bool ``` True if elements come out in descending order. Mirror of `isSorted`. #### function iter ```kestrel func iter() -> Self ``` Returns `self`. The blanket conformance pivot — iterators *are* iterables. #### function last ```kestrel 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. #### function map ```kestrel public func map[U](as: (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] ``` #### function max ```kestrel public consuming func max() -> Item? ``` Largest element, or `None` for an empty iterator. Ties go to the first occurrence. #### function min ```kestrel 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 ``` #### function next ```kestrel public mutating func next() -> K? ``` Returns the next key, or `None` when the underlying iterator is exhausted. # Examples ``` var it = ["a": 1].keys.iter(); it.next(); // Some("a") it.next(); // None ``` #### function nth ```kestrel 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) ``` #### function peekable ```kestrel 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) ``` #### function product ```kestrel 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 ``` #### function reduce ```kestrel 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 ``` #### function scan ```kestrel public func scan[Acc](from: Acc, by: (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] ``` #### function skip ```kestrel 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(); // [] ``` #### function skipWhile ```kestrel public func skipWhile(where: (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] ``` #### function sorted ```kestrel 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] ``` #### function stepBy ```kestrel 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] ``` #### function sum ```kestrel 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 ``` #### function take ```kestrel 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] ``` #### function takeWhile ```kestrel public func takeWhile(where: (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] ``` #### function tryFold ```kestrel 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") ``` #### function tryForEach ```kestrel public mutating func tryForEach[E]((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 ``` #### function unzip ```kestrel 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"] ``` #### function zip ```kestrel 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)] ``` ### struct KeysView ```kestrel public struct KeysView[K, V] where K: Hashable { /* private fields */ } ``` Lazy `Iterable` view over the keys of a dictionary. Returned by `Dictionary.keys`. Constructing the view is O(1) — it stores the bucket pointer and capacity. The view is invalidated by any mutation that may reallocate. # Examples ``` let dict = ["a": 1, "b": 2]; for k in dict.keys { print(k) } let arr = Array(from: dict.keys); ``` # Representation `(buckets, capacity)` — a pointer into the source dictionary's bucket array plus the total slot count. # Memory Model Value type that borrows the source dictionary's buffer. #### initializer From Buckets ```kestrel init(buckets: Pointer[Bucket[K, V]], capacity: Int64) ``` Internal — constructs a view from a bucket pointer and capacity. Use `Dictionary.keys` to obtain a view. **Iterable** #### typealias Item ```kestrel type Item = K ``` `Iterable` element type — `K`. #### typealias TargetIterator ```kestrel type TargetIterator = KeysIterator[K, V] ``` Concrete iterator type returned by `iter()`. #### function iter ```kestrel public func iter() -> KeysIterator[K, V] ``` Returns a fresh `KeysIterator[K, V]` over the view. Each call returns a new iterator starting at the beginning of the bucket array. ### struct ReversedSliceIterator ```kestrel public struct ReversedSliceIterator[T] { /* private fields */ } ``` #### initializer init ```kestrel public init(ptr: Pointer[T], remaining: Int64) ``` **Iterator** #### typealias Item ```kestrel type Item = T ``` #### typealias TargetIterator ```kestrel type TargetIterator = Self ``` #### function all ```kestrel 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) ``` #### function any ```kestrel 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 ``` #### function chain ```kestrel 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] ``` #### function collect ```kestrel 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] ``` #### function compactMap ```kestrel public func compactMap[T]() -> FilterMapIterator[Self, T] where Item == Optional[T] ``` Drops `None`s and unwraps `Some`s — 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] ``` #### function contains ```kestrel 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 ``` #### function count ```kestrel 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 ``` #### function cycle ```kestrel 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] ``` #### function enumerate ```kestrel 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}") }; ``` #### function filter ```kestrel public func filter(where: (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] ``` #### function filterMap ```kestrel public func filterMap[U](as: (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] ``` #### function first ```kestrel 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 ``` #### function firstIndex ```kestrel 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 ``` #### function flatMap ```kestrel public func flatMap[U](as: (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] ``` #### function flatten ```kestrel 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] ``` #### function fold ```kestrel 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 ``` #### function forEach ```kestrel 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) }; ``` #### function fuse ```kestrel 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. #### function inspect ```kestrel public func inspect((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(); ``` #### function intersperse ```kestrel 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] ``` #### function intersperseWith ```kestrel public func intersperseWith(with: () -> 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] ``` #### function isSorted ```kestrel 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) ``` #### function isSortedDescending ```kestrel public consuming func isSortedDescending() -> Bool ``` True if elements come out in descending order. Mirror of `isSorted`. #### function iter ```kestrel func iter() -> Self ``` Returns `self`. The blanket conformance pivot — iterators *are* iterables. #### function last ```kestrel 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. #### function map ```kestrel public func map[U](as: (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] ``` #### function max ```kestrel public consuming func max() -> Item? ``` Largest element, or `None` for an empty iterator. Ties go to the first occurrence. #### function min ```kestrel 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 ``` #### function next ```kestrel public mutating func next() -> Optional[T] ``` #### function nth ```kestrel 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) ``` #### function peekable ```kestrel 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) ``` #### function product ```kestrel 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 ``` #### function reduce ```kestrel 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 ``` #### function scan ```kestrel public func scan[Acc](from: Acc, by: (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] ``` #### function skip ```kestrel 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(); // [] ``` #### function skipWhile ```kestrel public func skipWhile(where: (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] ``` #### function sorted ```kestrel 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] ``` #### function stepBy ```kestrel 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] ``` #### function sum ```kestrel 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 ``` #### function take ```kestrel 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] ``` #### function takeWhile ```kestrel public func takeWhile(where: (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] ``` #### function tryFold ```kestrel 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") ``` #### function tryForEach ```kestrel public mutating func tryForEach[E]((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 ``` #### function unzip ```kestrel 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"] ``` #### function zip ```kestrel 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)] ``` ### struct ReversedView ```kestrel public struct ReversedView[T] { /* private fields */ } ``` Multi-pass lazy view that iterates a contiguous collection back-to-front without allocating. #### field count ```kestrel public var count: Int64 { get } ``` #### field first ```kestrel public var first: Optional[T] { get } ``` #### initializer init ```kestrel public init(slice: ArraySlice[T]) ``` #### field isEmpty ```kestrel public var isEmpty: Bool { get } ``` #### field last ```kestrel public var last: Optional[T] { get } ``` #### subscript subscript ```kestrel public subscript(Int64) -> T { get } ``` #### function toArray ```kestrel public func toArray() -> Array[T] ``` **Iterable** #### typealias Item ```kestrel type Item = T ``` #### typealias TargetIterator ```kestrel type TargetIterator = ReversedSliceIterator[T] ``` #### function iter ```kestrel public func iter() -> ReversedSliceIterator[T] ``` ### protocol SeqRange ```kestrel public protocol SeqRange ``` Resolves any range-like type to a half-open `Range[Int64]` given a collection length. Used by `removeSubrange` and `replaceSubrange` so they accept `Range`, `ClosedRange`, `RangeFrom`, `RangeUpTo`, and `RangeThrough` through a single generic parameter. #### function resolve ```kestrel func resolve(Int64) -> Range[Int64] ``` ### struct Set ```kestrel public struct Set[T, H = DefaultHasher] where T: Hashable, H: Hasher, H: Defaultable { /* private fields */ } ``` An unordered hash set of unique elements, parameterized over the hasher type `H` (defaults to `DefaultHasher`). Backed by a `Dictionary[T, Unit, H]` — the dictionary's keys are the set's elements, and `Unit` fills the value slot. Inherits O(1) average-case lookup, insertion, and removal, plus copy-on-write storage from the underlying dictionary: copying a `Set` is O(1), with the deep clone deferred until either side mutates. Iteration order is unspecified. For ordered or associative-style storage, see `Array[T]` and `Dictionary[K, V]`. # Examples ``` var fruits: Set = ["apple", "banana", "cherry"]; fruits.insert("date"); fruits.contains("apple"); // true fruits.remove("banana"); let a: Set = [1, 2, 3]; let b: Set = [3, 4, 5]; a.union(b); // {1, 2, 3, 4, 5} a.intersection(b); // {3} a.isSubset(of: b); // false ``` # Set Literals Sets share array-literal syntax — you tell the compiler which one you want via the type annotation: ``` let empty: Set[Int64] = []; let numbers: Set = [1, 2, 3]; let strings: Set[String] = ["a", "b", "c"]; ``` # Hashing Each element's hash is computed via `T: Hashable` and stored in the underlying dictionary's bucket. Swap the hasher type by writing `Set[T, SipHasher]` etc.; the default `DefaultHasher` is FNV-1a (see `DefaultHasher` for caveats around adversarial inputs). # Representation One field, `dict: Dictionary[T, Unit, H]`. All set operations delegate to the dictionary. # Memory Model Reference-counted storage with copy-on-write *value* semantics — inherited from the backing `Dictionary`. Copying a `Set` is O(1) and shares storage; the next mutation triggers the deep clone so the change is invisible to other copies. # Guarantees - Elements are unique by `Hashable`/`Equatable` equality. - Iteration order is **not** specified. - Operations marked O(1) are amortized; the underlying dictionary resizes geometrically. #### initializer Array Literal ```kestrel public init(arrayLiteral: LiteralSlice[T]) ``` Creates a set from an array literal slice — emitted by the compiler when you write `let s: Set = [1, 2, 3]`. Pre-allocates capacity to the literal's element count (so the build avoids resizing) and inserts each element. Duplicates collapse. # Examples ``` // Triggered by the array-literal-with-Set-annotation syntax: let nums: Set = [1, 2, 3]; ``` #### typealias Element ```kestrel type Element = T ``` `ExpressibleByArrayLiteral` element type — equals `T`. #### initializer Empty ```kestrel public init() ``` Creates an empty set with no allocation. The first insert allocates the smallest dictionary bucket array (currently 8 slots). For pre-sized creation, use `init(capacity:)`. # Examples ``` let set = Set[String](); set.isEmpty; // true set.capacity; // 0 ``` #### initializer From Iterable ```kestrel public init[I](from: I) where I: Iterable, I.Item == T ``` Creates a set by inserting every element produced by an iterable. Duplicates collapse silently (insert returns `false` for the already-present case). Capacity grows geometrically as inserts arrive — for sized sources, follow up with `shrinkToFit()` if memory matters. # Examples ``` let arr = [1, 2, 2, 3, 3, 3]; let set = Set(from: arr); // {1, 2, 3} let r = Set(from: 1..<4); // {1, 2, 3} ``` #### initializer Literal Bridge ```kestrel public init(_arrayLiteralPointer: consuming lang.ptr[T], _arrayLiteralCount: consuming lang.i64) ``` Compiler-emitted bridge for `[a, b, c]` literals constructing a `Set`. Forwards to `init(arrayLiteral:)` after wrapping the raw `(ptr, count)` in a `LiteralSlice`. Not called by user code. # Safety The compiler guarantees `_arrayLiteralPointer` covers exactly `_arrayLiteralCount` initialized elements of `T`. #### initializer With Capacity ```kestrel public init(capacity: Int64) ``` Creates an empty set sized to hold at least `capacity` elements without resizing. The actual allocated capacity rounds up to the next power of two (minimum 8) per the underlying dictionary policy. A non-positive `capacity` behaves like `init()`. Panics on allocation failure. # Examples ``` var set = Set[String](capacity: 1000); set.capacity; // 1024 set.count; // 0 ``` #### function all ```kestrel public func all(where: (T) -> Bool) -> Bool ``` `true` when every element satisfies `predicate` (vacuously true for empty sets). Short-circuits on the first failure. Dual of `any { ... }`. # Examples ``` Set([2, 4, 6]).all { (x) in x % 2 == 0 }; // true Set([1, 2, 4]).all { (x) in x % 2 == 0 }; // false Set[Int64]().all { (x) in false }; // true (vacuous) ``` #### function any ```kestrel public func any(where: (T) -> Bool) -> Bool ``` `true` when at least one element satisfies `predicate`. Alias for `contains { ... }` — both names exist so predicate-style code reads naturally regardless of context. Short-circuits. # Examples ``` Set([1, 2, 3]).any { (x) in x > 2 }; // true Set[Int64]().any { (x) in true }; // false (empty) ``` #### field capacity ```kestrel public var capacity: Int64 { get } ``` Total bucket capacity in the backing dictionary — always `>= count`. Resizes (via the dictionary's 75% load policy) trigger the next insert past the threshold. Use `reserveCapacity(...)` to pre-grow and `shrinkToFit()` to release excess. # Examples ``` let set = Set[String](capacity: 100); set.capacity; // 128 ``` #### function clear ```kestrel public mutating func clear() ``` Removes every element, leaving capacity untouched. Forwards to the dictionary's `clear()`. Follow with `shrinkToFit()` to release the buffer. # Examples ``` var set: Set = [1, 2, 3]; set.clear(); // set == {} set.capacity; // unchanged ``` #### function compactMap ```kestrel public func compactMap[U]((T) -> U?) -> Set[U, H] where U: Hashable ``` Returns a new set with each element run through `transform`, dropping any `None` results. Useful for parse-or-skip patterns. Same uniqueness caveat as `map(...)` — collisions in the transformed values collapse. # Examples ``` let set: Set = ["1", "two", "3"]; let nums = set.compactMap { (s) in Int64.parse(s) }; // {1, 3} — "two" failed to parse ``` #### function contains ```kestrel public func contains(T) -> Bool ``` `true` if `element` is a member of the set; O(1) average. Forwards to the dictionary's key lookup. For predicate-based search use `contains { ... }`. # Examples ``` let set: Set = [1, 2, 3]; set.contains(2); // true set.contains(5); // false ``` #### function contains ```kestrel public func contains(where: (T) -> Bool) -> Bool ``` `true` if any element satisfies `predicate`. Linear scan; short-circuits on the first match. `false` for empty sets. The aliased shape `any { ... }` exists for symmetry with `Array`. # Examples ``` Set([1, 2, 3]).contains { (x) in x > 2 }; // true Set([1, 2, 3]).contains { (x) in x > 5 }; // false ``` #### field count ```kestrel public var count: Int64 { get } ``` Number of unique elements; O(1). Forwards to the backing dictionary's `count`. # Examples ``` Set([1, 2, 3]).count; // 3 Set[Int64]().count; // 0 ``` #### function countItems ```kestrel public func countItems(where: (T) -> Bool) -> Int64 ``` Returns the number of elements for which `predicate` is true. Linear scan, no short-circuit. For just a presence check use `any { ... }`; for a yes/no on every element, `all { ... }`. # Examples ``` Set([1, 2, 3, 4, 5]).countItems { (x) in x % 2 == 0 }; // 2 Set[Int64]().countItems { (x) in true }; // 0 ``` #### function deepClone ```kestrel public func deepClone() -> Set[T, H] ``` Returns a fully-detached copy of the set with no shared storage; every element is also `clone()`-d. Use over `clone()` when you specifically want to break the lazy COW share — for example, before passing the copy to another thread or system that might race with further mutations. # Examples ``` let a: Set = [[1, 2], [3, 4]]; // Set of arrays let b = a.deepClone(); // fully independent copy ``` #### field dict ```kestrel var dict: Dictionary[T, Unit, H] ``` Backing dictionary. Keys are the set's elements; values are always `Unit()`. #### function difference ```kestrel public func difference(Set[T, H]) -> Set[T, H] ``` Returns a new set of every element in `self` that is **not** in `other` — the set difference, "self minus other". Non-mutating mirror of `formDifference(...)`. Order of arguments matters: `a.difference(b)` is generally not equal to `b.difference(a)`. # Examples ``` let a: Set = [1, 2, 3]; let b: Set = [2, 3, 4]; a.difference(b); // {1} b.difference(a); // {4} ``` #### function filter ```kestrel public func filter(where: (T) -> Bool) -> Set[T, H] ``` Returns a new set containing only elements for which `predicate` is true. Non-mutating mirror of `retain { ... }`. Allocates a fresh set; for in-place filtering use `retain` or `removeAll { ... }`. # Examples ``` let set: Set = [1, 2, 3, 4, 5]; let evens = set.filter { (x) in x % 2 == 0 }; // {2, 4} ``` #### function first ```kestrel public func first(where: (T) -> Bool) -> T? ``` Returns *some* element matching `predicate`, or `None`. "First" is determined by iteration order, which is unspecified — treat the result as arbitrary among matching elements. Short-circuits on the first match. # Examples ``` let set: Set = [1, 2, 3, 4, 5]; set.first { (x) in x > 3 }; // Some(4) or Some(5) set.first { (x) in x > 99 }; // None ``` #### function flatMap ```kestrel public func flatMap[U]((T) -> Set[U, H]) -> Set[U, H] where U: Hashable ``` Returns a new set formed by unioning every set produced by `transform`. Each element maps to a `Set[U, H]`; those sets are merged together. The result holds the unique union — duplicates across sub-sets collapse, as with all set operations. # Examples ``` let set: Set = [1, 2]; let expanded = set.flatMap { (x) in Set([x, x * 10]) }; // {1, 10, 2, 20} ``` #### function formDifference ```kestrel public mutating func formDifference(Set[T, H]) ``` In-place difference: removes every element of `self` that **is** in `other`. Mutating mirror of `difference(...)`. The result is "self minus other". # Examples ``` var a: Set = [1, 2, 3]; let b: Set = [2, 3, 4]; a.formDifference(b); // a == {1} ``` #### function formIntersection ```kestrel public mutating func formIntersection(Set[T, H]) ``` In-place intersection: removes every element of `self` that is **not** in `other`. Mutating mirror of `intersection(...)`. Iterates over `self`, so the cost scales with `self.count`, not `other.count`. # Examples ``` var a: Set = [1, 2, 3]; let b: Set = [2, 3, 4]; a.formIntersection(b); // a == {2, 3} ``` #### function formSymmetricDifference ```kestrel public mutating func formSymmetricDifference(Set[T, H]) ``` In-place symmetric difference: keeps elements in exactly one of `self` or `other`. Mutating mirror of `symmetricDifference(...)`. Two passes: removes shared elements, then inserts elements unique to `other`. # Examples ``` var a: Set = [1, 2, 3]; let b: Set = [2, 3, 4]; a.formSymmetricDifference(b); // a == {1, 4} ``` #### function formUnion ```kestrel public mutating func formUnion(Set[T, H]) ``` In-place union: adds every element of `other` to `self`. Mutating mirror of `union(...)`. For multi-source unions, chain calls or use `insert(contentsOf:)` over the elements. # Examples ``` var a: Set = [1, 2]; let b: Set = [2, 3]; a.formUnion(b); // a == {1, 2, 3} ``` #### function getDict ```kestrel func getDict() -> Dictionary[T, Unit, H] ``` Returns the backing `Dictionary[T, Unit, H]`. Internal helper for extensions that need direct dictionary access. #### function insert ```kestrel public mutating func insert(T) -> Bool ``` Inserts `element`, returning whether it was newly added. Returns `true` if the element was added, `false` if it was already present (in which case the set is unchanged). May trigger a dictionary resize and COW. For bulk inserts, see `insert(contentsOf:)`. # Examples ``` var set: Set = [1, 2]; set.insert(3); // true; set == {1, 2, 3} set.insert(2); // false; already present ``` #### function insert ```kestrel public mutating func insert[I](contentsOf: I) where I: Iterable, I.Item == T ``` Inserts every element produced by an iterable; duplicates collapse silently. Sugar for "insert in a loop". For union with another `Set`, prefer `formUnion(...)` — it's the same semantically but reads more naturally. # Examples ``` var set: Set = [1, 2]; set.insert(contentsOf: [3, 4, 5]); // {1, 2, 3, 4, 5} set.insert(contentsOf: 5..<8); // {1, 2, 3, 4, 5, 6, 7} ``` #### function intersection ```kestrel public func intersection(Set[T, H]) -> Set[T, H] ``` Returns a new set containing only elements present in both `self` and `other`. Non-mutating mirror of `formIntersection(...)`. For efficiency, iterates over `self`; pass the smaller set as the receiver if it matters. # Examples ``` let a: Set = [1, 2, 3]; let b: Set = [2, 3, 4]; a.intersection(b); // {2, 3} ``` #### function isDisjoint ```kestrel public func isDisjoint(with: Set[T, H]) -> Bool ``` `true` if `self` and `other` share no elements. Iterates over the smaller set for efficiency (swaps the arguments internally if needed). Empty sets are disjoint from anything, including each other. # Examples ``` let a: Set = [1, 2]; let b: Set = [3, 4]; let c: Set = [2, 3]; a.isDisjoint(with: b); // true a.isDisjoint(with: c); // false (share 2) ``` #### field isEmpty ```kestrel public var isEmpty: Bool { get } ``` `true` when the set has no elements; equivalent to `count == 0`. # Examples ``` Set[Int64]().isEmpty; // true Set([1]).isEmpty; // false ``` #### function isStrictSubset ```kestrel public func isStrictSubset(of: Set[T, H]) -> Bool ``` `true` if `self` is a subset of `other` and the two sets are not equal. Strict (proper) subset — excludes the case where the sets are equal. Mirror of `isStrictSuperset(of:)`. # Examples ``` let a: Set = [1, 2]; let b: Set = [1, 2, 3]; a.isStrictSubset(of: b); // true a.isStrictSubset(of: a); // false (equal, not strict) ``` #### function isStrictSuperset ```kestrel public func isStrictSuperset(of: Set[T, H]) -> Bool ``` `true` if `self` is a superset of `other` and the two sets are not equal. Strict (proper) superset. Mirror of `isStrictSubset(of:)`. # Examples ``` let a: Set = [1, 2, 3]; let b: Set = [1, 2]; a.isStrictSuperset(of: b); // true a.isStrictSuperset(of: a); // false (equal, not strict) ``` #### function isSubset ```kestrel public func isSubset(of: Set[T, H]) -> Bool ``` `true` if every element of `self` appears in `other`. A set is always a subset of itself (reflexive). Short-circuits on the first missing element, and skips the inner scan when `self.count > other.count`. For "subset but not equal" use `isStrictSubset(of:)`. # Examples ``` let a: Set = [1, 2]; let b: Set = [1, 2, 3]; a.isSubset(of: b); // true b.isSubset(of: a); // false a.isSubset(of: a); // true ``` #### function isSuperset ```kestrel public func isSuperset(of: Set[T, H]) -> Bool ``` `true` if every element of `other` appears in `self`. Reflexive (a set is its own superset). Implemented as `other.isSubset(of: self)` for code reuse. # Examples ``` let a: Set = [1, 2, 3]; let b: Set = [1, 2]; a.isSuperset(of: b); // true b.isSuperset(of: a); // false ``` #### function map ```kestrel public func map[U]((T) -> U) -> Set[U, H] where U: Hashable ``` Returns a new set with each element run through `transform`. **Cardinality may shrink**: if `transform` maps two distinct elements to the same output, the result holds only one copy (sets are unique). For an `Optional`-aware variant that drops `None`, use `compactMap(...)`. # Examples ``` let set: Set = [1, 2, 3]; let doubled = set.map { (x) in x * 2 }; // {2, 4, 6} let words: Set = ["Hello", "WORLD"]; let lower = words.map { (s) in s.lowercase() }; // {"hello", "world"} — even though both originals lowercase to distinct strings ``` #### function max ```kestrel public func max() -> T? ``` Returns the largest element, or `None` for an empty set. Single linear pass. Mirror of `min()`. # Examples ``` Set([3, 1, 4]).max(); // Some(4) Set[Int64]().max(); // None ``` #### function min ```kestrel public func min() -> T? ``` Returns the smallest element, or `None` for an empty set. Single linear pass; ties go to the first occurrence in iteration order (which is unspecified, so equally-minimal elements compare equal anyway). # Examples ``` Set([3, 1, 4]).min(); // Some(1) Set[Int64]().min(); // None ``` #### function remove ```kestrel public mutating func remove(T) -> Bool ``` Removes `element` if present; returns whether anything was removed. Leaves a tombstone in the backing dictionary — see `Dictionary.remove`. Tombstones are reclaimed by the next resize. Triggers COW only when an element is actually removed. # Examples ``` var set: Set = [1, 2, 3]; set.remove(2); // true; set == {1, 3} set.remove(5); // false; set unchanged ``` #### function removeAll ```kestrel public mutating func removeAll(where: (T) -> Bool) ``` Removes every element for which `predicate` is true. Inverse of `retain { ... }`. Same two-pass structure. # Examples ``` var set: Set = [1, 2, 3, 4, 5]; set.removeAll { (x) in x % 2 == 0 }; // {1, 3, 5} ``` #### function reserveCapacity ```kestrel public mutating func reserveCapacity(Int64) ``` Grows the backing dictionary so at least `minimumCapacity` elements fit without resizing. No-op when current capacity already suffices. Implemented by rebuilding the underlying dictionary at the new capacity (a little heavier than `Dictionary.reserveCapacity` directly, since it reinserts each element). Opposite of `shrinkToFit()`. # Examples ``` var set = Set[String](); set.reserveCapacity(1000); // No reallocations for the first ~750 inserts. ``` #### function retain ```kestrel public mutating func retain(where: (T) -> Bool) ``` Keeps only elements for which `predicate` is true. Two-pass implementation: collects elements to remove, then deletes each. Stable in iteration semantics (set is unordered anyway). Mirror is `removeAll { ... }`. # Examples ``` var set: Set = [1, 2, 3, 4, 5]; set.retain { (x) in x % 2 == 0 }; // {2, 4} ``` #### function shrinkToFit ```kestrel public mutating func shrinkToFit() ``` Reduces backing-dictionary capacity to fit the current count. Rebuilds the dictionary at a smaller capacity, dropping any tombstones. No-op when capacity already matches. Useful after large removals. # Examples ``` var set = Set[String](capacity: 1000); set.insert("a"); set.shrinkToFit(); // capacity drops toward count ``` #### function sorted ```kestrel public func sorted() -> Array[T] ``` Returns the set's elements as an ascending-sorted `Array[T]`. Convenience for "I want this set as an ordered list". Duplicates have already collapsed in the set, so the result has no repeats. # Examples ``` Set([3, 1, 4, 1, 5]).sorted(); // [1, 3, 4, 5] ``` #### function sum ```kestrel public func sum() -> T ``` Returns the sum of every element, starting from `T()` (the default-constructed zero). Empty sets return `T()` — `0` for `Int64`, `""` for `String`, etc. Linear in `count`. # Examples ``` Set([1, 2, 3]).sum(); // 6 Set[Int64]().sum(); // 0 ``` #### function symmetricDifference ```kestrel public func symmetricDifference(Set[T, H]) -> Set[T, H] ``` Returns a new set of elements in exactly one of `self` or `other`. Non-mutating mirror of `formSymmetricDifference(...)`. Equivalent to `union(...) - intersection(...)`. The operation is commutative — order of arguments doesn't change the result. # Examples ``` let a: Set = [1, 2, 3]; let b: Set = [2, 3, 4]; a.symmetricDifference(b); // {1, 4} ``` #### function toArray ```kestrel public func toArray() -> Array[T] ``` Returns an `Array[T]` with every element of the set. Order matches iteration order (i.e. unspecified). Capacity is pre-reserved to `count` so the build avoids reallocations. For an ordering, follow with `Array.sort()` or `sorted()` (in the `T: Comparable` extension below). # Examples ``` let set: Set = [1, 2, 3]; let arr = set.toArray(); // [1, 2, 3] in some order ``` #### function union ```kestrel public func union(Set[T, H]) -> Set[T, H] ``` Returns a new set containing every element from `self` and `other`. Non-mutating mirror of `formUnion(...)`. Internally clones `self` (cheap COW) and adds `other` into the copy. # Examples ``` let a: Set = [1, 2, 3]; let b: Set = [3, 4, 5]; a.union(b); // {1, 2, 3, 4, 5} ``` **Iterable** #### typealias Item ```kestrel type Item = T ``` `Iterable` element type — `T`. #### typealias TargetIterator ```kestrel type TargetIterator = SetIterator[T, H] ``` Concrete iterator type returned by `iter()`. #### function iter ```kestrel public func iter() -> SetIterator[T, H] ``` Returns a single-pass `SetIterator[T, H]` over the elements. Order is unspecified and may change between mutations. The iterator borrows the underlying buffer; do not mutate the set while iterating. # Examples ``` for item in set.iter() { print(item); } let arr = Array(from: set.iter()); ``` **Cloneable** #### function clone ```kestrel public func clone() -> Set[T, H] ``` Returns a `Set` sharing the same storage; the deep copy is deferred until either side mutates. O(1) — bumps the backing dictionary's `RcBox` refcount. The first mutation on either side triggers the deep clone. For an immediate eager copy, use `deepClone()` (in the `T: Cloneable` extension below). # Examples ``` let a: Set = [1, 2, 3]; var b = a.clone(); // O(1), shares storage b.insert(4); // b deep-copies here; a is unchanged ``` **Equatable** #### typealias Output ```kestrel type Output = Bool ``` #### function equal ```kestrel public func equal(to: Self) -> Bool ``` Bridges `Equal.equal(to:)` to `Equatable.isEqual(to:)`. #### function isEqual ```kestrel public func isEqual(to: Set[T, H]) -> Bool ``` `true` when `self` and `other` contain exactly the same elements. Order-independent (sets are unordered). Implemented as "equal counts and `self.isSubset(of: other)`" — short-circuits at the count check. # Examples ``` Set([1, 2, 3]).isEqual(to: Set([3, 2, 1])); // true Set([1, 2]).isEqual(to: Set([1, 2, 3])); // false ``` #### function notEqual ```kestrel public func notEqual(to: Self) -> Bool ``` Default `!=`: delegates to `==` so there's a single source of truth. **Formattable** #### function format ```kestrel public func format(into: mutating StringBuilder, FormatOptions) ``` Renders the set as `"{" + elements.joined(", ") + "}"`, passing `options` to each element's `format`. # Examples ``` Set([1, 2, 3]).format(); // "{1, 2, 3}" — order unspecified Set[Int64]().format(); // "{}" "\{Set([1, 2, 3])}"; // "{1, 2, 3}" via interpolation ``` #### function formatted ```kestrel public func formatted(FormatOptions) -> String ``` Returns this value rendered as a `String`. Convenience wrapper: creates a `StringBuilder`, calls `format(into:)`, and returns the built string. Uses a distinct name to avoid overload-resolution ambiguity with `format(into:)`. **ExpressibleByArrayLiteral** #### initializer Array Literal ```kestrel init(arrayLiteral: LiteralSlice[Element]) ``` Builds an instance from a literal slice of elements. ### struct SetIterator ```kestrel public struct SetIterator[T, H = DefaultHasher] where T: Hashable, H: Hasher, H: Defaultable { /* private fields */ } ``` Single-pass forward iterator over the elements of a `Set[T, H]`. Returned by `Set.iter()`. Wraps the underlying `DictionaryIterator[T, Unit]` and discards the (unused) value half of each entry, yielding only the key. Iteration order matches the underlying bucket layout and is unspecified. # Examples ``` let set: Set = [1, 2, 3]; for item in set { print(item); } ``` # Representation Wraps a `DictionaryIterator[T, Unit]`. # Memory Model Value type. Aliases the source set's bucket array; do not retain across mutations of the set. #### initializer From Dict ```kestrel public init(dictIter: DictionaryIterator[T, Unit]) ``` Wraps a `DictionaryIterator` to yield only its keys. Low-level — prefer `Set.iter()` over calling this directly. **Iterator** #### typealias Item ```kestrel type Item = T ``` Element type yielded by `next()` — `T`. #### typealias TargetIterator ```kestrel type TargetIterator = Self ``` #### function all ```kestrel 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) ``` #### function any ```kestrel 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 ``` #### function chain ```kestrel 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] ``` #### function collect ```kestrel 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] ``` #### function compactMap ```kestrel public func compactMap[T]() -> FilterMapIterator[Self, T] where Item == Optional[T] ``` Drops `None`s and unwraps `Some`s — 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] ``` #### function contains ```kestrel 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 ``` #### function count ```kestrel 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 ``` #### function cycle ```kestrel 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] ``` #### function enumerate ```kestrel 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}") }; ``` #### function filter ```kestrel public func filter(where: (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] ``` #### function filterMap ```kestrel public func filterMap[U](as: (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] ``` #### function first ```kestrel 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 ``` #### function firstIndex ```kestrel 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 ``` #### function flatMap ```kestrel public func flatMap[U](as: (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] ``` #### function flatten ```kestrel 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] ``` #### function fold ```kestrel 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 ``` #### function forEach ```kestrel 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) }; ``` #### function fuse ```kestrel 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. #### function inspect ```kestrel public func inspect((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(); ``` #### function intersperse ```kestrel 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] ``` #### function intersperseWith ```kestrel public func intersperseWith(with: () -> 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] ``` #### function isSorted ```kestrel 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) ``` #### function isSortedDescending ```kestrel public consuming func isSortedDescending() -> Bool ``` True if elements come out in descending order. Mirror of `isSorted`. #### function iter ```kestrel func iter() -> Self ``` Returns `self`. The blanket conformance pivot — iterators *are* iterables. #### function last ```kestrel 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. #### function map ```kestrel public func map[U](as: (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] ``` #### function max ```kestrel public consuming func max() -> Item? ``` Largest element, or `None` for an empty iterator. Ties go to the first occurrence. #### function min ```kestrel 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 ``` #### function next ```kestrel public mutating func next() -> T? ``` Returns the next element, or `None` when the underlying iterator is exhausted. Once exhausted, the iterator stays exhausted. # Examples ``` var it = Set([1, 2]).iter(); it.next(); // Some(1) — order unspecified it.next(); // Some(2) it.next(); // None ``` #### function nth ```kestrel 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) ``` #### function peekable ```kestrel 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) ``` #### function product ```kestrel 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 ``` #### function reduce ```kestrel 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 ``` #### function scan ```kestrel public func scan[Acc](from: Acc, by: (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] ``` #### function skip ```kestrel 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(); // [] ``` #### function skipWhile ```kestrel public func skipWhile(where: (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] ``` #### function sorted ```kestrel 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] ``` #### function stepBy ```kestrel 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] ``` #### function sum ```kestrel 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 ``` #### function take ```kestrel 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] ``` #### function takeWhile ```kestrel public func takeWhile(where: (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] ``` #### function tryFold ```kestrel 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") ``` #### function tryForEach ```kestrel public mutating func tryForEach[E]((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 ``` #### function unzip ```kestrel 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"] ``` #### function zip ```kestrel 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)] ``` ### protocol Slice ```kestrel public protocol Slice[T] ``` Shared read-only protocol for contiguous collections. `Slice[T]` is the contiguous-collection counterpart to `Str` in `std.text`: one kernel method (`asSlice`), all read-only logic in a protocol extension. Both `Array[T]` and `ArraySlice[T]` conform, so generic code constrained to `S: Slice[T]` accepts either without overloading. # Examples ``` func sum[S](s: S) -> Int64 where S: Slice[Int64] { var total: Int64 = 0; for elem in s { total = total + elem } total } sum([1, 2, 3]); // works with Array sum([1, 2, 3].asSlice()); // works with ArraySlice ``` #### function all ```kestrel public func all(where: (T) -> Bool) -> Bool ``` `true` when every element satisfies `predicate`. O(n). Short-circuits on the first failure. Vacuously true for empty collections. # Examples ``` [2, 4, 6].all(where: { it % 2 == 0 }); // true [2, 3, 6].all(where: { it % 2 == 0 }); // false ``` #### function any ```kestrel public func any(where: (T) -> Bool) -> Bool ``` `true` when at least one element satisfies `predicate`. O(n). Short-circuits on the first match. Always `false` for empty collections. # Examples ``` [1, 2, 3].any(where: { it > 2 }); // true [1, 2, 3].any(where: { it > 5 }); // false ``` #### function asPointer ```kestrel public func asPointer() -> Pointer[T] ``` Pointer to the first element. The pointer aliases the collection's buffer; do not outlive the source or mutate through it. # Safety Reading past `count` is undefined behavior. #### function asSlice ```kestrel func asSlice() -> ArraySlice[T] ``` #### function binarySearch ```kestrel public func binarySearch(T) -> Int64? ``` Binary search for `element`. Returns its index or `None`. O(log n). When duplicates exist, which index is returned is unspecified. # Safety The collection must be sorted in ascending order. Calling on unsorted data won't crash but may produce false negatives. # Examples ``` [1, 2, 3, 4, 5].binarySearch(3); // Some(2) [1, 2, 3, 4, 5].binarySearch(6); // None ``` #### function chunks ```kestrel public func chunks(of: Int64) -> ChunksView[T] ``` Multi-pass lazy view over non-overlapping `size`-sized chunks. The trailing chunk may be shorter than `size`. Multi-pass: query `count`, index with `view.get(i)`, and iterate repeatedly without re-creating the view. # Errors Panics if `size <= 0`. # Examples ``` let v = [1, 2, 3, 4, 5].chunks(of: 2); v.count; // 3 v.get(2); // ArraySlice[5] for c in v { ... } ``` #### function compactMap ```kestrel public func compactMap[U]((T) -> Optional[U]) -> Array[U] ``` Maps every element through `transform`, dropping `.None` results. O(n). # Examples ``` ["1", "x", "3"].compactMap { Int64.parse(it) }; // [1, 3] ``` #### function contains ```kestrel public func contains(T) -> Bool ``` `true` if the collection contains `element`. O(n). Linear scan; short-circuits on the first match. # Examples ``` [1, 2, 3].contains(2); // true [1, 2, 3].contains(5); // false ``` #### field count ```kestrel public var count: Int64 { get } ``` Element count. O(1). # Examples ``` [1, 2, 3].count; // 3 [].count; // 0 ``` #### function countItems ```kestrel public func countItems(where: (T) -> Bool) -> Int64 ``` Number of elements for which `predicate` is true. O(n). # Examples ``` [1, 2, 3, 4, 5].countItems(where: { it % 2 == 0 }); // 2 ``` #### function drop ```kestrel public func drop(first: Int64) -> ArraySlice[T] ``` Returns a slice with the first `count` elements skipped. O(1). Complement of `prefix`. # Errors Panics if `count > self.count`. # Examples ``` [1, 2, 3, 4, 5].drop(first: 2); // ArraySlice[3, 4, 5] ``` #### function drop ```kestrel public func drop(last: Int64) -> ArraySlice[T] ``` Returns a slice with the last `count` elements skipped. O(1). Complement of `suffix`. # Errors Panics if `count > self.count`. # Examples ``` [1, 2, 3, 4, 5].drop(last: 2); // ArraySlice[1, 2, 3] ``` #### function ends ```kestrel public func ends[__opaque_0](with: __opaque_0) -> Bool where __opaque_0: Slice[T] ``` `true` if the trailing elements match `suffix`. O(k) where k is the suffix length. Accepts any `Slice[T]` conformer. # Examples ``` [1, 2, 3].ends(with: [2, 3]); // true [1, 2, 3].ends(with: [1, 2]); // false [1, 2, 3].ends(with: []); // true (vacuous) ``` #### function ensureUnique ```kestrel mutating func ensureUnique() ``` #### function filter ```kestrel public func filter(where: (T) -> Bool) -> Array[T] ``` Returns a new array containing every element matching `predicate`. O(n). Result size is unknown; uses geometric growth. # Examples ``` [1, 2, 3, 4].filter(where: { it % 2 == 0 }); // [2, 4] ``` #### function first ```kestrel public func first() -> T? ``` First element, or `.None` for an empty collection. O(1). Read-only — to remove the first element from an `Array`, use `popFirst()`. # Examples ``` [1, 2, 3].first(); // Some(1) [].first(); // None ``` #### function first ```kestrel public func first(where: (T) -> Bool) -> T? ``` First element matching `predicate`, or `None`. O(n). # Examples ``` [1, 2, 3, 4, 5].first(where: { it > 3 }); // Some(4) ``` #### function firstIndex ```kestrel public func firstIndex(where: (T) -> Bool) -> Int64? ``` Index of the first element matching `predicate`, or `None`. O(n). Short-circuits on the first match. For value-based search on `Equatable` collections, use `firstIndex(of:)`. # Examples ``` [1, 2, 3, 4, 5].firstIndex(where: { it > 3 }); // Some(3) [1, 2, 3].firstIndex(where: { it > 10 }); // None ``` #### function firstIndex ```kestrel public func firstIndex(of: T) -> Int64? ``` Index of the first element equal to `element`, or `None`. O(n). # Examples ``` [1, 2, 3, 2].firstIndex(of: 2); // Some(1) [1, 2, 3].firstIndex(of: 5); // None ``` #### function flatMap ```kestrel public func flatMap[U]((T) -> Array[U]) -> Array[U] ``` Maps every element through `transform` and concatenates the results into one flat array. O(n + total_output). # Examples ``` [1, 2, 3].flatMap { [it, it * 10] }; // [1, 10, 2, 20, 3, 30] ``` #### function format ```kestrel public func format(into: mutating StringBuilder, FormatOptions) ``` Renders as `"[e1, e2, ...]"`. Empty collections render as `"[]"`. # Examples ``` [1, 2, 3].format(); // "[1, 2, 3]" [].format(); // "[]" ``` #### field indices ```kestrel public var indices: Range[Int64] { get } ``` Half-open range `0.. Bool ``` Element-wise equality. O(n). Short-circuits on the first mismatch. Order matters. # Examples ``` [1, 2, 3].isEqual(to: [1, 2, 3]); // true [1, 2, 3].isEqual(to: [3, 2, 1]); // false ``` #### function isSorted ```kestrel public func isSorted() -> Bool ``` `true` if elements are in non-decreasing order. O(n). Equal adjacent elements are allowed. Empty and single-element collections are vacuously sorted. # Examples ``` [1, 2, 3].isSorted(); // true [1, 3, 2].isSorted(); // false [1, 1, 1].isSorted(); // true [].isSorted(); // true ``` #### function isValidIndex ```kestrel public func isValidIndex(Int64) -> Bool ``` `true` if `index` is in `[0, count)`. # Examples ``` [10, 20, 30].isValidIndex(2); // true [10, 20, 30].isValidIndex(3); // false [10, 20, 30].isValidIndex(-1); // false ``` #### function last ```kestrel public func last() -> T? ``` Last element, or `.None` for an empty collection. O(1). Read-only — to remove the last element from an `Array`, use `pop()`. # Examples ``` [1, 2, 3].last(); // Some(3) [].last(); // None ``` #### function last ```kestrel public func last(where: (T) -> Bool) -> T? ``` Last element matching `predicate`, or `None`. O(n). # Examples ``` [1, 2, 3, 2, 1].last(where: { it > 1 }); // Some(2) ``` #### function lastIndex ```kestrel public func lastIndex(where: (T) -> Bool) -> Int64? ``` Index of the last element matching `predicate`, or `None`. O(n). Scans from the back; short-circuits on the first match. # Examples ``` [1, 2, 3, 2, 1].lastIndex(where: { it == 2 }); // Some(3) ``` #### function lastIndex ```kestrel public func lastIndex(of: T) -> Int64? ``` Index of the last element equal to `element`, or `None`. O(n). # Examples ``` [1, 2, 3, 2].lastIndex(of: 2); // Some(3) [1, 2, 3].lastIndex(of: 5); // None ``` #### function map ```kestrel public func map[U]((T) -> U) -> Array[U] ``` Maps every element through `transform` into a new array. O(n). Pre-sizes the result buffer to `self.count`, so no growth steps. For the lazy version that fuses into a chain, use `iter().map { ... }`. # Examples ``` [1, 2, 3].map { it * 2 }; // [2, 4, 6] [1, 2, 3].map { it.format() }; // ["1", "2", "3"] ``` #### function max ```kestrel public func max() -> T? ``` Largest element, or `None` if empty. O(n). Ties go to the first occurrence. # Examples ``` [3, 1, 4].max(); // Some(4) [].max(); // None ``` #### function min ```kestrel public func min() -> T? ``` Smallest element, or `None` if empty. O(n). Ties go to the first occurrence. # Examples ``` [3, 1, 4].min(); // Some(1) [].min(); // None ``` #### function prefix ```kestrel public func prefix(Int64) -> ArraySlice[T] ``` Returns a slice over the first `count` elements. O(1). # Errors Panics if `count > self.count`. # Examples ``` [1, 2, 3, 4, 5].prefix(3); // ArraySlice[1, 2, 3] [1, 2].prefix(0); // empty slice ``` #### function reversed ```kestrel public func reversed() -> ReversedView[T] ``` Multi-pass lazy reversed view. Iterates back-to-front and supports indexed access in O(1). # Examples ``` let v = [1, 2, 3].reversed(); v.first(); // Some(3) v.toArray(); // [3, 2, 1] — eager copy ``` #### function sorted ```kestrel public func sorted() -> Array[T] ``` Returns a new sorted array; original unchanged. O(n log n). # Examples ``` let arr = [3, 1, 4, 1, 5]; arr.sorted(); // [1, 1, 3, 4, 5] // arr is still [3, 1, 4, 1, 5] ``` #### function split ```kestrel public func split(where: (T) -> Bool) -> ArraySplitWhereView[T] ``` Multi-pass lazy view over the segments produced by splitting at each element matching `predicate`. Matching elements are dropped. # Examples ``` let v = [1, -1, 2, 3, -1, 4].split(where: { it < 0 }); for seg in v { ... } ``` #### function split ```kestrel public func split(T) -> ArraySplitView[T] ``` Multi-pass lazy view over the segments produced by splitting on each occurrence of `separator`. Separators are dropped; empty runs between adjacent separators are preserved. Use `view.toArray()` to materialize all segments into an owned `Array[ArraySlice[T]]`. # Examples ``` let v = [1, 0, 2, 0, 3].split(separator: 0); for seg in v { ... } // ArraySlice[1], ArraySlice[2], ArraySlice[3] v.toArray(); // eager: 3 segments [1, 2, 3].split(separator: 0).toArray(); // [ArraySlice[1, 2, 3]] — separator not found, single segment ``` #### function starts ```kestrel public func starts[__opaque_0](with: __opaque_0) -> Bool where __opaque_0: Slice[T] ``` `true` if the leading elements match `prefix`. O(k) where k is the prefix length. Accepts any `Slice[T]` conformer. # Examples ``` [1, 2, 3].starts(with: [1, 2]); // true [1, 2, 3].starts(with: [2, 3]); // false [1, 2, 3].starts(with: []); // true (vacuous) ``` #### subscript subscript ```kestrel public subscript[I](I) -> I.SeqOutput { get set } ``` #### subscript subscript ```kestrel public subscript[I](checked: I) -> I.SeqOutput? { get } ``` #### subscript subscript ```kestrel public subscript[I](unchecked: I) -> I.SeqOutput { get set } ``` #### subscript subscript ```kestrel public subscript[I](clamped: I) -> I.SeqClampedOutput { get set } ``` #### subscript subscript ```kestrel public subscript[I](wrapped: I) -> I.SeqWrappedOutput { get set } ``` #### function suffix ```kestrel public func suffix(Int64) -> ArraySlice[T] ``` Returns a slice over the last `count` elements. O(1). # Errors Panics if `count > self.count`. # Examples ``` [1, 2, 3, 4, 5].suffix(2); // ArraySlice[4, 5] ``` #### function unique ```kestrel public func unique() -> Array[T] ``` Returns a new array with duplicates removed, preserving first-occurrence order. O(n²). For the mutating variant on `Array`, see `removeDuplicates()`. # Examples ``` [1, 2, 1, 3, 2, 4].unique(); // [1, 2, 3, 4] ``` #### function windows ```kestrel public func windows(of: Int64) -> WindowsView[T] ``` Multi-pass lazy view over overlapping `size`-sized sliding windows. Adjacent windows overlap by `size - 1` elements. Empty when the source has fewer than `size` elements. # Errors Panics if `size <= 0`. # Examples ``` let v = [1, 2, 3, 4].windows(of: 2); v.count; // 3 for w in v { ... } ``` **Iterable** #### typealias Item ```kestrel type Item ``` The element type that iteration yields. #### typealias TargetIterator ```kestrel type TargetIterator ``` The concrete iterator type returned by `iter()`. Constrained so `TargetIterator.Item` matches `Self.Item`. #### function iter ```kestrel public func iter() -> ArraySliceIterator[T] ``` Forward iterator over the elements. # Examples ``` for item in [1, 2, 3] { ... } ``` ### struct ValuesIterator ```kestrel public struct ValuesIterator[K, V] where K: Hashable { /* private fields */ } ``` Single-pass iterator yielding only the values of a dictionary. Wraps a `DictionaryIterator[K, V]` and discards the key half of each entry. Order matches the underlying entry iteration and is unspecified. # Examples ``` var it = ["a": 1, "b": 2].values.iter(); it.next(); // Some(1) — order unspecified it.next(); // Some(2) it.next(); // None ``` # Representation Wraps a `DictionaryIterator[K, V]`. # Memory Model Value type. Aliases dictionary storage; do not retain across mutations. #### initializer From Dict ```kestrel public init(dictIter: DictionaryIterator[K, V]) ``` Wraps a `DictionaryIterator` to yield only its values. Prefer `ValuesView.iter()` over calling this directly. **Iterator** #### typealias Item ```kestrel type Item = V ``` Element type yielded by `next()` — `V`. #### typealias TargetIterator ```kestrel type TargetIterator = Self ``` #### function all ```kestrel 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) ``` #### function any ```kestrel 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 ``` #### function chain ```kestrel 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] ``` #### function collect ```kestrel 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] ``` #### function compactMap ```kestrel public func compactMap[T]() -> FilterMapIterator[Self, T] where Item == Optional[T] ``` Drops `None`s and unwraps `Some`s — 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] ``` #### function contains ```kestrel 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 ``` #### function count ```kestrel 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 ``` #### function cycle ```kestrel 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] ``` #### function enumerate ```kestrel 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}") }; ``` #### function filter ```kestrel public func filter(where: (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] ``` #### function filterMap ```kestrel public func filterMap[U](as: (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] ``` #### function first ```kestrel 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 ``` #### function firstIndex ```kestrel 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 ``` #### function flatMap ```kestrel public func flatMap[U](as: (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] ``` #### function flatten ```kestrel 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] ``` #### function fold ```kestrel 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 ``` #### function forEach ```kestrel 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) }; ``` #### function fuse ```kestrel 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. #### function inspect ```kestrel public func inspect((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(); ``` #### function intersperse ```kestrel 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] ``` #### function intersperseWith ```kestrel public func intersperseWith(with: () -> 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] ``` #### function isSorted ```kestrel 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) ``` #### function isSortedDescending ```kestrel public consuming func isSortedDescending() -> Bool ``` True if elements come out in descending order. Mirror of `isSorted`. #### function iter ```kestrel func iter() -> Self ``` Returns `self`. The blanket conformance pivot — iterators *are* iterables. #### function last ```kestrel 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. #### function map ```kestrel public func map[U](as: (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] ``` #### function max ```kestrel public consuming func max() -> Item? ``` Largest element, or `None` for an empty iterator. Ties go to the first occurrence. #### function min ```kestrel 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 ``` #### function next ```kestrel public mutating func next() -> V? ``` Returns the next value, or `None` when the underlying iterator is exhausted. # Examples ``` var it = ["a": 1].values.iter(); it.next(); // Some(1) it.next(); // None ``` #### function nth ```kestrel 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) ``` #### function peekable ```kestrel 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) ``` #### function product ```kestrel 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 ``` #### function reduce ```kestrel 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 ``` #### function scan ```kestrel public func scan[Acc](from: Acc, by: (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] ``` #### function skip ```kestrel 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(); // [] ``` #### function skipWhile ```kestrel public func skipWhile(where: (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] ``` #### function sorted ```kestrel 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] ``` #### function stepBy ```kestrel 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] ``` #### function sum ```kestrel 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 ``` #### function take ```kestrel 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] ``` #### function takeWhile ```kestrel public func takeWhile(where: (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] ``` #### function tryFold ```kestrel 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") ``` #### function tryForEach ```kestrel public mutating func tryForEach[E]((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 ``` #### function unzip ```kestrel 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"] ``` #### function zip ```kestrel 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)] ``` ### struct ValuesView ```kestrel public struct ValuesView[K, V] where K: Hashable { /* private fields */ } ``` Lazy `Iterable` view over the values of a dictionary. Returned by `Dictionary.values`. Constructing the view is O(1) — it stores the bucket pointer and capacity. The view is invalidated by any mutation that may reallocate. # Examples ``` let dict = ["a": 1, "b": 2]; for v in dict.values { print(v) } let sum = dict.values.iter().sum(); ``` # Representation `(buckets, capacity)` — a pointer into the source dictionary's bucket array plus the total slot count. # Memory Model Value type that borrows the source dictionary's buffer. #### initializer From Buckets ```kestrel init(buckets: Pointer[Bucket[K, V]], capacity: Int64) ``` Internal — constructs a view from a bucket pointer and capacity. Use `Dictionary.values` to obtain a view. **Iterable** #### typealias Item ```kestrel type Item = V ``` `Iterable` element type — `V`. #### typealias TargetIterator ```kestrel type TargetIterator = ValuesIterator[K, V] ``` Concrete iterator type returned by `iter()`. #### function iter ```kestrel public func iter() -> ValuesIterator[K, V] ``` Returns a fresh `ValuesIterator[K, V]` over the view. Each call returns a new iterator starting at the beginning of the bucket array. ### struct WindowsIterator ```kestrel public struct WindowsIterator[T] { /* private fields */ } ``` #### initializer init ```kestrel public init(ptr: Pointer[T], totalCount: Int64, windowSize: Int64) ``` **Iterator** #### typealias Item ```kestrel type Item = ArraySlice[T] ``` #### typealias TargetIterator ```kestrel type TargetIterator = Self ``` #### function all ```kestrel 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) ``` #### function any ```kestrel 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 ``` #### function chain ```kestrel 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] ``` #### function collect ```kestrel 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] ``` #### function compactMap ```kestrel public func compactMap[T]() -> FilterMapIterator[Self, T] where Item == Optional[T] ``` Drops `None`s and unwraps `Some`s — 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] ``` #### function contains ```kestrel 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 ``` #### function count ```kestrel 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 ``` #### function cycle ```kestrel 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] ``` #### function enumerate ```kestrel 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}") }; ``` #### function filter ```kestrel public func filter(where: (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] ``` #### function filterMap ```kestrel public func filterMap[U](as: (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] ``` #### function first ```kestrel 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 ``` #### function firstIndex ```kestrel 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 ``` #### function flatMap ```kestrel public func flatMap[U](as: (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] ``` #### function flatten ```kestrel 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] ``` #### function fold ```kestrel 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 ``` #### function forEach ```kestrel 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) }; ``` #### function fuse ```kestrel 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. #### function inspect ```kestrel public func inspect((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(); ``` #### function intersperse ```kestrel 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] ``` #### function intersperseWith ```kestrel public func intersperseWith(with: () -> 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] ``` #### function isSorted ```kestrel 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) ``` #### function isSortedDescending ```kestrel public consuming func isSortedDescending() -> Bool ``` True if elements come out in descending order. Mirror of `isSorted`. #### function iter ```kestrel func iter() -> Self ``` Returns `self`. The blanket conformance pivot — iterators *are* iterables. #### function last ```kestrel 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. #### function map ```kestrel public func map[U](as: (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] ``` #### function max ```kestrel public consuming func max() -> Item? ``` Largest element, or `None` for an empty iterator. Ties go to the first occurrence. #### function min ```kestrel 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 ``` #### function next ```kestrel public mutating func next() -> Optional[ArraySlice[T]] ``` #### function nth ```kestrel 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) ``` #### function peekable ```kestrel 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) ``` #### function product ```kestrel 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 ``` #### function reduce ```kestrel 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 ``` #### function scan ```kestrel public func scan[Acc](from: Acc, by: (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] ``` #### function skip ```kestrel 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(); // [] ``` #### function skipWhile ```kestrel public func skipWhile(where: (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] ``` #### function sorted ```kestrel 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] ``` #### function stepBy ```kestrel 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] ``` #### function sum ```kestrel 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 ``` #### function take ```kestrel 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] ``` #### function takeWhile ```kestrel public func takeWhile(where: (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] ``` #### function tryFold ```kestrel 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") ``` #### function tryForEach ```kestrel public mutating func tryForEach[E]((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 ``` #### function unzip ```kestrel 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"] ``` #### function zip ```kestrel 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)] ``` ### struct WindowsView ```kestrel public struct WindowsView[T] { /* private fields */ } ``` Multi-pass lazy view over overlapping fixed-size sliding windows. #### field count ```kestrel public var count: Int64 { get } ``` #### field first ```kestrel public var first: Optional[ArraySlice[T]] { get } ``` #### initializer init ```kestrel public init(slice: ArraySlice[T], windowSize: Int64) ``` #### field isEmpty ```kestrel public var isEmpty: Bool { get } ``` #### field last ```kestrel public var last: Optional[ArraySlice[T]] { get } ``` #### subscript subscript ```kestrel public subscript(Int64) -> ArraySlice[T] { get } ``` #### function toArray ```kestrel public func toArray() -> Array[ArraySlice[T]] ``` **Iterable** #### typealias Item ```kestrel type Item = ArraySlice[T] ``` #### typealias TargetIterator ```kestrel type TargetIterator = WindowsIterator[T] ``` #### function iter ```kestrel public func iter() -> WindowsIterator[T] ``` --- ## std.core ### protocol AddAssign ```kestrel public protocol AddAssign[Other = Self] ``` Raw protocol backing the `+=` operator. In-place mutation lets conforming types avoid the temporary that a `self = self + other` rewrite would produce — important for collections (e.g. `Array += other`) and other types where the binary `+` would copy. #### function addAssign ```kestrel mutating func addAssign(Other) ``` Mutates `self` to `self + other`. ### protocol Addable ```kestrel public protocol Addable[Other = Self] ``` Raw protocol backing the `+` operator. `Output` may differ from `Self` and `Other` — this is what allows mixed-type arithmetic (e.g. `Vector + Scalar -> Vector`) without losing precision. The associated `zero` value gives sums (and `Iterator.sum`) a starting point and is the additive identity by definition. # Examples ``` 2 + 3 // 5 Int64.zero // 0 ``` #### typealias Output ```kestrel type Output ``` #### function add ```kestrel consuming func add(consuming Other) -> Output ``` Returns `self + other`. #### field zero ```kestrel static var zero: Self { get } ``` The additive identity — a value `z` such that `x + z == x` for all `x`. ### protocol And ```kestrel public protocol And[Other = Self] ``` Raw protocol backing the `and` keyword operator. The `other` operand is a thunk so that conformers can short-circuit: the right-hand side must not be evaluated when `self` is falsy. The stdlib implementations on `Bool` and the optional types all honour this; user implementations should too. # Examples ``` true and false // false true and { true } // true (closure form, mostly internal) ``` #### typealias Output ```kestrel type Output ``` #### function logicalAnd ```kestrel func logicalAnd(() -> Other) -> Output ``` Returns `self and other()`. The closure runs only if needed. ### typealias ArrayLiteralType ```kestrel public type ArrayLiteralType[T] = std.collections.Array[T] ``` ### protocol ArrayMatchable ```kestrel public protocol ArrayMatchable ``` Protocol enabling array patterns (`[a, b]`, `[a, ..rest]`, `[a, .., z]`, `[a, ..rest, z]`). The compiler routes match-arm element access through `matchGet` and rest-binding through `matchSlice` — they take `Int64` bounds the compiler has already verified. A conformer may assume `0 <= index < matchLength()` and `0 <= from <= to <= matchLength()` and skip its own bounds checks; the conformance is unsafe to satisfy if those invariants don't hold. `Array[T]` and `ArraySlice[T]` are the canonical conformers. #### typealias Element ```kestrel type Element ``` #### function matchGet ```kestrel func matchGet(Int64) -> Element ``` Returns the element at `index`. Caller (the compiler) guarantees `0 <= index < matchLength()` — implementations may skip bounds checks. #### function matchLength ```kestrel func matchLength() -> Int64 ``` Total number of elements available to match. #### function matchSlice ```kestrel func matchSlice(Int64, Int64) -> ArraySlice[Element] ``` Returns the slice `[from, to)`. Caller guarantees `0 <= from <= to <= matchLength()`. ### protocol BitwiseAnd ```kestrel public protocol BitwiseAnd[Other = Self] ``` Raw protocol backing the `&` operator. Implemented by every integer width; `Output` is `Self` for the standard integer types but may differ for SIMD or bitset wrappers. # Examples ``` 0b1100 & 0b1010 // 0b1000 ``` #### typealias Output ```kestrel type Output ``` #### function bitwiseAnd ```kestrel consuming func bitwiseAnd(consuming Other) -> Output ``` Returns `self & other`. ### protocol BitwiseAndAssign ```kestrel public protocol BitwiseAndAssign[Other = Self] ``` Raw protocol backing the `&=` operator. #### function bitwiseAndAssign ```kestrel mutating func bitwiseAndAssign(Other) ``` Mutates `self` to `self & other`. ### protocol BitwiseNot ```kestrel public protocol BitwiseNot ``` Raw protocol backing the unary `~` operator. #### typealias Output ```kestrel type Output ``` #### function bitwiseNot ```kestrel consuming func bitwiseNot() -> Output ``` Returns `~self` — every bit flipped. ### protocol BitwiseOr ```kestrel public protocol BitwiseOr[Other = Self] ``` Raw protocol backing the `|` operator. #### typealias Output ```kestrel type Output ``` #### function bitwiseOr ```kestrel consuming func bitwiseOr(consuming Other) -> Output ``` Returns `self | other`. ### protocol BitwiseOrAssign ```kestrel public protocol BitwiseOrAssign[Other = Self] ``` Raw protocol backing the `|=` operator. #### function bitwiseOrAssign ```kestrel mutating func bitwiseOrAssign(Other) ``` Mutates `self` to `self | other`. ### protocol BitwiseXor ```kestrel public protocol BitwiseXor[Other = Self] ``` Raw protocol backing the `^` operator. #### typealias Output ```kestrel type Output ``` #### function bitwiseXor ```kestrel consuming func bitwiseXor(consuming Other) -> Output ``` Returns `self ^ other`. ### protocol BitwiseXorAssign ```kestrel public protocol BitwiseXorAssign[Other = Self] ``` Raw protocol backing the `^=` operator. #### function bitwiseXorAssign ```kestrel mutating func bitwiseXorAssign(Other) ``` Mutates `self` to `self ^ other`. ### struct Bool ```kestrel public struct Bool { /* private fields */ } ``` Two-state truth value with `true` and `false` as its only inhabitants. `Bool` is the canonical conformer of every logical, conditional, and equality protocol in `std.core`: equality, matching, hashing, formatting, `and`/`or`/`not`, plus FFI compatibility for crossing the C boundary as a single byte. Custom types rarely need to wrap `Bool`; conform to the individual protocols (e.g. `BooleanConditional`) instead. # Examples ``` let alive = true; if alive { greet() } let votes = [true, false, true]; let yesCount = votes.iter().filter { it }.count(); // 2 ``` # Representation Wraps a single `lang.i1`. The runtime promotes to a byte at FFI boundaries (`FFISafe` conformance). #### initializer Bool Literal ```kestrel public init(boolLiteral: lang.i1) ``` Builds a `Bool` from the primitive `lang.i1` produced by a literal. **Equatable** #### typealias Output ```kestrel type Output = Bool ``` #### function equal ```kestrel public func equal(to: Self) -> Bool ``` Bridges `Equal.equal(to:)` to `Equatable.isEqual(to:)`. #### function isEqual ```kestrel public func isEqual(to: Bool) -> Bool ``` Returns `true` if both bits agree. Drives `==` for `Bool`. #### function notEqual ```kestrel public func notEqual(to: Self) -> Bool ``` Default `!=`: delegates to `==` so there's a single source of truth. **Matchable** #### function matches ```kestrel public func matches(Bool) -> Bool ``` Pattern-match form of `isEqual`: `case true =>` and `case false =>` dispatch through here. **Formattable** #### function format ```kestrel public func format(into: mutating StringBuilder, FormatOptions) ``` Renders as `"true"` / `"false"`. With `options.debug`, wraps as `"Bool(true)"` / `"Bool(false)"` for diagnostic dumps. # Examples ``` true.format() // "true" false.format(FormatOptions.debug()) // "Bool(false)" ``` #### function formatted ```kestrel public func formatted(FormatOptions) -> String ``` Returns this value rendered as a `String`. Convenience wrapper: creates a `StringBuilder`, calls `format(into:)`, and returns the built string. Uses a distinct name to avoid overload-resolution ambiguity with `format(into:)`. **Hashable** #### function hash ```kestrel public func hash[H](into: mutating H) where H: Hasher ``` Feeds a single `0` or `1` byte into `hasher`. Compatible with how the stdlib hashes other primitives — equal `Bool`s always hash equal. **And** #### typealias Output ```kestrel type Output = Bool ``` #### typealias Output ```kestrel type Output = Bool ``` #### typealias Output ```kestrel type Output = Bool ``` #### function logicalAnd ```kestrel public func logicalAnd(() -> Bool) -> Bool ``` Short-circuiting `and`: `other` runs only when `self` is `true`. The closure form is what the `and` keyword lowers into; users typically write `a and b` rather than calling this directly. **Or** #### typealias Output ```kestrel type Output ``` #### function logicalOr ```kestrel public func logicalOr(() -> Bool) -> Bool ``` Short-circuiting `or`: `other` runs only when `self` is `false`. **Not** #### typealias Output ```kestrel type Output ``` #### function logicalNot ```kestrel public func logicalNot() -> Bool ``` Bit-flip; `not true == false`. **ExpressibleByBoolLiteral** #### initializer Bool Literal ```kestrel init(boolLiteral: lang.i1) ``` Builds an instance from a boolean literal. **BooleanConditional** #### function boolValue ```kestrel public func boolValue() -> lang.i1 ``` Returns the wrapped `lang.i1` so `if`/`while` can branch on it without a redundant `Bool` round-trip. ### protocol BooleanConditional ```kestrel public protocol BooleanConditional ``` Protocol for types that may appear directly in `if`, `while`, and other boolean contexts. `Bool` is the canonical conformer. The method returns the primitive `lang.i1` rather than `Bool` to avoid a circular dependency between the conditional lowering and `Bool` itself. #### function boolValue ```kestrel func boolValue() -> lang.i1 ``` Returns the underlying truth value as a primitive `i1`. ### typealias BooleanLiteralType ```kestrel public type BooleanLiteralType = Bool ``` Default type for boolean literals (`let b = true` → `Bool`). ### typealias CharLiteralType ```kestrel public type CharLiteralType = Char ``` Default type for character literals (`let c = 'a'` → `Char`). ### protocol Cloneable ```kestrel public protocol Cloneable ``` Protocol for types that need custom logic when duplicated. `Cloneable` extends `Copyable` so that cloneable values can flow through generic code that asks only for `Copyable`. The compiler invokes `clone()` automatically wherever a `Cloneable` value would otherwise be implicitly copied (assignment, argument pass, return). The implementation decides how deep the copy goes — `RcBox`, for example, only bumps the refcount. # Examples ``` let a = RcBox(value: 1); let b = a; // implicit clone() — refcount bumps to 2 let c = a.clone(); // explicit clone — refcount bumps to 3 ``` #### function clone ```kestrel func clone() -> Self ``` Returns a copy of `self`. Conformers define the depth and any side effects (e.g. refcount adjustments). ### struct ClosedRange ```kestrel public struct ClosedRange[T] where T: Steppable, T: Comparable { /* private fields */ } ``` Closed range `[start, end]` — produced by the `..=` operator. Both endpoints are included in iteration. # Examples ``` for i in 0..=3 { print(i) } // 0, 1, 2, 3 (0..=10).contains(10) // true (vs Range, which excludes the upper) ``` # Representation Two values: `start` and `end`. No heap allocation. #### initializer From Bounds ```kestrel public init(T, T) ``` Builds the closed range `[start, end]`. #### function contains ```kestrel public func contains(T) -> Bool ``` Returns `true` iff `start <= value <= end`. #### field end ```kestrel public var end: T ``` Upper bound — included. #### field isEmpty ```kestrel public var isEmpty: Bool { get } ``` `true` when `start > end` (no values are produced). #### field start ```kestrel public var start: T ``` Lower bound — included. **Equatable** #### typealias Output ```kestrel type Output = Bool ``` #### function equal ```kestrel public func equal(to: Self) -> Bool ``` Bridges `Equal.equal(to:)` to `Equatable.isEqual(to:)`. #### function isEqual ```kestrel public func isEqual(to: ClosedRange[T]) -> Bool ``` Equal when both bounds match. #### function notEqual ```kestrel public func notEqual(to: Self) -> Bool ``` Default `!=`: delegates to `==` so there's a single source of truth. **Iterable** #### typealias Item ```kestrel type Item = T ``` #### typealias TargetIterator ```kestrel type TargetIterator = ClosedRangeIterator[T] ``` #### function iter ```kestrel public func iter() -> ClosedRangeIterator[T] ``` Returns a fresh iterator over the range. **SeqIndex** #### typealias SeqOutput ```kestrel type SeqOutput = ArraySlice[T] ``` #### function readSeq ```kestrel public func readSeq(from: ArraySlice[T]) -> ArraySlice[T] ``` #### function readSeqChecked ```kestrel public func readSeqChecked(from: ArraySlice[T]) -> ArraySlice[T]? ``` #### function readSeqUnchecked ```kestrel public func readSeqUnchecked(from: ArraySlice[T]) -> ArraySlice[T] ``` #### function writeSeq ```kestrel public func writeSeq(to: ArraySlice[T], with: ArraySlice[T]) ``` #### function writeSeqUnchecked ```kestrel public func writeSeqUnchecked(to: ArraySlice[T], with: ArraySlice[T]) ``` **SeqRange** #### function resolve ```kestrel public func resolve(Int64) -> Range[Int64] ``` **BytesIndex** #### typealias BytesYield ```kestrel type BytesYield = BytesView ``` #### function readBytes ```kestrel public func readBytes(from: BytesView) -> BytesView ``` #### function readBytesChecked ```kestrel public func readBytesChecked(from: BytesView) -> BytesView? ``` #### function readBytesUnchecked ```kestrel public func readBytesUnchecked(from: BytesView) -> BytesView ``` **BytesClampable** #### typealias BytesClampedYield ```kestrel type BytesClampedYield = BytesView ``` #### function readBytesClamped ```kestrel public func readBytesClamped(from: BytesView) -> BytesView ``` **BytesWrappable** #### typealias BytesWrappedYield ```kestrel type BytesWrappedYield = BytesView ``` #### function readBytesWrapped ```kestrel public func readBytesWrapped(from: BytesView) -> BytesView ``` **BytesSubstringIndex** #### function readBytesSubstring ```kestrel public func readBytesSubstring(from: BytesView) -> String ``` **CharsIndex** #### typealias CharsYield ```kestrel type CharsYield = CharsView ``` #### function readChars ```kestrel public func readChars(from: CharsView) -> CharsView ``` #### function readCharsChecked ```kestrel public func readCharsChecked(from: CharsView) -> CharsView? ``` **CharsClampable** #### typealias CharsClampedYield ```kestrel type CharsClampedYield = CharsView ``` #### function readCharsClamped ```kestrel public func readCharsClamped(from: CharsView) -> CharsView ``` **CharsWrappable** #### typealias CharsWrappedYield ```kestrel type CharsWrappedYield = CharsView ``` #### function readCharsWrapped ```kestrel public func readCharsWrapped(from: CharsView) -> CharsView ``` **CharsSubstringIndex** #### function readCharsSubstring ```kestrel public func readCharsSubstring(from: CharsView) -> String ``` **GraphemesIndex** #### typealias GraphemesYield ```kestrel type GraphemesYield = GraphemesView ``` #### function readGraphemes ```kestrel public func readGraphemes(from: GraphemesView) -> GraphemesView ``` #### function readGraphemesChecked ```kestrel public func readGraphemesChecked(from: GraphemesView) -> GraphemesView? ``` **GraphemesClampable** #### typealias GraphemesClampedYield ```kestrel type GraphemesClampedYield = GraphemesView ``` #### function readGraphemesClamped ```kestrel public func readGraphemesClamped(from: GraphemesView) -> GraphemesView ``` **GraphemesWrappable** #### typealias GraphemesWrappedYield ```kestrel type GraphemesWrappedYield = GraphemesView ``` #### function readGraphemesWrapped ```kestrel public func readGraphemesWrapped(from: GraphemesView) -> GraphemesView ``` **GraphemesSubstringIndex** #### function readGraphemesSubstring ```kestrel public func readGraphemesSubstring(from: GraphemesView) -> String ``` **LinesIndex** #### typealias LinesYield ```kestrel type LinesYield = LinesView ``` #### function readLines ```kestrel public func readLines(from: LinesView) -> LinesView ``` #### function readLinesChecked ```kestrel public func readLinesChecked(from: LinesView) -> LinesView? ``` **LinesClampable** #### typealias LinesClampedYield ```kestrel type LinesClampedYield = LinesView ``` #### function readLinesClamped ```kestrel public func readLinesClamped(from: LinesView) -> LinesView ``` **LinesWrappable** #### typealias LinesWrappedYield ```kestrel type LinesWrappedYield = LinesView ``` #### function readLinesWrapped ```kestrel public func readLinesWrapped(from: LinesView) -> LinesView ``` **LinesSubstringIndex** #### function readLinesSubstring ```kestrel public func readLinesSubstring(from: LinesView) -> String ``` ### protocol ClosedRangeConstructible ```kestrel public protocol ClosedRangeConstructible[Other = Self] ``` Raw protocol backing the closed `..=` operator (`start..=end`). #### typealias Output ```kestrel type Output ``` #### function inclusiveRange ```kestrel func inclusiveRange(to: Other) -> Output ``` Builds the closed range `[self, end]`. ### struct ClosedRangeIterator ```kestrel public struct ClosedRangeIterator[T] where T: Steppable, T: Comparable { /* private fields */ } ``` Iterator over a `ClosedRange[T]`. Differs from `RangeIterator` in that it yields `end` and uses an extra `finished` bit so it can terminate after emitting the upper bound. # Representation `current`, `end`, and a one-bit `finished` flag. #### initializer From Bounds ```kestrel public init(current: T, end: T, finished: Bool) ``` Builds an iterator yielding `current` through `end` inclusive. Pass `finished: true` to construct an already-exhausted iterator. **Iterator** #### typealias Item ```kestrel type Item = T ``` #### typealias TargetIterator ```kestrel type TargetIterator = Self ``` #### function all ```kestrel 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) ``` #### function any ```kestrel 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 ``` #### function chain ```kestrel 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] ``` #### function collect ```kestrel 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] ``` #### function compactMap ```kestrel public func compactMap[T]() -> FilterMapIterator[Self, T] where Item == Optional[T] ``` Drops `None`s and unwraps `Some`s — 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] ``` #### function contains ```kestrel 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 ``` #### function count ```kestrel 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 ``` #### function cycle ```kestrel 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] ``` #### function enumerate ```kestrel 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}") }; ``` #### function filter ```kestrel public func filter(where: (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] ``` #### function filterMap ```kestrel public func filterMap[U](as: (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] ``` #### function first ```kestrel 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 ``` #### function firstIndex ```kestrel 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 ``` #### function flatMap ```kestrel public func flatMap[U](as: (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] ``` #### function flatten ```kestrel 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] ``` #### function fold ```kestrel 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 ``` #### function forEach ```kestrel 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) }; ``` #### function fuse ```kestrel 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. #### function inspect ```kestrel public func inspect((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(); ``` #### function intersperse ```kestrel 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] ``` #### function intersperseWith ```kestrel public func intersperseWith(with: () -> 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] ``` #### function isSorted ```kestrel 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) ``` #### function isSortedDescending ```kestrel public consuming func isSortedDescending() -> Bool ``` True if elements come out in descending order. Mirror of `isSorted`. #### function iter ```kestrel func iter() -> Self ``` Returns `self`. The blanket conformance pivot — iterators *are* iterables. #### function last ```kestrel 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. #### function map ```kestrel public func map[U](as: (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] ``` #### function max ```kestrel public consuming func max() -> Item? ``` Largest element, or `None` for an empty iterator. Ties go to the first occurrence. #### function min ```kestrel 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 ``` #### function next ```kestrel public mutating func next() -> T? ``` Yields the next value, or `.None` when past `end`. #### function nth ```kestrel 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) ``` #### function peekable ```kestrel 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) ``` #### function product ```kestrel 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 ``` #### function reduce ```kestrel 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 ``` #### function scan ```kestrel public func scan[Acc](from: Acc, by: (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] ``` #### function skip ```kestrel 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(); // [] ``` #### function skipWhile ```kestrel public func skipWhile(where: (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] ``` #### function sorted ```kestrel 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] ``` #### function stepBy ```kestrel 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] ``` #### function sum ```kestrel 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 ``` #### function take ```kestrel 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] ``` #### function takeWhile ```kestrel public func takeWhile(where: (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] ``` #### function tryFold ```kestrel 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") ``` #### function tryForEach ```kestrel public mutating func tryForEach[E]((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 ``` #### function unzip ```kestrel 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"] ``` #### function zip ```kestrel 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)] ``` ### protocol Coalesce ```kestrel public protocol Coalesce[Default] ``` Raw protocol backing the `??` operator. Implemented by `Optional[T]` (with `Default = T`, `Output = T`) and by `Result[T, E]` (with `Default = T`, `Output = T`). The operand is a thunk so the default expression is only evaluated when needed — this matters when the default has side effects or is expensive to compute. # Examples ``` let name: String? = .None; name ?? "anonymous" // "anonymous" let cached: String? = .Some("hi"); cached ?? expensiveLookup() // "hi" — expensiveLookup() not called ``` #### typealias Output ```kestrel type Output ``` #### function coalesce ```kestrel func coalesce(() -> Default) -> Output ``` Returns the contained value, or the result of `default()` if absent. ### protocol Comparable ```kestrel public protocol Comparable ``` Protocol for types with a total ordering. Conformers implement a single `compare(other:) -> Ordering`; the blanket extension below derives `<`, `<=`, `>`, `>=`, and `!=` (the last shadowing the `Equatable` default since it can be cheaper via `compare`). `Comparable` extends `Equatable`, so equal values and a `compare` returning `.Equal` must agree. # Examples ``` public struct Version: Comparable { public var major: Int64 public var minor: Int64 public func isEqual(to other: Version) -> Bool { self.major == other.major and self.minor == other.minor } public func compare(other: Version) -> Ordering { self.major.compare(other.major) .then(self.minor.compare(other.minor)) } } ``` #### function compare ```kestrel func compare(Self) -> Ordering ``` Returns the ordering of `self` relative to `other`. Must be a total order — for any `a`, `b`, `c` exactly one of `Less`, `Equal`, `Greater` holds, and the order is transitive. **Equatable** #### typealias Output ```kestrel type Output = Bool ``` #### function equal ```kestrel public func equal(to: Self) -> Bool ``` Bridges `Equal.equal(to:)` to `Equatable.isEqual(to:)`. #### function isEqual ```kestrel func isEqual(to: Self) -> Bool ``` Returns `true` iff `self` and `other` are considered equal. Should be reflexive, symmetric, and transitive — `Hashable` requires equal values to hash equal, so don't drift from those laws. #### function notEqual ```kestrel public func notEqual(to: Self) -> Bool ``` Default `!=`: delegates to `==` so there's a single source of truth. **Less** #### typealias Output ```kestrel type Output = Bool ``` #### typealias Output ```kestrel type Output = Bool ``` #### typealias Output ```kestrel type Output = Bool ``` #### typealias Output ```kestrel type Output = Bool ``` #### function lessThan ```kestrel public func lessThan(Self) -> Bool ``` `<` derived from `compare`. **LessOrEqual** #### typealias Output ```kestrel type Output ``` #### function lessThanOrEqual ```kestrel public func lessThanOrEqual(Self) -> Bool ``` `<=` derived from `compare`. **Greater** #### typealias Output ```kestrel type Output ``` #### function greaterThan ```kestrel public func greaterThan(Self) -> Bool ``` `>` derived from `compare`. **GreaterOrEqual** #### typealias Output ```kestrel type Output ``` #### function greaterThanOrEqual ```kestrel public func greaterThanOrEqual(Self) -> Bool ``` `>=` derived from `compare`. **RangeMatchable** #### function isAtLeast ```kestrel public func isAtLeast(Self) -> Bool ``` `start..` lower-bound check, derived from `compare`. #### function isAtMost ```kestrel public func isAtMost(Self) -> Bool ``` `..=end` upper-bound check, derived from `compare`. #### function isBelow ```kestrel public func isBelow(Self) -> Bool ``` `.. Output ``` Returns `self / other`. ### protocol Equal ```kestrel public protocol Equal[Other = Self] ``` Raw protocol backing the `==` operator. Most user code should conform to `Equatable` instead, which conforms to `Equal[Self]` automatically with `Output = Bool`. Implement `Equal` directly only when you need a non-Bool result (e.g. lifting equality into a vector type that returns a mask). # Examples ``` 1 == 1 // true "a" == "b" // false ``` #### typealias Output ```kestrel type Output ``` #### function equal ```kestrel func equal(to: Other) -> Output ``` Returns the equality result as `Output` — typically `Bool`. ### protocol Equatable ```kestrel public protocol Equatable ``` Protocol for types whose values can be compared for equality. `Equatable` is the semantic counterpart to the raw `Equal[Self]` operator protocol: conformers implement `isEqual` returning `Bool`, and a blanket extension below derives both `==` and `!=`. Most types should reach for `Equatable` rather than `Equal` directly — the `Bool` associated-type binding is wired up automatically. # Examples ``` public struct Point: Equatable { public var x: Int64 public var y: Int64 public func isEqual(to other: Point) -> Bool { self.x == other.x and self.y == other.y } } Point(x: 1, y: 2) == Point(x: 1, y: 2) // true ``` #### function isEqual ```kestrel func isEqual(to: Self) -> Bool ``` Returns `true` iff `self` and `other` are considered equal. Should be reflexive, symmetric, and transitive — `Hashable` requires equal values to hash equal, so don't drift from those laws. **Equal** #### typealias Output ```kestrel type Output = Bool ``` #### typealias Output ```kestrel type Output = Bool ``` #### function equal ```kestrel public func equal(to: Self) -> Bool ``` Bridges `Equal.equal(to:)` to `Equatable.isEqual(to:)`. **NotEqual** #### typealias Output ```kestrel type Output ``` #### function notEqual ```kestrel public func notEqual(to: Self) -> Bool ``` Default `!=`: delegates to `==` so there's a single source of truth. ### protocol ExpressibleByArrayLiteral ```kestrel public protocol ExpressibleByArrayLiteral ``` User-facing protocol for array-literal lowering. Provides a `LiteralSlice` view over the literal's contents so the implementation can iterate or copy without juggling raw pointers. #### initializer Array Literal ```kestrel init(arrayLiteral: LiteralSlice[Element]) ``` Builds an instance from a literal slice of elements. **_ExpressibleByArrayLiteral** #### typealias Element ```kestrel type Element ``` #### initializer Literal Bridge ```kestrel init(_arrayLiteralPointer: consuming lang.ptr[Element], _arrayLiteralCount: consuming lang.i64) ``` Compiler-emitted init taking a raw pointer and count. Both params are `consuming`: the compiler hands ownership of the stack buffer's address (and the count) over to the implementation, which stores them in its own storage. This convention is what the MIR lowering's structural predicate looks for — implementations that deviate will be silently skipped during literal lowering. ### protocol ExpressibleByBoolLiteral ```kestrel public protocol ExpressibleByBoolLiteral ``` Protocol for types that accept a `true`/`false` literal. The init takes a primitive `lang.i1` rather than `Bool` because `Bool` itself conforms — the literal lowering needs a representation that does not depend on the type being constructed. #### initializer Bool Literal ```kestrel init(boolLiteral: lang.i1) ``` Builds an instance from a boolean literal. ### protocol ExpressibleByCharLiteral ```kestrel public protocol ExpressibleByCharLiteral ``` Protocol for types that accept a character literal (`'a'`). #### initializer Char Literal ```kestrel init(charLiteral: lang.i32) ``` Builds an instance from a character literal. ### protocol ExpressibleByDictionaryLiteral ```kestrel public protocol ExpressibleByDictionaryLiteral ``` User-facing protocol for dictionary-literal lowering. Mirrors `ExpressibleByArrayLiteral` but for key-value pairs. #### initializer Dictionary Literal ```kestrel init(dictionaryLiteral: LiteralSlice[(Key, Value)]) ``` Builds an instance from a literal slice of key-value pairs. **_ExpressibleByDictionaryLiteral** #### typealias Key ```kestrel type Key ``` #### initializer Literal Bridge ```kestrel init(consuming lang.ptr[(Key, Value)], consuming lang.i64) ``` Compiler-emitted init taking a raw `(Key, Value)` pointer and count. Both params are `consuming` for the same reason as the array bridge: the compiler hands ownership of the stack buffer to the implementation. MIR lowering matches on the unwrapped param shape, so an impl that deviates from this convention will be skipped during literal lowering. #### typealias Value ```kestrel type Value ``` ### protocol ExpressibleByFloatLiteral ```kestrel public protocol ExpressibleByFloatLiteral ``` Protocol for types that accept a floating-point literal (e.g. `3.14`). #### initializer Float Literal ```kestrel init(floatLiteral: lang.f64) ``` Builds an instance from a floating-point literal. ### protocol ExpressibleByIntLiteral ```kestrel public protocol ExpressibleByIntLiteral ``` Protocol for types that accept an integer literal (e.g. `42`, `0xff`). All the standard integer widths conform; types outside `std.numeric` (for example a `BigInt` or a fixed-point number) can also conform to opt in to the literal syntax. #### initializer Int Literal ```kestrel init(intLiteral: lang.i64) ``` Builds an instance from an integer literal. ### protocol ExpressibleByNullLiteral ```kestrel public protocol ExpressibleByNullLiteral ``` Protocol for types that accept the `null` literal. `Optional[T]` is the canonical conformer; it produces `.None`. Types that wrap an optional or have a meaningful "absent" state may also conform. #### initializer Null Literal ```kestrel init() ``` Builds the absent/none instance. ### protocol ExpressibleByStringLiteral ```kestrel public protocol ExpressibleByStringLiteral ``` Protocol for types that accept a string literal (`"…"`). The init receives a raw pointer and byte length so that string literal lowering does not require the target type to already exist in stdlib form. #### initializer String Literal ```kestrel init(stringLiteral: lang.ptr[lang.i8], lang.i64) ``` Builds an instance from a string literal. ### typealias FloatLiteralType ```kestrel public type FloatLiteralType = Float64 ``` Default type for float literals (`let x = 1.0` → `Float64`). ### protocol FromResidual ```kestrel public protocol FromResidual[Residual] ``` Protocol that lets a return type absorb a `try`-propagated residual. Implement when your error/optional type should be reachable via `try` from another type with a different residual. For example, `Result[T, E]` implements `FromResidual[E]` so that `try someResult` inside a function returning `Result[T, E]` rebuilds the failure. #### function fromResidual ```kestrel static func fromResidual(Residual) -> Self ``` Builds an instance carrying `residual` as its failure payload. ### protocol Greater ```kestrel public protocol Greater[Other = Self] ``` Raw protocol backing the `>` operator. See `Less` for guidance. #### typealias Output ```kestrel type Output ``` #### function greaterThan ```kestrel func greaterThan(Other) -> Output ``` Returns the greater-than result as `Output` — typically `Bool`. ### protocol GreaterOrEqual ```kestrel public protocol GreaterOrEqual[Other = Self] ``` Raw protocol backing the `>=` operator. See `Less` for guidance. #### typealias Output ```kestrel type Output ``` #### function greaterThanOrEqual ```kestrel func greaterThanOrEqual(Other) -> Output ``` Returns the greater-than-or-equal result as `Output` — typically `Bool`. ### protocol Hashable ```kestrel public protocol Hashable ``` Protocol for types whose values can be hashed. `Hashable` extends `Equatable`: the contract is that `a == b` implies `a.hash(into:)` and `b.hash(into:)` feed the same bytes to the hasher. Violating this breaks `Set` and `Dictionary` — equal lookups won't land on the equal stored value. The hasher is generic so the same hash impl works across hashing algorithms (SipHash, FxHash, etc.). # Examples ``` public struct Tag: Hashable { public var name: String public func isEqual(to other: Tag) -> Bool { self.name == other.name } public func hash[H](mutating into hasher: H) where H: Hasher { self.name.hash(into: hasher) } } ``` #### function hash ```kestrel func hash[H](into: mutating H) where H: Hasher ``` Feeds this value's bytes into `hasher`. Must be deterministic across calls and consistent with `isEqual`. **Equatable** #### typealias Output ```kestrel type Output = Bool ``` #### function equal ```kestrel public func equal(to: Self) -> Bool ``` Bridges `Equal.equal(to:)` to `Equatable.isEqual(to:)`. #### function isEqual ```kestrel func isEqual(to: Self) -> Bool ``` Returns `true` iff `self` and `other` are considered equal. Should be reflexive, symmetric, and transitive — `Hashable` requires equal values to hash equal, so don't drift from those laws. #### function notEqual ```kestrel public func notEqual(to: Self) -> Bool ``` Default `!=`: delegates to `==` so there's a single source of truth. ### protocol Hasher ```kestrel public protocol Hasher ``` Protocol for hash algorithm implementations consumed by `Hashable`. The contract is the same as Rust / Swift: `Hashable`-conforming types `write` their bytes into the hasher; the hasher accumulates state and emits a `UInt64` digest on `finish()`. Used by `Set`, `Dictionary`, and any structure that wants stable hashes. #### function finish ```kestrel mutating func finish() -> UInt64 ``` Returns the finalised hash. After calling `finish` the hasher's state is unspecified — don't reuse it. #### function write ```kestrel mutating func write(ArraySlice[UInt8]) ``` Mixes `bytes` into the running hash state. ### typealias IntegerLiteralType ```kestrel public type IntegerLiteralType = Int64 ``` Default type for integer literals (`let x = 1` → `Int64`). ### protocol LeftShift ```kestrel public protocol LeftShift[Other = Int64] ``` Raw protocol backing the `<<` operator. `Other` defaults to `Int64` — the standard shift count type. Conforming types may narrow this to a different count where appropriate. # Errors Standard integer types panic on out-of-range shift counts (see the `shiftLeft` documentation on the integer types). #### typealias Output ```kestrel type Output ``` #### function shiftLeft ```kestrel consuming func shiftLeft(by: consuming Other) -> Output ``` Returns `self << count`. ### protocol LeftShiftAssign ```kestrel public protocol LeftShiftAssign[Other] ``` Raw protocol backing the `<<=` operator. #### function shiftLeftAssign ```kestrel mutating func shiftLeftAssign(by: Other) ``` Mutates `self` to `self << count`. ### protocol Less ```kestrel public protocol Less[Other = Self] ``` Raw protocol backing the `<` operator. `Comparable` derives `Less`, `LessOrEqual`, `Greater`, `GreaterOrEqual` from a single `compare()` method, so prefer conforming to `Comparable` for totally-ordered types. #### typealias Output ```kestrel type Output ``` #### function lessThan ```kestrel func lessThan(Other) -> Output ``` Returns the less-than result as `Output` — typically `Bool`. ### protocol LessOrEqual ```kestrel public protocol LessOrEqual[Other = Self] ``` Raw protocol backing the `<=` operator. See `Less` for guidance. #### typealias Output ```kestrel type Output ``` #### function lessThanOrEqual ```kestrel func lessThanOrEqual(Other) -> Output ``` Returns the less-than-or-equal result as `Output` — typically `Bool`. ### protocol Matchable ```kestrel public protocol Matchable ``` Protocol enabling `match` against custom types via the `case` pattern. Conformers decide what "matches" means — for `Bool` and the integer types it is straight equality; for ranges it is containment. The compiler lowers `case =>` to a `matches` call. #### function matches ```kestrel func matches(Self) -> Bool ``` Returns `true` if `other` matches the receiver. ### protocol Modulo ```kestrel public protocol Modulo[Other = Self] ``` Raw protocol backing the `%` operator. For integers this is the remainder of truncated division, with the sign of the dividend. Use `floorMod` (defined on integer types) when you want Euclidean / floor-style remainder semantics. #### typealias Output ```kestrel type Output ``` #### function modulo ```kestrel consuming func modulo(consuming Other) -> Output ``` Returns `self % other`. ### protocol ModuloAssign ```kestrel public protocol ModuloAssign[Other = Self] ``` Raw protocol backing the `%=` operator. #### function modAssign ```kestrel mutating func modAssign(Other) ``` Mutates `self` to `self % other`. ### protocol Multipliable ```kestrel public protocol Multipliable[Other = Self] ``` Raw protocol backing the `*` operator. The associated `one` value is the multiplicative identity, used as the starting accumulator for products and powers. # Examples ``` 6 * 7 // 42 Int64.one // 1 ``` #### typealias Output ```kestrel type Output ``` #### function multiply ```kestrel consuming func multiply(consuming Other) -> Output ``` Returns `self * other`. #### field one ```kestrel static var one: Self { get } ``` The multiplicative identity — a value `o` such that `x * o == x` for all `x`. ### protocol MultiplyAssign ```kestrel public protocol MultiplyAssign[Other = Self] ``` Raw protocol backing the `*=` operator. #### function multiplyAssign ```kestrel mutating func multiplyAssign(Other) ``` Mutates `self` to `self * other`. ### protocol Negatable ```kestrel public protocol Negatable ``` Raw protocol backing the unary `-` operator. On signed two's-complement integers, negating the minimum value overflows (e.g. `-Int8.minValue == Int8.minValue`); the operator wraps. Use `checkedNegate` if overflow needs to surface. #### typealias Output ```kestrel type Output ``` #### function negate ```kestrel consuming func negate() -> Output ``` Returns `-self`. ### protocol Not ```kestrel public protocol Not ``` Raw protocol backing the `not` keyword operator. #### typealias Output ```kestrel type Output ``` #### function logicalNot ```kestrel func logicalNot() -> Output ``` Returns `not self`. ### protocol NotEqual ```kestrel public protocol NotEqual[Other = Self] ``` Raw protocol backing the `!=` operator. `Equatable` provides a default `notEqual` derived from `equal`, so conforming to `Equatable` is enough for both `==` and `!=`. #### typealias Output ```kestrel type Output ``` #### function notEqual ```kestrel func notEqual(to: Other) -> Output ``` Returns the inequality result as `Output` — typically `Bool`. ### typealias NullLiteralType ```kestrel public type NullLiteralType[T] = std.result.Optional[T] ``` Default type for null literals (`let x = null` → `Optional[T]`). ### protocol Or ```kestrel public protocol Or[Other = Self] ``` Raw protocol backing the `or` keyword operator. As with `And`, `other` is a thunk so the right-hand side can be skipped when `self` already determines the result. #### typealias Output ```kestrel type Output ``` #### function logicalOr ```kestrel func logicalOr(() -> Other) -> Output ``` Returns `self or other()`. The closure runs only if needed. ### enum Ordering ```kestrel public enum Ordering ``` The three-valued result of a `Comparable.compare()` call. `Ordering` is the lingua franca for comparison: types implementing `Comparable` define a single `compare` returning this enum, and the stdlib derives `<`, `<=`, `>`, `>=` on top. The `then` / `thenWith` helpers make it easy to chain comparisons over multiple fields without nested `if`s. # Examples ``` let cmp = a.compare(b); match cmp { .Less => "ascending", .Equal => "tied", .Greater => "descending" } // Chain field comparisons: by lastName, then firstName. a.lastName.compare(b.lastName) .then(a.firstName.compare(b.firstName)) ``` # Representation A plain three-state enum with no payload — lowers to a small integer tag. #### case Equal ```kestrel case Equal ``` The two values compared equal. #### case Greater ```kestrel case Greater ``` The receiver compared greater than the argument. #### case Less ```kestrel case Less ``` The receiver compared less than the argument. #### function reverse ```kestrel public func reverse() -> Ordering ``` Swaps `Less` and `Greater`; leaves `Equal` alone. Useful for sorting in reverse without writing a second comparator. # Examples ``` Ordering.Less.reverse() // .Greater Ordering.Equal.reverse() // .Equal ``` #### function then ```kestrel public func then(Ordering) -> Ordering ``` Tie-breaker chain: returns `self` if it is non-`Equal`, otherwise `other`. The eager form — both arguments are evaluated. # Examples ``` Ordering.Equal.then(.Less) // .Less Ordering.Greater.then(.Less) // .Greater (self wins) ``` #### function thenWith ```kestrel public func thenWith(() -> Ordering) -> Ordering ``` Lazy variant of `then` — `compare` runs only when `self` is `Equal`. Prefer this when computing the secondary comparison is expensive. **Equatable** #### typealias Output ```kestrel type Output = Bool ``` #### function equal ```kestrel public func equal(to: Self) -> Bool ``` Bridges `Equal.equal(to:)` to `Equatable.isEqual(to:)`. #### function isEqual ```kestrel public func isEqual(to: Ordering) -> Bool ``` Equality on the orderings themselves: same variant ⇒ equal. #### function notEqual ```kestrel public func notEqual(to: Self) -> Bool ``` Default `!=`: delegates to `==` so there's a single source of truth. **Formattable** #### function format ```kestrel public func format(into: mutating StringBuilder, FormatOptions) ``` Renders as `"Less"`, `"Equal"`, or `"Greater"`. With `debug` set, prefixes with the type name (`"Ordering.Less"`). #### function formatted ```kestrel public func formatted(FormatOptions) -> String ``` Returns this value rendered as a `String`. Convenience wrapper: creates a `StringBuilder`, calls `format(into:)`, and returns the built string. Uses a distinct name to avoid overload-resolution ambiguity with `format(into:)`. ### struct Range ```kestrel public struct Range[T] where T: Steppable, T: Comparable { /* private fields */ } ``` Half-open range `[start, end)` — produced by the `..<` operator. `Range` is `Iterable`, so `for x in 0..<10 { … }` works directly. `T` must be `Steppable` (defines `successor()`) and `Comparable` (so the iterator knows when to stop). Empty ranges (`start >= end`) yield nothing. # Examples ``` for i in 0..<3 { print(i) } // 0, 1, 2 (0..<10).contains(5) // true (0..<0).isEmpty() // true ``` # Representation Two values: `start` and `end`. No heap allocation. #### initializer From Bounds ```kestrel public init(T, T) ``` Builds the range `[start, end)`. #### function contains ```kestrel public func contains(T) -> Bool ``` Returns `true` iff `start <= value < end`. #### field end ```kestrel public var end: T ``` Upper bound — excluded from the range. #### field isEmpty ```kestrel public var isEmpty: Bool { get } ``` `true` when `start >= end` (no values are produced). #### field start ```kestrel public var start: T ``` Lower bound — included in the range. **Equatable** #### typealias Output ```kestrel type Output = Bool ``` #### function equal ```kestrel public func equal(to: Self) -> Bool ``` Bridges `Equal.equal(to:)` to `Equatable.isEqual(to:)`. #### function isEqual ```kestrel public func isEqual(to: Range[T]) -> Bool ``` Equal when both bounds match. Useful for range-keyed lookups and tests, not a structural property of the iteration order. #### function notEqual ```kestrel public func notEqual(to: Self) -> Bool ``` Default `!=`: delegates to `==` so there's a single source of truth. **Iterable** #### typealias Item ```kestrel type Item = T ``` #### typealias TargetIterator ```kestrel type TargetIterator = RangeIterator[T] ``` #### function iter ```kestrel public func iter() -> RangeIterator[T] ``` Returns a fresh iterator over the range. Multiple calls produce independent iterators — `Range` is value-typed. **SeqIndex** #### typealias SeqOutput ```kestrel type SeqOutput = ArraySlice[T] ``` #### function readSeq ```kestrel public func readSeq(from: ArraySlice[T]) -> ArraySlice[T] ``` #### function readSeqChecked ```kestrel public func readSeqChecked(from: ArraySlice[T]) -> ArraySlice[T]? ``` #### function readSeqUnchecked ```kestrel public func readSeqUnchecked(from: ArraySlice[T]) -> ArraySlice[T] ``` #### function writeSeq ```kestrel public func writeSeq(to: ArraySlice[T], with: ArraySlice[T]) ``` #### function writeSeqUnchecked ```kestrel public func writeSeqUnchecked(to: ArraySlice[T], with: ArraySlice[T]) ``` **SeqClampable** #### typealias SeqClampedOutput ```kestrel type SeqClampedOutput = ArraySlice[T] ``` #### function readSeqClamped ```kestrel public func readSeqClamped(from: ArraySlice[T]) -> ArraySlice[T] ``` #### function writeSeqClamped ```kestrel public func writeSeqClamped(to: ArraySlice[T], with: ArraySlice[T]) ``` **SeqRange** #### function resolve ```kestrel public func resolve(Int64) -> Range[Int64] ``` **BytesIndex** #### typealias BytesYield ```kestrel type BytesYield = BytesView ``` #### function readBytes ```kestrel public func readBytes(from: BytesView) -> BytesView ``` #### function readBytesChecked ```kestrel public func readBytesChecked(from: BytesView) -> BytesView? ``` #### function readBytesUnchecked ```kestrel public func readBytesUnchecked(from: BytesView) -> BytesView ``` **BytesClampable** #### typealias BytesClampedYield ```kestrel type BytesClampedYield = BytesView ``` #### function readBytesClamped ```kestrel public func readBytesClamped(from: BytesView) -> BytesView ``` **BytesWrappable** #### typealias BytesWrappedYield ```kestrel type BytesWrappedYield = BytesView ``` #### function readBytesWrapped ```kestrel public func readBytesWrapped(from: BytesView) -> BytesView ``` **BytesSubstringIndex** #### function readBytesSubstring ```kestrel public func readBytesSubstring(from: BytesView) -> String ``` **CharsIndex** #### typealias CharsYield ```kestrel type CharsYield = CharsView ``` #### function readChars ```kestrel public func readChars(from: CharsView) -> CharsView ``` #### function readCharsChecked ```kestrel public func readCharsChecked(from: CharsView) -> CharsView? ``` **CharsClampable** #### typealias CharsClampedYield ```kestrel type CharsClampedYield = CharsView ``` #### function readCharsClamped ```kestrel public func readCharsClamped(from: CharsView) -> CharsView ``` **CharsWrappable** #### typealias CharsWrappedYield ```kestrel type CharsWrappedYield = CharsView ``` #### function readCharsWrapped ```kestrel public func readCharsWrapped(from: CharsView) -> CharsView ``` **CharsSubstringIndex** #### function readCharsSubstring ```kestrel public func readCharsSubstring(from: CharsView) -> String ``` **GraphemesIndex** #### typealias GraphemesYield ```kestrel type GraphemesYield = GraphemesView ``` #### function readGraphemes ```kestrel public func readGraphemes(from: GraphemesView) -> GraphemesView ``` #### function readGraphemesChecked ```kestrel public func readGraphemesChecked(from: GraphemesView) -> GraphemesView? ``` **GraphemesClampable** #### typealias GraphemesClampedYield ```kestrel type GraphemesClampedYield = GraphemesView ``` #### function readGraphemesClamped ```kestrel public func readGraphemesClamped(from: GraphemesView) -> GraphemesView ``` **GraphemesWrappable** #### typealias GraphemesWrappedYield ```kestrel type GraphemesWrappedYield = GraphemesView ``` #### function readGraphemesWrapped ```kestrel public func readGraphemesWrapped(from: GraphemesView) -> GraphemesView ``` **GraphemesSubstringIndex** #### function readGraphemesSubstring ```kestrel public func readGraphemesSubstring(from: GraphemesView) -> String ``` **LinesIndex** #### typealias LinesYield ```kestrel type LinesYield = LinesView ``` #### function readLines ```kestrel public func readLines(from: LinesView) -> LinesView ``` #### function readLinesChecked ```kestrel public func readLinesChecked(from: LinesView) -> LinesView? ``` **LinesClampable** #### typealias LinesClampedYield ```kestrel type LinesClampedYield = LinesView ``` #### function readLinesClamped ```kestrel public func readLinesClamped(from: LinesView) -> LinesView ``` **LinesWrappable** #### typealias LinesWrappedYield ```kestrel type LinesWrappedYield = LinesView ``` #### function readLinesWrapped ```kestrel public func readLinesWrapped(from: LinesView) -> LinesView ``` **LinesSubstringIndex** #### function readLinesSubstring ```kestrel public func readLinesSubstring(from: LinesView) -> String ``` ### protocol RangeConstructible ```kestrel public protocol RangeConstructible[Other = Self] ``` Raw protocol backing the half-open `..<` operator (`start.. Output ``` Builds the half-open range `[self, end)`. ### struct RangeFrom ```kestrel public struct RangeFrom[T] where T: Steppable, T: Comparable { /* private fields */ } ``` Partial range `[start, +∞)` — produced by the postfix `..` operator. `RangeFrom` is `Iterable` and produces an infinite iterator. Use `break` to terminate iteration. # Examples ``` for i in 0.. { if i >= 5 { break; } print(i) } (10..).contains(42) // true ``` # Representation Single value: `start`. No heap allocation. #### initializer From Start ```kestrel public init(T) ``` #### function contains ```kestrel public func contains(T) -> Bool ``` Returns `true` iff `value >= start`. #### field start ```kestrel public var start: T ``` Lower bound — included in the range. **Equatable** #### typealias Output ```kestrel type Output = Bool ``` #### function equal ```kestrel public func equal(to: Self) -> Bool ``` Bridges `Equal.equal(to:)` to `Equatable.isEqual(to:)`. #### function isEqual ```kestrel public func isEqual(to: RangeFrom[T]) -> Bool ``` Structural equality. #### function notEqual ```kestrel public func notEqual(to: Self) -> Bool ``` Default `!=`: delegates to `==` so there's a single source of truth. **Iterable** #### typealias Item ```kestrel type Item = T ``` #### typealias TargetIterator ```kestrel type TargetIterator = RangeFromIterator[T] ``` #### function iter ```kestrel public func iter() -> RangeFromIterator[T] ``` Returns a fresh infinite iterator starting at `start`. **SeqIndex** #### typealias SeqOutput ```kestrel type SeqOutput = ArraySlice[T] ``` #### function readSeq ```kestrel public func readSeq(from: ArraySlice[T]) -> ArraySlice[T] ``` #### function readSeqChecked ```kestrel public func readSeqChecked(from: ArraySlice[T]) -> ArraySlice[T]? ``` #### function readSeqUnchecked ```kestrel public func readSeqUnchecked(from: ArraySlice[T]) -> ArraySlice[T] ``` #### function writeSeq ```kestrel public func writeSeq(to: ArraySlice[T], with: ArraySlice[T]) ``` #### function writeSeqUnchecked ```kestrel public func writeSeqUnchecked(to: ArraySlice[T], with: ArraySlice[T]) ``` **SeqRange** #### function resolve ```kestrel public func resolve(Int64) -> Range[Int64] ``` **BytesIndex** #### typealias BytesYield ```kestrel type BytesYield = BytesView ``` #### function readBytes ```kestrel public func readBytes(from: BytesView) -> BytesView ``` #### function readBytesChecked ```kestrel public func readBytesChecked(from: BytesView) -> BytesView? ``` #### function readBytesUnchecked ```kestrel public func readBytesUnchecked(from: BytesView) -> BytesView ``` **BytesClampable** #### typealias BytesClampedYield ```kestrel type BytesClampedYield = BytesView ``` #### function readBytesClamped ```kestrel public func readBytesClamped(from: BytesView) -> BytesView ``` **BytesWrappable** #### typealias BytesWrappedYield ```kestrel type BytesWrappedYield = BytesView ``` #### function readBytesWrapped ```kestrel public func readBytesWrapped(from: BytesView) -> BytesView ``` **BytesSubstringIndex** #### function readBytesSubstring ```kestrel public func readBytesSubstring(from: BytesView) -> String ``` **CharsIndex** #### typealias CharsYield ```kestrel type CharsYield = CharsView ``` #### function readChars ```kestrel public func readChars(from: CharsView) -> CharsView ``` #### function readCharsChecked ```kestrel public func readCharsChecked(from: CharsView) -> CharsView? ``` **CharsClampable** #### typealias CharsClampedYield ```kestrel type CharsClampedYield = CharsView ``` #### function readCharsClamped ```kestrel public func readCharsClamped(from: CharsView) -> CharsView ``` **CharsWrappable** #### typealias CharsWrappedYield ```kestrel type CharsWrappedYield = CharsView ``` #### function readCharsWrapped ```kestrel public func readCharsWrapped(from: CharsView) -> CharsView ``` **CharsSubstringIndex** #### function readCharsSubstring ```kestrel public func readCharsSubstring(from: CharsView) -> String ``` **GraphemesIndex** #### typealias GraphemesYield ```kestrel type GraphemesYield = GraphemesView ``` #### function readGraphemes ```kestrel public func readGraphemes(from: GraphemesView) -> GraphemesView ``` #### function readGraphemesChecked ```kestrel public func readGraphemesChecked(from: GraphemesView) -> GraphemesView? ``` **GraphemesClampable** #### typealias GraphemesClampedYield ```kestrel type GraphemesClampedYield = GraphemesView ``` #### function readGraphemesClamped ```kestrel public func readGraphemesClamped(from: GraphemesView) -> GraphemesView ``` **GraphemesWrappable** #### typealias GraphemesWrappedYield ```kestrel type GraphemesWrappedYield = GraphemesView ``` #### function readGraphemesWrapped ```kestrel public func readGraphemesWrapped(from: GraphemesView) -> GraphemesView ``` **GraphemesSubstringIndex** #### function readGraphemesSubstring ```kestrel public func readGraphemesSubstring(from: GraphemesView) -> String ``` **LinesIndex** #### typealias LinesYield ```kestrel type LinesYield = LinesView ``` #### function readLines ```kestrel public func readLines(from: LinesView) -> LinesView ``` #### function readLinesChecked ```kestrel public func readLinesChecked(from: LinesView) -> LinesView? ``` **LinesClampable** #### typealias LinesClampedYield ```kestrel type LinesClampedYield = LinesView ``` #### function readLinesClamped ```kestrel public func readLinesClamped(from: LinesView) -> LinesView ``` **LinesWrappable** #### typealias LinesWrappedYield ```kestrel type LinesWrappedYield = LinesView ``` #### function readLinesWrapped ```kestrel public func readLinesWrapped(from: LinesView) -> LinesView ``` **LinesSubstringIndex** #### function readLinesSubstring ```kestrel public func readLinesSubstring(from: LinesView) -> String ``` ### protocol RangeFromConstructible ```kestrel public protocol RangeFromConstructible ``` Protocol backing the postfix `..` operator (`start..`). `Output` is the range type produced — usually `RangeFrom[Self]`. #### typealias Output ```kestrel type Output ``` #### function rangeFrom ```kestrel func rangeFrom() -> Output ``` Builds the partial range `[self, +∞)`. ### struct RangeFromIterator ```kestrel public struct RangeFromIterator[T] where T: Steppable, T: Comparable { /* private fields */ } ``` Iterator over a `RangeFrom[T]`. Yields successive values via `Steppable.successor()` with no upper bound — callers must `break`. # Representation Single value: `current` (next yield). #### initializer From Start ```kestrel public init(current: T) ``` **Iterator** #### typealias Item ```kestrel type Item = T ``` #### typealias TargetIterator ```kestrel type TargetIterator = Self ``` #### function all ```kestrel 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) ``` #### function any ```kestrel 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 ``` #### function chain ```kestrel 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] ``` #### function collect ```kestrel 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] ``` #### function compactMap ```kestrel public func compactMap[T]() -> FilterMapIterator[Self, T] where Item == Optional[T] ``` Drops `None`s and unwraps `Some`s — 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] ``` #### function contains ```kestrel 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 ``` #### function count ```kestrel 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 ``` #### function cycle ```kestrel 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] ``` #### function enumerate ```kestrel 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}") }; ``` #### function filter ```kestrel public func filter(where: (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] ``` #### function filterMap ```kestrel public func filterMap[U](as: (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] ``` #### function first ```kestrel 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 ``` #### function firstIndex ```kestrel 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 ``` #### function flatMap ```kestrel public func flatMap[U](as: (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] ``` #### function flatten ```kestrel 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] ``` #### function fold ```kestrel 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 ``` #### function forEach ```kestrel 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) }; ``` #### function fuse ```kestrel 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. #### function inspect ```kestrel public func inspect((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(); ``` #### function intersperse ```kestrel 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] ``` #### function intersperseWith ```kestrel public func intersperseWith(with: () -> 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] ``` #### function isSorted ```kestrel 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) ``` #### function isSortedDescending ```kestrel public consuming func isSortedDescending() -> Bool ``` True if elements come out in descending order. Mirror of `isSorted`. #### function iter ```kestrel func iter() -> Self ``` Returns `self`. The blanket conformance pivot — iterators *are* iterables. #### function last ```kestrel 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. #### function map ```kestrel public func map[U](as: (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] ``` #### function max ```kestrel public consuming func max() -> Item? ``` Largest element, or `None` for an empty iterator. Ties go to the first occurrence. #### function min ```kestrel 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 ``` #### function next ```kestrel public mutating func next() -> T? ``` Yields the next value. Never returns `.None` — infinite iterator. #### function nth ```kestrel 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) ``` #### function peekable ```kestrel 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) ``` #### function product ```kestrel 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 ``` #### function reduce ```kestrel 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 ``` #### function scan ```kestrel public func scan[Acc](from: Acc, by: (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] ``` #### function skip ```kestrel 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(); // [] ``` #### function skipWhile ```kestrel public func skipWhile(where: (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] ``` #### function sorted ```kestrel 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] ``` #### function stepBy ```kestrel 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] ``` #### function sum ```kestrel 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 ``` #### function take ```kestrel 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] ``` #### function takeWhile ```kestrel public func takeWhile(where: (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] ``` #### function tryFold ```kestrel 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") ``` #### function tryForEach ```kestrel public mutating func tryForEach[E]((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 ``` #### function unzip ```kestrel 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"] ``` #### function zip ```kestrel 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)] ``` ### struct RangeIterator ```kestrel public struct RangeIterator[T] where T: Steppable, T: Comparable { /* private fields */ } ``` Iterator over a half-open `Range[T]`. Yields successive values via `Steppable.successor()` until reaching (but not including) `end`. # Representation Two values: `current` (next yield) and `end` (sentinel). #### initializer From Bounds ```kestrel public init(current: T, end: T) ``` Builds an iterator that yields `current`, `current.successor()`, … stopping before `end`. **Iterator** #### typealias Item ```kestrel type Item = T ``` #### typealias TargetIterator ```kestrel type TargetIterator = Self ``` #### function all ```kestrel 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) ``` #### function any ```kestrel 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 ``` #### function chain ```kestrel 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] ``` #### function collect ```kestrel 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] ``` #### function compactMap ```kestrel public func compactMap[T]() -> FilterMapIterator[Self, T] where Item == Optional[T] ``` Drops `None`s and unwraps `Some`s — 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] ``` #### function contains ```kestrel 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 ``` #### function count ```kestrel 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 ``` #### function cycle ```kestrel 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] ``` #### function enumerate ```kestrel 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}") }; ``` #### function filter ```kestrel public func filter(where: (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] ``` #### function filterMap ```kestrel public func filterMap[U](as: (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] ``` #### function first ```kestrel 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 ``` #### function firstIndex ```kestrel 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 ``` #### function flatMap ```kestrel public func flatMap[U](as: (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] ``` #### function flatten ```kestrel 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] ``` #### function fold ```kestrel 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 ``` #### function forEach ```kestrel 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) }; ``` #### function fuse ```kestrel 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. #### function inspect ```kestrel public func inspect((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(); ``` #### function intersperse ```kestrel 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] ``` #### function intersperseWith ```kestrel public func intersperseWith(with: () -> 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] ``` #### function isSorted ```kestrel 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) ``` #### function isSortedDescending ```kestrel public consuming func isSortedDescending() -> Bool ``` True if elements come out in descending order. Mirror of `isSorted`. #### function iter ```kestrel func iter() -> Self ``` Returns `self`. The blanket conformance pivot — iterators *are* iterables. #### function last ```kestrel 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. #### function map ```kestrel public func map[U](as: (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] ``` #### function max ```kestrel public consuming func max() -> Item? ``` Largest element, or `None` for an empty iterator. Ties go to the first occurrence. #### function min ```kestrel 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 ``` #### function next ```kestrel public mutating func next() -> T? ``` Yields the next value, or `.None` when exhausted. #### function nth ```kestrel 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) ``` #### function peekable ```kestrel 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) ``` #### function product ```kestrel 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 ``` #### function reduce ```kestrel 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 ``` #### function scan ```kestrel public func scan[Acc](from: Acc, by: (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] ``` #### function skip ```kestrel 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(); // [] ``` #### function skipWhile ```kestrel public func skipWhile(where: (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] ``` #### function sorted ```kestrel 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] ``` #### function stepBy ```kestrel 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] ``` #### function sum ```kestrel 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 ``` #### function take ```kestrel 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] ``` #### function takeWhile ```kestrel public func takeWhile(where: (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] ``` #### function tryFold ```kestrel 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") ``` #### function tryForEach ```kestrel public mutating func tryForEach[E]((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 ``` #### function unzip ```kestrel 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"] ``` #### function zip ```kestrel 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)] ``` ### protocol RangeMatchable ```kestrel public protocol RangeMatchable[Bound = Self] ``` Protocol enabling range patterns (`start..=end`, `.. Bool ``` Returns `true` when `self >= bound`. Powers `start..` patterns. #### function isAtMost ```kestrel func isAtMost(Bound) -> Bool ``` Returns `true` when `self <= bound`. Powers `..=end` patterns. #### function isBelow ```kestrel func isBelow(Bound) -> Bool ``` Returns `true` when `self < bound`. Powers `.. Bool ``` Returns `true` iff `value <= end`. #### field end ```kestrel public var end: T ``` Upper bound — included in the range. **Equatable** #### typealias Output ```kestrel type Output = Bool ``` #### function equal ```kestrel public func equal(to: Self) -> Bool ``` Bridges `Equal.equal(to:)` to `Equatable.isEqual(to:)`. #### function isEqual ```kestrel public func isEqual(to: RangeThrough[T]) -> Bool ``` Structural equality. #### function notEqual ```kestrel public func notEqual(to: Self) -> Bool ``` Default `!=`: delegates to `==` so there's a single source of truth. **SeqIndex** #### typealias SeqOutput ```kestrel type SeqOutput = ArraySlice[T] ``` #### function readSeq ```kestrel public func readSeq(from: ArraySlice[T]) -> ArraySlice[T] ``` #### function readSeqChecked ```kestrel public func readSeqChecked(from: ArraySlice[T]) -> ArraySlice[T]? ``` #### function readSeqUnchecked ```kestrel public func readSeqUnchecked(from: ArraySlice[T]) -> ArraySlice[T] ``` #### function writeSeq ```kestrel public func writeSeq(to: ArraySlice[T], with: ArraySlice[T]) ``` #### function writeSeqUnchecked ```kestrel public func writeSeqUnchecked(to: ArraySlice[T], with: ArraySlice[T]) ``` **SeqRange** #### function resolve ```kestrel public func resolve(Int64) -> Range[Int64] ``` **BytesIndex** #### typealias BytesYield ```kestrel type BytesYield = BytesView ``` #### function readBytes ```kestrel public func readBytes(from: BytesView) -> BytesView ``` #### function readBytesChecked ```kestrel public func readBytesChecked(from: BytesView) -> BytesView? ``` #### function readBytesUnchecked ```kestrel public func readBytesUnchecked(from: BytesView) -> BytesView ``` **BytesClampable** #### typealias BytesClampedYield ```kestrel type BytesClampedYield = BytesView ``` #### function readBytesClamped ```kestrel public func readBytesClamped(from: BytesView) -> BytesView ``` **BytesWrappable** #### typealias BytesWrappedYield ```kestrel type BytesWrappedYield = BytesView ``` #### function readBytesWrapped ```kestrel public func readBytesWrapped(from: BytesView) -> BytesView ``` **BytesSubstringIndex** #### function readBytesSubstring ```kestrel public func readBytesSubstring(from: BytesView) -> String ``` **CharsIndex** #### typealias CharsYield ```kestrel type CharsYield = CharsView ``` #### function readChars ```kestrel public func readChars(from: CharsView) -> CharsView ``` #### function readCharsChecked ```kestrel public func readCharsChecked(from: CharsView) -> CharsView? ``` **CharsClampable** #### typealias CharsClampedYield ```kestrel type CharsClampedYield = CharsView ``` #### function readCharsClamped ```kestrel public func readCharsClamped(from: CharsView) -> CharsView ``` **CharsWrappable** #### typealias CharsWrappedYield ```kestrel type CharsWrappedYield = CharsView ``` #### function readCharsWrapped ```kestrel public func readCharsWrapped(from: CharsView) -> CharsView ``` **CharsSubstringIndex** #### function readCharsSubstring ```kestrel public func readCharsSubstring(from: CharsView) -> String ``` **GraphemesIndex** #### typealias GraphemesYield ```kestrel type GraphemesYield = GraphemesView ``` #### function readGraphemes ```kestrel public func readGraphemes(from: GraphemesView) -> GraphemesView ``` #### function readGraphemesChecked ```kestrel public func readGraphemesChecked(from: GraphemesView) -> GraphemesView? ``` **GraphemesClampable** #### typealias GraphemesClampedYield ```kestrel type GraphemesClampedYield = GraphemesView ``` #### function readGraphemesClamped ```kestrel public func readGraphemesClamped(from: GraphemesView) -> GraphemesView ``` **GraphemesWrappable** #### typealias GraphemesWrappedYield ```kestrel type GraphemesWrappedYield = GraphemesView ``` #### function readGraphemesWrapped ```kestrel public func readGraphemesWrapped(from: GraphemesView) -> GraphemesView ``` **GraphemesSubstringIndex** #### function readGraphemesSubstring ```kestrel public func readGraphemesSubstring(from: GraphemesView) -> String ``` **LinesIndex** #### typealias LinesYield ```kestrel type LinesYield = LinesView ``` #### function readLines ```kestrel public func readLines(from: LinesView) -> LinesView ``` #### function readLinesChecked ```kestrel public func readLinesChecked(from: LinesView) -> LinesView? ``` **LinesClampable** #### typealias LinesClampedYield ```kestrel type LinesClampedYield = LinesView ``` #### function readLinesClamped ```kestrel public func readLinesClamped(from: LinesView) -> LinesView ``` **LinesWrappable** #### typealias LinesWrappedYield ```kestrel type LinesWrappedYield = LinesView ``` #### function readLinesWrapped ```kestrel public func readLinesWrapped(from: LinesView) -> LinesView ``` **LinesSubstringIndex** #### function readLinesSubstring ```kestrel public func readLinesSubstring(from: LinesView) -> String ``` ### protocol RangeThroughConstructible ```kestrel public protocol RangeThroughConstructible ``` Protocol backing the prefix `..=` operator (`..=end`). `Output` is the range type produced — usually `RangeThrough[Self]`. #### typealias Output ```kestrel type Output ``` #### function rangeThrough ```kestrel func rangeThrough() -> Output ``` Builds the partial range `(-∞, self]`. ### struct RangeUpTo ```kestrel public struct RangeUpTo[T] where T: Comparable { /* private fields */ } ``` Partial range `(-∞, end)` — produced by the prefix `..<` operator. Not `Iterable` — there is no start to iterate from. # Examples ``` (..<10).contains(5) // true (..<10).contains(10) // false ``` # Representation Single value: `end`. No heap allocation. #### initializer From End ```kestrel public init(T) ``` #### function contains ```kestrel public func contains(T) -> Bool ``` Returns `true` iff `value < end`. #### field end ```kestrel public var end: T ``` Upper bound — excluded from the range. **Equatable** #### typealias Output ```kestrel type Output = Bool ``` #### function equal ```kestrel public func equal(to: Self) -> Bool ``` Bridges `Equal.equal(to:)` to `Equatable.isEqual(to:)`. #### function isEqual ```kestrel public func isEqual(to: RangeUpTo[T]) -> Bool ``` Structural equality. #### function notEqual ```kestrel public func notEqual(to: Self) -> Bool ``` Default `!=`: delegates to `==` so there's a single source of truth. **SeqIndex** #### typealias SeqOutput ```kestrel type SeqOutput = ArraySlice[T] ``` #### function readSeq ```kestrel public func readSeq(from: ArraySlice[T]) -> ArraySlice[T] ``` #### function readSeqChecked ```kestrel public func readSeqChecked(from: ArraySlice[T]) -> ArraySlice[T]? ``` #### function readSeqUnchecked ```kestrel public func readSeqUnchecked(from: ArraySlice[T]) -> ArraySlice[T] ``` #### function writeSeq ```kestrel public func writeSeq(to: ArraySlice[T], with: ArraySlice[T]) ``` #### function writeSeqUnchecked ```kestrel public func writeSeqUnchecked(to: ArraySlice[T], with: ArraySlice[T]) ``` **SeqRange** #### function resolve ```kestrel public func resolve(Int64) -> Range[Int64] ``` **BytesIndex** #### typealias BytesYield ```kestrel type BytesYield = BytesView ``` #### function readBytes ```kestrel public func readBytes(from: BytesView) -> BytesView ``` #### function readBytesChecked ```kestrel public func readBytesChecked(from: BytesView) -> BytesView? ``` #### function readBytesUnchecked ```kestrel public func readBytesUnchecked(from: BytesView) -> BytesView ``` **BytesClampable** #### typealias BytesClampedYield ```kestrel type BytesClampedYield = BytesView ``` #### function readBytesClamped ```kestrel public func readBytesClamped(from: BytesView) -> BytesView ``` **BytesWrappable** #### typealias BytesWrappedYield ```kestrel type BytesWrappedYield = BytesView ``` #### function readBytesWrapped ```kestrel public func readBytesWrapped(from: BytesView) -> BytesView ``` **BytesSubstringIndex** #### function readBytesSubstring ```kestrel public func readBytesSubstring(from: BytesView) -> String ``` **CharsIndex** #### typealias CharsYield ```kestrel type CharsYield = CharsView ``` #### function readChars ```kestrel public func readChars(from: CharsView) -> CharsView ``` #### function readCharsChecked ```kestrel public func readCharsChecked(from: CharsView) -> CharsView? ``` **CharsClampable** #### typealias CharsClampedYield ```kestrel type CharsClampedYield = CharsView ``` #### function readCharsClamped ```kestrel public func readCharsClamped(from: CharsView) -> CharsView ``` **CharsWrappable** #### typealias CharsWrappedYield ```kestrel type CharsWrappedYield = CharsView ``` #### function readCharsWrapped ```kestrel public func readCharsWrapped(from: CharsView) -> CharsView ``` **CharsSubstringIndex** #### function readCharsSubstring ```kestrel public func readCharsSubstring(from: CharsView) -> String ``` **GraphemesIndex** #### typealias GraphemesYield ```kestrel type GraphemesYield = GraphemesView ``` #### function readGraphemes ```kestrel public func readGraphemes(from: GraphemesView) -> GraphemesView ``` #### function readGraphemesChecked ```kestrel public func readGraphemesChecked(from: GraphemesView) -> GraphemesView? ``` **GraphemesClampable** #### typealias GraphemesClampedYield ```kestrel type GraphemesClampedYield = GraphemesView ``` #### function readGraphemesClamped ```kestrel public func readGraphemesClamped(from: GraphemesView) -> GraphemesView ``` **GraphemesWrappable** #### typealias GraphemesWrappedYield ```kestrel type GraphemesWrappedYield = GraphemesView ``` #### function readGraphemesWrapped ```kestrel public func readGraphemesWrapped(from: GraphemesView) -> GraphemesView ``` **GraphemesSubstringIndex** #### function readGraphemesSubstring ```kestrel public func readGraphemesSubstring(from: GraphemesView) -> String ``` **LinesIndex** #### typealias LinesYield ```kestrel type LinesYield = LinesView ``` #### function readLines ```kestrel public func readLines(from: LinesView) -> LinesView ``` #### function readLinesChecked ```kestrel public func readLinesChecked(from: LinesView) -> LinesView? ``` **LinesClampable** #### typealias LinesClampedYield ```kestrel type LinesClampedYield = LinesView ``` #### function readLinesClamped ```kestrel public func readLinesClamped(from: LinesView) -> LinesView ``` **LinesWrappable** #### typealias LinesWrappedYield ```kestrel type LinesWrappedYield = LinesView ``` #### function readLinesWrapped ```kestrel public func readLinesWrapped(from: LinesView) -> LinesView ``` **LinesSubstringIndex** #### function readLinesSubstring ```kestrel public func readLinesSubstring(from: LinesView) -> String ``` ### protocol RangeUpToConstructible ```kestrel public protocol RangeUpToConstructible ``` Protocol backing the prefix `..<` operator (`.. Output ``` Builds the partial range `(-∞, self)`. ### protocol RightShift ```kestrel public protocol RightShift[Other = Int64] ``` Raw protocol backing the `>>` operator. Behaviour for signed types is arithmetic shift (sign-preserving); unsigned types use logical shift. The `Other` default mirrors `LeftShift`. #### typealias Output ```kestrel type Output ``` #### function shiftRight ```kestrel consuming func shiftRight(by: consuming Other) -> Output ``` Returns `self >> count`. ### protocol RightShiftAssign ```kestrel public protocol RightShiftAssign[Other] ``` Raw protocol backing the `>>=` operator. #### function shiftRightAssign ```kestrel mutating func shiftRightAssign(by: Other) ``` Mutates `self` to `self >> count`. ### typealias StringLiteralType ```kestrel public type StringLiteralType = String ``` Default type for string literals (`let s = "hi"` → `String`). ### protocol SubtractAssign ```kestrel public protocol SubtractAssign[Other = Self] ``` Raw protocol backing the `-=` operator. #### function subtractAssign ```kestrel mutating func subtractAssign(Other) ``` Mutates `self` to `self - other`. ### protocol Subtractable ```kestrel public protocol Subtractable[Other = Self] ``` Raw protocol backing the `-` binary operator. #### typealias Output ```kestrel type Output ``` #### function subtract ```kestrel consuming func subtract(consuming Other) -> Output ``` Returns `self - other`. ### protocol Tryable ```kestrel public protocol Tryable ``` Protocol enabling the `try expr` operator. `Output` is the success value the operator yields; `Residual` is the "residual" — typically an `Err` variant, a `None`, or a typed error — that gets propagated. The compiler lowers `try x` to roughly `match x.tryExtract() { .Continue(v) => v, .Break(r) => return Self.fromResidual(r) }`, which is why the enclosing function's return type must conform to `FromResidual[Residual]`. # Examples ``` // Optional and Result both conform; `try` chains them seamlessly. func parseAndDouble(s: String) -> Int64? { let n = try Int64.parse(s); // .None short-circuits the whole function .Some(n * 2) } ``` #### typealias Output ```kestrel type Output ``` The value produced by `try expr` on success. #### typealias Residual ```kestrel type Residual ``` The residual carried out of `try expr` on failure. #### function tryExtract ```kestrel consuming func tryExtract() -> ControlFlow[Output, Residual] ``` Splits `self` into the success value or the early-return residual. ### protocol _ExpressibleByArrayLiteral ```kestrel public protocol _ExpressibleByArrayLiteral ``` Compiler-internal protocol for array-literal lowering. The lexer/parser lower `[a, b, c]` to a call into this init with a raw pointer to a stack-allocated buffer of `Element`s. Only the compiler uses this directly; user types should conform to `ExpressibleByArrayLiteral` (which extends this with a friendlier API). #### typealias Element ```kestrel type Element ``` #### initializer Literal Bridge ```kestrel init(_arrayLiteralPointer: consuming lang.ptr[Element], _arrayLiteralCount: consuming lang.i64) ``` Compiler-emitted init taking a raw pointer and count. Both params are `consuming`: the compiler hands ownership of the stack buffer's address (and the count) over to the implementation, which stores them in its own storage. This convention is what the MIR lowering's structural predicate looks for — implementations that deviate will be silently skipped during literal lowering. ### protocol _ExpressibleByDictionaryLiteral ```kestrel public protocol _ExpressibleByDictionaryLiteral ``` Compiler-internal protocol for dictionary-literal lowering. The compiler lowers `[k1: v1, k2: v2]` into a call with a raw pointer to a `(Key, Value)` buffer. As with array literals, user types should prefer `ExpressibleByDictionaryLiteral`. #### typealias Key ```kestrel type Key ``` #### initializer Literal Bridge ```kestrel init(consuming lang.ptr[(Key, Value)], consuming lang.i64) ``` Compiler-emitted init taking a raw `(Key, Value)` pointer and count. Both params are `consuming` for the same reason as the array bridge: the compiler hands ownership of the stack buffer to the implementation. MIR lowering matches on the unwrapped param shape, so an impl that deviates from this convention will be skipped during literal lowering. #### typealias Value ```kestrel type Value ``` ### function fatalError ```kestrel public func fatalError(String) -> Never ``` Aborts the process with `message`. Returns `!` (the never type), so the compiler treats any code after a `fatalError` call as unreachable. Use sparingly — almost every "this should be impossible" branch is better expressed as a `Result` error or a precondition check, because `fatalError` produces no recovery opportunity for the caller. # Examples ``` let mode = readMode(); match mode { .Read => doRead(), .Write => doWrite(), _ => fatalError("unsupported mode") } ``` --- ## std.ffi ### struct CString ```kestrel public struct CString { /* private fields */ } ``` A null-terminated, non-owning byte pointer suitable for `@extern(.C)` boundaries. `CString` is an FFI shim — it carries a `Pointer[UInt8]` that the C side will treat as `const char *`, but it does **not** own the memory. The pointer's lifetime, validity, and disposal are entirely the caller's responsibility. Two common ownership patterns: (1) the C side returns a pointer into static or `environ` memory — wrap it in a `CString` and read, but never free; (2) the Kestrel side allocates via `String.toCString()` — the caller must `free()` the result. # Examples ``` @extern(.C, mangleName: "puts") func puts(s: CString) -> Int32 let cstr = "Hello, C!".toCString(); let _ = puts(cstr); cstr.free(); ``` # Safety - The pointer must remain valid for as long as the `CString` is used. - The pointed-to bytes must end with a `0` terminator. - `length` is computed by scanning to the terminator — quadratic if you build long strings by repeated reads of `length`. - The caller chooses whether `free()` is appropriate (yes for self-allocated, no for borrowed pointers). # Representation A single `Pointer[UInt8]` field. No length is cached. # Memory Model Non-owning. Conforms to `FFISafe` so it passes through `@extern(.C)` signatures unchanged. #### initializer From Pointer ```kestrel public init(raw: Pointer[UInt8]) ``` Wraps an existing pointer as a `CString`. Performs no validation — the caller affirms that the pointer is null or points at null-terminated memory. # Safety - `rawPtr` must be null or point at a null-terminated byte sequence. - The pointed-to bytes must remain valid for the lifetime of the `CString`. - The caller decides whether `free()` is later appropriate. #### function free ```kestrel public func free() ``` Frees the buffer pointed to by this `CString` via libc `free`. No-op when the pointer is null. After this call the `CString` is dangling — do not read its bytes or call any other method that touches the pointer. # Safety Only call this on `CString`s whose pointer was produced by a prior `malloc` (e.g. via `String.toCString()`). Calling on a borrowed pointer (returned by `getenv`, a string literal, etc.) is undefined behaviour. #### field isNull ```kestrel public var isNull: Bool { get } ``` True if the wrapped pointer is null. A null `CString` should not be passed to a C function that expects a string; check this before calling. #### field length ```kestrel public var length: Int64 { get } ``` Length of the string in bytes, **excluding** the null terminator. Computed by linear scan — O(n). Cache the result if you need it more than once. Returns `0` for a null pointer (defensive: avoids dereferencing). #### field raw ```kestrel public var raw: Pointer[UInt8] ``` The underlying pointer to the null-terminated bytes. ### protocol FFISafe ```kestrel public protocol FFISafe ``` Marker protocol for types that can cross an `@extern(.C)` boundary. `FFISafe` is empty — conformance is purely a contract that the type's in-memory layout matches what a C function expects. Conformance is *not* automatically transitive at the type level: the compiler checks `FFISafe` constraints separately on each generic instantiation. The conformance rules: - Primitive numeric types and `Bool` conform automatically. - `Pointer[T]` conforms iff `T: FFISafe`. - Tuples of `FFISafe` types conform. - User structs may opt in (`struct Foo: FFISafe`); every field must itself be `FFISafe`. String and other heap-managed types do **not** conform — convert at the boundary with `String.toCString()` and pass `CString`. # Examples ``` struct Point: FFISafe { var x: Int32; var y: Int32 } @extern(.C, mangleName: "process_point") func processPoint(p: Point) -> Int32 ``` ### function free ```kestrel public func free(consuming RawPointer) ``` Wraps `free(3)` — releases memory previously returned by `malloc` / `realloc`. Calling `free` on a null pointer is defined as a no-op. Calling it on any other pointer that was not produced by these allocators (or has already been freed) is undefined behaviour. # Safety `ptr` must be either null or the original pointer returned by a previous `malloc` / `realloc`. After `free`, the pointer is dangling — do not read, write, or free it again. ### function malloc ```kestrel public func malloc(consuming Int64) -> RawPointer ``` Wraps `malloc(3)` — allocates `size` bytes of uninitialised memory. Returns a pointer to the start of the block, or null on failure. The memory is **uninitialised** — read it only after writing every byte you intend to use, or follow up with `memset` / `calloc` (not exposed here). Free with `free`. # Safety The returned pointer is raw. Callers are responsible for not reading uninitialised bytes, not exceeding `size`, and pairing every successful call with exactly one `free`. # Examples ``` let buf = malloc(1024); // ... use buf ... free(buf); ``` ### function memcmp ```kestrel public func memcmp(consuming RawPointer, consuming RawPointer, consuming Int64) -> Int32 ``` Wraps `memcmp(3)` — compares the first `n` bytes of `a` and `b`. Returns a negative value if the first differing byte in `a` is less than the corresponding byte in `b`, zero if all bytes are equal, positive otherwise. Comparison is unsigned, byte-by-byte. # Safety Both `a` and `b` must be valid for `n` bytes. ### function memcpy ```kestrel public func memcpy(consuming RawPointer, consuming RawPointer, consuming Int64) -> RawPointer ``` Wraps `memcpy(3)` — copies `n` bytes from `src` to `dest`. **Source and destination must not overlap** — use `memmove` if they might. Returns `dest` for convenience. No bounds checking; the caller must ensure both regions are valid for `n` bytes. # Safety `src` and `dest` must be valid for `n` bytes each, and the two regions must not overlap. ### function memmem ```kestrel public func memmem(consuming RawPointer, consuming Int64, consuming RawPointer, consuming Int64) -> RawPointer ``` Wraps `memmem(3)` — locates the first occurrence of the `needleLen`-byte `needle` in the `haystackLen`-byte `haystack`. Returns a pointer to the start of the match, or null if not found. `needleLen == 0` returns `haystack` (per glibc/macOS conventions — callers should check this before calling). Available on Linux and macOS; not on Windows. # Safety `haystack` must be valid for `haystackLen` bytes; `needle` must be valid for `needleLen` bytes. ### function memmove ```kestrel public func memmove(consuming RawPointer, consuming RawPointer, consuming Int64) -> RawPointer ``` Wraps `memmove(3)` — copies `n` bytes from `src` to `dest`, allowing overlap. Slightly slower than `memcpy` because it has to detect direction; use `memcpy` when you know the regions are disjoint. Returns `dest`. # Safety `src` and `dest` must each be valid for `n` bytes. Overlap is permitted. ### function memset ```kestrel public func memset(consuming RawPointer, consuming Int64, consuming Int64) -> RawPointer ``` Wraps `memset(3)` — fills `n` bytes starting at `dest` with the low byte of `c`. `c` is widened to `i64` to match the libc signature, but only the low 8 bits are used; pass `0` to zero the region. Returns `dest`. # Safety `dest` must be valid for `n` bytes of writes. ### function realloc ```kestrel public func realloc(consuming RawPointer, consuming Int64) -> RawPointer ``` Wraps `realloc(3)` — resizes a previously-`malloc`'d block. May return the same pointer or a new one; either way, the original pointer becomes invalid. Returns null on failure, in which case the original block is **not** freed — capture the return value before reassigning. Bytes beyond the old size in a grown block are uninitialised. # Safety `ptr` must be null or a pointer from a previous `malloc` / `realloc`. After a successful call, only the returned pointer is valid; after a failed call, only the original pointer is valid. # Examples ``` var buf = malloc(64); let bigger = realloc(buf, 256); // buf is no longer valid; use bigger ``` --- ## std.io.error ### struct IoError ```kestrel public struct IoError { /* private fields */ } ``` Structured I/O error: a classified `kind` plus the originating POSIX errno. Returned in the `Err` arm of every `Result` produced by `Read`, `Write`, `File`, `stdio`, and the `os.fs` helpers. Pattern-match on `kind` for programmatic dispatch; call `description()` for a short human-readable phrase. The convenience constructors at the bottom (`notFound()`, `permissionDenied()`, etc.) build common kinds without spelling the enum. # Examples ``` match File.open("missing.txt") { .Ok(f) => use(f), .Err(e) => match e.kind { .NotFound => createDefault(), .PermissionDenied => requestAccess(), _ => log(e.description()) } } ``` #### initializer From Code ```kestrel public init(code: Int32) ``` Builds an error from a raw POSIX errno; classifies the kind. #### initializer From Kind ```kestrel public init(kind: IoErrorKind) ``` Builds an error for a categorized kind. #### function description ```kestrel public func description() -> String ``` Returns a short human-readable phrase for the error kind. Unknown codes yield `"unknown error"`; for full coverage use `errno()` with a platform `strerror`. #### function errno ```kestrel public func errno() -> Int32 ``` The raw POSIX error code. Use for programmatic dispatch when pattern-matching on `kind` is too coarse — e.g. distinguishing between `.Other` codes. #### field kind ```kestrel public var kind: IoErrorKind ``` #### function last ```kestrel public static func last() -> IoError ``` Snapshots the current value of the platform's `errno` thread-local. Call immediately after a failed libc call — any other libc activity in between can clobber the value. ### enum IoErrorKind ```kestrel public enum IoErrorKind ``` Categorical classification of an I/O error. `IoError` carries one of these alongside its raw `errno`. The named variants cover the common categories applications dispatch on; everything else falls into `.Other` carrying the original POSIX code so no information is lost. Built from a code via `IoErrorKind.fromErrno(code:)`, or matched directly in error-handling code: ``` match e.kind { .NotFound => createDefault(), .PermissionDenied => promptForElevation(), .Other(c) => log("unhandled errno: " + c.toString()) } ``` #### case AlreadyExists ```kestrel case AlreadyExists ``` `EEXIST` — the path already exists (e.g. `O_CREAT | O_EXCL`). #### case BadFileDescriptor ```kestrel case BadFileDescriptor ``` `EBADF` — file descriptor is invalid or closed. #### case BrokenPipe ```kestrel case BrokenPipe ``` `EPIPE` — write to a pipe with no reader. #### case Interrupted ```kestrel case Interrupted ``` `EINTR` — operation interrupted by a signal. #### case InvalidInput ```kestrel case InvalidInput ``` `EINVAL` — invalid argument to a libc call. #### case IoFailure ```kestrel case IoFailure ``` `EIO` — generic kernel-reported I/O failure. #### case IsADirectory ```kestrel case IsADirectory ``` `EISDIR` — operation expected a file but got a directory. #### case NoSpaceLeft ```kestrel case NoSpaceLeft ``` `ENOSPC` — no space left on device. #### case NotADirectory ```kestrel case NotADirectory ``` `ENOTDIR` — a path component is not a directory. #### case NotFound ```kestrel case NotFound ``` `ENOENT` — the path does not exist. #### case NotPermitted ```kestrel case NotPermitted ``` `EPERM` — operation not permitted. #### case Other ```kestrel case Other(Int32) ``` Any other POSIX errno — keeps the original code so callers can still dispatch on the raw value. #### case OutOfMemory ```kestrel case OutOfMemory ``` `ENOMEM` — kernel allocation failed. #### case PermissionDenied ```kestrel case PermissionDenied ``` `EACCES` — caller lacks permission for the operation. #### case WouldBlock ```kestrel case WouldBlock ``` `EAGAIN` — non-blocking call would have blocked. #### function description ```kestrel public func description() -> String ``` Short human-readable phrase, locale-independent. #### function errno ```kestrel public func errno() -> Int32 ``` The POSIX errno corresponding to this kind. Lossless round-trip for all named variants and `.Other`. #### function fromErrno ```kestrel public static func fromErrno(Int32) -> IoErrorKind ``` Classifies a POSIX errno. Unknown codes fall through to `.Other(c)`. ### function alreadyExists ```kestrel public func alreadyExists() -> IoError ``` `EEXIST` — the path already exists (e.g. `O_CREAT | O_EXCL`). ### function brokenPipe ```kestrel public func brokenPipe() -> IoError ``` `EPIPE` — write to a pipe with no reader. ### function interrupted ```kestrel public func interrupted() -> IoError ``` `EINTR` — operation interrupted by a signal. ### function invalidInput ```kestrel public func invalidInput() -> IoError ``` `EINVAL` — invalid argument to a libc call. ### function notFound ```kestrel public func notFound() -> IoError ``` `ENOENT` — the path does not exist. ### function permissionDenied ```kestrel public func permissionDenied() -> IoError ``` `EACCES` — caller lacks permission for the operation. ### function wouldBlock ```kestrel public func wouldBlock() -> IoError ``` `EAGAIN` — non-blocking call would have blocked. --- ## std.io.file ### struct File ```kestrel public struct File { /* private fields */ } ``` RAII-owned POSIX file handle. The wrapped file descriptor is closed automatically when the `File` goes out of scope, so explicit `close` is never necessary. `File` is `not Copyable` to keep the descriptor uniquely owned — pass by reference or move it instead. Conforms to both `Readable` and `Writable`, although calls fail with `EBADF` if the open mode does not permit the direction (e.g. writing to a file opened with `open()`). # Examples ``` // Readable whole file in 4 KiB chunks. var file = try File.open("input.txt"); var buf = Array[UInt8](repeating: 0, count: 4096); while true { let n = try file.read(into: buf.asSlice()); if n == 0 { break } // process buf[0..n] } ``` # Representation One `libc.Fd` (32-bit signed integer) field. # Memory Model Owning, unique. The `deinit` calls `close(fd)` if `fd >= 0`; close errors are silently ignored — there's no caller to surface them to. #### initializer From Fd ```kestrel init(libc.Fd) ``` Internal init wrapping a raw descriptor; not for general use. #### function create ```kestrel public static func create(String) -> Result[File, IoError] ``` Creates (or truncates) `path` for writing with mode `0644`. Existing contents are discarded. # Examples ``` var file = try File.create("output.txt"); try writeString(file, "New content"); ``` #### function createNew ```kestrel public static func createNew(String) -> Result[File, IoError] ``` Creates a new file, failing if the path already exists. The canonical pattern for cooperative locking via lockfiles. # Errors Returns `Err` carrying `EEXIST` if the path already exists. # Examples ``` match File.createNew("lock.pid") { .Ok(f) => /* we hold the lock */ holdLock(f), .Err(e) => /* somebody else has it */ retryLater() } ``` #### field fd ```kestrel var fd: libc.Fd ``` #### function open ```kestrel public static func open(String) -> Result[File, IoError] ``` Opens an existing file for reading. The file must exist; missing paths surface as `Err(IoError.last())` carrying `ENOENT`, and permission failures as `EACCES`. #### function openAppend ```kestrel public static func openAppend(String) -> Result[File, IoError] ``` Opens (or creates) a file in append mode. Every write atomically lands at the current end of file regardless of where `seek` last left the cursor — the standard idiom for log files and any concurrent appender. #### function openReadWrite ```kestrel public static func openReadWrite(String) -> Result[File, IoError] ``` Opens an existing file for both reading and writing. Use for in-place modification of a file that already exists; for "create or open" semantics combine with `create` / `createNew` as appropriate. #### function position ```kestrel public mutating func position() -> Result[Int64, IoError] ``` Convenience for `seek(.Current(0))`. #### function rawFd ```kestrel public func rawFd() -> libc.Fd ``` Returns the underlying libc file descriptor for direct FFI use. Ownership stays with the `File`; do not call `close` on the returned value or the `deinit` will hit `EBADF`. #### function rewind ```kestrel public mutating func rewind() -> Result[(), IoError] ``` Convenience for `seek(.Start(0))` that drops the returned offset. #### function seek ```kestrel public mutating func seek(to: Seek) -> Result[Int64, IoError] ``` Calls `lseek(2)` with the requested anchor and offset. Returns the new absolute position from the start of the file. Seeking past EOF is allowed; a subsequent write extends the file (with a hole on filesystems that support sparse files). # Examples ``` var file = try File.openReadWrite("data.bin"); try file.seek(to: .Start(0)); // rewind try file.seek(to: .Current(100)); // skip 100 bytes let size = try file.seek(to: .End(0)); // size of file ``` **Readable** #### function read ```kestrel public mutating func read(into: ArraySlice[UInt8]) -> Result[Int64, IoError] ``` Calls `read(2)`. Advances the file position by the byte count returned. Short reads (`n < buf.count`) are normal — keep calling until `0` is returned (EOF) or an error fires. Use `readAll`/ `readExact` from `std.io.read` when looping by hand isn't wanted. **Writable** #### function flush ```kestrel public mutating func flush() -> Result[(), IoError] ``` No-op; `File` does no internal buffering. Reaches the kernel as soon as `write` returns, but does not call `fsync` — durability across power loss requires a separate, currently-unwrapped libc call. #### function write ```kestrel public mutating func write(from: ArraySlice[UInt8]) -> Result[Int64, IoError] ``` Calls `write(2)`. May write fewer bytes than supplied — wrap with `writeAll` from `std.io.write` to loop until done. ### enum Seek ```kestrel public enum Seek ``` Anchor + offset pair passed to `File.seek`. The three variants match POSIX `SEEK_SET`, `SEEK_CUR`, and `SEEK_END`; the payload is the offset in bytes (signed, so backwards seeks work). # Examples ``` try file.seek(to: .Start(0)); // beginning try file.seek(to: .Current(-10)); // back 10 bytes try file.seek(to: .End(0)); // end of file ``` #### case Current ```kestrel case Current(Int64) ``` Seek by `n` bytes from the current position. Negative values move backwards. #### case End ```kestrel case End(Int64) ``` Seek by `n` bytes from EOF. Use `0` to land exactly at EOF; negative values move backwards from the end. #### case Start ```kestrel case Start(Int64) ``` Seek to an absolute byte offset from the start of the file. ### function appendFileBytes ```kestrel public func appendFileBytes(String, Array[UInt8]) -> Result[(), IoError] ``` Appends bytes to `path`, creating if absent. Binary counterpart to `appendFileString`. ### function appendFileString ```kestrel public func appendFileString(String, String) -> Result[(), IoError] ``` Appends `content` to `path` as UTF-8, creating the file if absent. Atomic per-write under POSIX `O_APPEND` semantics — safe to call from multiple writers without intermediate locking, though writes longer than `PIPE_BUF` may interleave. ### function readFileBytes ```kestrel public func readFileBytes(String) -> Result[Array[UInt8], IoError] ``` Reads `path` into an `Array[UInt8]`. The binary counterpart to `readFileString` — does no UTF-8 decoding. ### function readFileString ```kestrel public func readFileString(String) -> Result[String, IoError] ``` Reads `path` into a `String`, decoding the bytes as UTF-8. Convenient for config files, source files, and other small/medium text. Slurps the entire file into memory — for huge inputs prefer streaming via `File` + `readAll`. # Examples ``` let cfg = try readFileString("config.json"); ``` ### function writeFileBytes ```kestrel public func writeFileBytes(String, Array[UInt8]) -> Result[(), IoError] ``` Writes `content` to `path`, creating or truncating as needed. Binary equivalent of `writeFileString`. ### function writeFileString ```kestrel public func writeFileString(String, String) -> Result[(), IoError] ``` Writes `content` to `path`, creating or truncating as needed. Bytes are the UTF-8 encoding of the string. The mirror of `readFileString`. --- ## std.io.libc ### typealias Fd ```kestrel public type Fd = Int32 ``` File descriptor type (wraps an int). ### function MODE_DEFAULT ```kestrel public func MODE_DEFAULT() -> Int32 ``` Default file mode (rw-r--r-- = 0o644 = 420 decimal). ### function O_APPEND ```kestrel public func O_APPEND() -> Int32 ``` Append to end of file. ### function O_CREAT ```kestrel public func O_CREAT() -> Int32 ``` ### function O_EXCL ```kestrel public func O_EXCL() -> Int32 ``` Fail if file exists (with O_CREAT). ### function O_RDONLY ```kestrel public func O_RDONLY() -> Int32 ``` Open for reading only. ### function O_RDWR ```kestrel public func O_RDWR() -> Int32 ``` Open for reading and writing. ### function O_TRUNC ```kestrel public func O_TRUNC() -> Int32 ``` Truncate file to zero length. ### function O_WRONLY ```kestrel public func O_WRONLY() -> Int32 ``` Open for writing only. ### function SEEK_CUR ```kestrel public func SEEK_CUR() -> Int32 ``` Seek from current position. ### function SEEK_END ```kestrel public func SEEK_END() -> Int32 ``` Seek from end of file. ### function SEEK_SET ```kestrel public func SEEK_SET() -> Int32 ``` Seek from beginning of file. ### function STDERR ```kestrel public func STDERR() -> Fd ``` Standard error file descriptor. ### function STDIN ```kestrel public func STDIN() -> Fd ``` Standard input file descriptor. ### function STDOUT ```kestrel public func STDOUT() -> Fd ``` Standard output file descriptor. ### function close ```kestrel public func close(Int32) -> Int32 ``` Closes a file descriptor. Returns 0 on success, -1 on error. ### function errno ```kestrel public func errno() -> Int32 ``` Returns the current errno value. ### function lseek ```kestrel public func lseek(Int32, Int64, Int32) -> Int64 ``` Seeks to a position in a file. Returns new position or -1 on error. ### function open ```kestrel public func open(Pointer[UInt8], Int32, Int32) -> Fd ``` Opens a file. Returns file descriptor or -1 on error. ### function read ```kestrel public func read(Int32, Pointer[UInt8], Int64) -> Int64 ``` Reads from a file descriptor. Returns bytes read, 0 on EOF, -1 on error. ### function write ```kestrel public func write(Int32, Pointer[UInt8], Int64) -> Int64 ``` Writes to a file descriptor. Returns bytes written or -1 on error. --- ## std.io.read ### struct Cursor ```kestrel public struct Cursor { /* private fields */ } ``` `Readable` over an in-memory `Array[UInt8]` with a movable position. Mirrors the role of Rust's `io::Cursor` — useful for tests, parsers, and any place a byte buffer needs to be presented as a `Readable` stream. The position is clamped to `[0, count]` by `setPosition`. `Cursor` clones share the underlying COW array. # Examples ``` var c = Cursor(data: [10, 20, 30].asArray()); var buf = Array[UInt8](repeating: 0, count: 2); try c.read(into: buf.asSlice()); // .Ok(2); buf == [10, 20] c.position() // 2 ``` #### initializer From Bytes ```kestrel public init(data: Array[UInt8]) ``` Builds a cursor positioned at byte 0 over `data`. #### field data ```kestrel var data: Array[UInt8] ``` #### field position ```kestrel public var position: Int64 ``` #### function setPosition ```kestrel public mutating func setPosition(to: Int64) ``` Sets the position. Negative values clamp to `0`; values past the end clamp to `count`. **Readable** #### function read ```kestrel public mutating func read(into: ArraySlice[UInt8]) -> Result[Int64, IoError] ``` Reads from the current position; returns `.Ok(0)` at EOF and advances the position by the byte count returned. **Cloneable** #### function clone ```kestrel public func clone() -> Cursor ``` Deep-clones the underlying byte array and copies the position. ### struct Empty ```kestrel public struct Empty { /* private fields */ } ``` `Readable` that always returns `0` (EOF). Useful as a placeholder reader or in tests that need to assert how a consumer handles an empty source. # Representation Zero-sized — no fields. #### initializer Default ```kestrel public init() ``` Builds the empty reader. **Readable** #### function read ```kestrel public mutating func read(into: ArraySlice[UInt8]) -> Result[Int64, IoError] ``` Always returns `.Ok(0)`. ### protocol Readable ```kestrel public protocol Readable ``` Protocol for byte-source streams. A single `read(into:)` call reads up to `buf.count` bytes into the provided slice and returns how many actually landed. A return of `0` means end-of-stream; a partial read (`n < buf.count`) is *not* an error — the caller is expected to loop, or to use `readExact` / `readAll` when a specific shape is required. # Examples ``` public struct DigitsReader: Readable { var next: UInt8 public mutating func read(into buf: ArraySlice[UInt8]) -> Result[Int64, IoError] { if buf.count == 0 { return .Ok(0) } buf.pointer.write(self.next); self.next = self.next + 1; .Ok(1) } } ``` #### function read ```kestrel mutating func read(into: ArraySlice[UInt8]) -> Result[Int64, IoError] ``` Reads up to `buf.count` bytes; returns the number of bytes actually written, with `0` signalling EOF. ### struct Repeat ```kestrel public struct Repeat { /* private fields */ } ``` `Readable` that yields the same byte forever — analogous to `/dev/zero` (with `byte: 0`) or `yes(1)`. Each `read` fills the entire destination. # Representation One `UInt8` field for the repeated byte. #### initializer From Byte ```kestrel public init(byte: UInt8) ``` Builds a reader that yields `byte` indefinitely. #### field byte ```kestrel var byte: UInt8 ``` **Readable** #### function read ```kestrel public mutating func read(into: ArraySlice[UInt8]) -> Result[Int64, IoError] ``` Fills `buf` with the repeated byte; returns `.Ok(buf.count)`. ### function readAll ```kestrel public func readAll[__opaque_0](mutating __opaque_0, into: mutating Array[UInt8]) -> Result[Int64, IoError] where __opaque_0: Readable ``` Drains `reader` into `buf`, appending every byte until EOF. Reads in 4 KiB chunks. Returns the total number of bytes appended. # Examples ``` var bytes = Array[UInt8](); var file = try File.open("input.bin"); let total = try readAll(file, into: bytes); ``` ### function readByte ```kestrel public func readByte[__opaque_0](mutating __opaque_0) -> Result[Optional[UInt8], IoError] where __opaque_0: Readable ``` Reads exactly one byte. Returns `.Ok(.None)` on EOF, `.Ok(.Some(b))` on success, or propagates a reader error. # Examples ``` match try readByte(reader) { .Some(b) => use(b), .None => /* EOF */ break } ``` ### function readExact ```kestrel public func readExact[__opaque_0](mutating __opaque_0, into: ArraySlice[UInt8]) -> Result[(), IoError] where __opaque_0: Readable ``` Reads exactly `buf.count` bytes; treats a short read (EOF reached early) as an error rather than a quiet truncation. Use when the caller wants binary fidelity — e.g. reading a fixed-width header. # Errors Returns `.Err(invalidInput())` if EOF is reached before `buf.count` bytes have been collected. # Examples ``` var header = Array[UInt8](repeating: 0, count: 16); try readExact(file, into: header.asSlice()); // must read 16 bytes ``` --- ## std.io.stdio ### struct Stderr ```kestrel public struct Stderr { /* private fields */ } ``` `Writable` over the process's standard error (file descriptor `2`). Mirrors `Stdout` but writes to `STDERR_FILENO`. Conventionally used for diagnostics, log lines, and anything that should not be captured by a downstream pipe consuming `stdout`. # Representation Zero-sized. #### initializer Default ```kestrel public init() ``` Builds a stderr handle. **Writable** #### function flush ```kestrel public mutating func flush() -> Result[(), IoError] ``` No-op; stderr is unbuffered at this layer. #### function write ```kestrel public mutating func write(from: ArraySlice[UInt8]) -> Result[Int64, IoError] ``` Calls `write(2)` on `STDERR_FILENO`. ### struct Stdin ```kestrel public struct Stdin { /* private fields */ } ``` `Readable` over the process's standard input (file descriptor `0`). Construct via `Stdin()` or the `stdin()` accessor. Stateless — every instance shares the same descriptor; concurrent readers race on the same pipe. # Representation Zero-sized — operations dispatch directly on `libc.STDIN()`. #### initializer Default ```kestrel public init() ``` Builds a stdin handle. **Readable** #### function read ```kestrel public mutating func read(into: ArraySlice[UInt8]) -> Result[Int64, IoError] ``` Calls `read(2)` on `STDIN_FILENO`. Returns `0` on EOF (e.g. after the user types Ctrl-D in a terminal). ### struct Stdout ```kestrel public struct Stdout { /* private fields */ } ``` `Writable` over the process's standard output (file descriptor `1`). As with `Stdin`, stateless — `flush` is a no-op because writes go straight to libc; line buffering / TTY behaviour is handled by libc or the terminal. # Representation Zero-sized. #### initializer Default ```kestrel public init() ``` Builds a stdout handle. **Writable** #### function flush ```kestrel public mutating func flush() -> Result[(), IoError] ``` No-op; stdout does no internal buffering at this layer. #### function write ```kestrel public mutating func write(from: ArraySlice[UInt8]) -> Result[Int64, IoError] ``` Calls `write(2)` on `STDOUT_FILENO`. ### function eprint ```kestrel public func eprint[__opaque_0](__opaque_0) -> Result[(), IoError] where __opaque_0: Formattable ``` Stderr counterpart to `print`. Useful for diagnostics that must not pollute a piped stdout. ### function eprintln ```kestrel public func eprintln[__opaque_0](__opaque_0) -> Result[(), IoError] where __opaque_0: Formattable ``` Stderr counterpart to `println`. ### function print ```kestrel public func print[__opaque_0](__opaque_0) -> Result[(), IoError] where __opaque_0: Formattable ``` Formats `value` with its default `FormatOptions` and writes the result to stdout. No trailing newline. # Examples ``` try print("count: "); try println(42); ``` ### function println ```kestrel public func println[__opaque_0](__opaque_0) -> Result[(), IoError] where __opaque_0: Formattable ``` Like `print`, plus a trailing `\n`. ### function printlnEmpty ```kestrel public func printlnEmpty() -> Result[(), IoError] ``` Writes a single newline to stdout — the no-argument form of `println`. ### function prompt ```kestrel public func prompt(String) -> Result[String, IoError] ``` Writes `message` to stdout, flushes, then reads a line from stdin. The flush matters for line-buffered terminals — without it the prompt would appear after the user's keystrokes. # Examples ``` let name = try prompt("Name: "); try println("Hello, " + name); ``` ### function readLine ```kestrel public func readLine() -> Result[String, IoError] ``` Reads a single line from stdin, stripping the trailing `\n` (and `\r` if present, for tolerance with Windows-style line endings). Returns an empty string on immediate EOF. TODO: the trailing-bytes are collected but the returned `String` is currently empty — see the comment in the body about `String.fromUtf8Bytes`. ### function stderr ```kestrel public func stderr() -> Stderr ``` Convenience constructor — equivalent to `Stderr()`. ### function stdin ```kestrel public func stdin() -> Stdin ``` Convenience constructor — equivalent to `Stdin()`. ### function stdout ```kestrel public func stdout() -> Stdout ``` Convenience constructor — equivalent to `Stdout()`. --- ## std.io.write ### struct Buffer ```kestrel public struct Buffer { /* private fields */ } ``` `Writable` that appends bytes to a growable `Array[UInt8]` — the in-memory counterpart to writing to a file. Useful for capturing output, building byte sequences before flushing to a real sink, or testing formatters. `Buffer` clones share the underlying COW array. # Examples ``` var b = Buffer(); try writeString(b, "Hello, "); try writeString(b, "World!"); b.toString() // "Hello, World!" ``` # Representation One `Array[UInt8]` field; capacity grows on demand. #### initializer Default ```kestrel public init() ``` Builds an empty buffer. #### initializer With Capacity ```kestrel public init(Int64) ``` Builds an empty buffer pre-sized to `capacity` bytes. Use when the approximate final size is known to skip intermediate growth. #### function asSlice ```kestrel public func asSlice() -> ArraySlice[UInt8] ``` Returns a non-owning slice view over the buffered bytes. The slice dangles once the buffer is mutated again — copy via `toArray` if you need to outlive the next write. #### function clear ```kestrel public mutating func clear() ``` Drops every byte but keeps the allocated capacity for reuse. #### field count ```kestrel public var count: Int64 { get } ``` Bytes currently held. #### field data ```kestrel var data: Array[UInt8] ``` #### field isEmpty ```kestrel public var isEmpty: Bool { get } ``` `true` when no bytes have been written. #### function toArray ```kestrel public func toArray() -> Array[UInt8] ``` Returns an owned copy of the buffered bytes. #### function toString ```kestrel public func toString() -> String ``` Interprets the buffered bytes as UTF-8 and returns the resulting `String`. Behaviour for invalid UTF-8 is currently undefined — validate upstream if untrusted bytes are involved. **Writable** #### function flush ```kestrel public mutating func flush() -> Result[(), IoError] ``` No-op; bytes are already "in" the buffer. #### function write ```kestrel public mutating func write(from: ArraySlice[UInt8]) -> Result[Int64, IoError] ``` Appends every byte from `buf`. Always succeeds with `.Ok(buf.count)`. **Cloneable** #### function clone ```kestrel public func clone() -> Buffer ``` Deep-clones the underlying byte array. ### struct Sink ```kestrel public struct Sink { /* private fields */ } ``` `Writable` that swallows everything — analogous to `/dev/null`. Useful for tests, benchmarks, and code paths where output is suppressed. # Representation Zero-sized — no fields. #### initializer Default ```kestrel public init() ``` Builds the discarding sink. **Writable** #### function flush ```kestrel public mutating func flush() -> Result[(), IoError] ``` No-op; always succeeds. #### function write ```kestrel public mutating func write(from: ArraySlice[UInt8]) -> Result[Int64, IoError] ``` Returns `.Ok(buf.count)` without storing the bytes. ### protocol Writable ```kestrel public protocol Writable ``` Protocol for byte-sink streams. Conformers expose a single-shot `write(from:)` and a `flush()` for buffered implementations. As with `Read`, a single `write` may move fewer bytes than supplied — this is not an error; use `writeAll` to loop until the whole slice is consumed. # Examples ``` public struct CountingSink: Writable { var written: Int64 = 0 public mutating func write(from buf: ArraySlice[UInt8]) -> Result[Int64, IoError] { self.written = self.written + buf.count; .Ok(buf.count) } public mutating func flush() -> Result[(), IoError] { .Ok(()) } } ``` #### function flush ```kestrel mutating func flush() -> Result[(), IoError] ``` Pushes any internally buffered bytes to the underlying destination. Unbuffered writers may implement this as a no-op. Errors here can surface conditions deferred from earlier `write` calls (broken pipe, disk full). #### function write ```kestrel mutating func write(from: ArraySlice[UInt8]) -> Result[Int64, IoError] ``` Writes up to `buf.count` bytes; returns how many actually moved. `.Ok(0)` indicates the sink could accept no more right now (full buffer / would-block); other amounts are partial successes that the caller may retry. ### function writeAll ```kestrel public func writeAll[__opaque_0](mutating __opaque_0, from: ArraySlice[UInt8]) -> Result[(), IoError] where __opaque_0: Writable ``` Writes every byte in `buf`, looping until the full slice has been consumed. Returns `.Err(brokenPipe())` if the writer reports `0` bytes written before the slice is exhausted (matches Rust's `WriteAll`/`ErrorKind::WriteZero`). # Examples ``` var file = try File.create("output.bin"); try writeAll(file, from: data.asSlice()); ``` ### function writeByte ```kestrel public func writeByte[__opaque_0](mutating __opaque_0, UInt8) -> Result[(), IoError] where __opaque_0: Writable ``` Writes a single byte, looping internally until it lands. ### function writeLine ```kestrel public func writeLine[__opaque_0](mutating __opaque_0, String) -> Result[(), IoError] where __opaque_0: Writable ``` Writes `s` followed by a single `\n`. Does not append `\r` on any platform — Kestrel writes Unix line endings everywhere by default. ### function writeString ```kestrel public func writeString[__opaque_0](mutating __opaque_0, String) -> Result[(), IoError] where __opaque_0: Writable ``` Writes the UTF-8 encoding of `s`. Empty strings short-circuit. Currently emits one byte per call into the writer — fine for buffered sinks like `Buffer`, expensive for raw `File`/`Stdout` (TODO: collect into a slice first). --- ## std.iter ### struct ChainIterator ```kestrel public struct ChainIterator[A, B] where A: Iterator, B: Iterator, B.Item == A.Item { /* private fields */ } ``` Lazy `chain` — yields all of `first`, then all of `second`. Returned by `Iterator.chain(other:)`. # Representation Both source iterators + a one-bit `firstDone` flag that latches when the first iterator runs out. #### initializer From Sources ```kestrel public init(first: A, second: B) ``` Builds a `ChainIterator`. Prefer `first.chain(other: second)`. #### field first ```kestrel internal var first: A ``` #### field firstDone ```kestrel internal var firstDone: Bool ``` #### field second ```kestrel internal var second: B ``` **Iterator** #### typealias Item ```kestrel type Item = A.Item ``` #### typealias TargetIterator ```kestrel type TargetIterator = Self ``` #### function all ```kestrel 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) ``` #### function any ```kestrel 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 ``` #### function chain ```kestrel 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] ``` #### function collect ```kestrel 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] ``` #### function compactMap ```kestrel public func compactMap[T]() -> FilterMapIterator[Self, T] where Item == Optional[T] ``` Drops `None`s and unwraps `Some`s — 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] ``` #### function contains ```kestrel 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 ``` #### function count ```kestrel 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 ``` #### function cycle ```kestrel 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] ``` #### function enumerate ```kestrel 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}") }; ``` #### function filter ```kestrel public func filter(where: (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] ``` #### function filterMap ```kestrel public func filterMap[U](as: (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] ``` #### function first ```kestrel 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 ``` #### function firstIndex ```kestrel 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 ``` #### function flatMap ```kestrel public func flatMap[U](as: (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] ``` #### function flatten ```kestrel 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] ``` #### function fold ```kestrel 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 ``` #### function forEach ```kestrel 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) }; ``` #### function fuse ```kestrel 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. #### function inspect ```kestrel public func inspect((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(); ``` #### function intersperse ```kestrel 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] ``` #### function intersperseWith ```kestrel public func intersperseWith(with: () -> 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] ``` #### function isSorted ```kestrel 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) ``` #### function isSortedDescending ```kestrel public consuming func isSortedDescending() -> Bool ``` True if elements come out in descending order. Mirror of `isSorted`. #### function iter ```kestrel func iter() -> Self ``` Returns `self`. The blanket conformance pivot — iterators *are* iterables. #### function last ```kestrel 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. #### function map ```kestrel public func map[U](as: (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] ``` #### function max ```kestrel public consuming func max() -> Item? ``` Largest element, or `None` for an empty iterator. Ties go to the first occurrence. #### function min ```kestrel 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 ``` #### function next ```kestrel public mutating func next() -> A.Item? ``` Pulls from `first` until it's empty, then forwards to `second`. #### function nth ```kestrel 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) ``` #### function peekable ```kestrel 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) ``` #### function product ```kestrel 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 ``` #### function reduce ```kestrel 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 ``` #### function scan ```kestrel public func scan[Acc](from: Acc, by: (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] ``` #### function skip ```kestrel 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(); // [] ``` #### function skipWhile ```kestrel public func skipWhile(where: (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] ``` #### function sorted ```kestrel 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] ``` #### function stepBy ```kestrel 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] ``` #### function sum ```kestrel 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 ``` #### function take ```kestrel 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] ``` #### function takeWhile ```kestrel public func takeWhile(where: (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] ``` #### function tryFold ```kestrel 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") ``` #### function tryForEach ```kestrel public mutating func tryForEach[E]((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 ``` #### function unzip ```kestrel 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"] ``` #### function zip ```kestrel 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)] ``` ### struct CycleIterator ```kestrel public struct CycleIterator[I] where I: Iterator { /* private fields */ } ``` Repeats a finite iterator forever by copying it on each lap. Returned by `Iterator.cycle()`. # Representation Two copies of the source: `original` (immutable template) and `current` (the working iterator). When `current` exhausts, it is reset from `original`. #### initializer From Source ```kestrel public init(iter: I) ``` Builds a `CycleIterator` that will replay `iter` forever. #### field current ```kestrel internal var current: I ``` #### field original ```kestrel internal var original: I ``` **Iterator** #### typealias Item ```kestrel type Item = I.Item ``` #### typealias TargetIterator ```kestrel type TargetIterator = Self ``` #### function all ```kestrel 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) ``` #### function any ```kestrel 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 ``` #### function chain ```kestrel 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] ``` #### function collect ```kestrel 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] ``` #### function compactMap ```kestrel public func compactMap[T]() -> FilterMapIterator[Self, T] where Item == Optional[T] ``` Drops `None`s and unwraps `Some`s — 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] ``` #### function contains ```kestrel 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 ``` #### function count ```kestrel 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 ``` #### function cycle ```kestrel 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] ``` #### function enumerate ```kestrel 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}") }; ``` #### function filter ```kestrel public func filter(where: (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] ``` #### function filterMap ```kestrel public func filterMap[U](as: (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] ``` #### function first ```kestrel 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 ``` #### function firstIndex ```kestrel 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 ``` #### function flatMap ```kestrel public func flatMap[U](as: (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] ``` #### function flatten ```kestrel 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] ``` #### function fold ```kestrel 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 ``` #### function forEach ```kestrel 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) }; ``` #### function fuse ```kestrel 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. #### function inspect ```kestrel public func inspect((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(); ``` #### function intersperse ```kestrel 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] ``` #### function intersperseWith ```kestrel public func intersperseWith(with: () -> 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] ``` #### function isSorted ```kestrel 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) ``` #### function isSortedDescending ```kestrel public consuming func isSortedDescending() -> Bool ``` True if elements come out in descending order. Mirror of `isSorted`. #### function iter ```kestrel func iter() -> Self ``` Returns `self`. The blanket conformance pivot — iterators *are* iterables. #### function last ```kestrel 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. #### function map ```kestrel public func map[U](as: (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] ``` #### function max ```kestrel public consuming func max() -> Item? ``` Largest element, or `None` for an empty iterator. Ties go to the first occurrence. #### function min ```kestrel 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 ``` #### function next ```kestrel public mutating func next() -> I.Item? ``` Pulls the current lap; on exhaustion, restarts and pulls again. #### function nth ```kestrel 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) ``` #### function peekable ```kestrel 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) ``` #### function product ```kestrel 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 ``` #### function reduce ```kestrel 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 ``` #### function scan ```kestrel public func scan[Acc](from: Acc, by: (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] ``` #### function skip ```kestrel 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(); // [] ``` #### function skipWhile ```kestrel public func skipWhile(where: (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] ``` #### function sorted ```kestrel 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] ``` #### function stepBy ```kestrel 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] ``` #### function sum ```kestrel 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 ``` #### function take ```kestrel 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] ``` #### function takeWhile ```kestrel public func takeWhile(where: (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] ``` #### function tryFold ```kestrel 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") ``` #### function tryForEach ```kestrel public mutating func tryForEach[E]((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 ``` #### function unzip ```kestrel 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"] ``` #### function zip ```kestrel 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)] ``` ### protocol DoubleEndedIterator ```kestrel public protocol DoubleEndedIterator ``` An iterator that can also yield from the back. Powers `rev()` and efficient "last N elements" patterns without first materialising the whole sequence. Front and back iteration share state — alternating `next()` and `nextBack()` is well-defined and meets in the middle. # Examples ``` // Defining a double-ended range struct Range: DoubleEndedIterator { type Item = Int64; var start: Int64; var end: Int64; mutating func next() -> Int64? { if start >= end { return None }; let v = start; start += 1; .Some(v) } mutating func nextBack() -> Int64? { if start >= end { return None }; end -= 1; .Some(end) } } var r = Range(start: 1, end: 4); r.next(); // Some(1) r.nextBack(); // Some(3) r.next(); // Some(2) r.nextBack(); // None (start >= end) ``` #### function nextBack ```kestrel mutating func nextBack() -> Item? ``` Yields the next element from the back, or `None` if the front and back have met. Can be interleaved freely with `next()`. #### function rev ```kestrel public func rev() -> ReversedIterator[Self] ``` Yields elements back-to-front by pulling `nextBack()` instead of `next()`. `O(1)` to construct — no buffering. # Examples ``` [1, 2, 3, 4, 5].iter().rev().collect(); // [5, 4, 3, 2, 1] [1, 2, 3, 4, 5].iter().rev().take(3).collect(); // [5, 4, 3] [1, 2, 3, 4, 5].iter().rev().first { it % 2 == 0 }; // Some(4) ``` **Iterator** #### typealias Item ```kestrel type Item ``` The element type produced by `next()`. #### typealias TargetIterator ```kestrel type TargetIterator = Self ``` #### function all ```kestrel 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) ``` #### function any ```kestrel 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 ``` #### function chain ```kestrel 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] ``` #### function collect ```kestrel 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] ``` #### function compactMap ```kestrel public func compactMap[T]() -> FilterMapIterator[Self, T] where Item == Optional[T] ``` Drops `None`s and unwraps `Some`s — 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] ``` #### function contains ```kestrel 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 ``` #### function count ```kestrel 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 ``` #### function cycle ```kestrel 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] ``` #### function enumerate ```kestrel 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}") }; ``` #### function filter ```kestrel public func filter(where: (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] ``` #### function filterMap ```kestrel public func filterMap[U](as: (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] ``` #### function first ```kestrel 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 ``` #### function firstIndex ```kestrel 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 ``` #### function flatMap ```kestrel public func flatMap[U](as: (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] ``` #### function flatten ```kestrel 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] ``` #### function fold ```kestrel 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 ``` #### function forEach ```kestrel 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) }; ``` #### function fuse ```kestrel 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. #### function inspect ```kestrel public func inspect((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(); ``` #### function intersperse ```kestrel 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] ``` #### function intersperseWith ```kestrel public func intersperseWith(with: () -> 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] ``` #### function isSorted ```kestrel 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) ``` #### function isSortedDescending ```kestrel public consuming func isSortedDescending() -> Bool ``` True if elements come out in descending order. Mirror of `isSorted`. #### function iter ```kestrel func iter() -> Self ``` Returns `self`. The blanket conformance pivot — iterators *are* iterables. #### function last ```kestrel 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. #### function map ```kestrel public func map[U](as: (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] ``` #### function max ```kestrel public consuming func max() -> Item? ``` Largest element, or `None` for an empty iterator. Ties go to the first occurrence. #### function min ```kestrel 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 ``` #### function next ```kestrel mutating func next() -> Item? ``` Yields the next element, or `None` once exhausted. The protocol does *not* require that subsequent calls keep returning `None` — wrap with `fuse()` if you need that guarantee. #### function nth ```kestrel 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) ``` #### function peekable ```kestrel 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) ``` #### function product ```kestrel 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 ``` #### function reduce ```kestrel 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 ``` #### function scan ```kestrel public func scan[Acc](from: Acc, by: (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] ``` #### function skip ```kestrel 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(); // [] ``` #### function skipWhile ```kestrel public func skipWhile(where: (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] ``` #### function sorted ```kestrel 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] ``` #### function stepBy ```kestrel 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] ``` #### function sum ```kestrel 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 ``` #### function take ```kestrel 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] ``` #### function takeWhile ```kestrel public func takeWhile(where: (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] ``` #### function tryFold ```kestrel 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") ``` #### function tryForEach ```kestrel public mutating func tryForEach[E]((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 ``` #### function unzip ```kestrel 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"] ``` #### function zip ```kestrel 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)] ``` ### struct EmptyIterator ```kestrel public struct EmptyIterator[T] { /* private fields */ } ``` Iterator that yields no elements. Returned by `empty()`. # Representation Zero-sized — no fields. #### initializer Default ```kestrel public init() ``` Builds an `EmptyIterator`. Prefer the free `empty()` function. **Iterator** #### typealias Item ```kestrel type Item = T ``` #### typealias TargetIterator ```kestrel type TargetIterator = Self ``` #### function all ```kestrel 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) ``` #### function any ```kestrel 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 ``` #### function chain ```kestrel 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] ``` #### function collect ```kestrel 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] ``` #### function compactMap ```kestrel public func compactMap[T]() -> FilterMapIterator[Self, T] where Item == Optional[T] ``` Drops `None`s and unwraps `Some`s — 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] ``` #### function contains ```kestrel 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 ``` #### function count ```kestrel 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 ``` #### function cycle ```kestrel 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] ``` #### function enumerate ```kestrel 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}") }; ``` #### function filter ```kestrel public func filter(where: (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] ``` #### function filterMap ```kestrel public func filterMap[U](as: (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] ``` #### function first ```kestrel 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 ``` #### function firstIndex ```kestrel 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 ``` #### function flatMap ```kestrel public func flatMap[U](as: (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] ``` #### function flatten ```kestrel 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] ``` #### function fold ```kestrel 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 ``` #### function forEach ```kestrel 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) }; ``` #### function fuse ```kestrel 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. #### function inspect ```kestrel public func inspect((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(); ``` #### function intersperse ```kestrel 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] ``` #### function intersperseWith ```kestrel public func intersperseWith(with: () -> 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] ``` #### function isSorted ```kestrel 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) ``` #### function isSortedDescending ```kestrel public consuming func isSortedDescending() -> Bool ``` True if elements come out in descending order. Mirror of `isSorted`. #### function iter ```kestrel func iter() -> Self ``` Returns `self`. The blanket conformance pivot — iterators *are* iterables. #### function last ```kestrel 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. #### function map ```kestrel public func map[U](as: (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] ``` #### function max ```kestrel public consuming func max() -> Item? ``` Largest element, or `None` for an empty iterator. Ties go to the first occurrence. #### function min ```kestrel 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 ``` #### function next ```kestrel public mutating func next() -> T? ``` Always `None`. #### function nth ```kestrel 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) ``` #### function peekable ```kestrel 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) ``` #### function product ```kestrel 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 ``` #### function reduce ```kestrel 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 ``` #### function scan ```kestrel public func scan[Acc](from: Acc, by: (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] ``` #### function skip ```kestrel 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(); // [] ``` #### function skipWhile ```kestrel public func skipWhile(where: (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] ``` #### function sorted ```kestrel 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] ``` #### function stepBy ```kestrel 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] ``` #### function sum ```kestrel 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 ``` #### function take ```kestrel 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] ``` #### function takeWhile ```kestrel public func takeWhile(where: (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] ``` #### function tryFold ```kestrel 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") ``` #### function tryForEach ```kestrel public mutating func tryForEach[E]((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 ``` #### function unzip ```kestrel 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"] ``` #### function zip ```kestrel 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)] ``` ### struct EnumerateIterator ```kestrel public struct EnumerateIterator[I] where I: Iterator { /* private fields */ } ``` Lazy `enumerate` — pairs each element with its zero-based position. Returned by `Iterator.enumerate()`. # Representation Source iterator + a running `Int64` index that ticks per element. #### initializer From Source ```kestrel public init(inner: I) ``` Builds an `EnumerateIterator` with the index starting at 0. Prefer `inner.enumerate()`. #### field index ```kestrel internal var index: Int64 ``` #### field inner ```kestrel internal var inner: I ``` **Iterator** #### typealias Item ```kestrel type Item = (Int64, I.Item) ``` #### typealias TargetIterator ```kestrel type TargetIterator = Self ``` #### function all ```kestrel 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) ``` #### function any ```kestrel 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 ``` #### function chain ```kestrel 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] ``` #### function collect ```kestrel 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] ``` #### function compactMap ```kestrel public func compactMap[T]() -> FilterMapIterator[Self, T] where Item == Optional[T] ``` Drops `None`s and unwraps `Some`s — 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] ``` #### function contains ```kestrel 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 ``` #### function count ```kestrel 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 ``` #### function cycle ```kestrel 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] ``` #### function enumerate ```kestrel 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}") }; ``` #### function filter ```kestrel public func filter(where: (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] ``` #### function filterMap ```kestrel public func filterMap[U](as: (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] ``` #### function first ```kestrel 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 ``` #### function firstIndex ```kestrel 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 ``` #### function flatMap ```kestrel public func flatMap[U](as: (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] ``` #### function flatten ```kestrel 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] ``` #### function fold ```kestrel 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 ``` #### function forEach ```kestrel 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) }; ``` #### function fuse ```kestrel 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. #### function inspect ```kestrel public func inspect((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(); ``` #### function intersperse ```kestrel 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] ``` #### function intersperseWith ```kestrel public func intersperseWith(with: () -> 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] ``` #### function isSorted ```kestrel 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) ``` #### function isSortedDescending ```kestrel public consuming func isSortedDescending() -> Bool ``` True if elements come out in descending order. Mirror of `isSorted`. #### function iter ```kestrel func iter() -> Self ``` Returns `self`. The blanket conformance pivot — iterators *are* iterables. #### function last ```kestrel 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. #### function map ```kestrel public func map[U](as: (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] ``` #### function max ```kestrel public consuming func max() -> Item? ``` Largest element, or `None` for an empty iterator. Ties go to the first occurrence. #### function min ```kestrel 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 ``` #### function next ```kestrel public mutating func next() -> (Int64, I.Item)? ``` Pulls the next element and pairs it with the current index, then increments the index. #### function nth ```kestrel 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) ``` #### function peekable ```kestrel 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) ``` #### function product ```kestrel 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 ``` #### function reduce ```kestrel 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 ``` #### function scan ```kestrel public func scan[Acc](from: Acc, by: (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] ``` #### function skip ```kestrel 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(); // [] ``` #### function skipWhile ```kestrel public func skipWhile(where: (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] ``` #### function sorted ```kestrel 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] ``` #### function stepBy ```kestrel 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] ``` #### function sum ```kestrel 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 ``` #### function take ```kestrel 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] ``` #### function takeWhile ```kestrel public func takeWhile(where: (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] ``` #### function tryFold ```kestrel 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") ``` #### function tryForEach ```kestrel public mutating func tryForEach[E]((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 ``` #### function unzip ```kestrel 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"] ``` #### function zip ```kestrel 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)] ``` ### protocol ExactSizeIterator ```kestrel public protocol ExactSizeIterator ``` An iterator that knows its remaining length up front. Conform when you can answer cheaply — consumers (notably `collect`) use it to pre-allocate exact capacity. #### function isEmpty ```kestrel public func isEmpty() -> Bool ``` `true` when no elements remain. Equivalent to `remaining == 0`. #### field remaining ```kestrel var remaining: Int64 { get } ``` Number of elements still to come. Decreases by one each time `next()` returns `Some`; reaches zero when the iterator is exhausted. **Iterator** #### typealias Item ```kestrel type Item ``` The element type produced by `next()`. #### typealias TargetIterator ```kestrel type TargetIterator = Self ``` #### function all ```kestrel 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) ``` #### function any ```kestrel 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 ``` #### function chain ```kestrel 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] ``` #### function collect ```kestrel 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] ``` #### function compactMap ```kestrel public func compactMap[T]() -> FilterMapIterator[Self, T] where Item == Optional[T] ``` Drops `None`s and unwraps `Some`s — 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] ``` #### function contains ```kestrel 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 ``` #### function count ```kestrel 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 ``` #### function cycle ```kestrel 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] ``` #### function enumerate ```kestrel 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}") }; ``` #### function filter ```kestrel public func filter(where: (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] ``` #### function filterMap ```kestrel public func filterMap[U](as: (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] ``` #### function first ```kestrel 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 ``` #### function firstIndex ```kestrel 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 ``` #### function flatMap ```kestrel public func flatMap[U](as: (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] ``` #### function flatten ```kestrel 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] ``` #### function fold ```kestrel 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 ``` #### function forEach ```kestrel 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) }; ``` #### function fuse ```kestrel 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. #### function inspect ```kestrel public func inspect((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(); ``` #### function intersperse ```kestrel 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] ``` #### function intersperseWith ```kestrel public func intersperseWith(with: () -> 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] ``` #### function isSorted ```kestrel 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) ``` #### function isSortedDescending ```kestrel public consuming func isSortedDescending() -> Bool ``` True if elements come out in descending order. Mirror of `isSorted`. #### function iter ```kestrel func iter() -> Self ``` Returns `self`. The blanket conformance pivot — iterators *are* iterables. #### function last ```kestrel 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. #### function map ```kestrel public func map[U](as: (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] ``` #### function max ```kestrel public consuming func max() -> Item? ``` Largest element, or `None` for an empty iterator. Ties go to the first occurrence. #### function min ```kestrel 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 ``` #### function next ```kestrel mutating func next() -> Item? ``` Yields the next element, or `None` once exhausted. The protocol does *not* require that subsequent calls keep returning `None` — wrap with `fuse()` if you need that guarantee. #### function nth ```kestrel 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) ``` #### function peekable ```kestrel 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) ``` #### function product ```kestrel 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 ``` #### function reduce ```kestrel 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 ``` #### function scan ```kestrel public func scan[Acc](from: Acc, by: (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] ``` #### function skip ```kestrel 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(); // [] ``` #### function skipWhile ```kestrel public func skipWhile(where: (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] ``` #### function sorted ```kestrel 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] ``` #### function stepBy ```kestrel 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] ``` #### function sum ```kestrel 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 ``` #### function take ```kestrel 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] ``` #### function takeWhile ```kestrel public func takeWhile(where: (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] ``` #### function tryFold ```kestrel 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") ``` #### function tryForEach ```kestrel public mutating func tryForEach[E]((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 ``` #### function unzip ```kestrel 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"] ``` #### function zip ```kestrel 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)] ``` ### struct FilterIterator ```kestrel public struct FilterIterator[I] where I: Iterator { /* private fields */ } ``` Lazy `filter` — yields only elements where the predicate returns `true`. Returned by `Iterator.filter(_:)`. # Representation Source iterator + predicate closure. `next()` skips ahead until the predicate accepts. #### initializer From Source ```kestrel public init(inner: I, where: (I.Item) -> Bool) ``` Builds a `FilterIterator`. Prefer `inner.filter(predicate)`. #### field inner ```kestrel internal var inner: I ``` #### field predicate ```kestrel internal var predicate: (I.Item) -> Bool ``` **Iterator** #### typealias Item ```kestrel type Item = I.Item ``` #### typealias TargetIterator ```kestrel type TargetIterator = Self ``` #### function all ```kestrel 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) ``` #### function any ```kestrel 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 ``` #### function chain ```kestrel 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] ``` #### function collect ```kestrel 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] ``` #### function compactMap ```kestrel public func compactMap[T]() -> FilterMapIterator[Self, T] where Item == Optional[T] ``` Drops `None`s and unwraps `Some`s — 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] ``` #### function contains ```kestrel 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 ``` #### function count ```kestrel 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 ``` #### function cycle ```kestrel 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] ``` #### function enumerate ```kestrel 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}") }; ``` #### function filter ```kestrel public func filter(where: (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] ``` #### function filterMap ```kestrel public func filterMap[U](as: (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] ``` #### function first ```kestrel 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 ``` #### function firstIndex ```kestrel 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 ``` #### function flatMap ```kestrel public func flatMap[U](as: (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] ``` #### function flatten ```kestrel 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] ``` #### function fold ```kestrel 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 ``` #### function forEach ```kestrel 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) }; ``` #### function fuse ```kestrel 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. #### function inspect ```kestrel public func inspect((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(); ``` #### function intersperse ```kestrel 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] ``` #### function intersperseWith ```kestrel public func intersperseWith(with: () -> 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] ``` #### function isSorted ```kestrel 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) ``` #### function isSortedDescending ```kestrel public consuming func isSortedDescending() -> Bool ``` True if elements come out in descending order. Mirror of `isSorted`. #### function iter ```kestrel func iter() -> Self ``` Returns `self`. The blanket conformance pivot — iterators *are* iterables. #### function last ```kestrel 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. #### function map ```kestrel public func map[U](as: (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] ``` #### function max ```kestrel public consuming func max() -> Item? ``` Largest element, or `None` for an empty iterator. Ties go to the first occurrence. #### function min ```kestrel 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 ``` #### function next ```kestrel public mutating func next() -> I.Item? ``` Pulls until an element satisfies `predicate`, returning it. `None` when the source is exhausted with no further match. #### function nth ```kestrel 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) ``` #### function peekable ```kestrel 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) ``` #### function product ```kestrel 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 ``` #### function reduce ```kestrel 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 ``` #### function scan ```kestrel public func scan[Acc](from: Acc, by: (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] ``` #### function skip ```kestrel 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(); // [] ``` #### function skipWhile ```kestrel public func skipWhile(where: (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] ``` #### function sorted ```kestrel 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] ``` #### function stepBy ```kestrel 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] ``` #### function sum ```kestrel 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 ``` #### function take ```kestrel 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] ``` #### function takeWhile ```kestrel public func takeWhile(where: (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] ``` #### function tryFold ```kestrel 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") ``` #### function tryForEach ```kestrel public mutating func tryForEach[E]((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 ``` #### function unzip ```kestrel 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"] ``` #### function zip ```kestrel 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)] ``` ### struct FilterMapIterator ```kestrel public struct FilterMapIterator[I, U] where I: Iterator { /* private fields */ } ``` Lazy `filterMap` / `compactMap` — runs a transform that returns `Optional[U]` and drops `None`s. Returned by both `Iterator.filterMap(_:)` and `Iterator.compactMap()`. # Representation Source iterator + transform closure. `next()` skips ahead until the transform yields `Some`. #### initializer From Source ```kestrel public init(inner: I, as: (I.Item) -> U?) ``` Builds a `FilterMapIterator`. Prefer `inner.filterMap(...)` / `inner.compactMap()`. #### field inner ```kestrel internal var inner: I ``` #### field transform ```kestrel internal var transform: (I.Item) -> U? ``` **Iterator** #### typealias Item ```kestrel type Item = U ``` #### typealias TargetIterator ```kestrel type TargetIterator = Self ``` #### function all ```kestrel 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) ``` #### function any ```kestrel 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 ``` #### function chain ```kestrel 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] ``` #### function collect ```kestrel 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] ``` #### function compactMap ```kestrel public func compactMap[T]() -> FilterMapIterator[Self, T] where Item == Optional[T] ``` Drops `None`s and unwraps `Some`s — 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] ``` #### function contains ```kestrel 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 ``` #### function count ```kestrel 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 ``` #### function cycle ```kestrel 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] ``` #### function enumerate ```kestrel 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}") }; ``` #### function filter ```kestrel public func filter(where: (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] ``` #### function filterMap ```kestrel public func filterMap[U](as: (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] ``` #### function first ```kestrel 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 ``` #### function firstIndex ```kestrel 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 ``` #### function flatMap ```kestrel public func flatMap[U](as: (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] ``` #### function flatten ```kestrel 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] ``` #### function fold ```kestrel 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 ``` #### function forEach ```kestrel 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) }; ``` #### function fuse ```kestrel 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. #### function inspect ```kestrel public func inspect((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(); ``` #### function intersperse ```kestrel 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] ``` #### function intersperseWith ```kestrel public func intersperseWith(with: () -> 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] ``` #### function isSorted ```kestrel 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) ``` #### function isSortedDescending ```kestrel public consuming func isSortedDescending() -> Bool ``` True if elements come out in descending order. Mirror of `isSorted`. #### function iter ```kestrel func iter() -> Self ``` Returns `self`. The blanket conformance pivot — iterators *are* iterables. #### function last ```kestrel 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. #### function map ```kestrel public func map[U](as: (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] ``` #### function max ```kestrel public consuming func max() -> Item? ``` Largest element, or `None` for an empty iterator. Ties go to the first occurrence. #### function min ```kestrel 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 ``` #### function next ```kestrel public mutating func next() -> U? ``` Pulls until `transform` returns `Some`, then yields it. #### function nth ```kestrel 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) ``` #### function peekable ```kestrel 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) ``` #### function product ```kestrel 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 ``` #### function reduce ```kestrel 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 ``` #### function scan ```kestrel public func scan[Acc](from: Acc, by: (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] ``` #### function skip ```kestrel 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(); // [] ``` #### function skipWhile ```kestrel public func skipWhile(where: (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] ``` #### function sorted ```kestrel 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] ``` #### function stepBy ```kestrel 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] ``` #### function sum ```kestrel 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 ``` #### function take ```kestrel 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] ``` #### function takeWhile ```kestrel public func takeWhile(where: (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] ``` #### function tryFold ```kestrel 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") ``` #### function tryForEach ```kestrel public mutating func tryForEach[E]((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 ``` #### function unzip ```kestrel 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"] ``` #### function zip ```kestrel 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)] ``` ### struct FlatMapIterator ```kestrel public struct FlatMapIterator[I, U] where I: Iterator, U: Iterator { /* private fields */ } ``` Lazy `flatMap` — turns each element of the source into an iterator and concatenates the results. Returned by `Iterator.flatMap(_:)`. # Representation Source iterator + transform closure + a one-slot buffer (`current`) holding the inner iterator currently being drained. #### initializer From Source ```kestrel public init(inner: I, as: (I.Item) -> U) ``` Builds a `FlatMapIterator` with no inner iterator buffered. #### field current ```kestrel internal var current: U? ``` #### field inner ```kestrel internal var inner: I ``` #### field transform ```kestrel internal var transform: (I.Item) -> U ``` **Iterator** #### typealias Item ```kestrel type Item = U.Item ``` #### typealias TargetIterator ```kestrel type TargetIterator = Self ``` #### function all ```kestrel 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) ``` #### function any ```kestrel 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 ``` #### function chain ```kestrel 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] ``` #### function collect ```kestrel 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] ``` #### function compactMap ```kestrel public func compactMap[T]() -> FilterMapIterator[Self, T] where Item == Optional[T] ``` Drops `None`s and unwraps `Some`s — 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] ``` #### function contains ```kestrel 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 ``` #### function count ```kestrel 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 ``` #### function cycle ```kestrel 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] ``` #### function enumerate ```kestrel 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}") }; ``` #### function filter ```kestrel public func filter(where: (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] ``` #### function filterMap ```kestrel public func filterMap[U](as: (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] ``` #### function first ```kestrel 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 ``` #### function firstIndex ```kestrel 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 ``` #### function flatMap ```kestrel public func flatMap[U](as: (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] ``` #### function flatten ```kestrel 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] ``` #### function fold ```kestrel 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 ``` #### function forEach ```kestrel 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) }; ``` #### function fuse ```kestrel 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. #### function inspect ```kestrel public func inspect((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(); ``` #### function intersperse ```kestrel 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] ``` #### function intersperseWith ```kestrel public func intersperseWith(with: () -> 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] ``` #### function isSorted ```kestrel 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) ``` #### function isSortedDescending ```kestrel public consuming func isSortedDescending() -> Bool ``` True if elements come out in descending order. Mirror of `isSorted`. #### function iter ```kestrel func iter() -> Self ``` Returns `self`. The blanket conformance pivot — iterators *are* iterables. #### function last ```kestrel 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. #### function map ```kestrel public func map[U](as: (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] ``` #### function max ```kestrel public consuming func max() -> Item? ``` Largest element, or `None` for an empty iterator. Ties go to the first occurrence. #### function min ```kestrel 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 ``` #### function next ```kestrel public mutating func next() -> U.Item? ``` Drains the buffered inner iterator; when it runs out, pulls the next source element, transforms it into a fresh inner iterator, and continues. #### function nth ```kestrel 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) ``` #### function peekable ```kestrel 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) ``` #### function product ```kestrel 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 ``` #### function reduce ```kestrel 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 ``` #### function scan ```kestrel public func scan[Acc](from: Acc, by: (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] ``` #### function skip ```kestrel 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(); // [] ``` #### function skipWhile ```kestrel public func skipWhile(where: (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] ``` #### function sorted ```kestrel 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] ``` #### function stepBy ```kestrel 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] ``` #### function sum ```kestrel 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 ``` #### function take ```kestrel 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] ``` #### function takeWhile ```kestrel public func takeWhile(where: (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] ``` #### function tryFold ```kestrel 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") ``` #### function tryForEach ```kestrel public mutating func tryForEach[E]((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 ``` #### function unzip ```kestrel 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"] ``` #### function zip ```kestrel 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)] ``` ### struct FlattenIterator ```kestrel public struct FlattenIterator[I] where I: Iterator, I.Item: Iterator { /* private fields */ } ``` Lazy `flatten` — concatenates the inner iterators of an iterator-of-iterators. Returned by `Iterator.flatten()`. # Representation Source iterator + a one-slot buffer holding the inner iterator currently being drained. #### initializer From Source ```kestrel public init(inner: I) ``` Builds a `FlattenIterator` with no inner iterator buffered. #### field current ```kestrel internal var current: I.Item? ``` #### field inner ```kestrel internal var inner: I ``` **Iterator** #### typealias Item ```kestrel type Item = I.Item.Item ``` #### typealias TargetIterator ```kestrel type TargetIterator = Self ``` #### function all ```kestrel 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) ``` #### function any ```kestrel 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 ``` #### function chain ```kestrel 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] ``` #### function collect ```kestrel 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] ``` #### function compactMap ```kestrel public func compactMap[T]() -> FilterMapIterator[Self, T] where Item == Optional[T] ``` Drops `None`s and unwraps `Some`s — 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] ``` #### function contains ```kestrel 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 ``` #### function count ```kestrel 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 ``` #### function cycle ```kestrel 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] ``` #### function enumerate ```kestrel 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}") }; ``` #### function filter ```kestrel public func filter(where: (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] ``` #### function filterMap ```kestrel public func filterMap[U](as: (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] ``` #### function first ```kestrel 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 ``` #### function firstIndex ```kestrel 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 ``` #### function flatMap ```kestrel public func flatMap[U](as: (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] ``` #### function flatten ```kestrel 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] ``` #### function fold ```kestrel 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 ``` #### function forEach ```kestrel 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) }; ``` #### function fuse ```kestrel 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. #### function inspect ```kestrel public func inspect((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(); ``` #### function intersperse ```kestrel 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] ``` #### function intersperseWith ```kestrel public func intersperseWith(with: () -> 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] ``` #### function isSorted ```kestrel 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) ``` #### function isSortedDescending ```kestrel public consuming func isSortedDescending() -> Bool ``` True if elements come out in descending order. Mirror of `isSorted`. #### function iter ```kestrel func iter() -> Self ``` Returns `self`. The blanket conformance pivot — iterators *are* iterables. #### function last ```kestrel 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. #### function map ```kestrel public func map[U](as: (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] ``` #### function max ```kestrel public consuming func max() -> Item? ``` Largest element, or `None` for an empty iterator. Ties go to the first occurrence. #### function min ```kestrel 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 ``` #### function next ```kestrel public mutating func next() -> I.Item.Item? ``` Drains the buffered inner iterator, then pulls the next inner iterator from the source. #### function nth ```kestrel 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) ``` #### function peekable ```kestrel 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) ``` #### function product ```kestrel 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 ``` #### function reduce ```kestrel 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 ``` #### function scan ```kestrel public func scan[Acc](from: Acc, by: (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] ``` #### function skip ```kestrel 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(); // [] ``` #### function skipWhile ```kestrel public func skipWhile(where: (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] ``` #### function sorted ```kestrel 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] ``` #### function stepBy ```kestrel 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] ``` #### function sum ```kestrel 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 ``` #### function take ```kestrel 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] ``` #### function takeWhile ```kestrel public func takeWhile(where: (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] ``` #### function tryFold ```kestrel 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") ``` #### function tryForEach ```kestrel public mutating func tryForEach[E]((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 ``` #### function unzip ```kestrel 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"] ``` #### function zip ```kestrel 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)] ``` ### struct FusedIterator ```kestrel public struct FusedIterator[I] where I: Iterator { /* private fields */ } ``` Wraps a source so that once `None` is returned, future calls also return `None`. Returned by `Iterator.fuse()`. # Representation Source iterator + a one-bit latch. #### initializer From Source ```kestrel public init(inner: I) ``` Builds a `FusedIterator` in the "still active" state. #### field done ```kestrel internal var done: Bool ``` #### field inner ```kestrel internal var inner: I ``` **Iterator** #### typealias Item ```kestrel type Item = I.Item ``` #### typealias TargetIterator ```kestrel type TargetIterator = Self ``` #### function all ```kestrel 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) ``` #### function any ```kestrel 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 ``` #### function chain ```kestrel 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] ``` #### function collect ```kestrel 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] ``` #### function compactMap ```kestrel public func compactMap[T]() -> FilterMapIterator[Self, T] where Item == Optional[T] ``` Drops `None`s and unwraps `Some`s — 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] ``` #### function contains ```kestrel 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 ``` #### function count ```kestrel 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 ``` #### function cycle ```kestrel 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] ``` #### function enumerate ```kestrel 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}") }; ``` #### function filter ```kestrel public func filter(where: (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] ``` #### function filterMap ```kestrel public func filterMap[U](as: (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] ``` #### function first ```kestrel 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 ``` #### function firstIndex ```kestrel 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 ``` #### function flatMap ```kestrel public func flatMap[U](as: (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] ``` #### function flatten ```kestrel 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] ``` #### function fold ```kestrel 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 ``` #### function forEach ```kestrel 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) }; ``` #### function fuse ```kestrel 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. #### function inspect ```kestrel public func inspect((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(); ``` #### function intersperse ```kestrel 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] ``` #### function intersperseWith ```kestrel public func intersperseWith(with: () -> 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] ``` #### function isSorted ```kestrel 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) ``` #### function isSortedDescending ```kestrel public consuming func isSortedDescending() -> Bool ``` True if elements come out in descending order. Mirror of `isSorted`. #### function iter ```kestrel func iter() -> Self ``` Returns `self`. The blanket conformance pivot — iterators *are* iterables. #### function last ```kestrel 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. #### function map ```kestrel public func map[U](as: (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] ``` #### function max ```kestrel public consuming func max() -> Item? ``` Largest element, or `None` for an empty iterator. Ties go to the first occurrence. #### function min ```kestrel 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 ``` #### function next ```kestrel public mutating func next() -> I.Item? ``` Forwards `next()`; latches `done = true` on the first `None` and returns `None` forever afterwards. #### function nth ```kestrel 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) ``` #### function peekable ```kestrel 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) ``` #### function product ```kestrel 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 ``` #### function reduce ```kestrel 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 ``` #### function scan ```kestrel public func scan[Acc](from: Acc, by: (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] ``` #### function skip ```kestrel 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(); // [] ``` #### function skipWhile ```kestrel public func skipWhile(where: (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] ``` #### function sorted ```kestrel 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] ``` #### function stepBy ```kestrel 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] ``` #### function sum ```kestrel 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 ``` #### function take ```kestrel 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] ``` #### function takeWhile ```kestrel public func takeWhile(where: (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] ``` #### function tryFold ```kestrel 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") ``` #### function tryForEach ```kestrel public mutating func tryForEach[E]((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 ``` #### function unzip ```kestrel 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"] ``` #### function zip ```kestrel 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)] ``` ### struct InspectIterator ```kestrel public struct InspectIterator[I] where I: Iterator { /* private fields */ } ``` Side-effecting passthrough. Calls `inspector` on each element and then yields it unchanged. Returned by `Iterator.inspect(_:)`. # Representation Source iterator + inspector closure. No buffering. #### initializer From Source ```kestrel public init(inner: I, inspector: (I.Item) -> ()) ``` Builds an `InspectIterator`. Prefer `inner.inspect(inspector)`. #### field inner ```kestrel internal var inner: I ``` #### field inspector ```kestrel internal var inspector: (I.Item) -> () ``` **Iterator** #### typealias Item ```kestrel type Item = I.Item ``` #### typealias TargetIterator ```kestrel type TargetIterator = Self ``` #### function all ```kestrel 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) ``` #### function any ```kestrel 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 ``` #### function chain ```kestrel 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] ``` #### function collect ```kestrel 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] ``` #### function compactMap ```kestrel public func compactMap[T]() -> FilterMapIterator[Self, T] where Item == Optional[T] ``` Drops `None`s and unwraps `Some`s — 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] ``` #### function contains ```kestrel 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 ``` #### function count ```kestrel 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 ``` #### function cycle ```kestrel 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] ``` #### function enumerate ```kestrel 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}") }; ``` #### function filter ```kestrel public func filter(where: (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] ``` #### function filterMap ```kestrel public func filterMap[U](as: (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] ``` #### function first ```kestrel 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 ``` #### function firstIndex ```kestrel 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 ``` #### function flatMap ```kestrel public func flatMap[U](as: (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] ``` #### function flatten ```kestrel 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] ``` #### function fold ```kestrel 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 ``` #### function forEach ```kestrel 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) }; ``` #### function fuse ```kestrel 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. #### function inspect ```kestrel public func inspect((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(); ``` #### function intersperse ```kestrel 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] ``` #### function intersperseWith ```kestrel public func intersperseWith(with: () -> 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] ``` #### function isSorted ```kestrel 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) ``` #### function isSortedDescending ```kestrel public consuming func isSortedDescending() -> Bool ``` True if elements come out in descending order. Mirror of `isSorted`. #### function iter ```kestrel func iter() -> Self ``` Returns `self`. The blanket conformance pivot — iterators *are* iterables. #### function last ```kestrel 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. #### function map ```kestrel public func map[U](as: (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] ``` #### function max ```kestrel public consuming func max() -> Item? ``` Largest element, or `None` for an empty iterator. Ties go to the first occurrence. #### function min ```kestrel 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 ``` #### function next ```kestrel public mutating func next() -> I.Item? ``` Pulls from the source, calls `inspector` on the value, and yields it. #### function nth ```kestrel 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) ``` #### function peekable ```kestrel 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) ``` #### function product ```kestrel 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 ``` #### function reduce ```kestrel 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 ``` #### function scan ```kestrel public func scan[Acc](from: Acc, by: (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] ``` #### function skip ```kestrel 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(); // [] ``` #### function skipWhile ```kestrel public func skipWhile(where: (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] ``` #### function sorted ```kestrel 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] ``` #### function stepBy ```kestrel 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] ``` #### function sum ```kestrel 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 ``` #### function take ```kestrel 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] ``` #### function takeWhile ```kestrel public func takeWhile(where: (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] ``` #### function tryFold ```kestrel 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") ``` #### function tryForEach ```kestrel public mutating func tryForEach[E]((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 ``` #### function unzip ```kestrel 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"] ``` #### function zip ```kestrel 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)] ``` ### struct IntersperseIterator ```kestrel public struct IntersperseIterator[I] where I: Iterator { /* private fields */ } ``` Lazy `intersperse` — inserts a copy of `separator` between consecutive elements. Returned by `Iterator.intersperse(separator:)`. # Representation Source iterator + separator value + a `needsSeparator` flag + a one-slot pending-element buffer (used to remember an element while a separator is being yielded). #### initializer From Source ```kestrel public init(inner: I, with: I.Item) ``` Builds an `IntersperseIterator`. #### field inner ```kestrel internal var inner: I ``` #### field needsSeparator ```kestrel internal var needsSeparator: Bool ``` #### field pendingItem ```kestrel internal var pendingItem: I.Item? ``` #### field separator ```kestrel internal var separator: I.Item ``` **Iterator** #### typealias Item ```kestrel type Item = I.Item ``` #### typealias TargetIterator ```kestrel type TargetIterator = Self ``` #### function all ```kestrel 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) ``` #### function any ```kestrel 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 ``` #### function chain ```kestrel 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] ``` #### function collect ```kestrel 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] ``` #### function compactMap ```kestrel public func compactMap[T]() -> FilterMapIterator[Self, T] where Item == Optional[T] ``` Drops `None`s and unwraps `Some`s — 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] ``` #### function contains ```kestrel 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 ``` #### function count ```kestrel 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 ``` #### function cycle ```kestrel 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] ``` #### function enumerate ```kestrel 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}") }; ``` #### function filter ```kestrel public func filter(where: (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] ``` #### function filterMap ```kestrel public func filterMap[U](as: (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] ``` #### function first ```kestrel 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 ``` #### function firstIndex ```kestrel 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 ``` #### function flatMap ```kestrel public func flatMap[U](as: (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] ``` #### function flatten ```kestrel 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] ``` #### function fold ```kestrel 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 ``` #### function forEach ```kestrel 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) }; ``` #### function fuse ```kestrel 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. #### function inspect ```kestrel public func inspect((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(); ``` #### function intersperse ```kestrel 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] ``` #### function intersperseWith ```kestrel public func intersperseWith(with: () -> 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] ``` #### function isSorted ```kestrel 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) ``` #### function isSortedDescending ```kestrel public consuming func isSortedDescending() -> Bool ``` True if elements come out in descending order. Mirror of `isSorted`. #### function iter ```kestrel func iter() -> Self ``` Returns `self`. The blanket conformance pivot — iterators *are* iterables. #### function last ```kestrel 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. #### function map ```kestrel public func map[U](as: (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] ``` #### function max ```kestrel public consuming func max() -> Item? ``` Largest element, or `None` for an empty iterator. Ties go to the first occurrence. #### function min ```kestrel 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 ``` #### function next ```kestrel public mutating func next() -> I.Item? ``` Returns the buffered element if one is pending, otherwise pulls the next source element — yielding a separator instead the second time around. #### function nth ```kestrel 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) ``` #### function peekable ```kestrel 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) ``` #### function product ```kestrel 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 ``` #### function reduce ```kestrel 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 ``` #### function scan ```kestrel public func scan[Acc](from: Acc, by: (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] ``` #### function skip ```kestrel 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(); // [] ``` #### function skipWhile ```kestrel public func skipWhile(where: (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] ``` #### function sorted ```kestrel 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] ``` #### function stepBy ```kestrel 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] ``` #### function sum ```kestrel 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 ``` #### function take ```kestrel 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] ``` #### function takeWhile ```kestrel public func takeWhile(where: (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] ``` #### function tryFold ```kestrel 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") ``` #### function tryForEach ```kestrel public mutating func tryForEach[E]((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 ``` #### function unzip ```kestrel 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"] ``` #### function zip ```kestrel 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)] ``` ### struct IntersperseWithIterator ```kestrel public struct IntersperseWithIterator[I] where I: Iterator { /* private fields */ } ``` Lazy `intersperseWith` — like `IntersperseIterator`, but builds each separator on demand by calling a closure. Returned by `Iterator.intersperseWith(separator:)`. # Representation Same as `IntersperseIterator`, except the stored value is a zero-arg closure producing fresh separators. #### initializer From Source ```kestrel public init(inner: I, with: () -> I.Item) ``` Builds an `IntersperseWithIterator`. #### field inner ```kestrel internal var inner: I ``` #### field needsSeparator ```kestrel internal var needsSeparator: Bool ``` #### field pendingItem ```kestrel internal var pendingItem: I.Item? ``` #### field separator ```kestrel internal var separator: () -> I.Item ``` **Iterator** #### typealias Item ```kestrel type Item = I.Item ``` #### typealias TargetIterator ```kestrel type TargetIterator = Self ``` #### function all ```kestrel 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) ``` #### function any ```kestrel 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 ``` #### function chain ```kestrel 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] ``` #### function collect ```kestrel 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] ``` #### function compactMap ```kestrel public func compactMap[T]() -> FilterMapIterator[Self, T] where Item == Optional[T] ``` Drops `None`s and unwraps `Some`s — 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] ``` #### function contains ```kestrel 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 ``` #### function count ```kestrel 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 ``` #### function cycle ```kestrel 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] ``` #### function enumerate ```kestrel 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}") }; ``` #### function filter ```kestrel public func filter(where: (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] ``` #### function filterMap ```kestrel public func filterMap[U](as: (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] ``` #### function first ```kestrel 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 ``` #### function firstIndex ```kestrel 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 ``` #### function flatMap ```kestrel public func flatMap[U](as: (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] ``` #### function flatten ```kestrel 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] ``` #### function fold ```kestrel 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 ``` #### function forEach ```kestrel 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) }; ``` #### function fuse ```kestrel 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. #### function inspect ```kestrel public func inspect((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(); ``` #### function intersperse ```kestrel 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] ``` #### function intersperseWith ```kestrel public func intersperseWith(with: () -> 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] ``` #### function isSorted ```kestrel 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) ``` #### function isSortedDescending ```kestrel public consuming func isSortedDescending() -> Bool ``` True if elements come out in descending order. Mirror of `isSorted`. #### function iter ```kestrel func iter() -> Self ``` Returns `self`. The blanket conformance pivot — iterators *are* iterables. #### function last ```kestrel 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. #### function map ```kestrel public func map[U](as: (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] ``` #### function max ```kestrel public consuming func max() -> Item? ``` Largest element, or `None` for an empty iterator. Ties go to the first occurrence. #### function min ```kestrel 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 ``` #### function next ```kestrel public mutating func next() -> I.Item? ``` Same logic as `IntersperseIterator.next`, but each separator is produced by calling `separator()`. #### function nth ```kestrel 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) ``` #### function peekable ```kestrel 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) ``` #### function product ```kestrel 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 ``` #### function reduce ```kestrel 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 ``` #### function scan ```kestrel public func scan[Acc](from: Acc, by: (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] ``` #### function skip ```kestrel 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(); // [] ``` #### function skipWhile ```kestrel public func skipWhile(where: (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] ``` #### function sorted ```kestrel 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] ``` #### function stepBy ```kestrel 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] ``` #### function sum ```kestrel 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 ``` #### function take ```kestrel 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] ``` #### function takeWhile ```kestrel public func takeWhile(where: (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] ``` #### function tryFold ```kestrel 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") ``` #### function tryForEach ```kestrel public mutating func tryForEach[E]((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 ``` #### function unzip ```kestrel 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"] ``` #### function zip ```kestrel 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)] ``` ### protocol Iterable ```kestrel public protocol Iterable ``` A type that can hand out an iterator over its contents — what `for-in` loops desugar through, and what most collections conform to. `Iterable` is one level above `Iterator`: a collection conforms to `Iterable` and produces a fresh `Iter` each call to `iter()`, leaving the source intact. (Compare with `Iterator`, which is consumed in place.) Every `Iterator` is also `Iterable` via the blanket conformance below — `iter()` on an iterator returns itself. # Examples ``` for item in myCollection { // identical to: // var it = myCollection.iter(); // while let .Some(item) = it.next() { ... } } ``` #### typealias Item ```kestrel type Item ``` The element type that iteration yields. #### typealias TargetIterator ```kestrel type TargetIterator ``` The concrete iterator type returned by `iter()`. Constrained so `TargetIterator.Item` matches `Self.Item`. #### function iter ```kestrel func iter() -> TargetIterator ``` Builds a fresh iterator over the contents. ### protocol Iterator ```kestrel public protocol Iterator ``` #### function all ```kestrel 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) ``` #### function any ```kestrel 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 ``` #### function chain ```kestrel 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] ``` #### function collect ```kestrel 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] ``` #### function compactMap ```kestrel public func compactMap[T]() -> FilterMapIterator[Self, T] where Item == Optional[T] ``` Drops `None`s and unwraps `Some`s — 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] ``` #### function contains ```kestrel 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 ``` #### function count ```kestrel 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 ``` #### function cycle ```kestrel 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] ``` #### function enumerate ```kestrel 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}") }; ``` #### function filter ```kestrel public func filter(where: (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] ``` #### function filterMap ```kestrel public func filterMap[U](as: (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] ``` #### function first ```kestrel 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 ``` #### function first ```kestrel public mutating func first() -> Item? ``` First element, or `None` if empty. Consumes only the first element. Equivalent to `next()`, but reads more naturally as a terminal. #### function firstIndex ```kestrel 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 ``` #### function flatMap ```kestrel public func flatMap[U](as: (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] ``` #### function flatten ```kestrel 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] ``` #### function fold ```kestrel 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 ``` #### function forEach ```kestrel 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) }; ``` #### function fuse ```kestrel 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. #### function inspect ```kestrel public func inspect((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(); ``` #### function intersperse ```kestrel 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] ``` #### function intersperseWith ```kestrel public func intersperseWith(with: () -> 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] ``` #### function isSorted ```kestrel 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) ``` #### function isSorted ```kestrel public consuming func isSorted(by: (Item, Item) -> Bool) -> Bool ``` True if every adjacent pair satisfies `comparator(prev, next)` — i.e. they are already in the order `comparator` defines. # Examples ``` // Descending check [5, 4, 3, 2, 1].iter().isSorted { (a, b) in a >= b }; // true // By absolute value [-1, 2, -3, 4].iter().isSorted { (a, b) in a.abs() <= b.abs() }; // true ``` #### function isSorted ```kestrel public consuming func isSorted[K](byKey: (Item) -> K) -> Bool where K: Comparable ``` True if elements are sorted ascending by `key(element)`. Sugar over `isSorted(by:)` for the common "by-key" shape. # Examples ``` let words = ["a", "bb", "ccc"]; words.iter().isSorted { it.count }; // true ``` #### function isSortedDescending ```kestrel public consuming func isSortedDescending() -> Bool ``` True if elements come out in descending order. Mirror of `isSorted`. #### function last ```kestrel 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. #### function map ```kestrel public func map[U](as: (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] ``` #### function max ```kestrel public consuming func max() -> Item? ``` Largest element, or `None` for an empty iterator. Ties go to the first occurrence. #### function max ```kestrel public consuming func max[K](byKey: (Item) -> K) -> Item? where K: Comparable ``` The element with the largest `key(element)`. Mirror of `min(byKey:)`. #### function min ```kestrel 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 ``` #### function min ```kestrel public consuming func min[K](byKey: (Item) -> K) -> Item? where K: Comparable ``` The element with the smallest `key(element)`. Ties go to the first occurrence. # Examples ``` let people = [("Alice", 30), ("Bob", 25), ("Charlie", 35)]; people.iter().min { it.1 }; // Some(("Bob", 25)) ``` #### function next ```kestrel mutating func next() -> Item? ``` Yields the next element, or `None` once exhausted. The protocol does *not* require that subsequent calls keep returning `None` — wrap with `fuse()` if you need that guarantee. #### function nth ```kestrel 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) ``` #### function peekable ```kestrel 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) ``` #### function product ```kestrel 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 ``` #### function reduce ```kestrel 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 ``` #### function scan ```kestrel public func scan[Acc](from: Acc, by: (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] ``` #### function skip ```kestrel 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(); // [] ``` #### function skipWhile ```kestrel public func skipWhile(where: (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] ``` #### function sorted ```kestrel 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] ``` #### function stepBy ```kestrel 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] ``` #### function sum ```kestrel 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 ``` #### function take ```kestrel 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] ``` #### function takeWhile ```kestrel public func takeWhile(where: (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] ``` #### function tryFold ```kestrel 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") ``` #### function tryForEach ```kestrel public mutating func tryForEach[E]((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 ``` #### function unzip ```kestrel 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"] ``` #### function zip ```kestrel 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)] ``` **Iterable** #### typealias Item ```kestrel type Item ``` The element type produced by `next()`. #### typealias Item ```kestrel type Item = Self.Item ``` #### typealias TargetIterator ```kestrel type TargetIterator = Self ``` #### function iter ```kestrel func iter() -> Self ``` Returns `self`. The blanket conformance pivot — iterators *are* iterables. ### struct MapIterator ```kestrel public struct MapIterator[I, U] where I: Iterator { /* private fields */ } ``` Lazy `map` — applies a transform to each element of `inner` as values are pulled. Returned by `Iterator.map(_:)`. # Representation Wraps the source iterator and the transform closure. No buffering — elements pass through one at a time. #### initializer From Source ```kestrel public init(inner: I, as: (I.Item) -> U) ``` Builds a `MapIterator` from `inner` and `transform`. Prefer `inner.map(transform)`. #### field inner ```kestrel internal var inner: I ``` #### field transform ```kestrel internal var transform: (I.Item) -> U ``` **Iterator** #### typealias Item ```kestrel type Item = U ``` #### typealias TargetIterator ```kestrel type TargetIterator = Self ``` #### function all ```kestrel 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) ``` #### function any ```kestrel 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 ``` #### function chain ```kestrel 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] ``` #### function collect ```kestrel 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] ``` #### function compactMap ```kestrel public func compactMap[T]() -> FilterMapIterator[Self, T] where Item == Optional[T] ``` Drops `None`s and unwraps `Some`s — 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] ``` #### function contains ```kestrel 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 ``` #### function count ```kestrel 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 ``` #### function cycle ```kestrel 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] ``` #### function enumerate ```kestrel 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}") }; ``` #### function filter ```kestrel public func filter(where: (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] ``` #### function filterMap ```kestrel public func filterMap[U](as: (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] ``` #### function first ```kestrel 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 ``` #### function firstIndex ```kestrel 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 ``` #### function flatMap ```kestrel public func flatMap[U](as: (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] ``` #### function flatten ```kestrel 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] ``` #### function fold ```kestrel 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 ``` #### function forEach ```kestrel 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) }; ``` #### function fuse ```kestrel 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. #### function inspect ```kestrel public func inspect((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(); ``` #### function intersperse ```kestrel 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] ``` #### function intersperseWith ```kestrel public func intersperseWith(with: () -> 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] ``` #### function isSorted ```kestrel 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) ``` #### function isSortedDescending ```kestrel public consuming func isSortedDescending() -> Bool ``` True if elements come out in descending order. Mirror of `isSorted`. #### function iter ```kestrel func iter() -> Self ``` Returns `self`. The blanket conformance pivot — iterators *are* iterables. #### function last ```kestrel 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. #### function map ```kestrel public func map[U](as: (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] ``` #### function max ```kestrel public consuming func max() -> Item? ``` Largest element, or `None` for an empty iterator. Ties go to the first occurrence. #### function min ```kestrel 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 ``` #### function next ```kestrel public mutating func next() -> U? ``` Pulls the next element from `inner` and runs `transform` on it. #### function nth ```kestrel 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) ``` #### function peekable ```kestrel 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) ``` #### function product ```kestrel 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 ``` #### function reduce ```kestrel 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 ``` #### function scan ```kestrel public func scan[Acc](from: Acc, by: (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] ``` #### function skip ```kestrel 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(); // [] ``` #### function skipWhile ```kestrel public func skipWhile(where: (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] ``` #### function sorted ```kestrel 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] ``` #### function stepBy ```kestrel 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] ``` #### function sum ```kestrel 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 ``` #### function take ```kestrel 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] ``` #### function takeWhile ```kestrel public func takeWhile(where: (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] ``` #### function tryFold ```kestrel 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") ``` #### function tryForEach ```kestrel public mutating func tryForEach[E]((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 ``` #### function unzip ```kestrel 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"] ``` #### function zip ```kestrel 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)] ``` ### struct OnceIterator ```kestrel public struct OnceIterator[T] { /* private fields */ } ``` Iterator that yields a single value, then nothing. Returned by `once(value:)`. # Representation One `Optional[T]` field. `next()` empties it on first call. #### initializer From Value ```kestrel public init(value: T) ``` Builds a `OnceIterator` carrying `value`. #### field value ```kestrel internal var value: T? ``` **Iterator** #### typealias Item ```kestrel type Item = T ``` #### typealias TargetIterator ```kestrel type TargetIterator = Self ``` #### function all ```kestrel 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) ``` #### function any ```kestrel 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 ``` #### function chain ```kestrel 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] ``` #### function collect ```kestrel 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] ``` #### function compactMap ```kestrel public func compactMap[T]() -> FilterMapIterator[Self, T] where Item == Optional[T] ``` Drops `None`s and unwraps `Some`s — 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] ``` #### function contains ```kestrel 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 ``` #### function count ```kestrel 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 ``` #### function cycle ```kestrel 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] ``` #### function enumerate ```kestrel 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}") }; ``` #### function filter ```kestrel public func filter(where: (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] ``` #### function filterMap ```kestrel public func filterMap[U](as: (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] ``` #### function first ```kestrel 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 ``` #### function firstIndex ```kestrel 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 ``` #### function flatMap ```kestrel public func flatMap[U](as: (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] ``` #### function flatten ```kestrel 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] ``` #### function fold ```kestrel 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 ``` #### function forEach ```kestrel 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) }; ``` #### function fuse ```kestrel 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. #### function inspect ```kestrel public func inspect((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(); ``` #### function intersperse ```kestrel 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] ``` #### function intersperseWith ```kestrel public func intersperseWith(with: () -> 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] ``` #### function isSorted ```kestrel 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) ``` #### function isSortedDescending ```kestrel public consuming func isSortedDescending() -> Bool ``` True if elements come out in descending order. Mirror of `isSorted`. #### function iter ```kestrel func iter() -> Self ``` Returns `self`. The blanket conformance pivot — iterators *are* iterables. #### function last ```kestrel 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. #### function map ```kestrel public func map[U](as: (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] ``` #### function max ```kestrel public consuming func max() -> Item? ``` Largest element, or `None` for an empty iterator. Ties go to the first occurrence. #### function min ```kestrel 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 ``` #### function next ```kestrel public mutating func next() -> T? ``` Returns the value once, then `None` forever after. #### function nth ```kestrel 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) ``` #### function peekable ```kestrel 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) ``` #### function product ```kestrel 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 ``` #### function reduce ```kestrel 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 ``` #### function scan ```kestrel public func scan[Acc](from: Acc, by: (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] ``` #### function skip ```kestrel 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(); // [] ``` #### function skipWhile ```kestrel public func skipWhile(where: (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] ``` #### function sorted ```kestrel 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] ``` #### function stepBy ```kestrel 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] ``` #### function sum ```kestrel 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 ``` #### function take ```kestrel 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] ``` #### function takeWhile ```kestrel public func takeWhile(where: (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] ``` #### function tryFold ```kestrel 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") ``` #### function tryForEach ```kestrel public mutating func tryForEach[E]((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 ``` #### function unzip ```kestrel 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"] ``` #### function zip ```kestrel 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)] ``` ### struct PeekableIterator ```kestrel public struct PeekableIterator[I] where I: Iterator { /* private fields */ } ``` Iterator wrapper that lets you peek at the next element without consuming it. Returned by `Iterator.peekable()`. # Representation Source iterator + a one-slot lookahead buffer (`peeked`). `peek()` fills the buffer; `next()` drains it before pulling the source. #### initializer From Source ```kestrel public init(inner: I) ``` Builds a `PeekableIterator` with no value buffered. #### field inner ```kestrel internal var inner: I ``` #### function peek ```kestrel public mutating func peek() -> I.Item? ``` Returns the next element without consuming it. Subsequent `peek()` calls keep returning the same value until `next()` is called. #### field peeked ```kestrel internal var peeked: Optional[I.Item]? ``` **Iterator** #### typealias Item ```kestrel type Item = I.Item ``` #### typealias TargetIterator ```kestrel type TargetIterator = Self ``` #### function all ```kestrel 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) ``` #### function any ```kestrel 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 ``` #### function chain ```kestrel 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] ``` #### function collect ```kestrel 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] ``` #### function compactMap ```kestrel public func compactMap[T]() -> FilterMapIterator[Self, T] where Item == Optional[T] ``` Drops `None`s and unwraps `Some`s — 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] ``` #### function contains ```kestrel 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 ``` #### function count ```kestrel 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 ``` #### function cycle ```kestrel 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] ``` #### function enumerate ```kestrel 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}") }; ``` #### function filter ```kestrel public func filter(where: (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] ``` #### function filterMap ```kestrel public func filterMap[U](as: (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] ``` #### function first ```kestrel 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 ``` #### function firstIndex ```kestrel 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 ``` #### function flatMap ```kestrel public func flatMap[U](as: (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] ``` #### function flatten ```kestrel 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] ``` #### function fold ```kestrel 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 ``` #### function forEach ```kestrel 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) }; ``` #### function fuse ```kestrel 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. #### function inspect ```kestrel public func inspect((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(); ``` #### function intersperse ```kestrel 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] ``` #### function intersperseWith ```kestrel public func intersperseWith(with: () -> 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] ``` #### function isSorted ```kestrel 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) ``` #### function isSortedDescending ```kestrel public consuming func isSortedDescending() -> Bool ``` True if elements come out in descending order. Mirror of `isSorted`. #### function iter ```kestrel func iter() -> Self ``` Returns `self`. The blanket conformance pivot — iterators *are* iterables. #### function last ```kestrel 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. #### function map ```kestrel public func map[U](as: (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] ``` #### function max ```kestrel public consuming func max() -> Item? ``` Largest element, or `None` for an empty iterator. Ties go to the first occurrence. #### function min ```kestrel 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 ``` #### function next ```kestrel public mutating func next() -> I.Item? ``` Returns the buffered value if present, otherwise pulls the source. #### function nth ```kestrel 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) ``` #### function peekable ```kestrel 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) ``` #### function product ```kestrel 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 ``` #### function reduce ```kestrel 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 ``` #### function scan ```kestrel public func scan[Acc](from: Acc, by: (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] ``` #### function skip ```kestrel 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(); // [] ``` #### function skipWhile ```kestrel public func skipWhile(where: (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] ``` #### function sorted ```kestrel 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] ``` #### function stepBy ```kestrel 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] ``` #### function sum ```kestrel 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 ``` #### function take ```kestrel 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] ``` #### function takeWhile ```kestrel public func takeWhile(where: (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] ``` #### function tryFold ```kestrel 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") ``` #### function tryForEach ```kestrel public mutating func tryForEach[E]((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 ``` #### function unzip ```kestrel 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"] ``` #### function zip ```kestrel 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)] ``` ### struct RepeatIterator ```kestrel public struct RepeatIterator[T] { /* private fields */ } ``` Iterator that yields the same value indefinitely. Returned by `repeatValue(value:)`. # Representation One `T` field that is copied on every `next()` call. #### initializer From Value ```kestrel public init(value: T) ``` Builds a `RepeatIterator` over `value`. #### field value ```kestrel internal var value: T ``` **Iterator** #### typealias Item ```kestrel type Item = T ``` #### typealias TargetIterator ```kestrel type TargetIterator = Self ``` #### function all ```kestrel 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) ``` #### function any ```kestrel 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 ``` #### function chain ```kestrel 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] ``` #### function collect ```kestrel 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] ``` #### function compactMap ```kestrel public func compactMap[T]() -> FilterMapIterator[Self, T] where Item == Optional[T] ``` Drops `None`s and unwraps `Some`s — 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] ``` #### function contains ```kestrel 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 ``` #### function count ```kestrel 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 ``` #### function cycle ```kestrel 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] ``` #### function enumerate ```kestrel 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}") }; ``` #### function filter ```kestrel public func filter(where: (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] ``` #### function filterMap ```kestrel public func filterMap[U](as: (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] ``` #### function first ```kestrel 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 ``` #### function firstIndex ```kestrel 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 ``` #### function flatMap ```kestrel public func flatMap[U](as: (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] ``` #### function flatten ```kestrel 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] ``` #### function fold ```kestrel 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 ``` #### function forEach ```kestrel 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) }; ``` #### function fuse ```kestrel 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. #### function inspect ```kestrel public func inspect((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(); ``` #### function intersperse ```kestrel 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] ``` #### function intersperseWith ```kestrel public func intersperseWith(with: () -> 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] ``` #### function isSorted ```kestrel 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) ``` #### function isSortedDescending ```kestrel public consuming func isSortedDescending() -> Bool ``` True if elements come out in descending order. Mirror of `isSorted`. #### function iter ```kestrel func iter() -> Self ``` Returns `self`. The blanket conformance pivot — iterators *are* iterables. #### function last ```kestrel 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. #### function map ```kestrel public func map[U](as: (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] ``` #### function max ```kestrel public consuming func max() -> Item? ``` Largest element, or `None` for an empty iterator. Ties go to the first occurrence. #### function min ```kestrel 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 ``` #### function next ```kestrel public mutating func next() -> T? ``` Returns a fresh copy of the stored value every call. #### function nth ```kestrel 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) ``` #### function peekable ```kestrel 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) ``` #### function product ```kestrel 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 ``` #### function reduce ```kestrel 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 ``` #### function scan ```kestrel public func scan[Acc](from: Acc, by: (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] ``` #### function skip ```kestrel 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(); // [] ``` #### function skipWhile ```kestrel public func skipWhile(where: (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] ``` #### function sorted ```kestrel 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] ``` #### function stepBy ```kestrel 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] ``` #### function sum ```kestrel 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 ``` #### function take ```kestrel 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] ``` #### function takeWhile ```kestrel public func takeWhile(where: (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] ``` #### function tryFold ```kestrel 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") ``` #### function tryForEach ```kestrel public mutating func tryForEach[E]((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 ``` #### function unzip ```kestrel 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"] ``` #### function zip ```kestrel 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)] ``` ### struct RepeatNIterator ```kestrel public struct RepeatNIterator[T] { /* private fields */ } ``` Iterator that yields the same value `count` times, then stops. Returned by `repeatN(value:count:)`. # Representation `T` payload + an `Int64` countdown. #### initializer From Value ```kestrel public init(value: T, count: Int64) ``` Builds a `RepeatNIterator` that will yield `value` exactly `count` times. #### field remaining ```kestrel internal var remaining: Int64 ``` #### field value ```kestrel internal var value: T ``` **Iterator** #### typealias Item ```kestrel type Item = T ``` #### typealias TargetIterator ```kestrel type TargetIterator = Self ``` #### function all ```kestrel 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) ``` #### function any ```kestrel 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 ``` #### function chain ```kestrel 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] ``` #### function collect ```kestrel 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] ``` #### function compactMap ```kestrel public func compactMap[T]() -> FilterMapIterator[Self, T] where Item == Optional[T] ``` Drops `None`s and unwraps `Some`s — 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] ``` #### function contains ```kestrel 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 ``` #### function count ```kestrel 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 ``` #### function cycle ```kestrel 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] ``` #### function enumerate ```kestrel 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}") }; ``` #### function filter ```kestrel public func filter(where: (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] ``` #### function filterMap ```kestrel public func filterMap[U](as: (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] ``` #### function first ```kestrel 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 ``` #### function firstIndex ```kestrel 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 ``` #### function flatMap ```kestrel public func flatMap[U](as: (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] ``` #### function flatten ```kestrel 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] ``` #### function fold ```kestrel 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 ``` #### function forEach ```kestrel 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) }; ``` #### function fuse ```kestrel 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. #### function inspect ```kestrel public func inspect((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(); ``` #### function intersperse ```kestrel 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] ``` #### function intersperseWith ```kestrel public func intersperseWith(with: () -> 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] ``` #### function isSorted ```kestrel 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) ``` #### function isSortedDescending ```kestrel public consuming func isSortedDescending() -> Bool ``` True if elements come out in descending order. Mirror of `isSorted`. #### function iter ```kestrel func iter() -> Self ``` Returns `self`. The blanket conformance pivot — iterators *are* iterables. #### function last ```kestrel 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. #### function map ```kestrel public func map[U](as: (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] ``` #### function max ```kestrel public consuming func max() -> Item? ``` Largest element, or `None` for an empty iterator. Ties go to the first occurrence. #### function min ```kestrel 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 ``` #### function next ```kestrel public mutating func next() -> T? ``` Decrements `remaining` and returns a fresh copy of the value; returns `None` once the counter hits zero. #### function nth ```kestrel 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) ``` #### function peekable ```kestrel 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) ``` #### function product ```kestrel 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 ``` #### function reduce ```kestrel 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 ``` #### function scan ```kestrel public func scan[Acc](from: Acc, by: (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] ``` #### function skip ```kestrel 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(); // [] ``` #### function skipWhile ```kestrel public func skipWhile(where: (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] ``` #### function sorted ```kestrel 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] ``` #### function stepBy ```kestrel 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] ``` #### function sum ```kestrel 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 ``` #### function take ```kestrel 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] ``` #### function takeWhile ```kestrel public func takeWhile(where: (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] ``` #### function tryFold ```kestrel 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") ``` #### function tryForEach ```kestrel public mutating func tryForEach[E]((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 ``` #### function unzip ```kestrel 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"] ``` #### function zip ```kestrel 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)] ``` ### struct ReversedIterator ```kestrel public struct ReversedIterator[I] where I: DoubleEndedIterator, I: Iterator { /* private fields */ } ``` Wraps a `DoubleEndedIterator` to walk it back to front. The `Iterator` conformance is added by the `extend ReversedIterator[I]: DoubleEndedIterator` block in `iterator.ks`. Returned by `DoubleEndedIterator.rev()`. # Representation Just the inner iterator — no buffering. #### initializer From Source ```kestrel public init(inner: I) ``` Builds a `ReversedIterator`. Prefer `inner.rev()`. #### field inner ```kestrel internal var inner: I ``` **Iterator** #### typealias Item ```kestrel type Item = I.Item ``` #### typealias TargetIterator ```kestrel type TargetIterator = Self ``` #### function all ```kestrel 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) ``` #### function any ```kestrel 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 ``` #### function chain ```kestrel 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] ``` #### function collect ```kestrel 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] ``` #### function compactMap ```kestrel public func compactMap[T]() -> FilterMapIterator[Self, T] where Item == Optional[T] ``` Drops `None`s and unwraps `Some`s — 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] ``` #### function contains ```kestrel 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 ``` #### function count ```kestrel 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 ``` #### function cycle ```kestrel 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] ``` #### function enumerate ```kestrel 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}") }; ``` #### function filter ```kestrel public func filter(where: (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] ``` #### function filterMap ```kestrel public func filterMap[U](as: (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] ``` #### function first ```kestrel 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 ``` #### function firstIndex ```kestrel 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 ``` #### function flatMap ```kestrel public func flatMap[U](as: (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] ``` #### function flatten ```kestrel 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] ``` #### function fold ```kestrel 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 ``` #### function forEach ```kestrel 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) }; ``` #### function fuse ```kestrel 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. #### function inspect ```kestrel public func inspect((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(); ``` #### function intersperse ```kestrel 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] ``` #### function intersperseWith ```kestrel public func intersperseWith(with: () -> 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] ``` #### function isSorted ```kestrel 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) ``` #### function isSortedDescending ```kestrel public consuming func isSortedDescending() -> Bool ``` True if elements come out in descending order. Mirror of `isSorted`. #### function iter ```kestrel func iter() -> Self ``` Returns `self`. The blanket conformance pivot — iterators *are* iterables. #### function last ```kestrel 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. #### function map ```kestrel public func map[U](as: (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] ``` #### function max ```kestrel public consuming func max() -> Item? ``` Largest element, or `None` for an empty iterator. Ties go to the first occurrence. #### function min ```kestrel 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 ``` #### function next ```kestrel public mutating func next() -> I.Item? ``` Pulls from the back of the inner iterator (which is the front of the reversed view). #### function nth ```kestrel 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) ``` #### function peekable ```kestrel 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) ``` #### function product ```kestrel 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 ``` #### function reduce ```kestrel 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 ``` #### function scan ```kestrel public func scan[Acc](from: Acc, by: (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] ``` #### function skip ```kestrel 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(); // [] ``` #### function skipWhile ```kestrel public func skipWhile(where: (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] ``` #### function sorted ```kestrel 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] ``` #### function stepBy ```kestrel 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] ``` #### function sum ```kestrel 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 ``` #### function take ```kestrel 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] ``` #### function takeWhile ```kestrel public func takeWhile(where: (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] ``` #### function tryFold ```kestrel 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") ``` #### function tryForEach ```kestrel public mutating func tryForEach[E]((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 ``` #### function unzip ```kestrel 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"] ``` #### function zip ```kestrel 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)] ``` **DoubleEndedIterator** #### function nextBack ```kestrel public mutating func nextBack() -> I.Item? ``` Pulls from the front of the inner iterator (which is the back of the reversed view). #### function rev ```kestrel public func rev() -> ReversedIterator[Self] ``` Yields elements back-to-front by pulling `nextBack()` instead of `next()`. `O(1)` to construct — no buffering. # Examples ``` [1, 2, 3, 4, 5].iter().rev().collect(); // [5, 4, 3, 2, 1] [1, 2, 3, 4, 5].iter().rev().take(3).collect(); // [5, 4, 3] [1, 2, 3, 4, 5].iter().rev().first { it % 2 == 0 }; // Some(4) ``` ### struct ScanIterator ```kestrel public struct ScanIterator[I, Acc] where I: Iterator { /* private fields */ } ``` Lazy `scan` — yields the running fold accumulator after each step. Returned by `Iterator.scan(initial:combine:)`. # Representation Source iterator + the running accumulator state + the combine closure. #### initializer From Source ```kestrel public init(inner: I, from: Acc, by: (Acc, I.Item) -> Acc) ``` Builds a `ScanIterator` seeded with `initial`. #### field combine ```kestrel internal var combine: (Acc, I.Item) -> Acc ``` #### field inner ```kestrel internal var inner: I ``` #### field state ```kestrel internal var state: Acc ``` **Iterator** #### typealias Item ```kestrel type Item = Acc ``` #### typealias TargetIterator ```kestrel type TargetIterator = Self ``` #### function all ```kestrel 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) ``` #### function any ```kestrel 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 ``` #### function chain ```kestrel 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] ``` #### function collect ```kestrel 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] ``` #### function compactMap ```kestrel public func compactMap[T]() -> FilterMapIterator[Self, T] where Item == Optional[T] ``` Drops `None`s and unwraps `Some`s — 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] ``` #### function contains ```kestrel 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 ``` #### function count ```kestrel 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 ``` #### function cycle ```kestrel 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] ``` #### function enumerate ```kestrel 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}") }; ``` #### function filter ```kestrel public func filter(where: (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] ``` #### function filterMap ```kestrel public func filterMap[U](as: (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] ``` #### function first ```kestrel 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 ``` #### function firstIndex ```kestrel 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 ``` #### function flatMap ```kestrel public func flatMap[U](as: (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] ``` #### function flatten ```kestrel 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] ``` #### function fold ```kestrel 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 ``` #### function forEach ```kestrel 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) }; ``` #### function fuse ```kestrel 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. #### function inspect ```kestrel public func inspect((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(); ``` #### function intersperse ```kestrel 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] ``` #### function intersperseWith ```kestrel public func intersperseWith(with: () -> 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] ``` #### function isSorted ```kestrel 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) ``` #### function isSortedDescending ```kestrel public consuming func isSortedDescending() -> Bool ``` True if elements come out in descending order. Mirror of `isSorted`. #### function iter ```kestrel func iter() -> Self ``` Returns `self`. The blanket conformance pivot — iterators *are* iterables. #### function last ```kestrel 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. #### function map ```kestrel public func map[U](as: (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] ``` #### function max ```kestrel public consuming func max() -> Item? ``` Largest element, or `None` for an empty iterator. Ties go to the first occurrence. #### function min ```kestrel 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 ``` #### function next ```kestrel public mutating func next() -> Acc? ``` Pulls the next element, updates `state`, and yields the new state. #### function nth ```kestrel 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) ``` #### function peekable ```kestrel 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) ``` #### function product ```kestrel 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 ``` #### function reduce ```kestrel 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 ``` #### function scan ```kestrel public func scan[Acc](from: Acc, by: (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] ``` #### function skip ```kestrel 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(); // [] ``` #### function skipWhile ```kestrel public func skipWhile(where: (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] ``` #### function sorted ```kestrel 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] ``` #### function stepBy ```kestrel 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] ``` #### function sum ```kestrel 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 ``` #### function take ```kestrel 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] ``` #### function takeWhile ```kestrel public func takeWhile(where: (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] ``` #### function tryFold ```kestrel 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") ``` #### function tryForEach ```kestrel public mutating func tryForEach[E]((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 ``` #### function unzip ```kestrel 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"] ``` #### function zip ```kestrel 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)] ``` ### struct SkipIterator ```kestrel public struct SkipIterator[I] where I: Iterator { /* private fields */ } ``` Lazy `skip` — drops the first `count` elements, then yields the rest. Returned by `Iterator.skip(count:)`. # Representation Source iterator + a counter; the first `next()` call drains the budget by pulling the source. #### initializer From Source ```kestrel public init(inner: I, count: Int64) ``` Builds a `SkipIterator` that will drop `count` elements before yielding. #### field inner ```kestrel internal var inner: I ``` #### field remaining ```kestrel internal var remaining: Int64 ``` **Iterator** #### typealias Item ```kestrel type Item = I.Item ``` #### typealias TargetIterator ```kestrel type TargetIterator = Self ``` #### function all ```kestrel 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) ``` #### function any ```kestrel 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 ``` #### function chain ```kestrel 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] ``` #### function collect ```kestrel 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] ``` #### function compactMap ```kestrel public func compactMap[T]() -> FilterMapIterator[Self, T] where Item == Optional[T] ``` Drops `None`s and unwraps `Some`s — 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] ``` #### function contains ```kestrel 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 ``` #### function count ```kestrel 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 ``` #### function cycle ```kestrel 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] ``` #### function enumerate ```kestrel 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}") }; ``` #### function filter ```kestrel public func filter(where: (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] ``` #### function filterMap ```kestrel public func filterMap[U](as: (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] ``` #### function first ```kestrel 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 ``` #### function firstIndex ```kestrel 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 ``` #### function flatMap ```kestrel public func flatMap[U](as: (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] ``` #### function flatten ```kestrel 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] ``` #### function fold ```kestrel 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 ``` #### function forEach ```kestrel 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) }; ``` #### function fuse ```kestrel 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. #### function inspect ```kestrel public func inspect((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(); ``` #### function intersperse ```kestrel 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] ``` #### function intersperseWith ```kestrel public func intersperseWith(with: () -> 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] ``` #### function isSorted ```kestrel 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) ``` #### function isSortedDescending ```kestrel public consuming func isSortedDescending() -> Bool ``` True if elements come out in descending order. Mirror of `isSorted`. #### function iter ```kestrel func iter() -> Self ``` Returns `self`. The blanket conformance pivot — iterators *are* iterables. #### function last ```kestrel 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. #### function map ```kestrel public func map[U](as: (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] ``` #### function max ```kestrel public consuming func max() -> Item? ``` Largest element, or `None` for an empty iterator. Ties go to the first occurrence. #### function min ```kestrel 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 ``` #### function next ```kestrel public mutating func next() -> I.Item? ``` On first call, walks past `remaining` source elements; subsequent calls forward `next()` directly. #### function nth ```kestrel 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) ``` #### function peekable ```kestrel 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) ``` #### function product ```kestrel 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 ``` #### function reduce ```kestrel 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 ``` #### function scan ```kestrel public func scan[Acc](from: Acc, by: (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] ``` #### function skip ```kestrel 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(); // [] ``` #### function skipWhile ```kestrel public func skipWhile(where: (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] ``` #### function sorted ```kestrel 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] ``` #### function stepBy ```kestrel 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] ``` #### function sum ```kestrel 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 ``` #### function take ```kestrel 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] ``` #### function takeWhile ```kestrel public func takeWhile(where: (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] ``` #### function tryFold ```kestrel 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") ``` #### function tryForEach ```kestrel public mutating func tryForEach[E]((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 ``` #### function unzip ```kestrel 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"] ``` #### function zip ```kestrel 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)] ``` ### struct SkipWhileIterator ```kestrel public struct SkipWhileIterator[I] where I: Iterator { /* private fields */ } ``` Lazy `skipWhile` — drops a leading run of elements satisfying the predicate, then yields *every* remaining element. Returned by `Iterator.skipWhile(_:)`. # Representation Source iterator + predicate + a one-bit `doneSkipping` flag that latches once the skipping phase ends. #### initializer From Source ```kestrel public init(inner: I, where: (I.Item) -> Bool) ``` Builds a `SkipWhileIterator`. Prefer `inner.skipWhile(predicate)`. #### field doneSkipping ```kestrel internal var doneSkipping: Bool ``` #### field inner ```kestrel internal var inner: I ``` #### field predicate ```kestrel internal var predicate: (I.Item) -> Bool ``` **Iterator** #### typealias Item ```kestrel type Item = I.Item ``` #### typealias TargetIterator ```kestrel type TargetIterator = Self ``` #### function all ```kestrel 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) ``` #### function any ```kestrel 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 ``` #### function chain ```kestrel 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] ``` #### function collect ```kestrel 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] ``` #### function compactMap ```kestrel public func compactMap[T]() -> FilterMapIterator[Self, T] where Item == Optional[T] ``` Drops `None`s and unwraps `Some`s — 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] ``` #### function contains ```kestrel 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 ``` #### function count ```kestrel 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 ``` #### function cycle ```kestrel 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] ``` #### function enumerate ```kestrel 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}") }; ``` #### function filter ```kestrel public func filter(where: (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] ``` #### function filterMap ```kestrel public func filterMap[U](as: (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] ``` #### function first ```kestrel 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 ``` #### function firstIndex ```kestrel 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 ``` #### function flatMap ```kestrel public func flatMap[U](as: (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] ``` #### function flatten ```kestrel 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] ``` #### function fold ```kestrel 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 ``` #### function forEach ```kestrel 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) }; ``` #### function fuse ```kestrel 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. #### function inspect ```kestrel public func inspect((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(); ``` #### function intersperse ```kestrel 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] ``` #### function intersperseWith ```kestrel public func intersperseWith(with: () -> 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] ``` #### function isSorted ```kestrel 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) ``` #### function isSortedDescending ```kestrel public consuming func isSortedDescending() -> Bool ``` True if elements come out in descending order. Mirror of `isSorted`. #### function iter ```kestrel func iter() -> Self ``` Returns `self`. The blanket conformance pivot — iterators *are* iterables. #### function last ```kestrel 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. #### function map ```kestrel public func map[U](as: (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] ``` #### function max ```kestrel public consuming func max() -> Item? ``` Largest element, or `None` for an empty iterator. Ties go to the first occurrence. #### function min ```kestrel 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 ``` #### function next ```kestrel public mutating func next() -> I.Item? ``` On first call, drains source elements that match `predicate` and returns the first one that doesn't. After that, forwards `next()` directly. #### function nth ```kestrel 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) ``` #### function peekable ```kestrel 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) ``` #### function product ```kestrel 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 ``` #### function reduce ```kestrel 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 ``` #### function scan ```kestrel public func scan[Acc](from: Acc, by: (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] ``` #### function skip ```kestrel 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(); // [] ``` #### function skipWhile ```kestrel public func skipWhile(where: (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] ``` #### function sorted ```kestrel 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] ``` #### function stepBy ```kestrel 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] ``` #### function sum ```kestrel 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 ``` #### function take ```kestrel 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] ``` #### function takeWhile ```kestrel public func takeWhile(where: (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] ``` #### function tryFold ```kestrel 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") ``` #### function tryForEach ```kestrel public mutating func tryForEach[E]((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 ``` #### function unzip ```kestrel 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"] ``` #### function zip ```kestrel 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)] ``` ### struct StepByIterator ```kestrel public struct StepByIterator[I] where I: Iterator { /* private fields */ } ``` Lazy `stepBy` — yields every `step`-th element, starting with the first. Returned by `Iterator.stepBy(n:)`. # Representation Source iterator + step size + a one-bit `first` flag (the first element is always emitted; subsequent ones consume `step - 1` extra pulls). #### initializer From Source ```kestrel public init(inner: I, step: Int64) ``` Builds a `StepByIterator`. Caller guarantees `step >= 1`; `step == 0` produces undefined behaviour. #### field first ```kestrel internal var first: Bool ``` #### field inner ```kestrel internal var inner: I ``` #### field step ```kestrel internal var step: Int64 ``` **Iterator** #### typealias Item ```kestrel type Item = I.Item ``` #### typealias TargetIterator ```kestrel type TargetIterator = Self ``` #### function all ```kestrel 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) ``` #### function any ```kestrel 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 ``` #### function chain ```kestrel 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] ``` #### function collect ```kestrel 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] ``` #### function compactMap ```kestrel public func compactMap[T]() -> FilterMapIterator[Self, T] where Item == Optional[T] ``` Drops `None`s and unwraps `Some`s — 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] ``` #### function contains ```kestrel 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 ``` #### function count ```kestrel 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 ``` #### function cycle ```kestrel 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] ``` #### function enumerate ```kestrel 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}") }; ``` #### function filter ```kestrel public func filter(where: (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] ``` #### function filterMap ```kestrel public func filterMap[U](as: (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] ``` #### function first ```kestrel 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 ``` #### function firstIndex ```kestrel 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 ``` #### function flatMap ```kestrel public func flatMap[U](as: (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] ``` #### function flatten ```kestrel 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] ``` #### function fold ```kestrel 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 ``` #### function forEach ```kestrel 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) }; ``` #### function fuse ```kestrel 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. #### function inspect ```kestrel public func inspect((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(); ``` #### function intersperse ```kestrel 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] ``` #### function intersperseWith ```kestrel public func intersperseWith(with: () -> 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] ``` #### function isSorted ```kestrel 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) ``` #### function isSortedDescending ```kestrel public consuming func isSortedDescending() -> Bool ``` True if elements come out in descending order. Mirror of `isSorted`. #### function iter ```kestrel func iter() -> Self ``` Returns `self`. The blanket conformance pivot — iterators *are* iterables. #### function last ```kestrel 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. #### function map ```kestrel public func map[U](as: (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] ``` #### function max ```kestrel public consuming func max() -> Item? ``` Largest element, or `None` for an empty iterator. Ties go to the first occurrence. #### function min ```kestrel 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 ``` #### function next ```kestrel public mutating func next() -> I.Item? ``` Yields the first element on the first call; subsequently drains `step - 1` elements and yields the next. #### function nth ```kestrel 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) ``` #### function peekable ```kestrel 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) ``` #### function product ```kestrel 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 ``` #### function reduce ```kestrel 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 ``` #### function scan ```kestrel public func scan[Acc](from: Acc, by: (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] ``` #### function skip ```kestrel 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(); // [] ``` #### function skipWhile ```kestrel public func skipWhile(where: (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] ``` #### function sorted ```kestrel 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] ``` #### function stepBy ```kestrel 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] ``` #### function sum ```kestrel 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 ``` #### function take ```kestrel 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] ``` #### function takeWhile ```kestrel public func takeWhile(where: (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] ``` #### function tryFold ```kestrel 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") ``` #### function tryForEach ```kestrel public mutating func tryForEach[E]((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 ``` #### function unzip ```kestrel 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"] ``` #### function zip ```kestrel 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)] ``` ### struct TakeIterator ```kestrel public struct TakeIterator[I] where I: Iterator { /* private fields */ } ``` Lazy `take` — yields at most `count` elements from the source. Returned by `Iterator.take(count:)`. # Representation Source iterator + a counter that ticks down to zero. #### initializer From Source ```kestrel public init(inner: I, count: Int64) ``` Builds a `TakeIterator` with `count` capacity. #### field inner ```kestrel internal var inner: I ``` #### field remaining ```kestrel internal var remaining: Int64 ``` **Iterator** #### typealias Item ```kestrel type Item = I.Item ``` #### typealias TargetIterator ```kestrel type TargetIterator = Self ``` #### function all ```kestrel 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) ``` #### function any ```kestrel 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 ``` #### function chain ```kestrel 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] ``` #### function collect ```kestrel 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] ``` #### function compactMap ```kestrel public func compactMap[T]() -> FilterMapIterator[Self, T] where Item == Optional[T] ``` Drops `None`s and unwraps `Some`s — 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] ``` #### function contains ```kestrel 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 ``` #### function count ```kestrel 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 ``` #### function cycle ```kestrel 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] ``` #### function enumerate ```kestrel 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}") }; ``` #### function filter ```kestrel public func filter(where: (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] ``` #### function filterMap ```kestrel public func filterMap[U](as: (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] ``` #### function first ```kestrel 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 ``` #### function firstIndex ```kestrel 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 ``` #### function flatMap ```kestrel public func flatMap[U](as: (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] ``` #### function flatten ```kestrel 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] ``` #### function fold ```kestrel 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 ``` #### function forEach ```kestrel 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) }; ``` #### function fuse ```kestrel 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. #### function inspect ```kestrel public func inspect((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(); ``` #### function intersperse ```kestrel 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] ``` #### function intersperseWith ```kestrel public func intersperseWith(with: () -> 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] ``` #### function isSorted ```kestrel 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) ``` #### function isSortedDescending ```kestrel public consuming func isSortedDescending() -> Bool ``` True if elements come out in descending order. Mirror of `isSorted`. #### function iter ```kestrel func iter() -> Self ``` Returns `self`. The blanket conformance pivot — iterators *are* iterables. #### function last ```kestrel 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. #### function map ```kestrel public func map[U](as: (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] ``` #### function max ```kestrel public consuming func max() -> Item? ``` Largest element, or `None` for an empty iterator. Ties go to the first occurrence. #### function min ```kestrel 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 ``` #### function next ```kestrel public mutating func next() -> I.Item? ``` Decrements `remaining` and forwards `next()`; returns `None` once the budget hits zero. #### function nth ```kestrel 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) ``` #### function peekable ```kestrel 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) ``` #### function product ```kestrel 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 ``` #### function reduce ```kestrel 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 ``` #### function scan ```kestrel public func scan[Acc](from: Acc, by: (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] ``` #### function skip ```kestrel 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(); // [] ``` #### function skipWhile ```kestrel public func skipWhile(where: (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] ``` #### function sorted ```kestrel 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] ``` #### function stepBy ```kestrel 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] ``` #### function sum ```kestrel 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 ``` #### function take ```kestrel 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] ``` #### function takeWhile ```kestrel public func takeWhile(where: (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] ``` #### function tryFold ```kestrel 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") ``` #### function tryForEach ```kestrel public mutating func tryForEach[E]((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 ``` #### function unzip ```kestrel 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"] ``` #### function zip ```kestrel 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)] ``` ### struct TakeWhileIterator ```kestrel public struct TakeWhileIterator[I] where I: Iterator { /* private fields */ } ``` Lazy `takeWhile` — yields elements until the predicate first returns `false`, then permanently stops. Returned by `Iterator.takeWhile(_:)`. # Representation Source iterator + predicate + a one-bit `done` flag that latches once the predicate fails. #### initializer From Source ```kestrel public init(inner: I, where: (I.Item) -> Bool) ``` Builds a `TakeWhileIterator`. Prefer `inner.takeWhile(predicate)`. #### field done ```kestrel internal var done: Bool ``` #### field inner ```kestrel internal var inner: I ``` #### field predicate ```kestrel internal var predicate: (I.Item) -> Bool ``` **Iterator** #### typealias Item ```kestrel type Item = I.Item ``` #### typealias TargetIterator ```kestrel type TargetIterator = Self ``` #### function all ```kestrel 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) ``` #### function any ```kestrel 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 ``` #### function chain ```kestrel 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] ``` #### function collect ```kestrel 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] ``` #### function compactMap ```kestrel public func compactMap[T]() -> FilterMapIterator[Self, T] where Item == Optional[T] ``` Drops `None`s and unwraps `Some`s — 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] ``` #### function contains ```kestrel 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 ``` #### function count ```kestrel 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 ``` #### function cycle ```kestrel 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] ``` #### function enumerate ```kestrel 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}") }; ``` #### function filter ```kestrel public func filter(where: (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] ``` #### function filterMap ```kestrel public func filterMap[U](as: (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] ``` #### function first ```kestrel 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 ``` #### function firstIndex ```kestrel 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 ``` #### function flatMap ```kestrel public func flatMap[U](as: (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] ``` #### function flatten ```kestrel 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] ``` #### function fold ```kestrel 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 ``` #### function forEach ```kestrel 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) }; ``` #### function fuse ```kestrel 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. #### function inspect ```kestrel public func inspect((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(); ``` #### function intersperse ```kestrel 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] ``` #### function intersperseWith ```kestrel public func intersperseWith(with: () -> 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] ``` #### function isSorted ```kestrel 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) ``` #### function isSortedDescending ```kestrel public consuming func isSortedDescending() -> Bool ``` True if elements come out in descending order. Mirror of `isSorted`. #### function iter ```kestrel func iter() -> Self ``` Returns `self`. The blanket conformance pivot — iterators *are* iterables. #### function last ```kestrel 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. #### function map ```kestrel public func map[U](as: (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] ``` #### function max ```kestrel public consuming func max() -> Item? ``` Largest element, or `None` for an empty iterator. Ties go to the first occurrence. #### function min ```kestrel 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 ``` #### function next ```kestrel public mutating func next() -> I.Item? ``` Returns the next element if `predicate` still accepts; latches `done = true` and returns `None` on the first rejection or underlying exhaustion. #### function nth ```kestrel 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) ``` #### function peekable ```kestrel 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) ``` #### function product ```kestrel 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 ``` #### function reduce ```kestrel 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 ``` #### function scan ```kestrel public func scan[Acc](from: Acc, by: (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] ``` #### function skip ```kestrel 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(); // [] ``` #### function skipWhile ```kestrel public func skipWhile(where: (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] ``` #### function sorted ```kestrel 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] ``` #### function stepBy ```kestrel 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] ``` #### function sum ```kestrel 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 ``` #### function take ```kestrel 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] ``` #### function takeWhile ```kestrel public func takeWhile(where: (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] ``` #### function tryFold ```kestrel 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") ``` #### function tryForEach ```kestrel public mutating func tryForEach[E]((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 ``` #### function unzip ```kestrel 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"] ``` #### function zip ```kestrel 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)] ``` ### struct ZipIterator ```kestrel public struct ZipIterator[A, B] where A: Iterator, B: Iterator { /* private fields */ } ``` Lazy `zip` — pairs elements from two iterators. Stops at the shorter one. Returned by `Iterator.zip(other:)`. # Representation Holds both source iterators. No buffering. #### initializer From Sources ```kestrel public init(first: A, second: B) ``` Builds a `ZipIterator`. Prefer `first.zip(other: second)`. #### field first ```kestrel internal var first: A ``` #### field second ```kestrel internal var second: B ``` **Iterator** #### typealias Item ```kestrel type Item = (A.Item, B.Item) ``` #### typealias TargetIterator ```kestrel type TargetIterator = Self ``` #### function all ```kestrel 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) ``` #### function any ```kestrel 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 ``` #### function chain ```kestrel 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] ``` #### function collect ```kestrel 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] ``` #### function compactMap ```kestrel public func compactMap[T]() -> FilterMapIterator[Self, T] where Item == Optional[T] ``` Drops `None`s and unwraps `Some`s — 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] ``` #### function contains ```kestrel 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 ``` #### function count ```kestrel 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 ``` #### function cycle ```kestrel 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] ``` #### function enumerate ```kestrel 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}") }; ``` #### function filter ```kestrel public func filter(where: (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] ``` #### function filterMap ```kestrel public func filterMap[U](as: (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] ``` #### function first ```kestrel 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 ``` #### function firstIndex ```kestrel 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 ``` #### function flatMap ```kestrel public func flatMap[U](as: (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] ``` #### function flatten ```kestrel 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] ``` #### function fold ```kestrel 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 ``` #### function forEach ```kestrel 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) }; ``` #### function fuse ```kestrel 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. #### function inspect ```kestrel public func inspect((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(); ``` #### function intersperse ```kestrel 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] ``` #### function intersperseWith ```kestrel public func intersperseWith(with: () -> 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] ``` #### function isSorted ```kestrel 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) ``` #### function isSortedDescending ```kestrel public consuming func isSortedDescending() -> Bool ``` True if elements come out in descending order. Mirror of `isSorted`. #### function iter ```kestrel func iter() -> Self ``` Returns `self`. The blanket conformance pivot — iterators *are* iterables. #### function last ```kestrel 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. #### function map ```kestrel public func map[U](as: (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] ``` #### function max ```kestrel public consuming func max() -> Item? ``` Largest element, or `None` for an empty iterator. Ties go to the first occurrence. #### function min ```kestrel 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 ``` #### function next ```kestrel public mutating func next() -> (A.Item, B.Item)? ``` Pulls one element from each side and pairs them. `None` if either runs out. #### function nth ```kestrel 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) ``` #### function peekable ```kestrel 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) ``` #### function product ```kestrel 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 ``` #### function reduce ```kestrel 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 ``` #### function scan ```kestrel public func scan[Acc](from: Acc, by: (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] ``` #### function skip ```kestrel 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(); // [] ``` #### function skipWhile ```kestrel public func skipWhile(where: (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] ``` #### function sorted ```kestrel 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] ``` #### function stepBy ```kestrel 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] ``` #### function sum ```kestrel 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 ``` #### function take ```kestrel 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] ``` #### function takeWhile ```kestrel public func takeWhile(where: (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] ``` #### function tryFold ```kestrel 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") ``` #### function tryForEach ```kestrel public mutating func tryForEach[E]((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 ``` #### function unzip ```kestrel 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"] ``` #### function zip ```kestrel 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)] ``` ### function empty ```kestrel public func empty[T]() -> EmptyIterator[T] ``` Returns an `EmptyIterator[T]`. Useful as a "neutral element" in iterator algebra (`a.chain(other: empty())`). ### function once ```kestrel public func once[T](T) -> OnceIterator[T] ``` Returns a `OnceIterator` that yields `value` and then nothing. Equivalent to `[value].iter()` without the array allocation. ### function repeatN ```kestrel public func repeatN[T](T, Int64) -> RepeatNIterator[T] ``` Returns a `RepeatNIterator` that yields `count` copies of `value`, then stops. ### function repeatValue ```kestrel public func repeatValue[T](T) -> RepeatIterator[T] ``` Returns a `RepeatIterator` that yields copies of `value` forever. Combine with `take` to cap it. --- ## std.memory ### protocol Allocator ```kestrel public protocol Allocator ``` Protocol for raw-memory allocators. `Allocator` is the indirection collections use so they can be parameterised over allocation strategy (e.g. `Array[T, A]`, `Buffer[T, A]`, custom arenas). All three methods are `mutating` so stateful allocators (arenas, pools) can update their bookkeeping; stateless wrappers around `malloc` don't need to. # Examples ``` var alloc = SystemAllocator(); if let .Some(p) = alloc.allocate(Layout.of[Int64]()) { // ... use p ... alloc.deallocate(p, Layout.of[Int64]()) } ``` #### function allocate ```kestrel mutating func allocate(Layout) -> RawPointer? ``` Returns a pointer to a fresh region matching `layout`, or `.None` when allocation fails. Returned memory is uninitialised. #### function deallocate ```kestrel mutating func deallocate(RawPointer, Layout) ``` Releases memory previously returned by `allocate` / `reallocate`. `layout` must match the layout used to obtain the pointer. # Safety `ptr` must have been produced by this allocator (or a clone of it) for `layout`. Mismatching the layout, double-freeing, or freeing a pointer from another allocator is undefined behavior. #### function reallocate ```kestrel mutating func reallocate(RawPointer, Layout, Layout) -> RawPointer? ``` Resizes the allocation at `ptr` from `oldLayout` to `newLayout`. On failure the original allocation is left intact and `.None` is returned. On success the old pointer must not be reused — use the returned pointer instead. ### struct ArraySlice ```kestrel public struct ArraySlice[T] { /* private fields */ } ``` Non-owning view over a contiguous run of `T` values. `Slice` is the standard "borrow" type for arrays, buffers, and any other contiguous storage: it stores a pointer + length and provides safe and unchecked indexing, sub-slicing, iteration, and pattern matching. The slice does **not** track or extend the lifetime of the underlying storage — keeping a slice past the end of its source is a use-after-free. # Examples ``` let arr = [1, 2, 3, 4]; let s = arr.asSlice(); s[safe: 0] // .Some(1) s[safe: 99] // .None for x in s.iter() { print(x) } ``` # Memory Model Non-owning. Drop the source (`Array`, `Buffer`, literal scope) and the slice becomes dangling. Slices freely copy — they're just `(ptr, len)` pairs. #### initializer From Pointer ```kestrel public init(pointer: Pointer[T], count: Int64) ``` Builds a slice from an existing pointer and element count. The caller is responsible for ensuring `count` elements live at `pointer`. #### field count ```kestrel public var count: Int64 { get } ``` Element count. #### function first ```kestrel public func first() -> Optional[T] ``` First element, or `.None` for an empty slice. #### field isEmpty ```kestrel public var isEmpty: Bool { get } ``` `true` when `count == 0`. #### function last ```kestrel public func last() -> Optional[T] ``` Last element, or `.None` for an empty slice. #### field pointer ```kestrel public var pointer: Pointer[T] { get } ``` Pointer to the first element. `pointer.offset(by: i)` reaches element `i` (0-indexed). **ArrayMatchable** #### typealias Element ```kestrel type Element = T ``` #### function matchGet ```kestrel public func matchGet(Int64) -> T ``` Compiler-driven element read; safe to skip the bounds check because the matcher emits `index < matchLength()` first. #### function matchLength ```kestrel public func matchLength() -> Int64 ``` Element count, exposed to the pattern matcher. #### function matchSlice ```kestrel public func matchSlice(Int64, Int64) -> ArraySlice[T] ``` Sub-slice for rest-pattern bindings (`..rest`). As above, the matcher guarantees `0 <= from <= to <= matchLength()`. **Slice** #### function all ```kestrel public func all(where: (T) -> Bool) -> Bool ``` `true` when every element satisfies `predicate`. O(n). Short-circuits on the first failure. Vacuously true for empty collections. # Examples ``` [2, 4, 6].all(where: { it % 2 == 0 }); // true [2, 3, 6].all(where: { it % 2 == 0 }); // false ``` #### function any ```kestrel public func any(where: (T) -> Bool) -> Bool ``` `true` when at least one element satisfies `predicate`. O(n). Short-circuits on the first match. Always `false` for empty collections. # Examples ``` [1, 2, 3].any(where: { it > 2 }); // true [1, 2, 3].any(where: { it > 5 }); // false ``` #### function asPointer ```kestrel public func asPointer() -> Pointer[T] ``` Pointer to the first element. The pointer aliases the collection's buffer; do not outlive the source or mutate through it. # Safety Reading past `count` is undefined behavior. #### function asSlice ```kestrel public func asSlice() -> ArraySlice[T] ``` Returns `self` — `ArraySlice` is already the borrowed view. #### function binarySearch ```kestrel public func binarySearch(T) -> Int64? ``` Binary search for `element`. Returns its index or `None`. O(log n). When duplicates exist, which index is returned is unspecified. # Safety The collection must be sorted in ascending order. Calling on unsorted data won't crash but may produce false negatives. # Examples ``` [1, 2, 3, 4, 5].binarySearch(3); // Some(2) [1, 2, 3, 4, 5].binarySearch(6); // None ``` #### function chunks ```kestrel public func chunks(of: Int64) -> ChunksView[T] ``` Multi-pass lazy view over non-overlapping `size`-sized chunks. The trailing chunk may be shorter than `size`. Multi-pass: query `count`, index with `view.get(i)`, and iterate repeatedly without re-creating the view. # Errors Panics if `size <= 0`. # Examples ``` let v = [1, 2, 3, 4, 5].chunks(of: 2); v.count; // 3 v.get(2); // ArraySlice[5] for c in v { ... } ``` #### function compactMap ```kestrel public func compactMap[U]((T) -> Optional[U]) -> Array[U] ``` Maps every element through `transform`, dropping `.None` results. O(n). # Examples ``` ["1", "x", "3"].compactMap { Int64.parse(it) }; // [1, 3] ``` #### function contains ```kestrel public func contains(T) -> Bool ``` `true` if the collection contains `element`. O(n). Linear scan; short-circuits on the first match. # Examples ``` [1, 2, 3].contains(2); // true [1, 2, 3].contains(5); // false ``` #### field count ```kestrel public var count: Int64 { get } ``` Element count. O(1). # Examples ``` [1, 2, 3].count; // 3 [].count; // 0 ``` #### function countItems ```kestrel public func countItems(where: (T) -> Bool) -> Int64 ``` Number of elements for which `predicate` is true. O(n). # Examples ``` [1, 2, 3, 4, 5].countItems(where: { it % 2 == 0 }); // 2 ``` #### function drop ```kestrel public func drop(first: Int64) -> ArraySlice[T] ``` Returns a slice with the first `count` elements skipped. O(1). Complement of `prefix`. # Errors Panics if `count > self.count`. # Examples ``` [1, 2, 3, 4, 5].drop(first: 2); // ArraySlice[3, 4, 5] ``` #### function ends ```kestrel public func ends[__opaque_0](with: __opaque_0) -> Bool where __opaque_0: Slice[T] ``` `true` if the trailing elements match `suffix`. O(k) where k is the suffix length. Accepts any `Slice[T]` conformer. # Examples ``` [1, 2, 3].ends(with: [2, 3]); // true [1, 2, 3].ends(with: [1, 2]); // false [1, 2, 3].ends(with: []); // true (vacuous) ``` #### function ensureUnique ```kestrel public mutating func ensureUnique() ``` No-op — `ArraySlice` is a non-owning view with no COW barrier. #### function filter ```kestrel public func filter(where: (T) -> Bool) -> Array[T] ``` Returns a new array containing every element matching `predicate`. O(n). Result size is unknown; uses geometric growth. # Examples ``` [1, 2, 3, 4].filter(where: { it % 2 == 0 }); // [2, 4] ``` #### function first ```kestrel public func first() -> T? ``` First element, or `.None` for an empty collection. O(1). Read-only — to remove the first element from an `Array`, use `popFirst()`. # Examples ``` [1, 2, 3].first(); // Some(1) [].first(); // None ``` #### function firstIndex ```kestrel public func firstIndex(where: (T) -> Bool) -> Int64? ``` Index of the first element matching `predicate`, or `None`. O(n). Short-circuits on the first match. For value-based search on `Equatable` collections, use `firstIndex(of:)`. # Examples ``` [1, 2, 3, 4, 5].firstIndex(where: { it > 3 }); // Some(3) [1, 2, 3].firstIndex(where: { it > 10 }); // None ``` #### function flatMap ```kestrel public func flatMap[U]((T) -> Array[U]) -> Array[U] ``` Maps every element through `transform` and concatenates the results into one flat array. O(n + total_output). # Examples ``` [1, 2, 3].flatMap { [it, it * 10] }; // [1, 10, 2, 20, 3, 30] ``` #### function format ```kestrel public func format(into: mutating StringBuilder, FormatOptions) ``` Renders as `"[e1, e2, ...]"`. Empty collections render as `"[]"`. # Examples ``` [1, 2, 3].format(); // "[1, 2, 3]" [].format(); // "[]" ``` #### field indices ```kestrel public var indices: Range[Int64] { get } ``` Half-open range `0.. Bool ``` Element-wise equality. O(n). Short-circuits on the first mismatch. Order matters. # Examples ``` [1, 2, 3].isEqual(to: [1, 2, 3]); // true [1, 2, 3].isEqual(to: [3, 2, 1]); // false ``` #### function isSorted ```kestrel public func isSorted() -> Bool ``` `true` if elements are in non-decreasing order. O(n). Equal adjacent elements are allowed. Empty and single-element collections are vacuously sorted. # Examples ``` [1, 2, 3].isSorted(); // true [1, 3, 2].isSorted(); // false [1, 1, 1].isSorted(); // true [].isSorted(); // true ``` #### function isValidIndex ```kestrel public func isValidIndex(Int64) -> Bool ``` `true` if `index` is in `[0, count)`. # Examples ``` [10, 20, 30].isValidIndex(2); // true [10, 20, 30].isValidIndex(3); // false [10, 20, 30].isValidIndex(-1); // false ``` #### function iter ```kestrel public func iter() -> ArraySliceIterator[T] ``` Forward iterator over the elements. # Examples ``` for item in [1, 2, 3] { ... } ``` #### function last ```kestrel public func last() -> T? ``` Last element, or `.None` for an empty collection. O(1). Read-only — to remove the last element from an `Array`, use `pop()`. # Examples ``` [1, 2, 3].last(); // Some(3) [].last(); // None ``` #### function lastIndex ```kestrel public func lastIndex(where: (T) -> Bool) -> Int64? ``` Index of the last element matching `predicate`, or `None`. O(n). Scans from the back; short-circuits on the first match. # Examples ``` [1, 2, 3, 2, 1].lastIndex(where: { it == 2 }); // Some(3) ``` #### function map ```kestrel public func map[U]((T) -> U) -> Array[U] ``` Maps every element through `transform` into a new array. O(n). Pre-sizes the result buffer to `self.count`, so no growth steps. For the lazy version that fuses into a chain, use `iter().map { ... }`. # Examples ``` [1, 2, 3].map { it * 2 }; // [2, 4, 6] [1, 2, 3].map { it.format() }; // ["1", "2", "3"] ``` #### function max ```kestrel public func max() -> T? ``` Largest element, or `None` if empty. O(n). Ties go to the first occurrence. # Examples ``` [3, 1, 4].max(); // Some(4) [].max(); // None ``` #### function min ```kestrel public func min() -> T? ``` Smallest element, or `None` if empty. O(n). Ties go to the first occurrence. # Examples ``` [3, 1, 4].min(); // Some(1) [].min(); // None ``` #### function prefix ```kestrel public func prefix(Int64) -> ArraySlice[T] ``` Returns a slice over the first `count` elements. O(1). # Errors Panics if `count > self.count`. # Examples ``` [1, 2, 3, 4, 5].prefix(3); // ArraySlice[1, 2, 3] [1, 2].prefix(0); // empty slice ``` #### function reversed ```kestrel public func reversed() -> ReversedView[T] ``` Multi-pass lazy reversed view. Iterates back-to-front and supports indexed access in O(1). # Examples ``` let v = [1, 2, 3].reversed(); v.first(); // Some(3) v.toArray(); // [3, 2, 1] — eager copy ``` #### function sorted ```kestrel public func sorted() -> Array[T] ``` Returns a new sorted array; original unchanged. O(n log n). # Examples ``` let arr = [3, 1, 4, 1, 5]; arr.sorted(); // [1, 1, 3, 4, 5] // arr is still [3, 1, 4, 1, 5] ``` #### function split ```kestrel public func split(where: (T) -> Bool) -> ArraySplitWhereView[T] ``` Multi-pass lazy view over the segments produced by splitting at each element matching `predicate`. Matching elements are dropped. # Examples ``` let v = [1, -1, 2, 3, -1, 4].split(where: { it < 0 }); for seg in v { ... } ``` #### function starts ```kestrel public func starts[__opaque_0](with: __opaque_0) -> Bool where __opaque_0: Slice[T] ``` `true` if the leading elements match `prefix`. O(k) where k is the prefix length. Accepts any `Slice[T]` conformer. # Examples ``` [1, 2, 3].starts(with: [1, 2]); // true [1, 2, 3].starts(with: [2, 3]); // false [1, 2, 3].starts(with: []); // true (vacuous) ``` #### subscript subscript ```kestrel public subscript[I](I) -> I.SeqOutput { get set } ``` #### function suffix ```kestrel public func suffix(Int64) -> ArraySlice[T] ``` Returns a slice over the last `count` elements. O(1). # Errors Panics if `count > self.count`. # Examples ``` [1, 2, 3, 4, 5].suffix(2); // ArraySlice[4, 5] ``` #### function unique ```kestrel public func unique() -> Array[T] ``` Returns a new array with duplicates removed, preserving first-occurrence order. O(n²). For the mutating variant on `Array`, see `removeDuplicates()`. # Examples ``` [1, 2, 1, 3, 2, 4].unique(); // [1, 2, 3, 4] ``` #### function windows ```kestrel public func windows(of: Int64) -> WindowsView[T] ``` Multi-pass lazy view over overlapping `size`-sized sliding windows. Adjacent windows overlap by `size - 1` elements. Empty when the source has fewer than `size` elements. # Errors Panics if `size <= 0`. # Examples ``` let v = [1, 2, 3, 4].windows(of: 2); v.count; // 3 for w in v { ... } ``` **Iterable** #### typealias Item ```kestrel type Item = T ``` #### typealias TargetIterator ```kestrel type TargetIterator = ArraySliceIterator[T] ``` #### function iter ```kestrel public func iter() -> ArraySliceIterator[T] ``` Forward iterator over the elements. **Equatable** #### typealias Output ```kestrel type Output = Bool ``` #### function equal ```kestrel public func equal(to: Self) -> Bool ``` Bridges `Equal.equal(to:)` to `Equatable.isEqual(to:)`. #### function isEqual ```kestrel func isEqual(to: Self) -> Bool ``` Returns `true` iff `self` and `other` are considered equal. Should be reflexive, symmetric, and transitive — `Hashable` requires equal values to hash equal, so don't drift from those laws. #### function notEqual ```kestrel public func notEqual(to: Self) -> Bool ``` Default `!=`: delegates to `==` so there's a single source of truth. ### struct ArraySliceIterator ```kestrel public struct ArraySliceIterator[T] { /* private fields */ } ``` Forward iterator over an `ArraySlice[T]`. Holds a moving pointer and a remaining count; advancing reads through the pointer. # Representation A `Pointer[T]` cursor and an `Int64` countdown. #### initializer From Storage ```kestrel public init(ptr: Pointer[T], remaining: Int64) ``` Builds an iterator from a starting pointer and remaining count. **Iterator** #### typealias Item ```kestrel type Item = T ``` #### typealias TargetIterator ```kestrel type TargetIterator = Self ``` #### function all ```kestrel 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) ``` #### function any ```kestrel 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 ``` #### function chain ```kestrel 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] ``` #### function collect ```kestrel 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] ``` #### function compactMap ```kestrel public func compactMap[T]() -> FilterMapIterator[Self, T] where Item == Optional[T] ``` Drops `None`s and unwraps `Some`s — 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] ``` #### function contains ```kestrel 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 ``` #### function count ```kestrel 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 ``` #### function cycle ```kestrel 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] ``` #### function enumerate ```kestrel 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}") }; ``` #### function filter ```kestrel public func filter(where: (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] ``` #### function filterMap ```kestrel public func filterMap[U](as: (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] ``` #### function first ```kestrel 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 ``` #### function firstIndex ```kestrel 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 ``` #### function flatMap ```kestrel public func flatMap[U](as: (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] ``` #### function flatten ```kestrel 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] ``` #### function fold ```kestrel 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 ``` #### function forEach ```kestrel 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) }; ``` #### function fuse ```kestrel 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. #### function inspect ```kestrel public func inspect((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(); ``` #### function intersperse ```kestrel 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] ``` #### function intersperseWith ```kestrel public func intersperseWith(with: () -> 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] ``` #### function isSorted ```kestrel 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) ``` #### function isSortedDescending ```kestrel public consuming func isSortedDescending() -> Bool ``` True if elements come out in descending order. Mirror of `isSorted`. #### function iter ```kestrel func iter() -> Self ``` Returns `self`. The blanket conformance pivot — iterators *are* iterables. #### function last ```kestrel 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. #### function map ```kestrel public func map[U](as: (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] ``` #### function max ```kestrel public consuming func max() -> Item? ``` Largest element, or `None` for an empty iterator. Ties go to the first occurrence. #### function min ```kestrel 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 ``` #### function next ```kestrel public mutating func next() -> Optional[T] ``` Yields the next element, or `.None` when the count reaches zero. #### function nth ```kestrel 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) ``` #### function peekable ```kestrel 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) ``` #### function product ```kestrel 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 ``` #### function reduce ```kestrel 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 ``` #### function scan ```kestrel public func scan[Acc](from: Acc, by: (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] ``` #### function skip ```kestrel 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(); // [] ``` #### function skipWhile ```kestrel public func skipWhile(where: (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] ``` #### function sorted ```kestrel 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] ``` #### function stepBy ```kestrel 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] ``` #### function sum ```kestrel 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 ``` #### function take ```kestrel 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] ``` #### function takeWhile ```kestrel public func takeWhile(where: (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] ``` #### function tryFold ```kestrel 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") ``` #### function tryForEach ```kestrel public mutating func tryForEach[E]((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 ``` #### function unzip ```kestrel 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"] ``` #### function zip ```kestrel 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)] ``` ### struct Buffer ```kestrel public struct Buffer[T, A] where A: Allocator { /* private fields */ } ``` Owning, allocator-parameterised contiguous storage. `Buffer` is the building block underneath `Array`, `String`, and any other COW/growable collection. It owns its allocation, deallocates on drop, and is `not Copyable` to keep ownership unique. For a non-owning view see `Slice`; for a refcounted owning wrapper see `RcBox`. # Examples ``` var buf = Buffer[Int64, SystemAllocator](capacity: 4, allocator: SystemAllocator()); buf.write(at: 0, value: 10); buf.write(at: 1, value: 20); buf.read(at: 0) // .Some(10) buf.resize(to: 8); // grow in place if possible ``` # Representation A `Pointer[T]` to the storage, an `Int64` capacity, and the allocator instance. The buffer's contents are not initialised on construction — reading an uninitialised slot is undefined behavior. # Memory Model Owning, unique. The deinit reclaims storage via the same allocator. Marked `not Copyable` so an accidental `let b2 = b1` is rejected at compile time; use a higher-level COW wrapper (e.g. via `RcBox`) for shared semantics. #### initializer With Capacity ```kestrel public init(Int64, A) ``` Allocates a buffer holding `capacity` elements. Storage is uninitialised; the caller is responsible for writing valid `T`s before reading them. # Errors Panics with `"Buffer allocation failed"` if `allocator.allocate` returns `.None`. #### function asSlice ```kestrel public func asSlice() -> ArraySlice[T] ``` Returns a `ArraySlice[T]` over the entire buffer. The slice does not extend the buffer's lifetime; callers must keep the buffer alive for as long as they use the slice. #### field capacity ```kestrel public var capacity: Int64 { get } ``` Number of element slots — not the count of *initialised* elements. #### field pointer ```kestrel public var pointer: Pointer[T] { get } ``` Pointer to the first slot. #### function read ```kestrel public func read(unchecked: Int64) -> T ``` Reads slot `index` without bounds checking. # Safety `index` must satisfy `0 <= index < capacity`, and the slot must already hold an initialised `T`. Out-of-range or uninitialised reads are undefined behavior. #### function read ```kestrel public func read(at: Int64) -> T? ``` Reads slot `index`, returning `.None` when out of range. As with the unchecked form, the slot must already hold an initialised `T`. #### function resize ```kestrel public mutating func resize(to: Int64) ``` Grows or shrinks the storage to hold `newCapacity` elements via the allocator's `reallocate`. On success, existing initialised elements are preserved up to the smaller of the two capacities; the new pointer becomes the buffer's storage. # Errors Panics with `"Buffer resize failed"` if `reallocate` returns `.None` (the original allocation is left intact, but the panic aborts). #### function slice ```kestrel public func slice(from: Int64, to: Int64) -> ArraySlice[T]? ``` Returns a slice over `[start, end)`, or `.None` when the range falls outside `[0, capacity]`. As with `asSlice`, the slice borrows from the buffer. #### function write ```kestrel public func write(unchecked: Int64, T) ``` Writes `value` into slot `index` without bounds checking. # Safety Same precondition as `read(unchecked:)` — `0 <= index < capacity`. #### function write ```kestrel public func write(at: Int64, T) -> Bool ``` Writes `value` to slot `index`. Returns `false` (and does nothing) when out of range. ### struct CowBox ```kestrel public struct CowBox[T] where T: Cloneable { /* private fields */ } ``` Copy-on-write wrapper around `RcBox[T]`. Mutable owners use `CowBox`; read-only shared owners (like `StringSlice`) hold the inner `RcBox` directly via `shareBox()`. The mutation protocol is `write()` → modify → `setValue()`. # Examples ``` var box = CowBox(MyStorage()); var s = box.write(); // COW barrier — clones if shared s.len = s.len + 1; box.setValue(s); // write back ``` # Representation A single `RcBox[T]` field. # Memory Model Same as `RcBox`: non-atomic refcount. Cloning bumps the count; `write` splits off a private copy when shared. #### initializer From Value ```kestrel public init(T) ``` Allocates fresh storage holding `value` with refcount 1. #### initializer Inner ```kestrel public init(inner: RcBox[T]) ``` Adopts an existing `RcBox` without allocating. #### function isUnique ```kestrel public func isUnique() -> Bool ``` Returns `true` when no other clone shares this storage. #### function read ```kestrel public func read() -> T ``` Read access — clones the value so the caller gets an independent copy. getValue() returns a raw bitwise copy from the heap; cloning ensures owned resources (byte buffers, etc.) are properly duplicated. #### function setValue ```kestrel public func setValue(consuming T) ``` Writes `value` into the storage in place. Only valid after a preceding `write()` call (which ensures uniqueness). Takes `value` by consuming so the drop pass sees the caller's local as moved (Dead) — prevents double-free of shared buffers. #### function shareBox ```kestrel public func shareBox() -> RcBox[T] ``` Returns a shared `RcBox` pointing at the same storage (refcount bumped). Use this to hand read-only access to types like `StringSlice`. #### function write ```kestrel public mutating func write() -> T ``` Write access — clones storage if shared, then returns the (now unique) value. Caller modifies and calls `setValue`. **Cloneable** #### function clone ```kestrel public func clone() -> CowBox[T] ``` Shares storage with the returned clone (refcount bump). ### typealias GlobalAllocator ```kestrel public type GlobalAllocator = SystemAllocator ``` Project-wide default allocator, aliased to `SystemAllocator`. Override at the project level if a global custom allocator is needed. ### struct Layout ```kestrel public struct Layout { /* private fields */ } ``` Size + alignment pair describing the memory footprint of a type. Allocators take a `Layout` rather than a raw byte count so they can honour alignment requirements (SIMD types, page-aligned buffers, etc.). The static `of[T]` and `array[T]` factories cover the common cases; `merge` and `padToAlign` exist for hand-rolled struct layouts. # Examples ``` let l = Layout.of[Int64](); // size 8, alignment 8 let buf = Layout.array[UInt8](1024); // size 1024, alignment 1 allocator.allocate(l) ``` # Representation Two `Int64`s — `size` and `alignment`. No invariants enforced at construction; misaligned layouts are caught (or undefined) at the allocator level. #### initializer From Fields ```kestrel public init(size: Int64, alignment: Int64) ``` Builds a layout from explicit `size` and `alignment`. Caller is responsible for keeping `alignment` a power of two. #### field alignment ```kestrel public var alignment: Int64 ``` Required alignment in bytes — always a power of two for layouts produced by `of`/`array`. #### function array ```kestrel public static func array[T](Int64) -> Layout ``` Layout for `count` contiguous `T` values. Inherits the element's alignment; size is `sizeof[T] * count` with no inter-element padding (T is assumed already padded to its own alignment). #### function merge ```kestrel public func merge(with: Layout) -> (Layout, Int64) ``` Concatenates `other` after `self`, mimicking how a C struct lays out its second field. Returns the combined layout and the byte offset where `other`'s storage starts (handy for building field access tables by hand). #### function of ```kestrel public static func of[T]() -> Layout ``` Layout for a single value of `T` — uses the compiler-known `sizeof` and `alignof` for the type. #### function padToAlign ```kestrel public func padToAlign() -> Layout ``` Rounds `size` up to the next multiple of `alignment`. Use when emitting a value into a packed array — without padding, element `i+1` would land at the wrong offset. #### field size ```kestrel public var size: Int64 ``` Footprint in bytes. **Equatable** #### typealias Output ```kestrel type Output = Bool ``` #### function equal ```kestrel public func equal(to: Self) -> Bool ``` Bridges `Equal.equal(to:)` to `Equatable.isEqual(to:)`. #### function isEqual ```kestrel public func isEqual(to: Layout) -> Bool ``` Equal when both fields match. #### function notEqual ```kestrel public func notEqual(to: Self) -> Bool ``` Default `!=`: delegates to `==` so there's a single source of truth. ### struct LiteralSlice ```kestrel public struct LiteralSlice[T] { /* private fields */ } ``` Read-only view over the compiler-emitted backing buffer for an array literal. User code rarely names this type directly: it appears in `ExpressibleByArrayLiteral.init(arrayLiteral:)` and friends so that types accepting `[a, b, c]` literals can iterate the elements without touching raw pointers. The slice does **not** own the storage — the compiler keeps the literal alive for the duration of the call. # Examples ``` // Conforming to ExpressibleByArrayLiteral public struct MyVec[T]: ExpressibleByArrayLiteral { type Element = T public init(arrayLiteral lit: LiteralSlice[T]) { var v = MyVec(); for x in lit { v.push(x) } self = v } } ``` # Memory Model Non-owning. The backing storage is compiler-managed and lives for the scope of the literal expression. Capturing a `LiteralSlice` past that scope is a use-after-free. #### subscript Checked Index ```kestrel public subscript(checked: Int64) -> T? { get } ``` Reads element `index`, returning `.None` on out-of-bounds. #### initializer From Storage ```kestrel public init(pointer: lang.ptr[T], count: lang.i64) ``` Builds the slice from the raw pointer and count the compiler emits. #### subscript Indexed ```kestrel public subscript(Int64) -> T { get } ``` Reads element `index`, panicking on out-of-bounds. The default subscript: trades a single comparison for a guaranteed trap on bad input. Use `(unchecked:)` inside compiler-emitted init paths where the index is statically known in range, or `(checked:)` to handle out-of-range without a panic. # Errors Panics with `"LiteralSlice index out of bounds"` if `index < 0` or `index >= count`. #### subscript Unchecked Index ```kestrel public subscript(unchecked: Int64) -> T { get } ``` Reads element `index` without bounds checking. # Safety Undefined behavior if `index < 0` or `index >= count`. Compiler- emitted init paths that use this guarantee the index is in range; do not expose this subscript to user input without checking `count` first. #### field count ```kestrel public var count: Int64 { get } ``` Number of elements in the literal. #### field isEmpty ```kestrel public var isEmpty: Bool { get } ``` `true` for `[]`. **Iterable** #### typealias Item ```kestrel type Item = T ``` #### typealias TargetIterator ```kestrel type TargetIterator = LiteralSliceIterator[T] ``` #### function iter ```kestrel public func iter() -> LiteralSliceIterator[T] ``` Iterator over the elements in source order. ### struct LiteralSliceIterator ```kestrel public struct LiteralSliceIterator[T] { /* private fields */ } ``` Iterator yielded by `LiteralSlice.iter()`. Walks the backing buffer element-by-element, advancing a typed pointer. # Representation A `Pointer[T]` plus a remaining count. No `Slice` indirection — the iterator is what `LiteralSlice` hands out instead of exposing its pointer directly. #### initializer From Storage ```kestrel public init(ptr: Pointer[T], remaining: Int64) ``` Builds an iterator from a typed pointer and element count. Not normally called by user code. **Iterator** #### typealias Item ```kestrel type Item = T ``` #### typealias TargetIterator ```kestrel type TargetIterator = Self ``` #### function all ```kestrel 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) ``` #### function any ```kestrel 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 ``` #### function chain ```kestrel 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] ``` #### function collect ```kestrel 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] ``` #### function compactMap ```kestrel public func compactMap[T]() -> FilterMapIterator[Self, T] where Item == Optional[T] ``` Drops `None`s and unwraps `Some`s — 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] ``` #### function contains ```kestrel 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 ``` #### function count ```kestrel 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 ``` #### function cycle ```kestrel 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] ``` #### function enumerate ```kestrel 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}") }; ``` #### function filter ```kestrel public func filter(where: (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] ``` #### function filterMap ```kestrel public func filterMap[U](as: (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] ``` #### function first ```kestrel 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 ``` #### function firstIndex ```kestrel 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 ``` #### function flatMap ```kestrel public func flatMap[U](as: (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] ``` #### function flatten ```kestrel 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] ``` #### function fold ```kestrel 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 ``` #### function forEach ```kestrel 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) }; ``` #### function fuse ```kestrel 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. #### function inspect ```kestrel public func inspect((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(); ``` #### function intersperse ```kestrel 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] ``` #### function intersperseWith ```kestrel public func intersperseWith(with: () -> 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] ``` #### function isSorted ```kestrel 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) ``` #### function isSortedDescending ```kestrel public consuming func isSortedDescending() -> Bool ``` True if elements come out in descending order. Mirror of `isSorted`. #### function iter ```kestrel func iter() -> Self ``` Returns `self`. The blanket conformance pivot — iterators *are* iterables. #### function last ```kestrel 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. #### function map ```kestrel public func map[U](as: (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] ``` #### function max ```kestrel public consuming func max() -> Item? ``` Largest element, or `None` for an empty iterator. Ties go to the first occurrence. #### function min ```kestrel 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 ``` #### function next ```kestrel public mutating func next() -> T? ``` Yields the next element, or `.None` once the buffer is exhausted. #### function nth ```kestrel 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) ``` #### function peekable ```kestrel 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) ``` #### function product ```kestrel 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 ``` #### function reduce ```kestrel 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 ``` #### function scan ```kestrel public func scan[Acc](from: Acc, by: (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] ``` #### function skip ```kestrel 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(); // [] ``` #### function skipWhile ```kestrel public func skipWhile(where: (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] ``` #### function sorted ```kestrel 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] ``` #### function stepBy ```kestrel 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] ``` #### function sum ```kestrel 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 ``` #### function take ```kestrel 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] ``` #### function takeWhile ```kestrel public func takeWhile(where: (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] ``` #### function tryFold ```kestrel 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") ``` #### function tryForEach ```kestrel public mutating func tryForEach[E]((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 ``` #### function unzip ```kestrel 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"] ``` #### function zip ```kestrel 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)] ``` ### struct ManuallyDrop ```kestrel public struct ManuallyDrop[T] { /* private fields */ } ``` #### initializer init ```kestrel public init(T) ``` #### field value ```kestrel public var value: T { get } ``` ### struct Pointer ```kestrel public struct Pointer[T] { /* private fields */ } ``` Typed pointer to a single value of `T`. Element-typed counterpart to `RawPointer`: `offset(by:)` strides in units of `sizeof[T]`, and `pointee` reads/writes through the address. `Pointer[T]` is FFI-safe when `T` is. # Examples ``` var x = 42; let p = Pointer(to: x); p.read() // 42 p.write(100) // x is now 100 p.pointee = 7 // x is now 7 ``` # Representation One `lang.ptr[T]`. The wrapping struct is purely a typing convenience — it lowers to a bare machine pointer. # Memory Model Non-owning. The pointee's lifetime is the caller's responsibility; the pointer does not increment any refcount, register with any GC, or trigger a deinit. #### initializer From Raw ```kestrel public init(raw: lang.ptr[T]) ``` Wraps an existing primitive pointer. #### initializer To Value ```kestrel public init(to: T) ``` Takes the address of `value`. Equivalent to `&value` in C — the caller must ensure `value` outlives any use of the resulting pointer. #### field address ```kestrel public var address: UInt64 { get } ``` Numeric address — same value as `asRaw().address`. #### function asRaw ```kestrel public func asRaw() -> RawPointer ``` Drops the type tag, returning a `RawPointer` to the same address. #### function cast ```kestrel public func cast[U]() -> Pointer[U] ``` Reinterprets the address as a `Pointer[U]`. # Safety Same caveats as `RawPointer.cast` — the storage must be valid for `U` (size, alignment, contents) at the moment of the read/write. #### function dropInPlace ```kestrel public func dropInPlace() ``` Runs T's destructor at this address without copying the value to stack. The pointer remains valid but the pointee is left in a destroyed state. #### field isNull ```kestrel public var isNull: Bool { get } ``` Convenience for `address == 0`. #### function nullPointer ```kestrel public static func nullPointer() -> Pointer[T] ``` Returns a typed null pointer. #### function offset ```kestrel public func offset(by: Int64) -> Pointer[T] ``` Strides the pointer by `n` *elements* (multiplied by `sizeof[T]`). Compare with `RawPointer.offset`, which strides by raw bytes. #### field pointee ```kestrel public var pointee: T { get set } ``` Live view of the value at the address. `get` reads through the pointer; `set` writes. Both are unchecked — see `# Safety`. # Safety The pointer must be non-null and the storage must hold a valid initialised `T`. Reading past the end of an allocation, after the pointee has been freed, or through a dangling pointer is undefined behavior. #### field raw ```kestrel public var raw: lang.ptr[T] { get } ``` The wrapped primitive pointer. #### function read ```kestrel public func read() -> T ``` Reads `T` from the address. Same safety preconditions as `pointee.get`. #### function write ```kestrel public func write(consuming T) ``` Writes `value` through the pointer. Same safety preconditions as `pointee.set`. **Equatable** #### typealias Output ```kestrel type Output = Bool ``` #### function equal ```kestrel public func equal(to: Self) -> Bool ``` Bridges `Equal.equal(to:)` to `Equatable.isEqual(to:)`. #### function isEqual ```kestrel public func isEqual(to: Pointer[T]) -> Bool ``` Address-based equality. #### function notEqual ```kestrel public func notEqual(to: Self) -> Bool ``` Default `!=`: delegates to `==` so there's a single source of truth. **Hashable** #### function hash ```kestrel public func hash[H](into: mutating H) where H: Hasher ``` Hashes the underlying address. Heap allocations cluster on alignment boundaries, so the raw address has predictable low bits. We run the address through Murmur3's `fmix64` finalizer (two rounds of `xor-shift / multiply`) before hashing so every input bit avalanches across the 64-bit output. Without this, pointer-keyed maps see collision clustering driven by the allocator's stride. ### struct RawPointer ```kestrel public struct RawPointer { /* private fields */ } ``` Untyped pointer to raw memory — `void*` in C terms. Used at FFI boundaries and as an intermediate when casting between typed pointers. `RawPointer` deliberately exposes no read/write methods of its own; cast to `Pointer[T]` first via `cast[T]()`. Equality and hashing are address-based. # Examples ``` let p = RawPointer.nullPointer(); p.isNull // true let typed: Pointer[Int64] = p.cast[Int64]() ``` # Representation One `lang.ptr[lang.i8]`. FFI-safe — passes as a single machine pointer. #### initializer From Address ```kestrel public init(address: UInt64) ``` Reconstructs a pointer from a numeric address. Useful for platform-specific encodings (handles, MMIO addresses); incorrect addresses produce a pointer that dereferences to undefined memory. #### initializer From Raw ```kestrel public init(raw: lang.ptr[lang.i8]) ``` Wraps an existing primitive pointer. #### field address ```kestrel public var address: UInt64 { get } ``` Numeric address of the pointee. Round-trips through `RawPointer(address:)`. #### function cast ```kestrel public func cast[T]() -> Pointer[T] ``` Reinterprets the address as a `Pointer[T]`. # Safety The caller must ensure the address holds a valid `T` (correct size, alignment, and initialised contents) before reading through the returned pointer. #### field isNull ```kestrel public var isNull: Bool { get } ``` Convenience for `address == 0`. #### function nullPointer ```kestrel public static func nullPointer() -> RawPointer ``` Returns the canonical null pointer. #### function offset ```kestrel public func offset(by: Int64) -> RawPointer ``` Adds `bytes` to the address (no element-size scaling — this is raw byte arithmetic). Use `Pointer[T].offset` for element-typed strides. #### field raw ```kestrel public var raw: lang.ptr[lang.i8] ``` The wrapped primitive `i8*`. **Equatable** #### typealias Output ```kestrel type Output = Bool ``` #### function equal ```kestrel public func equal(to: Self) -> Bool ``` Bridges `Equal.equal(to:)` to `Equatable.isEqual(to:)`. #### function isEqual ```kestrel public func isEqual(to: RawPointer) -> Bool ``` Address-based equality. Two `RawPointer`s pointing into different allocations are equal iff their addresses coincide. #### function notEqual ```kestrel public func notEqual(to: Self) -> Bool ``` Default `!=`: delegates to `==` so there's a single source of truth. **Hashable** #### function hash ```kestrel public func hash[H](into: mutating H) where H: Hasher ``` Hashes the underlying address. Heap allocations cluster on alignment boundaries, so the raw address has predictable low bits. We run the address through Murmur3's `fmix64` finalizer (two rounds of `xor-shift / multiply`) before hashing so every input bit avalanches across the 64-bit output. Without this, pointer-keyed maps see collision clustering driven by the allocator's stride. ### struct RcBox ```kestrel public struct RcBox[T] { /* private fields */ } ``` Heap allocation with a strong-reference count, used as the underlying storage for the stdlib's copy-on-write types. `String`, `Array`, and `Dictionary` all wrap an `RcBox` so that a plain assignment shares storage and only the first mutating call pays for a deep copy. Reach for `RcBox` directly when building a similar COW type; for plain shared ownership without mutation prefer a more purpose-built container. # Examples ``` let a = RcBox(value: [1, 2, 3]); let b = a.clone(); // shares storage; refCount == 2 if b.isUnique() { ... } else { let c = b.deepClone(); /* ... */ } ``` # Representation One `Pointer[RcBoxStorage[T]]`. The pointed-to block holds an `Int64` refcount followed by the `T` value, allocated via `SystemAllocator`. # Memory Model Reference-counted, non-atomic (today — see TODOs). `clone()` increments the count and shares storage; `deinit` decrements and frees on zero. `deepClone()` allocates a fresh `RcBox` carrying a copied value. # Guarantees - `isUnique()` returning `true` means in-place mutation is safe; this is how COW types decide whether to copy. - The refcount is currently **not** atomic, so `RcBox` is not safe to share across threads. #### initializer From Value ```kestrel public init(T) ``` Allocates fresh storage holding `value` with refcount 1. Panics if the underlying `SystemAllocator` returns `.None`. # Errors Panics with `"RcBox allocation failed"` on allocation failure. #### function deepClone ```kestrel public func deepClone() -> RcBox[T] ``` Allocates fresh storage with a copy of the value. Used by COW types when `isUnique()` returns `false` — splits off a private copy so the caller can mutate without affecting other clones. #### function getValue ```kestrel public func getValue() -> T ``` Reads the wrapped value out of storage. Returns a copy — the underlying `T` is read through a pointer, so callers see a snapshot, not a live reference. #### function isUnique ```kestrel public func isUnique() -> Bool ``` Returns `true` when no other clone is sharing storage. The litmus test for "safe to mutate in place" in COW collections. #### function refCount ```kestrel public func refCount() -> Int64 ``` Current strong reference count. Mostly useful for tests and diagnostics; production COW logic should branch on `isUnique`. #### function setValue ```kestrel public func setValue(consuming T) ``` Overwrites the wrapped value in place. Safe only when this is the unique owner (`isUnique() == true`); otherwise other clones see the new value, defeating COW. The COW types check `isUnique` before calling this and `deepClone` otherwise. Takes `value` by consuming — the caller's copy is dead after this. **Cloneable** #### function clone ```kestrel public func clone() -> RcBox[T] ``` Bumps the refcount and returns a second `RcBox` pointing at the same storage. The receiver and the returned box now both reference the value; the next mutation should test `isUnique`. ### struct SystemAllocator ```kestrel public struct SystemAllocator { /* private fields */ } ``` `Allocator` backed by libc `malloc`/`free`/`realloc`. Used as the default `GlobalAllocator` and by every collection that doesn't pick a custom allocator. # Memory Model Stateless: the struct holds no fields. All bookkeeping lives in libc's heap. Cloning or copying the allocator has no effect on the heap state. #### initializer Default ```kestrel public init() ``` Builds a stateless system allocator. No heap interaction occurs here. **Allocator** #### function allocate ```kestrel public mutating func allocate(Layout) -> RawPointer? ``` Calls `malloc(layout.size)`. Alignment beyond `malloc`'s natural alignment (typically 16) is **not** honoured — types that need larger alignment should use a different allocator. #### function deallocate ```kestrel public mutating func deallocate(RawPointer, Layout) ``` Calls `free(ptr)`. The `layout` argument is ignored — kept for protocol conformance; allocators that need it (arenas) use it. #### function reallocate ```kestrel public mutating func reallocate(RawPointer, Layout, Layout) -> RawPointer? ``` Calls `realloc(ptr, newLayout.size)`. As with `allocate`, only `malloc`-natural alignment is guaranteed. --- ## std.net.libc ### function AF_INET ```kestrel public func AF_INET() -> Int32 ``` `AF_INET` — the IPv4 address family. Pass to `socket()` as the `domain` argument when opening an IPv4 socket. The numeric value is `2` on every POSIX platform we target. ### function INADDR_ANY ```kestrel public func INADDR_ANY() -> Int32 ``` `INADDR_ANY` — wildcard IPv4 address (`0.0.0.0`). Use as the `sin_addr` field of a `sockaddr_in` to bind a server socket to every local interface. ### function IPPROTO_TCP ```kestrel public func IPPROTO_TCP() -> Int32 ``` `IPPROTO_TCP` — the TCP transport protocol number (`6`). Pass to `socket()` as the `proto` argument when opening a TCP socket. ### function SOCKADDR_IN_SIZE ```kestrel public func SOCKADDR_IN_SIZE() -> Int32 ``` Size in bytes of `struct sockaddr_in` (`16`). Pass as the `addrlen` argument to `bind()` / `connect()` / `accept()` when working with IPv4 addresses. ### function SOCK_STREAM ```kestrel public func SOCK_STREAM() -> Int32 ``` `SOCK_STREAM` — connection-oriented byte stream (TCP). Pass to `socket()` as the `type_` argument. Pair with `IPPROTO_TCP` for explicit TCP, or `0` to let the kernel pick the default protocol for the family/type pair. ### function SOL_SOCKET ```kestrel public func SOL_SOCKET() -> Int32 ``` ### function SO_REUSEADDR ```kestrel public func SO_REUSEADDR() -> Int32 ``` `SO_REUSEADDR` — allow rebinding to an address still in `TIME_WAIT`. Pass as the `optname` argument of `setsockopt()` with `SOL_SOCKET` to let a server bind to a recently-used port without waiting for the kernel's grace period. Numeric value differs across platforms. ### function accept ```kestrel public func accept(Int32, Pointer[UInt8], Pointer[Int32]) -> Int32 ``` Wraps `accept(2)` — pulls the next connection off `sockfd`'s queue. Blocks until a connection arrives. Returns the new connected fd on success, `-1` on error. Pass null pointers for `addr` and `addrlen` if you don't need the client's address. ### function bind ```kestrel public func bind(Int32, Pointer[UInt8], Int32) -> Int32 ``` Wraps `bind(2)` — assigns a local address to `sockfd`. `addr` points at a packed `sockaddr_in` (or other family- appropriate layout) of length `addrlen`. Returns `0` on success, `-1` on error. ### function close ```kestrel public func close(Int32) -> Int32 ``` Wraps `close(2)` — releases a file descriptor. Safe to call on any fd (sockets, files, pipes). Returns `0` on success, `-1` on error. After `close`, `fd` becomes available for reuse by the kernel — do not use the value again. ### function connect ```kestrel public func connect(Int32, Pointer[UInt8], Int32) -> Int32 ``` Wraps `connect(2)` — initiates a connection on `sockfd` to the address at `addr`. Blocks until the handshake completes (for connection-oriented sockets). Returns `0` on success, `-1` on error. ### function errno ```kestrel public func errno() -> Int32 ``` Returns the current value of `errno` for the calling thread. Read it immediately after a failing libc call — any subsequent syscall (including the success of an unrelated one) may overwrite it. Implementation forwards to the platform-specific accessor: `__error` on darwin, `__errno_location` on linux. ### function freeaddrinfo ```kestrel public func freeaddrinfo(Pointer[UInt8]) ``` Wraps `freeaddrinfo(3)` — frees the linked list returned by `getaddrinfo`. Walks the `ai_next` chain and frees each node along with its embedded `sockaddr` and (if present) `ai_canonname` buffer. Always pair every successful `getaddrinfo` with one `freeaddrinfo` to avoid leaking the resolver's allocation. ### function getaddrinfo ```kestrel public func getaddrinfo(Pointer[UInt8], Pointer[UInt8], Pointer[UInt8], Pointer[Pointer[UInt8]]) -> Int32 ``` Wraps `getaddrinfo(3)` — DNS / service-name resolution. Resolves `node` (hostname or numeric address) and `service` (service name or port string) to a linked list of `addrinfo` records, written through `res`. `hints` constrains the result (family, socket type, protocol). Returns `0` on success or a non-zero `EAI_*` code on failure (note: not an `errno`). The caller must free the list with `freeaddrinfo`. # `addrinfo` struct layout (macOS, 48 bytes) ``` offset 0: ai_flags (i32) offset 4: ai_family (i32) offset 8: ai_socktype (i32) offset 12: ai_protocol (i32) offset 16: ai_addrlen (u32) offset 20: padding (4 bytes on macOS, differs from Linux) offset 24: ai_canonname (ptr) offset 32: ai_addr (ptr) offset 40: ai_next (ptr) ``` ### function htons ```kestrel public func htons(UInt16) -> UInt16 ``` Wraps `htons(3)` — host-to-network byte order for 16-bit values. On little-endian hosts this swaps the byte order; on big-endian hosts it is the identity. Use to convert a port number before writing it into a `sockaddr_in.sin_port` field. ### function listen ```kestrel public func listen(Int32, Int32) -> Int32 ``` Wraps `listen(2)` — marks `sockfd` as accepting incoming connections. `backlog` is the maximum length of the kernel's pending- connection queue; once full, further connect attempts are refused. Returns `0` on success, `-1` on error. ### function recv ```kestrel public func recv(Int32, Pointer[UInt8], Int64, Int32) -> Int64 ``` Wraps `recv(2)` — reads up to `len` bytes from `sockfd` into `buf`. Returns the byte count on success (which may be less than `len`), `0` on orderly shutdown by the peer, or `-1` on error. `flags` is a bitmask of `MSG_*` modifiers (`0` for the default). ### function send ```kestrel public func send(Int32, Pointer[UInt8], Int64, Int32) -> Int64 ``` Wraps `send(2)` — writes up to `len` bytes from `buf` to `sockfd`. May write fewer bytes than requested under back-pressure; the caller must loop until the buffer is drained. Returns the byte count on success or `-1` on error. ### function setsockopt ```kestrel public func setsockopt(Int32, Int32, Int32, Pointer[UInt8], Int32) -> Int32 ``` Wraps `setsockopt(2)` — configures one option on `sockfd`. `level` selects the option layer (e.g. `SOL_SOCKET`); `optname` is the per-layer option code (e.g. `SO_REUSEADDR`); `optval` / `optlen` describe the value. Returns `0` on success, `-1` on error. ### function socket ```kestrel public func socket(Int32, Int32, Int32) -> Int32 ``` Wraps `socket(2)` — creates a new socket fd. Returns the new file descriptor on success, or `-1` on error (call `errno()` for the cause). The caller owns the fd and is responsible for closing it via `close`. # Examples ``` let fd = socket(AF_INET(), SOCK_STREAM(), IPPROTO_TCP()); if fd < 0 { /* errno() */ } ``` --- ## std.net.socket ### struct TcpListener ```kestrel public struct TcpListener { /* private fields */ } ``` A bound, listening TCP server socket. Created by `TcpListener.bind(port:)` — sets `SO_REUSEADDR`, binds to `INADDR_ANY:port`, and calls `listen(2)` with backlog `128`. Accept connections via `accept()`, which blocks until the next client arrives. The owned fd is closed by the deinit. # Examples ``` let listener = match TcpListener.bind(8080) { .Ok(l) => l, .Err(e) => return .Err(e) }; while true { match listener.accept() { .Ok(stream) => /* handle stream */ {}, .Err(e) => break } } ``` # Representation A single `Int32` field — the listening socket fd. # Memory Model Owns its fd; closed on drop. #### initializer From Fd ```kestrel init(Int32) ``` Internal — wraps an existing fd. Callers should use `bind(port:)`. #### function accept ```kestrel public func accept() -> Result[TcpStream, IoError] ``` Blocks until the next client connects, then returns it as a `TcpStream`. Discards the client's address — pass non-null pointers to `libc.accept` directly if you need it. Each accepted connection has its own fd, independent of the listener. # Errors Returns `Err(IoError.last())` if `accept(2)` fails — common causes include `EINTR` (interrupted by signal) and `EMFILE` (per-process fd limit). #### function bind ```kestrel public static func bind(UInt16) -> Result[TcpListener, IoError] ``` Creates a server socket bound to `0.0.0.0:port` with `SO_REUSEADDR` and a backlog of 128. Walks the full setup — `socket` → `setsockopt` → `bind` → `listen` — and cleans up the partial fd on any failure. # Errors Returns `Err(IoError.last())` (captured `errno`) at any of the four steps; the most common case is `EADDRINUSE` if another process holds the port and `SO_REUSEADDR` is not enough. # Examples ``` let listener = TcpListener.bind(8080); ``` #### field fd ```kestrel var fd: Int32 ``` #### function rawFd ```kestrel public func rawFd() -> Int32 ``` Returns the underlying listening fd without giving up ownership. ### struct TcpStream ```kestrel public struct TcpStream { /* private fields */ } ``` A connected TCP byte stream — implements `Readable` and `Writable` on top of a POSIX socket fd. Returned by `TcpListener.accept()` (server side) and `TcpStream.connect(host:port:)` (client side). Reads and writes go directly through `recv(2)` / `send(2)`; partial reads/writes are surfaced — the caller is responsible for looping. The owned fd is closed automatically by the deinit unless `detachFd` has been called first. # Examples ``` var stream = match TcpStream.connect("example.com", 80) { .Ok(s) => s, .Err(e) => return .Err(e) }; // stream is Readable + Writable ``` # Representation A single `Int32` field holding the file descriptor; `-1` means "detached, do not close on drop". # Memory Model Owns its fd. Cloning is not provided — duplicate explicitly via `dup(2)` if you need it. #### initializer From Fd ```kestrel public init(Int32) ``` Wraps an existing socket fd as a `TcpStream`. The stream takes ownership; the deinit will close the fd. Callers obtaining the fd from `accept` / `socket` should hand it over and stop using it directly. #### function connect ```kestrel public static func connect(String, UInt16) -> Result[TcpStream, IoError] ``` Resolves `host`:`port` and returns a connected `TcpStream`. Uses `getaddrinfo` for resolution and tries the first result. Constrained to IPv4 / TCP via the `hints` block. On any failure the partially-built fd is closed and the resolver list is freed before returning. Does not currently fall through to the next `addrinfo` entry on a failed `connect` — try one address. # Errors - Returns `Err(IoError(code: eai))` with the `EAI_*` resolver code if `getaddrinfo` fails (note: this is a libc resolver code, not an `errno`). - Returns `Err(IoError.last())` from `errno` if `socket()` or `connect()` fail. # Examples ``` match TcpStream.connect("example.com", 80) { .Ok(stream) => /* use stream */ {}, .Err(e) => print(e.message) } ``` #### function detachFd ```kestrel public mutating func detachFd() -> Int32 ``` Releases ownership of the fd and returns it. Sets the internal fd to `-1` so the deinit becomes a no-op. The caller takes responsibility for closing the returned fd. Use this when handing the fd to another owner (e.g. an event loop or a child process). #### field fd ```kestrel var fd: Int32 ``` #### function rawFd ```kestrel public func rawFd() -> Int32 ``` Returns the underlying fd without giving up ownership. Useful for passing the fd to syscalls that the wrapper does not expose (`fcntl`, `setsockopt`, …). Do not close it yourself — the deinit still will. **Readable** #### function read ```kestrel public mutating func read(into: ArraySlice[UInt8]) -> Result[Int64, IoError] ``` Reads up to `buf.count` bytes into `buf`. Returns the byte count actually read. `0` indicates the peer closed the connection cleanly. Required by the `Readable` protocol. # Errors Returns `Err(IoError)` from the captured `errno` if `recv` returns `-1`. **Writable** #### function flush ```kestrel public mutating func flush() -> Result[(), IoError] ``` No-op — TCP sockets do not have an application-level write buffer. Always returns `Ok(())`. Provided to satisfy the `Writable` protocol so generic writers can call `flush` unconditionally. #### function write ```kestrel public mutating func write(from: ArraySlice[UInt8]) -> Result[Int64, IoError] ``` Writes up to `buf.count` bytes from `buf`. Returns the byte count actually written. May write fewer bytes than requested under back-pressure; loop until the buffer is drained. Required by the `Writable` protocol. # Errors Returns `Err(IoError)` from the captured `errno` if `send` returns `-1`. --- ## std.numeric ### typealias Float ```kestrel public type Float = Float64 ``` Default floating-point type — alias for `Float64`. Reach for `Float` when you want the recommended precision/performance trade-off; reach for `Float32` only when you specifically need 32-bit storage. ### struct Float32 ```kestrel public struct Float32 { /* private fields */ } ``` A 32-bit IEEE 754 single-precision float. Range is approximately ±3.4×10^38 with 6-9 significant decimal digits. Float literals without a type annotation default to `Float64`; annotate the binding to pick `Float32`. The type is `FFISafe` and lays out as a single `lang.f32`. # Examples ``` let pi = Float64.pi; let area = pi * radius * radius; let s = area.format(.{precision: 2}); // "314.16" ``` ``` let x = 3.14; // Float64 let y: Float32 = 3.14; // Float32 ``` # Special Values - `nan` — Not-a-Number, result of `0.0 / 0.0`, `sqrt(-1)`, etc. - `infinity` / `-infinity` — overflow or `1.0 / 0.0`. - Negative zero compares equal to positive zero but produces `-infinity` when used as a divisor. NaN comparisons are surprising: `nan == nan` is false and every ordered comparison against NaN is false. Use `isNaN` to test, never `== nan`. Any arithmetic with NaN propagates NaN. # Representation A single `lang.f32` field holding the raw IEEE 754 bit pattern. #### initializer Default ```kestrel public init() ``` Creates the zero value, satisfying `Defaultable`. #### initializer Float Literal ```kestrel public init(floatLiteral: lang.f64) ``` Compiler-emitted bridge for floating-point literals via `ExpressibleByFloatLiteral`. Rarely called directly. # Examples ``` let x: Float64 = 3.14; // implicit let y = Float64(floatLiteral: 3.14); // explicit ``` #### initializer From Float ```kestrel public init(from: Float64) ``` Converts between `Float32` and `Float64`. The 32→64 direction is exact; the 64→32 direction rounds and may overflow to ±infinity. # Examples ``` let f32: Float32 = 3.14; let f64 = Float64(from: f32); ``` #### initializer From Int ```kestrel public init(from: Int64) ``` Converts an `Int64` to a float. Values with magnitude greater than 2^53 lose low-order bits. # Examples ``` let n: Int64 = 42; let f = Float64(from: n); // 42.0 ``` #### initializer From Raw ```kestrel init(raw: lang.f32) ``` Wraps an existing `lang.f32` bit pattern. Internal; used by intrinsics. #### initializer Int Literal ```kestrel public init(intLiteral: lang.i64) ``` Bridge that lets bare integer literals appear where a float is expected. Conversion is exact up to ±2^53; larger magnitudes round. # Examples ``` let x: Float64 = 42; // 42.0 let y = 3.14 + 1; // 4.14 — `1` widened to Float64 ``` #### initializer Parsing ```kestrel public init(parsing: String) ``` Parses a `Float32` from a string. Recognises decimal (`"3.14"`), scientific (`"1.5e10"`, `"2.5E-3"`), and the special tokens `"inf"`, `"-inf"`, `"+inf"`, `"infinity"`, `"nan"` (case-insensitive). Returns `null` for any other input. # Examples ``` Float32(parsing: "3.14"); // Some(3.14) Float32(parsing: "-2.5e10"); // Some(-2.5e10) Float32(parsing: "inf"); // Some(infinity) Float32(parsing: "nan"); // Some(nan) Float32(parsing: "abc"); // None Float32(parsing: ""); // None ``` #### function abs ```kestrel public func abs() -> Float32 ``` Absolute value — clears the sign bit. NaN stays NaN; `-0.0` becomes `+0.0`. #### function acos ```kestrel public func acos() -> Float32 ``` Arc cosine, result in radians on `[0, π]`. Returns NaN outside `[-1.0, 1.0]`. #### function acosh ```kestrel public func acosh() -> Float32 ``` Inverse hyperbolic cosine. Returns NaN for inputs less than `1.0`. #### function asin ```kestrel public func asin() -> Float32 ``` Arc sine, result in radians on `[-π/2, π/2]`. Returns NaN outside `[-1.0, 1.0]`. #### function asinh ```kestrel public func asinh() -> Float32 ``` Inverse hyperbolic sine. Defined on all real inputs. #### function atan ```kestrel public func atan() -> Float32 ``` Arc tangent, result in radians on `[-π/2, π/2]`. For full-quadrant recovery use `atan2`. #### function atan2 ```kestrel public func atan2(Float32) -> Float32 ``` Two-argument arctangent — angle of the point `(x, self)` measured from the positive x-axis, on `[-π, π]`. Disambiguates quadrant where `atan` cannot. # Examples ``` (1.0).atan2(1.0); // π/4 (Q1) (1.0).atan2(-1.0); // 3π/4 (Q2) (-1.0).atan2(-1.0); // -3π/4 (Q3) (-1.0).atan2(1.0); // -π/4 (Q4) ``` #### function atanh ```kestrel public func atanh() -> Float32 ``` Inverse hyperbolic tangent. NaN outside `(-1.0, 1.0)`; `±inf` at ±1. #### function cbrt ```kestrel public func cbrt() -> Float32 ``` Real cube root. Defined for negatives — `(-8.0).cbrt() == -2.0`. #### function ceil ```kestrel public func ceil() -> Float32 ``` Smallest integer ≥ `self`. Rounds toward `+infinity`. # Examples ``` (3.2).ceil(); // 4.0 (-3.7).ceil(); // -3.0 ``` #### function clamp ```kestrel public func clamp(Float32, Float32) -> Float32 ``` Clamps `self` into `[min, max]`. NaN passes through unchanged. Caller must ensure `min <= max`. # Examples ``` (0.5).clamp(0.0, 1.0); // 0.5 (-0.5).clamp(0.0, 1.0); // 0.0 (1.5).clamp(0.0, 1.0); // 1.0 ``` #### function copysign ```kestrel public func copysign(from: Float32) -> Float32 ``` Returns a value with `self`'s magnitude and `other`'s sign — i.e. an IEEE 754 `copysign`. Useful for unbiased rounding tricks. #### function cos ```kestrel public func cos() -> Float32 ``` Cosine of `self` in radians. #### function cosh ```kestrel public func cosh() -> Float32 ``` Hyperbolic cosine. #### field e ```kestrel public static var e: Float32 { get } ``` Euler's number `e` ≈ 2.71828182845904… — base of the natural logarithm. #### field epsilon ```kestrel public static var epsilon: Float32 { get } ``` Machine epsilon — the smallest `e` such that `1.0 + e != 1.0`, ≈ 1.1920929e-7. Useful as a tolerance in approximate comparisons; scale by the operand magnitude for relative-error checks. # Examples ``` func almostEqual(a: Float64, b: Float64) -> Bool { (a - b).abs() < Float64.epsilon * a.abs().max(b.abs()); } ``` #### function exp ```kestrel public func exp() -> Float32 ``` `e^self` via libm. `(-inf).exp()` is `0.0`; `(inf).exp()` is `inf`. #### function exp2 ```kestrel public func exp2() -> Float32 ``` `2^self`. Useful for binary scaling. #### function expm1 ```kestrel public func expm1() -> Float32 ``` `e^self - 1`, computed without the cancellation that hurts `self.exp() - 1.0` for small `self`. #### function floor ```kestrel public func floor() -> Float32 ``` Largest integer ≤ `self`. Rounds toward `-infinity`. # Examples ``` (3.7).floor(); // 3.0 (-3.2).floor(); // -4.0 ``` #### function fma ```kestrel public func fma(Float32, Float32) -> Float32 ``` Fused multiply-add — `(self * a) + b` with a single rounding step. More accurate (and often faster) than separate `multiply`/`add`. # Examples ``` (2.0).fma(3.0, 4.0); // 10.0 ``` #### function fract ```kestrel public func fract() -> Float32 ``` Fractional part — `self - self.trunc()`. Sign matches `self`. # Examples ``` (3.7).fract(); // 0.7 (-3.7).fract(); // -0.7 ``` #### function hypot ```kestrel public func hypot(Float32) -> Float32 ``` Hypotenuse — `sqrt(self² + other²)`, computed via libm in a way that avoids intermediate overflow when one operand is very large. # Examples ``` (3.0).hypot(4.0); // 5.0 ``` #### field infinity ```kestrel public static var infinity: Float32 { get } ``` Positive infinity. Produced by overflow or `+x / 0.0` for `x > 0`. Arithmetic with infinity follows IEEE 754: finite + infinity is infinity, infinity − infinity is NaN. # Examples ``` Float64.infinity; // inf Float64.infinity + 1; // inf 1.0 / 0.0; // inf Float64.infinity.negate(); // -inf ``` #### field isFinite ```kestrel public var isFinite: Bool { get } ``` True if `self` is finite — equivalently, not NaN and not infinite. Includes zero and subnormals. #### field isInfinite ```kestrel public var isInfinite: Bool { get } ``` True if `self` is `+infinity` or `-infinity`. # Examples ``` Float64.infinity.isInfinite; // true Float64.infinity.negate().isInfinite; // true (1.0 / 0.0).isInfinite; // true Float64.nan.isInfinite; // false ``` #### field isNaN ```kestrel public var isNaN: Bool { get } ``` True if `self` is NaN. The only correct way to test for NaN — `==` returns false against NaN even when both operands are NaN. # Examples ``` (0.0 / 0.0).isNaN; // true Float64.nan.isNaN; // true (1.0).isNaN; // false Float64.infinity.isNaN; // false ``` #### field isNegative ```kestrel public var isNegative: Bool { get } ``` True if `self < 0.0`. False for `-0.0`, `nan`, zero, and positives. To detect signed zero specifically, use `sign`. #### field isNormal ```kestrel public var isNormal: Bool { get } ``` True if `self` is a *normal* number — finite, non-zero, and at least `minPositive` in magnitude. Subnormals, zero, infinity, and NaN are not normal. # Examples ``` (1.0).isNormal; // true (0.0).isNormal; // false Float64.minPositive.isNormal; // true (Float64.minPositive / 2.0).isNormal; // false (subnormal) ``` #### field isPositive ```kestrel public var isPositive: Bool { get } ``` True if `self > 0.0`. False for `+0.0`, `-0.0`, `nan`, and negatives. #### field isSubnormal ```kestrel public var isSubnormal: Bool { get } ``` True if `self` is subnormal (denormalized) — finite, non-zero, and smaller than `minPositive` in magnitude. Subnormals trade precision for range near zero. #### field isZero ```kestrel public var isZero: Bool { get } ``` True if `self` is `+0.0` or `-0.0`. Both signed zeros compare equal. #### function lerp ```kestrel public func lerp(to: Float32, Float32) -> Float32 ``` Linear interpolation — `self + (other - self) * t`. `t == 0` returns `self`, `t == 1` returns `other`; `t` outside `[0, 1]` extrapolates. # Examples ``` (0.0).lerp(to: 10.0, 0.0); // 0.0 (0.0).lerp(to: 10.0, 0.5); // 5.0 (0.0).lerp(to: 10.0, 1.0); // 10.0 (0.0).lerp(to: 10.0, 0.25); // 2.5 ``` #### function ln ```kestrel public func ln() -> Float32 ``` Natural logarithm. Negatives return NaN; zero returns `-inf`. # Examples ``` (1.0).ln(); // 0.0 Float64.e.ln(); // 1.0 (0.0).ln(); // -inf (-1.0).ln(); // nan ``` #### field ln10 ```kestrel public static var ln10: Float32 { get } ``` Natural logarithm of 10, ≈ 2.30258509299404… #### function ln1p ```kestrel public func ln1p() -> Float32 ``` `ln(1 + self)`, accurate for small `self` where `(1.0 + self).ln()` would lose digits. #### field ln2 ```kestrel public static var ln2: Float32 { get } ``` Natural logarithm of 2, ≈ 0.69314718055994… #### function log ```kestrel public func log(Float32) -> Float32 ``` Logarithm with arbitrary base, computed as `self.ln() / base.ln()`. Pick `log2` or `log10` directly when you can — they avoid the second libm call. #### function log10 ```kestrel public func log10() -> Float32 ``` Base-10 logarithm. #### function log2 ```kestrel public func log2() -> Float32 ``` Base-2 logarithm. #### field maxValue ```kestrel public static var maxValue: Float32 { get } ``` The most positive finite value, ≈ 3.4028235e38. #### field minPositive ```kestrel public static var minPositive: Float32 { get } ``` The smallest positive *normal* value, ≈ 1.17549435e-38. Values smaller than this are subnormal and lose precision. #### field minValue ```kestrel public static var minValue: Float32 { get } ``` The most negative finite value, ≈ -3.4028235e38. #### field nan ```kestrel public static var nan: Float32 { get } ``` Not-a-Number. Produced by undefined operations like `0.0 / 0.0` or `sqrt(-1.0)`. NaN propagates through arithmetic and is unequal to every value including itself — always test with `isNaN`. # Examples ``` Float64.nan.isNaN; // true Float64.nan == Float64.nan; // false (!) 0.0 / 0.0; // nan ``` #### function nextDown ```kestrel public func nextDown() -> Float32 ``` Next representable value less than `self`. Mirror of `nextUp`. #### function nextUp ```kestrel public func nextUp() -> Float32 ``` Next representable value greater than `self`. `+inf` and `nan` are fixed points; the largest finite value steps up to `+inf`. #### field pi ```kestrel public static var pi: Float32 { get } ``` The constant π ≈ 3.14159265358979… — circle circumference over diameter. #### function pow ```kestrel public func pow(Float32) -> Float32 ``` `self ^ exponent` via libm. Negative bases with non-integer exponents return NaN. # Examples ``` (2.0).pow(10.0); // 1024.0 (2.0).pow(0.5); // sqrt(2) (-2.0).pow(0.5); // nan ``` #### function powi ```kestrel public func powi(Int64) -> Float32 ``` Integer-exponent power via repeated squaring. Faster and more accurate than `pow` when the exponent is known to be integral. Negative exponents invert. # Examples ``` (2.0).powi(10); // 1024.0 (2.0).powi(-1); // 0.5 ``` #### field raw ```kestrel public var raw: lang.f32 ``` The underlying primitive `lang.f32` value (IEEE 754 bit pattern). Exposed for FFI and intrinsic use; reach for the typed surface for everything else. #### function remainder ```kestrel public func remainder(dividingBy: Float32) -> Float32 ``` IEEE 754 remainder — uses round-to-nearest division, not truncation. Differs from `%`: `(5.0).remainder(dividingBy: 3.0)` is `-1.0`, not `2.0`. #### function round ```kestrel public func round() -> Float32 ``` Round to nearest integer, breaking ties *away from zero* (banker's rounding is not used). # Examples ``` (3.4).round(); // 3.0 (3.5).round(); // 4.0 (tie → away from zero) (-3.5).round(); // -4.0 ``` #### field sign ```kestrel public var sign: Float32 { get } ``` Sign as a float: `-1.0`, `0.0`, or `1.0`. NaN propagates as NaN. Negative zero returns `-0.0` (which still compares equal to `0.0`). # Examples ``` (-3.14).sign; // -1.0 (0.0).sign; // 0.0 (3.14).sign; // 1.0 Float64.nan.sign; // nan ``` #### function sin ```kestrel public func sin() -> Float32 ``` Sine of `self` in radians. #### function sinCos ```kestrel public func sinCos() -> (Float32, Float32) ``` Sine and cosine in one call. Implemented via two libm calls today; kept for ergonomics and as a future optimisation point. # Examples ``` let (s, c) = angle.sinCos(); ``` #### function sinh ```kestrel public func sinh() -> Float32 ``` Hyperbolic sine. #### function sqrt ```kestrel public func sqrt() -> Float32 ``` Principal square root. Negatives return NaN (`-0.0` returns `-0.0`); `+inf` returns `+inf`. # Examples ``` (4.0).sqrt(); // 2.0 (-1.0).sqrt(); // nan ``` #### field sqrt2 ```kestrel public static var sqrt2: Float32 { get } ``` Square root of 2, ≈ 1.41421356237309… #### function tan ```kestrel public func tan() -> Float32 ``` Tangent of `self` in radians. Diverges to ±large near `π/2 + kπ`. #### function tanh ```kestrel public func tanh() -> Float32 ``` Hyperbolic tangent. Saturates at ±1 for large magnitudes. #### field tau ```kestrel public static var tau: Float32 { get } ``` Tau ≈ 6.28318530717958… — equal to `2π`, often more natural for "one full turn" rotational math. #### function toFloat64 ```kestrel public func toFloat64() -> Float64 ``` Converts to the sibling float type. Widening (32→64) is exact; narrowing (64→32) rounds and may overflow to ±infinity. #### function toInt64 ```kestrel public func toInt64() -> Int64? ``` Truncates toward zero into an `Int64`. Returns `None` for NaN, infinity, or values that fall outside the `Int64` range. # Examples ``` (3.7).toInt64(); // Some(3) (-3.7).toInt64(); // Some(-3) Float64.nan.toInt64(); // None Float64.infinity.toInt64(); // None ``` #### function trunc ```kestrel public func trunc() -> Float32 ``` Integer part, truncating toward zero. `floor` for positives, `ceil` for negatives. **Comparable** #### typealias Output ```kestrel type Output = Bool ``` #### function compare ```kestrel public func compare(Float32) -> Ordering ``` Three-way comparison returning an `Ordering`. NaN is *not* an ordered value — comparisons against NaN currently fall through to `.Equal`, which is wrong; gate inputs with `isNaN` if you need a well-defined answer. # Examples ``` (1.0).compare(2.0); // .Less (2.0).compare(2.0); // .Equal (3.0).compare(2.0); // .Greater (1.0).compare(Float64.infinity); // .Less ``` #### function greaterThan ```kestrel public func greaterThan(Self) -> Bool ``` `>` derived from `compare`. #### function greaterThanOrEqual ```kestrel public func greaterThanOrEqual(Self) -> Bool ``` `>=` derived from `compare`. #### function isAtLeast ```kestrel public func isAtLeast(Self) -> Bool ``` `start..` lower-bound check, derived from `compare`. #### function isAtMost ```kestrel public func isAtMost(Self) -> Bool ``` `..=end` upper-bound check, derived from `compare`. #### function isBelow ```kestrel public func isBelow(Self) -> Bool ``` `.. Bool ``` `<` derived from `compare`. #### function lessThanOrEqual ```kestrel public func lessThanOrEqual(Self) -> Bool ``` `<=` derived from `compare`. **Equatable** #### typealias Output ```kestrel type Output = Bool ``` #### function equal ```kestrel public func equal(to: Self) -> Bool ``` Bridges `Equal.equal(to:)` to `Equatable.isEqual(to:)`. #### function isEqual ```kestrel public func isEqual(to: Float32) -> Bool ``` IEEE 754 equality. NaN is not equal to itself; `+0.0` equals `-0.0`. # Examples ``` (3.14).isEqual(to: 3.14); // true (0.0).isEqual(to: -0.0); // true Float64.nan.isEqual(to: Float64.nan); // false (!) ``` #### function notEqual ```kestrel public func notEqual(to: Self) -> Bool ``` Default `!=`: delegates to `==` so there's a single source of truth. **Formattable** #### function format ```kestrel public func format(into: mutating StringBuilder, FormatOptions) ``` Formats the float directly into `writer`, honouring the supplied `FormatOptions`. Implements `Formattable`. # Examples ``` (3.14159).format(); // "3.14159" (3.14159).format(.{precision: 2}); // "3.14" (1234.5).format(.{floatStyle: .Scientific}); // "1.2345e3" (0.756).format(.{floatStyle: .Percent}); // "75.6%" (3.14).format(.{width: 8, fill: '0'}); // "00003.14" (3.14).format(.{sign: .Always}); // "+3.14" ``` #### function formatted ```kestrel public func formatted(FormatOptions) -> String ``` Returns this value rendered as a `String`. Convenience wrapper: creates a `StringBuilder`, calls `format(into:)`, and returns the built string. Uses a distinct name to avoid overload-resolution ambiguity with `format(into:)`. **Addable** #### typealias Output ```kestrel type Output = Float32 ``` #### typealias Output ```kestrel type Output = Float32 ``` #### typealias Output ```kestrel type Output = Float32 ``` #### typealias Output ```kestrel type Output = Float32 ``` #### typealias Output ```kestrel type Output = Float32 ``` #### function add ```kestrel public consuming func add(consuming Float32) -> Float32 ``` IEEE 754 addition. NaN propagates; `inf + (-inf)` is NaN; finite + inf is inf. #### field zero ```kestrel public static var zero: Float32 { get } ``` The additive identity, `0.0`. **Subtractable** #### typealias Output ```kestrel type Output ``` #### function subtract ```kestrel public consuming func subtract(consuming Float32) -> Float32 ``` IEEE 754 subtraction. `inf - inf` is NaN; otherwise mirrors `add`. **Multipliable** #### typealias Output ```kestrel type Output ``` #### function multiply ```kestrel public consuming func multiply(consuming Float32) -> Float32 ``` IEEE 754 multiplication. NaN propagates; `inf * 0` is NaN; sign of the result follows the usual algebra. #### field one ```kestrel public static var one: Float32 { get } ``` The multiplicative identity, `1.0`. **Divisible** #### typealias Output ```kestrel type Output ``` #### function divide ```kestrel public consuming func divide(consuming Float32) -> Float32 ``` IEEE 754 division. Unlike integer divide, dividing by zero does not trap — it produces ±infinity (or NaN for `0.0 / 0.0`). Special cases: - `x / 0.0` → `+inf` if `x > 0`, `-inf` if `x < 0`, `nan` if `x == 0` - `x / inf` → 0 for finite `x` - `inf / inf` → NaN # Examples ``` (10.0).divide(4.0); // 2.5 1.0 / 0.0; // inf 0.0 / 0.0; // nan ``` **Negatable** #### typealias Output ```kestrel type Output ``` #### function negate ```kestrel public consuming func negate() -> Float32 ``` IEEE 754 negation — flips the sign bit. `-nan` is still NaN; `-(-0.0)` is `+0.0`. **ExpressibleByFloatLiteral** #### initializer Float Literal ```kestrel init(floatLiteral: lang.f64) ``` Builds an instance from a floating-point literal. **ExpressibleByIntLiteral** #### initializer Int Literal ```kestrel init(intLiteral: lang.i64) ``` Builds an instance from an integer literal. **Defaultable** #### initializer Default ```kestrel init() ``` Builds the default-valued instance. **Convertible** #### initializer From Source ```kestrel init(from: From) ``` Creates an instance from `value`. ### struct Float64 ```kestrel public struct Float64 { /* private fields */ } ``` A 64-bit IEEE 754 double-precision float. Range is approximately ±1.8×10^308 with 15-17 significant decimal digits. Float literals without a type annotation default to `Float64`; annotate the binding to pick `Float32`. The type is `FFISafe` and lays out as a single `lang.f64`. # Examples ``` let pi = Float64.pi; let area = pi * radius * radius; let s = area.format(.{precision: 2}); // "314.16" ``` ``` let x = 3.14; // Float64 let y: Float32 = 3.14; // Float32 ``` # Special Values - `nan` — Not-a-Number, result of `0.0 / 0.0`, `sqrt(-1)`, etc. - `infinity` / `-infinity` — overflow or `1.0 / 0.0`. - Negative zero compares equal to positive zero but produces `-infinity` when used as a divisor. NaN comparisons are surprising: `nan == nan` is false and every ordered comparison against NaN is false. Use `isNaN` to test, never `== nan`. Any arithmetic with NaN propagates NaN. # Representation A single `lang.f64` field holding the raw IEEE 754 bit pattern. #### initializer Default ```kestrel public init() ``` Creates the zero value, satisfying `Defaultable`. #### initializer Float Literal ```kestrel public init(floatLiteral: lang.f64) ``` Compiler-emitted bridge for floating-point literals via `ExpressibleByFloatLiteral`. Rarely called directly. # Examples ``` let x: Float64 = 3.14; // implicit let y = Float64(floatLiteral: 3.14); // explicit ``` #### initializer From Float ```kestrel public init(from: Float32) ``` Converts between `Float32` and `Float64`. The 32→64 direction is exact; the 64→32 direction rounds and may overflow to ±infinity. # Examples ``` let f32: Float32 = 3.14; let f64 = Float64(from: f32); ``` #### initializer From Int ```kestrel public init(from: Int64) ``` Converts an `Int64` to a float. Values with magnitude greater than 2^53 lose low-order bits. # Examples ``` let n: Int64 = 42; let f = Float64(from: n); // 42.0 ``` #### initializer From Raw ```kestrel init(raw: lang.f64) ``` Wraps an existing `lang.f64` bit pattern. Internal; used by intrinsics. #### initializer Int Literal ```kestrel public init(intLiteral: lang.i64) ``` Bridge that lets bare integer literals appear where a float is expected. Conversion is exact up to ±2^53; larger magnitudes round. # Examples ``` let x: Float64 = 42; // 42.0 let y = 3.14 + 1; // 4.14 — `1` widened to Float64 ``` #### initializer Parsing ```kestrel public init(parsing: String) ``` Parses a `Float64` from a string. Recognises decimal (`"3.14"`), scientific (`"1.5e10"`, `"2.5E-3"`), and the special tokens `"inf"`, `"-inf"`, `"+inf"`, `"infinity"`, `"nan"` (case-insensitive). Returns `null` for any other input. # Examples ``` Float64(parsing: "3.14"); // Some(3.14) Float64(parsing: "-2.5e10"); // Some(-2.5e10) Float64(parsing: "inf"); // Some(infinity) Float64(parsing: "nan"); // Some(nan) Float64(parsing: "abc"); // None Float64(parsing: ""); // None ``` #### function abs ```kestrel public func abs() -> Float64 ``` Absolute value — clears the sign bit. NaN stays NaN; `-0.0` becomes `+0.0`. #### function acos ```kestrel public func acos() -> Float64 ``` Arc cosine, result in radians on `[0, π]`. Returns NaN outside `[-1.0, 1.0]`. #### function acosh ```kestrel public func acosh() -> Float64 ``` Inverse hyperbolic cosine. Returns NaN for inputs less than `1.0`. #### function asin ```kestrel public func asin() -> Float64 ``` Arc sine, result in radians on `[-π/2, π/2]`. Returns NaN outside `[-1.0, 1.0]`. #### function asinh ```kestrel public func asinh() -> Float64 ``` Inverse hyperbolic sine. Defined on all real inputs. #### function atan ```kestrel public func atan() -> Float64 ``` Arc tangent, result in radians on `[-π/2, π/2]`. For full-quadrant recovery use `atan2`. #### function atan2 ```kestrel public func atan2(Float64) -> Float64 ``` Two-argument arctangent — angle of the point `(x, self)` measured from the positive x-axis, on `[-π, π]`. Disambiguates quadrant where `atan` cannot. # Examples ``` (1.0).atan2(1.0); // π/4 (Q1) (1.0).atan2(-1.0); // 3π/4 (Q2) (-1.0).atan2(-1.0); // -3π/4 (Q3) (-1.0).atan2(1.0); // -π/4 (Q4) ``` #### function atanh ```kestrel public func atanh() -> Float64 ``` Inverse hyperbolic tangent. NaN outside `(-1.0, 1.0)`; `±inf` at ±1. #### function cbrt ```kestrel public func cbrt() -> Float64 ``` Real cube root. Defined for negatives — `(-8.0).cbrt() == -2.0`. #### function ceil ```kestrel public func ceil() -> Float64 ``` Smallest integer ≥ `self`. Rounds toward `+infinity`. # Examples ``` (3.2).ceil(); // 4.0 (-3.7).ceil(); // -3.0 ``` #### function clamp ```kestrel public func clamp(Float64, Float64) -> Float64 ``` Clamps `self` into `[min, max]`. NaN passes through unchanged. Caller must ensure `min <= max`. # Examples ``` (0.5).clamp(0.0, 1.0); // 0.5 (-0.5).clamp(0.0, 1.0); // 0.0 (1.5).clamp(0.0, 1.0); // 1.0 ``` #### function copysign ```kestrel public func copysign(from: Float64) -> Float64 ``` Returns a value with `self`'s magnitude and `other`'s sign — i.e. an IEEE 754 `copysign`. Useful for unbiased rounding tricks. #### function cos ```kestrel public func cos() -> Float64 ``` Cosine of `self` in radians. #### function cosh ```kestrel public func cosh() -> Float64 ``` Hyperbolic cosine. #### field e ```kestrel public static var e: Float64 { get } ``` Euler's number `e` ≈ 2.71828182845904… — base of the natural logarithm. #### field epsilon ```kestrel public static var epsilon: Float64 { get } ``` Machine epsilon — the smallest `e` such that `1.0 + e != 1.0`, ≈ 2.220446049250313e-16. Useful as a tolerance in approximate comparisons; scale by the operand magnitude for relative-error checks. # Examples ``` func almostEqual(a: Float64, b: Float64) -> Bool { (a - b).abs() < Float64.epsilon * a.abs().max(b.abs()); } ``` #### function exp ```kestrel public func exp() -> Float64 ``` `e^self` via libm. `(-inf).exp()` is `0.0`; `(inf).exp()` is `inf`. #### function exp2 ```kestrel public func exp2() -> Float64 ``` `2^self`. Useful for binary scaling. #### function expm1 ```kestrel public func expm1() -> Float64 ``` `e^self - 1`, computed without the cancellation that hurts `self.exp() - 1.0` for small `self`. #### function floor ```kestrel public func floor() -> Float64 ``` Largest integer ≤ `self`. Rounds toward `-infinity`. # Examples ``` (3.7).floor(); // 3.0 (-3.2).floor(); // -4.0 ``` #### function fma ```kestrel public func fma(Float64, Float64) -> Float64 ``` Fused multiply-add — `(self * a) + b` with a single rounding step. More accurate (and often faster) than separate `multiply`/`add`. # Examples ``` (2.0).fma(3.0, 4.0); // 10.0 ``` #### function fract ```kestrel public func fract() -> Float64 ``` Fractional part — `self - self.trunc()`. Sign matches `self`. # Examples ``` (3.7).fract(); // 0.7 (-3.7).fract(); // -0.7 ``` #### function hypot ```kestrel public func hypot(Float64) -> Float64 ``` Hypotenuse — `sqrt(self² + other²)`, computed via libm in a way that avoids intermediate overflow when one operand is very large. # Examples ``` (3.0).hypot(4.0); // 5.0 ``` #### field infinity ```kestrel public static var infinity: Float64 { get } ``` Positive infinity. Produced by overflow or `+x / 0.0` for `x > 0`. Arithmetic with infinity follows IEEE 754: finite + infinity is infinity, infinity − infinity is NaN. # Examples ``` Float64.infinity; // inf Float64.infinity + 1; // inf 1.0 / 0.0; // inf Float64.infinity.negate(); // -inf ``` #### field isFinite ```kestrel public var isFinite: Bool { get } ``` True if `self` is finite — equivalently, not NaN and not infinite. Includes zero and subnormals. #### field isInfinite ```kestrel public var isInfinite: Bool { get } ``` True if `self` is `+infinity` or `-infinity`. # Examples ``` Float64.infinity.isInfinite; // true Float64.infinity.negate().isInfinite; // true (1.0 / 0.0).isInfinite; // true Float64.nan.isInfinite; // false ``` #### field isNaN ```kestrel public var isNaN: Bool { get } ``` True if `self` is NaN. The only correct way to test for NaN — `==` returns false against NaN even when both operands are NaN. # Examples ``` (0.0 / 0.0).isNaN; // true Float64.nan.isNaN; // true (1.0).isNaN; // false Float64.infinity.isNaN; // false ``` #### field isNegative ```kestrel public var isNegative: Bool { get } ``` True if `self < 0.0`. False for `-0.0`, `nan`, zero, and positives. To detect signed zero specifically, use `sign`. #### field isNormal ```kestrel public var isNormal: Bool { get } ``` True if `self` is a *normal* number — finite, non-zero, and at least `minPositive` in magnitude. Subnormals, zero, infinity, and NaN are not normal. # Examples ``` (1.0).isNormal; // true (0.0).isNormal; // false Float64.minPositive.isNormal; // true (Float64.minPositive / 2.0).isNormal; // false (subnormal) ``` #### field isPositive ```kestrel public var isPositive: Bool { get } ``` True if `self > 0.0`. False for `+0.0`, `-0.0`, `nan`, and negatives. #### field isSubnormal ```kestrel public var isSubnormal: Bool { get } ``` True if `self` is subnormal (denormalized) — finite, non-zero, and smaller than `minPositive` in magnitude. Subnormals trade precision for range near zero. #### field isZero ```kestrel public var isZero: Bool { get } ``` True if `self` is `+0.0` or `-0.0`. Both signed zeros compare equal. #### function lerp ```kestrel public func lerp(to: Float64, Float64) -> Float64 ``` Linear interpolation — `self + (other - self) * t`. `t == 0` returns `self`, `t == 1` returns `other`; `t` outside `[0, 1]` extrapolates. # Examples ``` (0.0).lerp(to: 10.0, 0.0); // 0.0 (0.0).lerp(to: 10.0, 0.5); // 5.0 (0.0).lerp(to: 10.0, 1.0); // 10.0 (0.0).lerp(to: 10.0, 0.25); // 2.5 ``` #### function ln ```kestrel public func ln() -> Float64 ``` Natural logarithm. Negatives return NaN; zero returns `-inf`. # Examples ``` (1.0).ln(); // 0.0 Float64.e.ln(); // 1.0 (0.0).ln(); // -inf (-1.0).ln(); // nan ``` #### field ln10 ```kestrel public static var ln10: Float64 { get } ``` Natural logarithm of 10, ≈ 2.30258509299404… #### function ln1p ```kestrel public func ln1p() -> Float64 ``` `ln(1 + self)`, accurate for small `self` where `(1.0 + self).ln()` would lose digits. #### field ln2 ```kestrel public static var ln2: Float64 { get } ``` Natural logarithm of 2, ≈ 0.69314718055994… #### function log ```kestrel public func log(Float64) -> Float64 ``` Logarithm with arbitrary base, computed as `self.ln() / base.ln()`. Pick `log2` or `log10` directly when you can — they avoid the second libm call. #### function log10 ```kestrel public func log10() -> Float64 ``` Base-10 logarithm. #### function log2 ```kestrel public func log2() -> Float64 ``` Base-2 logarithm. #### field maxValue ```kestrel public static var maxValue: Float64 { get } ``` The most positive finite value, ≈ 1.7976931348623157e308. #### field minPositive ```kestrel public static var minPositive: Float64 { get } ``` The smallest positive *normal* value, ≈ 2.2250738585072014e-308. Values smaller than this are subnormal and lose precision. #### field minValue ```kestrel public static var minValue: Float64 { get } ``` The most negative finite value, ≈ -1.7976931348623157e308. #### field nan ```kestrel public static var nan: Float64 { get } ``` Not-a-Number. Produced by undefined operations like `0.0 / 0.0` or `sqrt(-1.0)`. NaN propagates through arithmetic and is unequal to every value including itself — always test with `isNaN`. # Examples ``` Float64.nan.isNaN; // true Float64.nan == Float64.nan; // false (!) 0.0 / 0.0; // nan ``` #### function nextDown ```kestrel public func nextDown() -> Float64 ``` Next representable value less than `self`. Mirror of `nextUp`. #### function nextUp ```kestrel public func nextUp() -> Float64 ``` Next representable value greater than `self`. `+inf` and `nan` are fixed points; the largest finite value steps up to `+inf`. #### field pi ```kestrel public static var pi: Float64 { get } ``` The constant π ≈ 3.14159265358979… — circle circumference over diameter. #### function pow ```kestrel public func pow(Float64) -> Float64 ``` `self ^ exponent` via libm. Negative bases with non-integer exponents return NaN. # Examples ``` (2.0).pow(10.0); // 1024.0 (2.0).pow(0.5); // sqrt(2) (-2.0).pow(0.5); // nan ``` #### function powi ```kestrel public func powi(Int64) -> Float64 ``` Integer-exponent power via repeated squaring. Faster and more accurate than `pow` when the exponent is known to be integral. Negative exponents invert. # Examples ``` (2.0).powi(10); // 1024.0 (2.0).powi(-1); // 0.5 ``` #### field raw ```kestrel public var raw: lang.f64 ``` The underlying primitive `lang.f64` value (IEEE 754 bit pattern). Exposed for FFI and intrinsic use; reach for the typed surface for everything else. #### function remainder ```kestrel public func remainder(dividingBy: Float64) -> Float64 ``` IEEE 754 remainder — uses round-to-nearest division, not truncation. Differs from `%`: `(5.0).remainder(dividingBy: 3.0)` is `-1.0`, not `2.0`. #### function round ```kestrel public func round() -> Float64 ``` Round to nearest integer, breaking ties *away from zero* (banker's rounding is not used). # Examples ``` (3.4).round(); // 3.0 (3.5).round(); // 4.0 (tie → away from zero) (-3.5).round(); // -4.0 ``` #### field sign ```kestrel public var sign: Float64 { get } ``` Sign as a float: `-1.0`, `0.0`, or `1.0`. NaN propagates as NaN. Negative zero returns `-0.0` (which still compares equal to `0.0`). # Examples ``` (-3.14).sign; // -1.0 (0.0).sign; // 0.0 (3.14).sign; // 1.0 Float64.nan.sign; // nan ``` #### function sin ```kestrel public func sin() -> Float64 ``` Sine of `self` in radians. #### function sinCos ```kestrel public func sinCos() -> (Float64, Float64) ``` Sine and cosine in one call. Implemented via two libm calls today; kept for ergonomics and as a future optimisation point. # Examples ``` let (s, c) = angle.sinCos(); ``` #### function sinh ```kestrel public func sinh() -> Float64 ``` Hyperbolic sine. #### function sqrt ```kestrel public func sqrt() -> Float64 ``` Principal square root. Negatives return NaN (`-0.0` returns `-0.0`); `+inf` returns `+inf`. # Examples ``` (4.0).sqrt(); // 2.0 (-1.0).sqrt(); // nan ``` #### field sqrt2 ```kestrel public static var sqrt2: Float64 { get } ``` Square root of 2, ≈ 1.41421356237309… #### function tan ```kestrel public func tan() -> Float64 ``` Tangent of `self` in radians. Diverges to ±large near `π/2 + kπ`. #### function tanh ```kestrel public func tanh() -> Float64 ``` Hyperbolic tangent. Saturates at ±1 for large magnitudes. #### field tau ```kestrel public static var tau: Float64 { get } ``` Tau ≈ 6.28318530717958… — equal to `2π`, often more natural for "one full turn" rotational math. #### function toFloat32 ```kestrel public func toFloat32() -> Float32 ``` Converts to the sibling float type. Widening (32→64) is exact; narrowing (64→32) rounds and may overflow to ±infinity. #### function toInt64 ```kestrel public func toInt64() -> Int64? ``` Truncates toward zero into an `Int64`. Returns `None` for NaN, infinity, or values that fall outside the `Int64` range. # Examples ``` (3.7).toInt64(); // Some(3) (-3.7).toInt64(); // Some(-3) Float64.nan.toInt64(); // None Float64.infinity.toInt64(); // None ``` #### function trunc ```kestrel public func trunc() -> Float64 ``` Integer part, truncating toward zero. `floor` for positives, `ceil` for negatives. **Comparable** #### typealias Output ```kestrel type Output = Bool ``` #### function compare ```kestrel public func compare(Float64) -> Ordering ``` Three-way comparison returning an `Ordering`. NaN is *not* an ordered value — comparisons against NaN currently fall through to `.Equal`, which is wrong; gate inputs with `isNaN` if you need a well-defined answer. # Examples ``` (1.0).compare(2.0); // .Less (2.0).compare(2.0); // .Equal (3.0).compare(2.0); // .Greater (1.0).compare(Float64.infinity); // .Less ``` #### function greaterThan ```kestrel public func greaterThan(Self) -> Bool ``` `>` derived from `compare`. #### function greaterThanOrEqual ```kestrel public func greaterThanOrEqual(Self) -> Bool ``` `>=` derived from `compare`. #### function isAtLeast ```kestrel public func isAtLeast(Self) -> Bool ``` `start..` lower-bound check, derived from `compare`. #### function isAtMost ```kestrel public func isAtMost(Self) -> Bool ``` `..=end` upper-bound check, derived from `compare`. #### function isBelow ```kestrel public func isBelow(Self) -> Bool ``` `.. Bool ``` `<` derived from `compare`. #### function lessThanOrEqual ```kestrel public func lessThanOrEqual(Self) -> Bool ``` `<=` derived from `compare`. **Equatable** #### typealias Output ```kestrel type Output = Bool ``` #### function equal ```kestrel public func equal(to: Self) -> Bool ``` Bridges `Equal.equal(to:)` to `Equatable.isEqual(to:)`. #### function isEqual ```kestrel public func isEqual(to: Float64) -> Bool ``` IEEE 754 equality. NaN is not equal to itself; `+0.0` equals `-0.0`. # Examples ``` (3.14).isEqual(to: 3.14); // true (0.0).isEqual(to: -0.0); // true Float64.nan.isEqual(to: Float64.nan); // false (!) ``` #### function notEqual ```kestrel public func notEqual(to: Self) -> Bool ``` Default `!=`: delegates to `==` so there's a single source of truth. **Formattable** #### function format ```kestrel public func format(into: mutating StringBuilder, FormatOptions) ``` Formats the float directly into `writer`, honouring the supplied `FormatOptions`. Implements `Formattable`. # Examples ``` (3.14159).format(); // "3.14159" (3.14159).format(.{precision: 2}); // "3.14" (1234.5).format(.{floatStyle: .Scientific}); // "1.2345e3" (0.756).format(.{floatStyle: .Percent}); // "75.6%" (3.14).format(.{width: 8, fill: '0'}); // "00003.14" (3.14).format(.{sign: .Always}); // "+3.14" ``` #### function formatted ```kestrel public func formatted(FormatOptions) -> String ``` Returns this value rendered as a `String`. Convenience wrapper: creates a `StringBuilder`, calls `format(into:)`, and returns the built string. Uses a distinct name to avoid overload-resolution ambiguity with `format(into:)`. **Addable** #### typealias Output ```kestrel type Output = Float64 ``` #### typealias Output ```kestrel type Output = Float64 ``` #### typealias Output ```kestrel type Output = Float64 ``` #### typealias Output ```kestrel type Output = Float64 ``` #### typealias Output ```kestrel type Output = Float64 ``` #### function add ```kestrel public consuming func add(consuming Float64) -> Float64 ``` IEEE 754 addition. NaN propagates; `inf + (-inf)` is NaN; finite + inf is inf. #### field zero ```kestrel public static var zero: Float64 { get } ``` The additive identity, `0.0`. **Subtractable** #### typealias Output ```kestrel type Output ``` #### function subtract ```kestrel public consuming func subtract(consuming Float64) -> Float64 ``` IEEE 754 subtraction. `inf - inf` is NaN; otherwise mirrors `add`. **Multipliable** #### typealias Output ```kestrel type Output ``` #### function multiply ```kestrel public consuming func multiply(consuming Float64) -> Float64 ``` IEEE 754 multiplication. NaN propagates; `inf * 0` is NaN; sign of the result follows the usual algebra. #### field one ```kestrel public static var one: Float64 { get } ``` The multiplicative identity, `1.0`. **Divisible** #### typealias Output ```kestrel type Output ``` #### function divide ```kestrel public consuming func divide(consuming Float64) -> Float64 ``` IEEE 754 division. Unlike integer divide, dividing by zero does not trap — it produces ±infinity (or NaN for `0.0 / 0.0`). Special cases: - `x / 0.0` → `+inf` if `x > 0`, `-inf` if `x < 0`, `nan` if `x == 0` - `x / inf` → 0 for finite `x` - `inf / inf` → NaN # Examples ``` (10.0).divide(4.0); // 2.5 1.0 / 0.0; // inf 0.0 / 0.0; // nan ``` **Negatable** #### typealias Output ```kestrel type Output ``` #### function negate ```kestrel public consuming func negate() -> Float64 ``` IEEE 754 negation — flips the sign bit. `-nan` is still NaN; `-(-0.0)` is `+0.0`. **ExpressibleByFloatLiteral** #### initializer Float Literal ```kestrel init(floatLiteral: lang.f64) ``` Builds an instance from a floating-point literal. **ExpressibleByIntLiteral** #### initializer Int Literal ```kestrel init(intLiteral: lang.i64) ``` Builds an instance from an integer literal. **Defaultable** #### initializer Default ```kestrel init() ``` Builds the default-valued instance. **Convertible** #### initializer From Source ```kestrel init(from: From) ``` Creates an instance from `value`. ### typealias Int ```kestrel public type Int = Int64 ``` Platform-sized signed integer — currently always `Int64`. ### struct Int16 ```kestrel public struct Int16 { /* private fields */ } ``` A 16-bit signed integer. Int16 is the 16-bit member of the integer family. The same surface area is provided across all widths; switch widths to trade range for memory or to match an FFI ABI. Arithmetic wraps on overflow by default — use the `*Checked` variants for overflow detection or `*Saturating` to clamp to `minValue`/`maxValue`. The type is `FFISafe` and lays out as a single `lang.i16` so it can cross C boundaries unchanged. # Examples ``` let a: Int64 = 100; let b = a + 50; // 150 let c = a * 2; // 200 let d = a.addChecked(Int64.maxValue); // None (overflow detected) ``` ``` // Bit twiddling (0b1010).countOnes // 2 (1).shiftLeft(by: 4) // 16 (-1).leadingZeros // 0 (all bits set) ``` # Representation A single `lang.i16` field. No padding, no headers — bit-identical to the corresponding C type. #### initializer Default ```kestrel public init() ``` Creates the zero value, satisfying `Defaultable`. # Examples ``` let n = Int64(); // 0 ``` #### initializer From Bytes ```kestrel public init[S](fromBytes: S) where S: Slice[UInt8] ``` Reassembles a `Int16` from 2 bytes in native byte order. Returns `null` if the input is not exactly 2 bytes long. #### initializer From Bytes Big Endian ```kestrel public init[S](fromBytesBigEndian: S) where S: Slice[UInt8] ``` Reassembles a `Int16` from 2 bytes in big-endian order. Returns `null` if the input is not exactly 2 bytes long. #### initializer From Bytes Little Endian ```kestrel public init[S](fromBytesLittleEndian: S) where S: Slice[UInt8] ``` Reassembles a `Int16` from 2 bytes in little-endian order. Returns `null` if the input is not exactly 2 bytes long. #### initializer From Integer ```kestrel public init(from: Int8) ``` Converts from `Int8`. Narrowing conversions truncate the high bits; signed→unsigned reinterprets the bit pattern. #### initializer From Integer ```kestrel public init(from: Int32) ``` Converts from `Int32`. Narrowing conversions truncate the high bits; signed→unsigned reinterprets the bit pattern. #### initializer From Integer ```kestrel public init(from: Int64) ``` Converts from `Int64`. Narrowing conversions truncate the high bits; signed→unsigned reinterprets the bit pattern. #### initializer From Integer ```kestrel public init(from: UInt8) ``` Converts from `UInt8`. Narrowing conversions truncate the high bits; signed→unsigned reinterprets the bit pattern. #### initializer From Integer ```kestrel public init(from: UInt16) ``` Converts from `UInt16`. Narrowing conversions truncate the high bits; signed→unsigned reinterprets the bit pattern. #### initializer From Integer ```kestrel public init(from: UInt32) ``` Converts from `UInt32`. Narrowing conversions truncate the high bits; signed→unsigned reinterprets the bit pattern. #### initializer From Integer ```kestrel public init(from: UInt64) ``` Converts from `UInt64`. Narrowing conversions truncate the high bits; signed→unsigned reinterprets the bit pattern. #### initializer From Raw ```kestrel init(raw: lang.i16) ``` Wraps an existing `lang.i16` without conversion. Internal constructor used by intrinsics; not part of the public API. #### initializer Int Literal ```kestrel public init(intLiteral: lang.i64) ``` Compiler-emitted bridge that turns an integer literal into a Int16. You will rarely call this directly — write the literal and let the `ExpressibleByIntLiteral` protocol pick it up. For widths smaller than 64 bits the literal is truncated with `lang.cast_i64_i16`. # Examples ``` let n: Int64 = 42; // implicit ``` #### initializer Parsing ```kestrel public init(parsing: String) ``` Parses a base-10 integer literal, optionally prefixed with `+` or `-`. Returns `null` for an empty string, a non-digit character, or a value that does not fit in `Int16`. # Examples ``` Int16(parsing: "42"); // Some(42) Int16(parsing: "-7"); // Some(-7) Int16(parsing: "abc"); // None ``` #### initializer Parsing with Radix ```kestrel public init(parsing: String, radix: Int64) ``` Parses an integer in `radix` (base 2-36 inclusive). Letters a-z are case-insensitive and represent digit values 10-35. # Examples ``` Int16(parsing: "ff", radix: 16); // Some(255 if it fits, else None) Int16(parsing: "101010", radix: 2); // Some(42) Int16(parsing: "z", radix: 36); // Some(35) ``` #### function absChecked ```kestrel public func absChecked() -> Int16? ``` Absolute value that returns `None` for `minValue` (whose absolute value overflows). #### function absSaturating ```kestrel public func absSaturating() -> Int16 ``` Absolute value that returns `maxValue` instead of wrapping `minValue`. #### function addChecked ```kestrel public func addChecked(Int16) -> Int16? ``` Wrapping addition that returns `None` instead of overflowing. #### function addSaturating ```kestrel public func addSaturating(Int16) -> Int16 ``` Addition that clamps to `maxValue`/`minValue` instead of wrapping. #### field bitWidth ```kestrel public static var bitWidth: Int64 { get } ``` The width in bits (16). Useful for shift bounds and bit-walks. #### field byteSwapped ```kestrel public var byteSwapped: Int16 { get } ``` Value with its byte order reversed. Use to convert between big- and little-endian; lowered to a `bswap` intrinsic. #### function clamp ```kestrel public func clamp(Int16, Int16) -> Int16 ``` Clamps `self` into `[min, max]`. Caller is responsible for ensuring `min <= max`; otherwise the result is undefined. # Examples ``` (5).clamp(0, 10); // 5 (-5).clamp(0, 10); // 0 (15).clamp(0, 10); // 10 ``` #### field countOnes ```kestrel public var countOnes: Int64 { get } ``` Population count — the number of `1` bits in the binary representation. Lowered to a `popcount` intrinsic where the target supports it. # Examples ``` (0b1010).countOnes; // 2 (0b1111).countOnes; // 4 (0).countOnes; // 0 ``` #### field countZeros ```kestrel public var countZeros: Int64 { get } ``` Complement of `countOnes`: equal to `bitWidth - countOnes`. #### function divideChecked ```kestrel public func divideChecked(Int16) -> Int16? ``` Division that returns `None` for divide-by-zero or for the `minValue / -1` overflow case. #### function gcd ```kestrel public func gcd(Int16) -> Int16 ``` Greatest common divisor via Euclidean algorithm. For signed types the inputs are taken absolute first; the result is always non-negative. # Examples ``` (12).gcd(8); // 4 (17).gcd(5); // 1 (coprime) (-12).gcd(8); // 4 ``` #### field isNegative ```kestrel public var isNegative: Bool { get } ``` True when `self < 0`. #### field isPositive ```kestrel public var isPositive: Bool { get } ``` True when `self > 0`. #### field isPowerOfTwo ```kestrel public var isPowerOfTwo: Bool { get } ``` True when the value is a positive power of two (`2^k` for `k >= 0`). Zero and negatives are excluded. Cheap branchless test built on `x & (x - 1) == 0`. # Examples ``` (1).isPowerOfTwo; // true (2^0) (4).isPowerOfTwo; // true (2^2) (3).isPowerOfTwo; // false (0).isPowerOfTwo; // false ``` #### field isZero ```kestrel public var isZero: Bool { get } ``` True when `self == 0`. #### function lcm ```kestrel public func lcm(Int16) -> Int16 ``` Least common multiple, computed as `|self| / gcd(self, other) * |other|` to avoid intermediate overflow. Returns zero if either input is zero. # Examples ``` (4).lcm(6); // 12 (3).lcm(5); // 15 (0).lcm(7); // 0 ``` #### field leadingZeros ```kestrel public var leadingZeros: Int64 { get } ``` Number of leading zero bits, counting from the most-significant end. For zero, returns `bitWidth`. # Examples ``` (1).leadingZeros; // bitWidth - 1 (0).leadingZeros; // bitWidth ``` #### field maxValue ```kestrel public static var maxValue: Int16 { get } ``` The largest representable value. This is 2^15 - 1 (32_767). #### field minValue ```kestrel public static var minValue: Int16 { get } ``` The smallest representable value. This is -2^15 (-32_768). Note that for signed types `minValue.negate()` overflows back to itself; use `negateChecked()` if you need to detect that. #### function multiplyChecked ```kestrel public func multiplyChecked(Int16) -> Int16? ``` Wrapping multiplication that returns `None` instead of overflowing. Implemented by multiplying then dividing back; replace with an overflow-detecting intrinsic when one is available. #### function multiplySaturating ```kestrel public func multiplySaturating(Int16) -> Int16 ``` Multiplication that clamps to `maxValue`/`minValue` instead of wrapping. The clamp direction follows the algebraic sign of the would-be result. #### function negateChecked ```kestrel public func negateChecked() -> Int16? ``` Negation that returns `None` for `minValue` (whose negation overflows). #### function negateSaturating ```kestrel public func negateSaturating() -> Int16 ``` Negation that returns `maxValue` instead of wrapping `minValue`. #### function pow ```kestrel public func pow(Int64) -> Int16 ``` Raises `self` to `exponent` via binary exponentiation. Wraps on overflow. Negative exponents return zero (integer truncation of the would-be fraction). # Examples ``` (2).pow(10); // 1024 (3).pow(4); // 81 (5).pow(-1); // 0 ``` #### field raw ```kestrel public var raw: lang.i16 ``` The underlying primitive `lang.i16` value. Exposed for FFI and intrinsic use; prefer the typed surface for everything else. #### function rotateLeft ```kestrel public func rotateLeft(by: Int64) -> Int16 ``` Rotates bits left by `count`, modulo `bitWidth`. Bits shifted past the MSB re-enter at the LSB. #### function rotateRight ```kestrel public func rotateRight(by: Int64) -> Int16 ``` Rotates bits right by `count`, modulo `bitWidth`. Mirror of `rotateLeft`. #### field sign ```kestrel public var sign: Int16 { get } ``` Sign as a `Int16`: `-1`, `0`, or `1`. #### function subtractChecked ```kestrel public func subtractChecked(Int16) -> Int16? ``` Wrapping subtraction that returns `None` instead of overflowing. #### function subtractSaturating ```kestrel public func subtractSaturating(Int16) -> Int16 ``` Subtraction that clamps to `maxValue`/`minValue` instead of wrapping. #### function toBytes ```kestrel public func toBytes() -> std.collections.Array[UInt8] ``` Splits this integer into 2 bytes in *native* (host) byte order. Use `toBytesBigEndian` / `toBytesLittleEndian` when serialising for a fixed wire format. # Examples ``` let bytes = Int16.maxValue.toBytes(); // 2 bytes, host order ``` #### function toBytesBigEndian ```kestrel public func toBytesBigEndian() -> std.collections.Array[UInt8] ``` Splits this integer into 2 bytes in big-endian order (most significant byte first — i.e. network byte order). #### function toBytesLittleEndian ```kestrel public func toBytesLittleEndian() -> std.collections.Array[UInt8] ``` Splits this integer into 2 bytes in little-endian order (least significant byte first). #### field trailingZeros ```kestrel public var trailingZeros: Int64 { get } ``` Number of trailing zero bits. Equal to `log2(self & -self)` for non-zero values; returns `bitWidth` for zero. Useful for finding the largest power of two dividing the value. **SignedInteger** #### function abs ```kestrel public func abs() -> Int16 ``` Absolute value. Wraps at the minimum value (`Int16.minValue.abs() == Int16.minValue`); use `absChecked` if that's a problem. **Steppable** #### function predecessor ```kestrel public func predecessor() -> Int16 ``` Predecessor — `self - 1`. Wraps at `minValue`. #### function successor ```kestrel public func successor() -> Int16 ``` Successor — `self + 1`. Wraps at `maxValue`. Used by `for-in` over integer ranges. **Comparable** #### typealias Output ```kestrel type Output = Bool ``` #### function compare ```kestrel public func compare(Int16) -> Ordering ``` Three-way comparison returning an `Ordering`. Signed types compare using two's-complement ordering; unsigned types use natural ordering. # Examples ``` (1).compare(2); // .Less (2).compare(2); // .Equal (3).compare(2); // .Greater ``` #### function greaterThan ```kestrel public func greaterThan(Self) -> Bool ``` `>` derived from `compare`. #### function greaterThanOrEqual ```kestrel public func greaterThanOrEqual(Self) -> Bool ``` `>=` derived from `compare`. #### function isAtLeast ```kestrel public func isAtLeast(Self) -> Bool ``` `start..` lower-bound check, derived from `compare`. #### function isAtMost ```kestrel public func isAtMost(Self) -> Bool ``` `..=end` upper-bound check, derived from `compare`. #### function isBelow ```kestrel public func isBelow(Self) -> Bool ``` `.. Bool ``` `<` derived from `compare`. #### function lessThanOrEqual ```kestrel public func lessThanOrEqual(Self) -> Bool ``` `<=` derived from `compare`. **Equatable** #### typealias Output ```kestrel type Output = Bool ``` #### function equal ```kestrel public func equal(to: Self) -> Bool ``` Bridges `Equal.equal(to:)` to `Equatable.isEqual(to:)`. #### function isEqual ```kestrel public func isEqual(to: Int16) -> Bool ``` Bit-for-bit equality. Backs the `==` operator. # Examples ``` (42).isEqual(to: 42); // true 42 == 42; // true ``` #### function notEqual ```kestrel public func notEqual(to: Self) -> Bool ``` Default `!=`: delegates to `==` so there's a single source of truth. **Matchable** #### function matches ```kestrel public func matches(Int16) -> Bool ``` Pattern-matching hook for `Matchable`. Identical to `isEqual`. **Formattable** #### function format ```kestrel public func format(into: mutating StringBuilder, FormatOptions) ``` Formats the integer directly into `writer`, honouring the supplied `FormatOptions`. Implements the `Formattable` protocol. # Examples ``` (42).format(); // "42" (255).format(.{radix: 16}); // "ff" (255).format(.{radix: 16, uppercase: true}); // "FF" (255).format(.{radix: 16, alternate: true}); // "0xff" (42).format(.{radix: 2, alternate: true}); // "0b101010" (42).format(.{width: .Some(5), fill: '0'}); // "00042" (-42).format(.{sign: .Always}); // "-42" ``` #### function formatted ```kestrel public func formatted(FormatOptions) -> String ``` Returns this value rendered as a `String`. Convenience wrapper: creates a `StringBuilder`, calls `format(into:)`, and returns the built string. Uses a distinct name to avoid overload-resolution ambiguity with `format(into:)`. **Hashable** #### function hash ```kestrel public func hash[H](into: mutating H) where H: Hasher ``` Feeds the raw bytes of this value into `hasher`. Endianness-agnostic only within a single process — do not persist hashes across builds. **Addable** #### typealias Output ```kestrel type Output = Int16 ``` #### typealias Output ```kestrel type Output = Int16 ``` #### typealias Output ```kestrel type Output = Int16 ``` #### typealias Output ```kestrel type Output = Int16 ``` #### typealias Output ```kestrel type Output = Int16 ``` #### typealias Output ```kestrel type Output = Int16 ``` #### typealias Output ```kestrel type Output = Int16 ``` #### typealias Output ```kestrel type Output = Int16 ``` #### typealias Output ```kestrel type Output = Int16 ``` #### typealias Output ```kestrel type Output = Int16 ``` #### typealias Output ```kestrel type Output = Int16 ``` #### typealias Output ```kestrel type Output = Int16 ``` #### typealias Output ```kestrel type Output = Range[Int16] ``` #### typealias Output ```kestrel type Output = ClosedRange[Int16] ``` #### typealias Output ```kestrel type Output = RangeFrom[Int16] ``` #### typealias Output ```kestrel type Output = RangeUpTo[Int16] ``` #### typealias Output ```kestrel type Output = RangeThrough[Int16] ``` #### function add ```kestrel public consuming func add(consuming Int16) -> Int16 ``` `self + other`, wrapping on overflow. Use `addChecked` to detect or `addSaturating` to clamp. #### field zero ```kestrel public static var zero: Int16 { get } ``` The additive identity, `0`. **Subtractable** #### typealias Output ```kestrel type Output ``` #### function subtract ```kestrel public consuming func subtract(consuming Int16) -> Int16 ``` `self - other`, wrapping on overflow. **Multipliable** #### typealias Output ```kestrel type Output ``` #### function multiply ```kestrel public consuming func multiply(consuming Int16) -> Int16 ``` `self * other`, wrapping on overflow. #### field one ```kestrel public static var one: Int16 { get } ``` The multiplicative identity, `1`. **Divisible** #### typealias Output ```kestrel type Output ``` #### function divide ```kestrel public consuming func divide(consuming Int16) -> Int16 ``` Truncating integer division (`self / other`). For signed types, `minValue / -1` wraps; use `divideChecked` to detect. # Errors Traps on division by zero (LLVM `udiv`/`sdiv` are UB on zero — the process aborts before producing a result). **Modulo** #### typealias Output ```kestrel type Output ``` #### function modulo ```kestrel public consuming func modulo(consuming Int16) -> Int16 ``` `self % other` — truncated remainder; the result has the sign of `self` for signed types. # Errors Traps on division by zero, like `divide`. **Negatable** #### typealias Output ```kestrel type Output ``` #### function negate ```kestrel public consuming func negate() -> Int16 ``` Two's-complement negation. Wraps at the minimum value: `Int16.minValue.negate() == Int16.minValue`. Use `negateChecked` to surface the overflow. **BitwiseAnd** #### typealias Output ```kestrel type Output ``` #### function bitwiseAnd ```kestrel public consuming func bitwiseAnd(consuming Int16) -> Int16 ``` Bitwise AND. `0b1010 & 0b1100 == 0b1000`. **BitwiseOr** #### typealias Output ```kestrel type Output ``` #### function bitwiseOr ```kestrel public consuming func bitwiseOr(consuming Int16) -> Int16 ``` Bitwise OR. `0b1010 | 0b1100 == 0b1110`. **BitwiseXor** #### typealias Output ```kestrel type Output ``` #### function bitwiseXor ```kestrel public consuming func bitwiseXor(consuming Int16) -> Int16 ``` Bitwise XOR. `0b1010 ^ 0b1100 == 0b0110`. **BitwiseNot** #### typealias Output ```kestrel type Output ``` #### function bitwiseNot ```kestrel public consuming func bitwiseNot() -> Int16 ``` Bitwise NOT — flips all bits. For signed types this is `-self - 1`. **LeftShift** #### typealias Output ```kestrel type Output ``` #### function shiftLeft ```kestrel public consuming func shiftLeft(by: consuming Int64) -> Int16 ``` Left shift by `count`. Behavior is undefined when `count >= bitWidth` — pre-mask the count if you can't guarantee the bound. **RightShift** #### typealias Output ```kestrel type Output ``` #### function shiftRight ```kestrel public consuming func shiftRight(by: consuming Int64) -> Int16 ``` Right shift by `count`. Arithmetic (sign-extending) for signed types, logical (zero-filling) for unsigned. Same `count` precondition as `shiftLeft`. **AddAssign** #### function addAssign ```kestrel public mutating func addAssign(Int16) ``` `self += other` **SubtractAssign** #### function subtractAssign ```kestrel public mutating func subtractAssign(Int16) ``` `self -= other` **MultiplyAssign** #### function multiplyAssign ```kestrel public mutating func multiplyAssign(Int16) ``` `self *= other` **DivideAssign** #### function divideAssign ```kestrel public mutating func divideAssign(Int16) ``` `self /= other` **ModuloAssign** #### function modAssign ```kestrel public mutating func modAssign(Int16) ``` `self %= other` **BitwiseAndAssign** #### function bitwiseAndAssign ```kestrel public mutating func bitwiseAndAssign(Int16) ``` `self &= other` **BitwiseOrAssign** #### function bitwiseOrAssign ```kestrel public mutating func bitwiseOrAssign(Int16) ``` `self |= other` **BitwiseXorAssign** #### function bitwiseXorAssign ```kestrel public mutating func bitwiseXorAssign(Int16) ``` `self ^= other` **LeftShiftAssign** #### function shiftLeftAssign ```kestrel public mutating func shiftLeftAssign(by: Int64) ``` `self <<= count` **RightShiftAssign** #### function shiftRightAssign ```kestrel public mutating func shiftRightAssign(by: Int64) ``` `self >>= count` **ExpressibleByIntLiteral** #### initializer Int Literal ```kestrel init(intLiteral: lang.i64) ``` Builds an instance from an integer literal. **Defaultable** #### initializer Default ```kestrel init() ``` Builds the default-valued instance. **RangeConstructible** #### typealias Output ```kestrel type Output ``` #### function exclusiveRange ```kestrel public func exclusiveRange(to: Int16) -> Range[Int16] ``` Builds a half-open range `self.. ClosedRange[Int16] ``` Builds a closed range `self..=end`. Sugar for the `..=` operator. **RangeFromConstructible** #### typealias Output ```kestrel type Output ``` #### function rangeFrom ```kestrel public func rangeFrom() -> RangeFrom[Int16] ``` Builds a partial range `self..` (from self, no upper bound). **RangeUpToConstructible** #### typealias Output ```kestrel type Output ``` #### function rangeUpTo ```kestrel public func rangeUpTo() -> RangeUpTo[Int16] ``` Builds a partial range `.. RangeThrough[Int16] ``` Builds a partial range `..=self` (through self, inclusive). **Convertible** #### initializer From Source ```kestrel init(from: From) ``` Creates an instance from `value`. ### struct Int32 ```kestrel public struct Int32 { /* private fields */ } ``` A 32-bit signed integer. Int32 is the 32-bit member of the integer family. The same surface area is provided across all widths; switch widths to trade range for memory or to match an FFI ABI. Arithmetic wraps on overflow by default — use the `*Checked` variants for overflow detection or `*Saturating` to clamp to `minValue`/`maxValue`. The type is `FFISafe` and lays out as a single `lang.i32` so it can cross C boundaries unchanged. # Examples ``` let a: Int64 = 100; let b = a + 50; // 150 let c = a * 2; // 200 let d = a.addChecked(Int64.maxValue); // None (overflow detected) ``` ``` // Bit twiddling (0b1010).countOnes // 2 (1).shiftLeft(by: 4) // 16 (-1).leadingZeros // 0 (all bits set) ``` # Representation A single `lang.i32` field. No padding, no headers — bit-identical to the corresponding C type. #### initializer Default ```kestrel public init() ``` Creates the zero value, satisfying `Defaultable`. # Examples ``` let n = Int64(); // 0 ``` #### initializer From Bytes ```kestrel public init[S](fromBytes: S) where S: Slice[UInt8] ``` Reassembles a `Int32` from 4 bytes in native byte order. Returns `null` if the input is not exactly 4 bytes long. #### initializer From Bytes Big Endian ```kestrel public init[S](fromBytesBigEndian: S) where S: Slice[UInt8] ``` Reassembles a `Int32` from 4 bytes in big-endian order. Returns `null` if the input is not exactly 4 bytes long. #### initializer From Bytes Little Endian ```kestrel public init[S](fromBytesLittleEndian: S) where S: Slice[UInt8] ``` Reassembles a `Int32` from 4 bytes in little-endian order. Returns `null` if the input is not exactly 4 bytes long. #### initializer From Integer ```kestrel public init(from: Int8) ``` Converts from `Int8`. Narrowing conversions truncate the high bits; signed→unsigned reinterprets the bit pattern. #### initializer From Integer ```kestrel public init(from: Int16) ``` Converts from `Int16`. Narrowing conversions truncate the high bits; signed→unsigned reinterprets the bit pattern. #### initializer From Integer ```kestrel public init(from: Int64) ``` Converts from `Int64`. Narrowing conversions truncate the high bits; signed→unsigned reinterprets the bit pattern. #### initializer From Integer ```kestrel public init(from: UInt8) ``` Converts from `UInt8`. Narrowing conversions truncate the high bits; signed→unsigned reinterprets the bit pattern. #### initializer From Integer ```kestrel public init(from: UInt16) ``` Converts from `UInt16`. Narrowing conversions truncate the high bits; signed→unsigned reinterprets the bit pattern. #### initializer From Integer ```kestrel public init(from: UInt32) ``` Converts from `UInt32`. Narrowing conversions truncate the high bits; signed→unsigned reinterprets the bit pattern. #### initializer From Integer ```kestrel public init(from: UInt64) ``` Converts from `UInt64`. Narrowing conversions truncate the high bits; signed→unsigned reinterprets the bit pattern. #### initializer From Raw ```kestrel init(raw: lang.i32) ``` Wraps an existing `lang.i32` without conversion. Internal constructor used by intrinsics; not part of the public API. #### initializer Int Literal ```kestrel public init(intLiteral: lang.i64) ``` Compiler-emitted bridge that turns an integer literal into a Int32. You will rarely call this directly — write the literal and let the `ExpressibleByIntLiteral` protocol pick it up. For widths smaller than 64 bits the literal is truncated with `lang.cast_i64_i32`. # Examples ``` let n: Int64 = 42; // implicit ``` #### initializer Parsing ```kestrel public init(parsing: String) ``` Parses a base-10 integer literal, optionally prefixed with `+` or `-`. Returns `null` for an empty string, a non-digit character, or a value that does not fit in `Int32`. # Examples ``` Int32(parsing: "42"); // Some(42) Int32(parsing: "-7"); // Some(-7) Int32(parsing: "abc"); // None ``` #### initializer Parsing with Radix ```kestrel public init(parsing: String, radix: Int64) ``` Parses an integer in `radix` (base 2-36 inclusive). Letters a-z are case-insensitive and represent digit values 10-35. # Examples ``` Int32(parsing: "ff", radix: 16); // Some(255 if it fits, else None) Int32(parsing: "101010", radix: 2); // Some(42) Int32(parsing: "z", radix: 36); // Some(35) ``` #### function absChecked ```kestrel public func absChecked() -> Int32? ``` Absolute value that returns `None` for `minValue` (whose absolute value overflows). #### function absSaturating ```kestrel public func absSaturating() -> Int32 ``` Absolute value that returns `maxValue` instead of wrapping `minValue`. #### function addChecked ```kestrel public func addChecked(Int32) -> Int32? ``` Wrapping addition that returns `None` instead of overflowing. #### function addSaturating ```kestrel public func addSaturating(Int32) -> Int32 ``` Addition that clamps to `maxValue`/`minValue` instead of wrapping. #### field bitWidth ```kestrel public static var bitWidth: Int64 { get } ``` The width in bits (32). Useful for shift bounds and bit-walks. #### field byteSwapped ```kestrel public var byteSwapped: Int32 { get } ``` Value with its byte order reversed. Use to convert between big- and little-endian; lowered to a `bswap` intrinsic. #### function clamp ```kestrel public func clamp(Int32, Int32) -> Int32 ``` Clamps `self` into `[min, max]`. Caller is responsible for ensuring `min <= max`; otherwise the result is undefined. # Examples ``` (5).clamp(0, 10); // 5 (-5).clamp(0, 10); // 0 (15).clamp(0, 10); // 10 ``` #### field countOnes ```kestrel public var countOnes: Int64 { get } ``` Population count — the number of `1` bits in the binary representation. Lowered to a `popcount` intrinsic where the target supports it. # Examples ``` (0b1010).countOnes; // 2 (0b1111).countOnes; // 4 (0).countOnes; // 0 ``` #### field countZeros ```kestrel public var countZeros: Int64 { get } ``` Complement of `countOnes`: equal to `bitWidth - countOnes`. #### function divideChecked ```kestrel public func divideChecked(Int32) -> Int32? ``` Division that returns `None` for divide-by-zero or for the `minValue / -1` overflow case. #### function gcd ```kestrel public func gcd(Int32) -> Int32 ``` Greatest common divisor via Euclidean algorithm. For signed types the inputs are taken absolute first; the result is always non-negative. # Examples ``` (12).gcd(8); // 4 (17).gcd(5); // 1 (coprime) (-12).gcd(8); // 4 ``` #### field isNegative ```kestrel public var isNegative: Bool { get } ``` True when `self < 0`. #### field isPositive ```kestrel public var isPositive: Bool { get } ``` True when `self > 0`. #### field isPowerOfTwo ```kestrel public var isPowerOfTwo: Bool { get } ``` True when the value is a positive power of two (`2^k` for `k >= 0`). Zero and negatives are excluded. Cheap branchless test built on `x & (x - 1) == 0`. # Examples ``` (1).isPowerOfTwo; // true (2^0) (4).isPowerOfTwo; // true (2^2) (3).isPowerOfTwo; // false (0).isPowerOfTwo; // false ``` #### field isZero ```kestrel public var isZero: Bool { get } ``` True when `self == 0`. #### function lcm ```kestrel public func lcm(Int32) -> Int32 ``` Least common multiple, computed as `|self| / gcd(self, other) * |other|` to avoid intermediate overflow. Returns zero if either input is zero. # Examples ``` (4).lcm(6); // 12 (3).lcm(5); // 15 (0).lcm(7); // 0 ``` #### field leadingZeros ```kestrel public var leadingZeros: Int64 { get } ``` Number of leading zero bits, counting from the most-significant end. For zero, returns `bitWidth`. # Examples ``` (1).leadingZeros; // bitWidth - 1 (0).leadingZeros; // bitWidth ``` #### field maxValue ```kestrel public static var maxValue: Int32 { get } ``` The largest representable value. This is 2^31 - 1 (2_147_483_647). #### field minValue ```kestrel public static var minValue: Int32 { get } ``` The smallest representable value. This is -2^31 (-2_147_483_648). Note that for signed types `minValue.negate()` overflows back to itself; use `negateChecked()` if you need to detect that. #### function multiplyChecked ```kestrel public func multiplyChecked(Int32) -> Int32? ``` Wrapping multiplication that returns `None` instead of overflowing. Implemented by multiplying then dividing back; replace with an overflow-detecting intrinsic when one is available. #### function multiplySaturating ```kestrel public func multiplySaturating(Int32) -> Int32 ``` Multiplication that clamps to `maxValue`/`minValue` instead of wrapping. The clamp direction follows the algebraic sign of the would-be result. #### function negateChecked ```kestrel public func negateChecked() -> Int32? ``` Negation that returns `None` for `minValue` (whose negation overflows). #### function negateSaturating ```kestrel public func negateSaturating() -> Int32 ``` Negation that returns `maxValue` instead of wrapping `minValue`. #### function pow ```kestrel public func pow(Int64) -> Int32 ``` Raises `self` to `exponent` via binary exponentiation. Wraps on overflow. Negative exponents return zero (integer truncation of the would-be fraction). # Examples ``` (2).pow(10); // 1024 (3).pow(4); // 81 (5).pow(-1); // 0 ``` #### field raw ```kestrel public var raw: lang.i32 ``` The underlying primitive `lang.i32` value. Exposed for FFI and intrinsic use; prefer the typed surface for everything else. #### function rotateLeft ```kestrel public func rotateLeft(by: Int64) -> Int32 ``` Rotates bits left by `count`, modulo `bitWidth`. Bits shifted past the MSB re-enter at the LSB. #### function rotateRight ```kestrel public func rotateRight(by: Int64) -> Int32 ``` Rotates bits right by `count`, modulo `bitWidth`. Mirror of `rotateLeft`. #### field sign ```kestrel public var sign: Int32 { get } ``` Sign as a `Int32`: `-1`, `0`, or `1`. #### function subtractChecked ```kestrel public func subtractChecked(Int32) -> Int32? ``` Wrapping subtraction that returns `None` instead of overflowing. #### function subtractSaturating ```kestrel public func subtractSaturating(Int32) -> Int32 ``` Subtraction that clamps to `maxValue`/`minValue` instead of wrapping. #### function toBytes ```kestrel public func toBytes() -> std.collections.Array[UInt8] ``` Splits this integer into 4 bytes in *native* (host) byte order. Use `toBytesBigEndian` / `toBytesLittleEndian` when serialising for a fixed wire format. # Examples ``` let bytes = Int32.maxValue.toBytes(); // 4 bytes, host order ``` #### function toBytesBigEndian ```kestrel public func toBytesBigEndian() -> std.collections.Array[UInt8] ``` Splits this integer into 4 bytes in big-endian order (most significant byte first — i.e. network byte order). #### function toBytesLittleEndian ```kestrel public func toBytesLittleEndian() -> std.collections.Array[UInt8] ``` Splits this integer into 4 bytes in little-endian order (least significant byte first). #### field trailingZeros ```kestrel public var trailingZeros: Int64 { get } ``` Number of trailing zero bits. Equal to `log2(self & -self)` for non-zero values; returns `bitWidth` for zero. Useful for finding the largest power of two dividing the value. **SignedInteger** #### function abs ```kestrel public func abs() -> Int32 ``` Absolute value. Wraps at the minimum value (`Int32.minValue.abs() == Int32.minValue`); use `absChecked` if that's a problem. **Steppable** #### function predecessor ```kestrel public func predecessor() -> Int32 ``` Predecessor — `self - 1`. Wraps at `minValue`. #### function successor ```kestrel public func successor() -> Int32 ``` Successor — `self + 1`. Wraps at `maxValue`. Used by `for-in` over integer ranges. **Comparable** #### typealias Output ```kestrel type Output = Bool ``` #### function compare ```kestrel public func compare(Int32) -> Ordering ``` Three-way comparison returning an `Ordering`. Signed types compare using two's-complement ordering; unsigned types use natural ordering. # Examples ``` (1).compare(2); // .Less (2).compare(2); // .Equal (3).compare(2); // .Greater ``` #### function greaterThan ```kestrel public func greaterThan(Self) -> Bool ``` `>` derived from `compare`. #### function greaterThanOrEqual ```kestrel public func greaterThanOrEqual(Self) -> Bool ``` `>=` derived from `compare`. #### function isAtLeast ```kestrel public func isAtLeast(Self) -> Bool ``` `start..` lower-bound check, derived from `compare`. #### function isAtMost ```kestrel public func isAtMost(Self) -> Bool ``` `..=end` upper-bound check, derived from `compare`. #### function isBelow ```kestrel public func isBelow(Self) -> Bool ``` `.. Bool ``` `<` derived from `compare`. #### function lessThanOrEqual ```kestrel public func lessThanOrEqual(Self) -> Bool ``` `<=` derived from `compare`. **Equatable** #### typealias Output ```kestrel type Output = Bool ``` #### function equal ```kestrel public func equal(to: Self) -> Bool ``` Bridges `Equal.equal(to:)` to `Equatable.isEqual(to:)`. #### function isEqual ```kestrel public func isEqual(to: Int32) -> Bool ``` Bit-for-bit equality. Backs the `==` operator. # Examples ``` (42).isEqual(to: 42); // true 42 == 42; // true ``` #### function notEqual ```kestrel public func notEqual(to: Self) -> Bool ``` Default `!=`: delegates to `==` so there's a single source of truth. **Matchable** #### function matches ```kestrel public func matches(Int32) -> Bool ``` Pattern-matching hook for `Matchable`. Identical to `isEqual`. **Formattable** #### function format ```kestrel public func format(into: mutating StringBuilder, FormatOptions) ``` Formats the integer directly into `writer`, honouring the supplied `FormatOptions`. Implements the `Formattable` protocol. # Examples ``` (42).format(); // "42" (255).format(.{radix: 16}); // "ff" (255).format(.{radix: 16, uppercase: true}); // "FF" (255).format(.{radix: 16, alternate: true}); // "0xff" (42).format(.{radix: 2, alternate: true}); // "0b101010" (42).format(.{width: .Some(5), fill: '0'}); // "00042" (-42).format(.{sign: .Always}); // "-42" ``` #### function formatted ```kestrel public func formatted(FormatOptions) -> String ``` Returns this value rendered as a `String`. Convenience wrapper: creates a `StringBuilder`, calls `format(into:)`, and returns the built string. Uses a distinct name to avoid overload-resolution ambiguity with `format(into:)`. **Hashable** #### function hash ```kestrel public func hash[H](into: mutating H) where H: Hasher ``` Feeds the raw bytes of this value into `hasher`. Endianness-agnostic only within a single process — do not persist hashes across builds. **Addable** #### typealias Output ```kestrel type Output = Int32 ``` #### typealias Output ```kestrel type Output = Int32 ``` #### typealias Output ```kestrel type Output = Int32 ``` #### typealias Output ```kestrel type Output = Int32 ``` #### typealias Output ```kestrel type Output = Int32 ``` #### typealias Output ```kestrel type Output = Int32 ``` #### typealias Output ```kestrel type Output = Int32 ``` #### typealias Output ```kestrel type Output = Int32 ``` #### typealias Output ```kestrel type Output = Int32 ``` #### typealias Output ```kestrel type Output = Int32 ``` #### typealias Output ```kestrel type Output = Int32 ``` #### typealias Output ```kestrel type Output = Int32 ``` #### typealias Output ```kestrel type Output = Range[Int32] ``` #### typealias Output ```kestrel type Output = ClosedRange[Int32] ``` #### typealias Output ```kestrel type Output = RangeFrom[Int32] ``` #### typealias Output ```kestrel type Output = RangeUpTo[Int32] ``` #### typealias Output ```kestrel type Output = RangeThrough[Int32] ``` #### function add ```kestrel public consuming func add(consuming Int32) -> Int32 ``` `self + other`, wrapping on overflow. Use `addChecked` to detect or `addSaturating` to clamp. #### field zero ```kestrel public static var zero: Int32 { get } ``` The additive identity, `0`. **Subtractable** #### typealias Output ```kestrel type Output ``` #### function subtract ```kestrel public consuming func subtract(consuming Int32) -> Int32 ``` `self - other`, wrapping on overflow. **Multipliable** #### typealias Output ```kestrel type Output ``` #### function multiply ```kestrel public consuming func multiply(consuming Int32) -> Int32 ``` `self * other`, wrapping on overflow. #### field one ```kestrel public static var one: Int32 { get } ``` The multiplicative identity, `1`. **Divisible** #### typealias Output ```kestrel type Output ``` #### function divide ```kestrel public consuming func divide(consuming Int32) -> Int32 ``` Truncating integer division (`self / other`). For signed types, `minValue / -1` wraps; use `divideChecked` to detect. # Errors Traps on division by zero (LLVM `udiv`/`sdiv` are UB on zero — the process aborts before producing a result). **Modulo** #### typealias Output ```kestrel type Output ``` #### function modulo ```kestrel public consuming func modulo(consuming Int32) -> Int32 ``` `self % other` — truncated remainder; the result has the sign of `self` for signed types. # Errors Traps on division by zero, like `divide`. **Negatable** #### typealias Output ```kestrel type Output ``` #### function negate ```kestrel public consuming func negate() -> Int32 ``` Two's-complement negation. Wraps at the minimum value: `Int32.minValue.negate() == Int32.minValue`. Use `negateChecked` to surface the overflow. **BitwiseAnd** #### typealias Output ```kestrel type Output ``` #### function bitwiseAnd ```kestrel public consuming func bitwiseAnd(consuming Int32) -> Int32 ``` Bitwise AND. `0b1010 & 0b1100 == 0b1000`. **BitwiseOr** #### typealias Output ```kestrel type Output ``` #### function bitwiseOr ```kestrel public consuming func bitwiseOr(consuming Int32) -> Int32 ``` Bitwise OR. `0b1010 | 0b1100 == 0b1110`. **BitwiseXor** #### typealias Output ```kestrel type Output ``` #### function bitwiseXor ```kestrel public consuming func bitwiseXor(consuming Int32) -> Int32 ``` Bitwise XOR. `0b1010 ^ 0b1100 == 0b0110`. **BitwiseNot** #### typealias Output ```kestrel type Output ``` #### function bitwiseNot ```kestrel public consuming func bitwiseNot() -> Int32 ``` Bitwise NOT — flips all bits. For signed types this is `-self - 1`. **LeftShift** #### typealias Output ```kestrel type Output ``` #### function shiftLeft ```kestrel public consuming func shiftLeft(by: consuming Int64) -> Int32 ``` Left shift by `count`. Behavior is undefined when `count >= bitWidth` — pre-mask the count if you can't guarantee the bound. **RightShift** #### typealias Output ```kestrel type Output ``` #### function shiftRight ```kestrel public consuming func shiftRight(by: consuming Int64) -> Int32 ``` Right shift by `count`. Arithmetic (sign-extending) for signed types, logical (zero-filling) for unsigned. Same `count` precondition as `shiftLeft`. **AddAssign** #### function addAssign ```kestrel public mutating func addAssign(Int32) ``` `self += other` **SubtractAssign** #### function subtractAssign ```kestrel public mutating func subtractAssign(Int32) ``` `self -= other` **MultiplyAssign** #### function multiplyAssign ```kestrel public mutating func multiplyAssign(Int32) ``` `self *= other` **DivideAssign** #### function divideAssign ```kestrel public mutating func divideAssign(Int32) ``` `self /= other` **ModuloAssign** #### function modAssign ```kestrel public mutating func modAssign(Int32) ``` `self %= other` **BitwiseAndAssign** #### function bitwiseAndAssign ```kestrel public mutating func bitwiseAndAssign(Int32) ``` `self &= other` **BitwiseOrAssign** #### function bitwiseOrAssign ```kestrel public mutating func bitwiseOrAssign(Int32) ``` `self |= other` **BitwiseXorAssign** #### function bitwiseXorAssign ```kestrel public mutating func bitwiseXorAssign(Int32) ``` `self ^= other` **LeftShiftAssign** #### function shiftLeftAssign ```kestrel public mutating func shiftLeftAssign(by: Int64) ``` `self <<= count` **RightShiftAssign** #### function shiftRightAssign ```kestrel public mutating func shiftRightAssign(by: Int64) ``` `self >>= count` **ExpressibleByIntLiteral** #### initializer Int Literal ```kestrel init(intLiteral: lang.i64) ``` Builds an instance from an integer literal. **Defaultable** #### initializer Default ```kestrel init() ``` Builds the default-valued instance. **RangeConstructible** #### typealias Output ```kestrel type Output ``` #### function exclusiveRange ```kestrel public func exclusiveRange(to: Int32) -> Range[Int32] ``` Builds a half-open range `self.. ClosedRange[Int32] ``` Builds a closed range `self..=end`. Sugar for the `..=` operator. **RangeFromConstructible** #### typealias Output ```kestrel type Output ``` #### function rangeFrom ```kestrel public func rangeFrom() -> RangeFrom[Int32] ``` Builds a partial range `self..` (from self, no upper bound). **RangeUpToConstructible** #### typealias Output ```kestrel type Output ``` #### function rangeUpTo ```kestrel public func rangeUpTo() -> RangeUpTo[Int32] ``` Builds a partial range `.. RangeThrough[Int32] ``` Builds a partial range `..=self` (through self, inclusive). **Convertible** #### initializer From Source ```kestrel init(from: From) ``` Creates an instance from `value`. ### struct Int64 ```kestrel public struct Int64 { /* private fields */ } ``` A 64-bit signed integer. Int64 is the 64-bit member of the integer family. The same surface area is provided across all widths; switch widths to trade range for memory or to match an FFI ABI. Arithmetic wraps on overflow by default — use the `*Checked` variants for overflow detection or `*Saturating` to clamp to `minValue`/`maxValue`. The type is `FFISafe` and lays out as a single `lang.i64` so it can cross C boundaries unchanged. # Examples ``` let a: Int64 = 100; let b = a + 50; // 150 let c = a * 2; // 200 let d = a.addChecked(Int64.maxValue); // None (overflow detected) ``` ``` // Bit twiddling (0b1010).countOnes // 2 (1).shiftLeft(by: 4) // 16 (-1).leadingZeros // 0 (all bits set) ``` # Representation A single `lang.i64` field. No padding, no headers — bit-identical to the corresponding C type. #### initializer Default ```kestrel public init() ``` Creates the zero value, satisfying `Defaultable`. # Examples ``` let n = Int64(); // 0 ``` #### initializer From Bytes ```kestrel public init[S](fromBytes: S) where S: Slice[UInt8] ``` Reassembles a `Int64` from 8 bytes in native byte order. Returns `null` if the input is not exactly 8 bytes long. #### initializer From Bytes Big Endian ```kestrel public init[S](fromBytesBigEndian: S) where S: Slice[UInt8] ``` Reassembles a `Int64` from 8 bytes in big-endian order. Returns `null` if the input is not exactly 8 bytes long. #### initializer From Bytes Little Endian ```kestrel public init[S](fromBytesLittleEndian: S) where S: Slice[UInt8] ``` Reassembles a `Int64` from 8 bytes in little-endian order. Returns `null` if the input is not exactly 8 bytes long. #### initializer From Integer ```kestrel public init(from: Int8) ``` Converts from `Int8`. Narrowing conversions truncate the high bits; signed→unsigned reinterprets the bit pattern. #### initializer From Integer ```kestrel public init(from: Int16) ``` Converts from `Int16`. Narrowing conversions truncate the high bits; signed→unsigned reinterprets the bit pattern. #### initializer From Integer ```kestrel public init(from: Int32) ``` Converts from `Int32`. Narrowing conversions truncate the high bits; signed→unsigned reinterprets the bit pattern. #### initializer From Integer ```kestrel public init(from: UInt8) ``` Converts from `UInt8`. Narrowing conversions truncate the high bits; signed→unsigned reinterprets the bit pattern. #### initializer From Integer ```kestrel public init(from: UInt16) ``` Converts from `UInt16`. Narrowing conversions truncate the high bits; signed→unsigned reinterprets the bit pattern. #### initializer From Integer ```kestrel public init(from: UInt32) ``` Converts from `UInt32`. Narrowing conversions truncate the high bits; signed→unsigned reinterprets the bit pattern. #### initializer From Integer ```kestrel public init(from: UInt64) ``` Converts from `UInt64`. Narrowing conversions truncate the high bits; signed→unsigned reinterprets the bit pattern. #### initializer From Raw ```kestrel init(raw: lang.i64) ``` Wraps an existing `lang.i64` without conversion. Internal constructor used by intrinsics; not part of the public API. #### initializer Int Literal ```kestrel public init(intLiteral: lang.i64) ``` Compiler-emitted bridge that turns an integer literal into a Int64. You will rarely call this directly — write the literal and let the `ExpressibleByIntLiteral` protocol pick it up. For widths smaller than 64 bits the literal is truncated with `lang.cast_i64_i64`. # Examples ``` let n: Int64 = 42; // implicit ``` #### initializer Parsing ```kestrel public init(parsing: String) ``` Parses a base-10 integer literal, optionally prefixed with `+` or `-`. Returns `null` for an empty string, a non-digit character, or a value that does not fit in `Int64`. # Examples ``` Int64(parsing: "42"); // Some(42) Int64(parsing: "-7"); // Some(-7) Int64(parsing: "abc"); // None ``` #### initializer Parsing with Radix ```kestrel public init(parsing: String, radix: Int64) ``` Parses an integer in `radix` (base 2-36 inclusive). Letters a-z are case-insensitive and represent digit values 10-35. # Examples ``` Int64(parsing: "ff", radix: 16); // Some(255 if it fits, else None) Int64(parsing: "101010", radix: 2); // Some(42) Int64(parsing: "z", radix: 36); // Some(35) ``` #### function absChecked ```kestrel public func absChecked() -> Int64? ``` Absolute value that returns `None` for `minValue` (whose absolute value overflows). #### function absSaturating ```kestrel public func absSaturating() -> Int64 ``` Absolute value that returns `maxValue` instead of wrapping `minValue`. #### function addChecked ```kestrel public func addChecked(Int64) -> Int64? ``` Wrapping addition that returns `None` instead of overflowing. #### function addSaturating ```kestrel public func addSaturating(Int64) -> Int64 ``` Addition that clamps to `maxValue`/`minValue` instead of wrapping. #### field bitWidth ```kestrel public static var bitWidth: Int64 { get } ``` The width in bits (64). Useful for shift bounds and bit-walks. #### field byteSwapped ```kestrel public var byteSwapped: Int64 { get } ``` Value with its byte order reversed. Use to convert between big- and little-endian; lowered to a `bswap` intrinsic. #### function clamp ```kestrel public func clamp(Int64, Int64) -> Int64 ``` Clamps `self` into `[min, max]`. Caller is responsible for ensuring `min <= max`; otherwise the result is undefined. # Examples ``` (5).clamp(0, 10); // 5 (-5).clamp(0, 10); // 0 (15).clamp(0, 10); // 10 ``` #### field countOnes ```kestrel public var countOnes: Int64 { get } ``` Population count — the number of `1` bits in the binary representation. Lowered to a `popcount` intrinsic where the target supports it. # Examples ``` (0b1010).countOnes; // 2 (0b1111).countOnes; // 4 (0).countOnes; // 0 ``` #### field countZeros ```kestrel public var countZeros: Int64 { get } ``` Complement of `countOnes`: equal to `bitWidth - countOnes`. #### function divideChecked ```kestrel public func divideChecked(Int64) -> Int64? ``` Division that returns `None` for divide-by-zero or for the `minValue / -1` overflow case. #### function gcd ```kestrel public func gcd(Int64) -> Int64 ``` Greatest common divisor via Euclidean algorithm. For signed types the inputs are taken absolute first; the result is always non-negative. # Examples ``` (12).gcd(8); // 4 (17).gcd(5); // 1 (coprime) (-12).gcd(8); // 4 ``` #### field isNegative ```kestrel public var isNegative: Bool { get } ``` True when `self < 0`. #### field isPositive ```kestrel public var isPositive: Bool { get } ``` True when `self > 0`. #### field isPowerOfTwo ```kestrel public var isPowerOfTwo: Bool { get } ``` True when the value is a positive power of two (`2^k` for `k >= 0`). Zero and negatives are excluded. Cheap branchless test built on `x & (x - 1) == 0`. # Examples ``` (1).isPowerOfTwo; // true (2^0) (4).isPowerOfTwo; // true (2^2) (3).isPowerOfTwo; // false (0).isPowerOfTwo; // false ``` #### field isZero ```kestrel public var isZero: Bool { get } ``` True when `self == 0`. #### function lcm ```kestrel public func lcm(Int64) -> Int64 ``` Least common multiple, computed as `|self| / gcd(self, other) * |other|` to avoid intermediate overflow. Returns zero if either input is zero. # Examples ``` (4).lcm(6); // 12 (3).lcm(5); // 15 (0).lcm(7); // 0 ``` #### field leadingZeros ```kestrel public var leadingZeros: Int64 { get } ``` Number of leading zero bits, counting from the most-significant end. For zero, returns `bitWidth`. # Examples ``` (1).leadingZeros; // bitWidth - 1 (0).leadingZeros; // bitWidth ``` #### field maxValue ```kestrel public static var maxValue: Int64 { get } ``` The largest representable value. This is 2^63 - 1 (9_223_372_036_854_775_807). #### field minValue ```kestrel public static var minValue: Int64 { get } ``` The smallest representable value. This is -2^63 (-9_223_372_036_854_775_808). Note that for signed types `minValue.negate()` overflows back to itself; use `negateChecked()` if you need to detect that. #### function multiplyChecked ```kestrel public func multiplyChecked(Int64) -> Int64? ``` Wrapping multiplication that returns `None` instead of overflowing. Implemented by multiplying then dividing back; replace with an overflow-detecting intrinsic when one is available. #### function multiplySaturating ```kestrel public func multiplySaturating(Int64) -> Int64 ``` Multiplication that clamps to `maxValue`/`minValue` instead of wrapping. The clamp direction follows the algebraic sign of the would-be result. #### function negateChecked ```kestrel public func negateChecked() -> Int64? ``` Negation that returns `None` for `minValue` (whose negation overflows). #### function negateSaturating ```kestrel public func negateSaturating() -> Int64 ``` Negation that returns `maxValue` instead of wrapping `minValue`. #### function pow ```kestrel public func pow(Int64) -> Int64 ``` Raises `self` to `exponent` via binary exponentiation. Wraps on overflow. Negative exponents return zero (integer truncation of the would-be fraction). # Examples ``` (2).pow(10); // 1024 (3).pow(4); // 81 (5).pow(-1); // 0 ``` #### field raw ```kestrel public var raw: lang.i64 ``` The underlying primitive `lang.i64` value. Exposed for FFI and intrinsic use; prefer the typed surface for everything else. #### function rotateLeft ```kestrel public func rotateLeft(by: Int64) -> Int64 ``` Rotates bits left by `count`, modulo `bitWidth`. Bits shifted past the MSB re-enter at the LSB. #### function rotateRight ```kestrel public func rotateRight(by: Int64) -> Int64 ``` Rotates bits right by `count`, modulo `bitWidth`. Mirror of `rotateLeft`. #### field sign ```kestrel public var sign: Int64 { get } ``` Sign as a `Int64`: `-1`, `0`, or `1`. #### function subtractChecked ```kestrel public func subtractChecked(Int64) -> Int64? ``` Wrapping subtraction that returns `None` instead of overflowing. #### function subtractSaturating ```kestrel public func subtractSaturating(Int64) -> Int64 ``` Subtraction that clamps to `maxValue`/`minValue` instead of wrapping. #### function toBytes ```kestrel public func toBytes() -> std.collections.Array[UInt8] ``` Splits this integer into 8 bytes in *native* (host) byte order. Use `toBytesBigEndian` / `toBytesLittleEndian` when serialising for a fixed wire format. # Examples ``` let bytes = Int64.maxValue.toBytes(); // 8 bytes, host order ``` #### function toBytesBigEndian ```kestrel public func toBytesBigEndian() -> std.collections.Array[UInt8] ``` Splits this integer into 8 bytes in big-endian order (most significant byte first — i.e. network byte order). #### function toBytesLittleEndian ```kestrel public func toBytesLittleEndian() -> std.collections.Array[UInt8] ``` Splits this integer into 8 bytes in little-endian order (least significant byte first). #### field trailingZeros ```kestrel public var trailingZeros: Int64 { get } ``` Number of trailing zero bits. Equal to `log2(self & -self)` for non-zero values; returns `bitWidth` for zero. Useful for finding the largest power of two dividing the value. **SignedInteger** #### function abs ```kestrel public func abs() -> Int64 ``` Absolute value. Wraps at the minimum value (`Int64.minValue.abs() == Int64.minValue`); use `absChecked` if that's a problem. **Steppable** #### function predecessor ```kestrel public func predecessor() -> Int64 ``` Predecessor — `self - 1`. Wraps at `minValue`. #### function successor ```kestrel public func successor() -> Int64 ``` Successor — `self + 1`. Wraps at `maxValue`. Used by `for-in` over integer ranges. **Comparable** #### typealias Output ```kestrel type Output = Bool ``` #### function compare ```kestrel public func compare(Int64) -> Ordering ``` Three-way comparison returning an `Ordering`. Signed types compare using two's-complement ordering; unsigned types use natural ordering. # Examples ``` (1).compare(2); // .Less (2).compare(2); // .Equal (3).compare(2); // .Greater ``` #### function greaterThan ```kestrel public func greaterThan(Self) -> Bool ``` `>` derived from `compare`. #### function greaterThanOrEqual ```kestrel public func greaterThanOrEqual(Self) -> Bool ``` `>=` derived from `compare`. #### function isAtLeast ```kestrel public func isAtLeast(Self) -> Bool ``` `start..` lower-bound check, derived from `compare`. #### function isAtMost ```kestrel public func isAtMost(Self) -> Bool ``` `..=end` upper-bound check, derived from `compare`. #### function isBelow ```kestrel public func isBelow(Self) -> Bool ``` `.. Bool ``` `<` derived from `compare`. #### function lessThanOrEqual ```kestrel public func lessThanOrEqual(Self) -> Bool ``` `<=` derived from `compare`. **Equatable** #### typealias Output ```kestrel type Output = Bool ``` #### function equal ```kestrel public func equal(to: Self) -> Bool ``` Bridges `Equal.equal(to:)` to `Equatable.isEqual(to:)`. #### function isEqual ```kestrel public func isEqual(to: Int64) -> Bool ``` Bit-for-bit equality. Backs the `==` operator. # Examples ``` (42).isEqual(to: 42); // true 42 == 42; // true ``` #### function notEqual ```kestrel public func notEqual(to: Self) -> Bool ``` Default `!=`: delegates to `==` so there's a single source of truth. **Matchable** #### function matches ```kestrel public func matches(Int64) -> Bool ``` Pattern-matching hook for `Matchable`. Identical to `isEqual`. **Formattable** #### function format ```kestrel public func format(into: mutating StringBuilder, FormatOptions) ``` Formats the integer directly into `writer`, honouring the supplied `FormatOptions`. Implements the `Formattable` protocol. # Examples ``` (42).format(); // "42" (255).format(.{radix: 16}); // "ff" (255).format(.{radix: 16, uppercase: true}); // "FF" (255).format(.{radix: 16, alternate: true}); // "0xff" (42).format(.{radix: 2, alternate: true}); // "0b101010" (42).format(.{width: .Some(5), fill: '0'}); // "00042" (-42).format(.{sign: .Always}); // "-42" ``` #### function formatted ```kestrel public func formatted(FormatOptions) -> String ``` Returns this value rendered as a `String`. Convenience wrapper: creates a `StringBuilder`, calls `format(into:)`, and returns the built string. Uses a distinct name to avoid overload-resolution ambiguity with `format(into:)`. **Hashable** #### function hash ```kestrel public func hash[H](into: mutating H) where H: Hasher ``` Feeds the raw bytes of this value into `hasher`. Endianness-agnostic only within a single process — do not persist hashes across builds. **Addable** #### typealias Output ```kestrel type Output = Int64 ``` #### typealias Output ```kestrel type Output = Int64 ``` #### typealias Output ```kestrel type Output = Int64 ``` #### typealias Output ```kestrel type Output = Int64 ``` #### typealias Output ```kestrel type Output = Int64 ``` #### typealias Output ```kestrel type Output = Int64 ``` #### typealias Output ```kestrel type Output = Int64 ``` #### typealias Output ```kestrel type Output = Int64 ``` #### typealias Output ```kestrel type Output = Int64 ``` #### typealias Output ```kestrel type Output = Int64 ``` #### typealias Output ```kestrel type Output = Int64 ``` #### typealias Output ```kestrel type Output = Int64 ``` #### typealias Output ```kestrel type Output = Range[Int64] ``` #### typealias Output ```kestrel type Output = ClosedRange[Int64] ``` #### typealias Output ```kestrel type Output = RangeFrom[Int64] ``` #### typealias Output ```kestrel type Output = RangeUpTo[Int64] ``` #### typealias Output ```kestrel type Output = RangeThrough[Int64] ``` #### function add ```kestrel public consuming func add(consuming Int64) -> Int64 ``` `self + other`, wrapping on overflow. Use `addChecked` to detect or `addSaturating` to clamp. #### field zero ```kestrel public static var zero: Int64 { get } ``` The additive identity, `0`. **Subtractable** #### typealias Output ```kestrel type Output ``` #### function subtract ```kestrel public consuming func subtract(consuming Int64) -> Int64 ``` `self - other`, wrapping on overflow. **Multipliable** #### typealias Output ```kestrel type Output ``` #### function multiply ```kestrel public consuming func multiply(consuming Int64) -> Int64 ``` `self * other`, wrapping on overflow. #### field one ```kestrel public static var one: Int64 { get } ``` The multiplicative identity, `1`. **Divisible** #### typealias Output ```kestrel type Output ``` #### function divide ```kestrel public consuming func divide(consuming Int64) -> Int64 ``` Truncating integer division (`self / other`). For signed types, `minValue / -1` wraps; use `divideChecked` to detect. # Errors Traps on division by zero (LLVM `udiv`/`sdiv` are UB on zero — the process aborts before producing a result). **Modulo** #### typealias Output ```kestrel type Output ``` #### function modulo ```kestrel public consuming func modulo(consuming Int64) -> Int64 ``` `self % other` — truncated remainder; the result has the sign of `self` for signed types. # Errors Traps on division by zero, like `divide`. **Negatable** #### typealias Output ```kestrel type Output ``` #### function negate ```kestrel public consuming func negate() -> Int64 ``` Two's-complement negation. Wraps at the minimum value: `Int64.minValue.negate() == Int64.minValue`. Use `negateChecked` to surface the overflow. **BitwiseAnd** #### typealias Output ```kestrel type Output ``` #### function bitwiseAnd ```kestrel public consuming func bitwiseAnd(consuming Int64) -> Int64 ``` Bitwise AND. `0b1010 & 0b1100 == 0b1000`. **BitwiseOr** #### typealias Output ```kestrel type Output ``` #### function bitwiseOr ```kestrel public consuming func bitwiseOr(consuming Int64) -> Int64 ``` Bitwise OR. `0b1010 | 0b1100 == 0b1110`. **BitwiseXor** #### typealias Output ```kestrel type Output ``` #### function bitwiseXor ```kestrel public consuming func bitwiseXor(consuming Int64) -> Int64 ``` Bitwise XOR. `0b1010 ^ 0b1100 == 0b0110`. **BitwiseNot** #### typealias Output ```kestrel type Output ``` #### function bitwiseNot ```kestrel public consuming func bitwiseNot() -> Int64 ``` Bitwise NOT — flips all bits. For signed types this is `-self - 1`. **LeftShift** #### typealias Output ```kestrel type Output ``` #### function shiftLeft ```kestrel public consuming func shiftLeft(by: consuming Int64) -> Int64 ``` Left shift by `count`. Behavior is undefined when `count >= bitWidth` — pre-mask the count if you can't guarantee the bound. **RightShift** #### typealias Output ```kestrel type Output ``` #### function shiftRight ```kestrel public consuming func shiftRight(by: consuming Int64) -> Int64 ``` Right shift by `count`. Arithmetic (sign-extending) for signed types, logical (zero-filling) for unsigned. Same `count` precondition as `shiftLeft`. **AddAssign** #### function addAssign ```kestrel public mutating func addAssign(Int64) ``` `self += other` **SubtractAssign** #### function subtractAssign ```kestrel public mutating func subtractAssign(Int64) ``` `self -= other` **MultiplyAssign** #### function multiplyAssign ```kestrel public mutating func multiplyAssign(Int64) ``` `self *= other` **DivideAssign** #### function divideAssign ```kestrel public mutating func divideAssign(Int64) ``` `self /= other` **ModuloAssign** #### function modAssign ```kestrel public mutating func modAssign(Int64) ``` `self %= other` **BitwiseAndAssign** #### function bitwiseAndAssign ```kestrel public mutating func bitwiseAndAssign(Int64) ``` `self &= other` **BitwiseOrAssign** #### function bitwiseOrAssign ```kestrel public mutating func bitwiseOrAssign(Int64) ``` `self |= other` **BitwiseXorAssign** #### function bitwiseXorAssign ```kestrel public mutating func bitwiseXorAssign(Int64) ``` `self ^= other` **LeftShiftAssign** #### function shiftLeftAssign ```kestrel public mutating func shiftLeftAssign(by: Int64) ``` `self <<= count` **RightShiftAssign** #### function shiftRightAssign ```kestrel public mutating func shiftRightAssign(by: Int64) ``` `self >>= count` **ExpressibleByIntLiteral** #### initializer Int Literal ```kestrel init(intLiteral: lang.i64) ``` Builds an instance from an integer literal. **Defaultable** #### initializer Default ```kestrel init() ``` Builds the default-valued instance. **RangeConstructible** #### typealias Output ```kestrel type Output ``` #### function exclusiveRange ```kestrel public func exclusiveRange(to: Int64) -> Range[Int64] ``` Builds a half-open range `self.. ClosedRange[Int64] ``` Builds a closed range `self..=end`. Sugar for the `..=` operator. **RangeFromConstructible** #### typealias Output ```kestrel type Output ``` #### function rangeFrom ```kestrel public func rangeFrom() -> RangeFrom[Int64] ``` Builds a partial range `self..` (from self, no upper bound). **RangeUpToConstructible** #### typealias Output ```kestrel type Output ``` #### function rangeUpTo ```kestrel public func rangeUpTo() -> RangeUpTo[Int64] ``` Builds a partial range `.. RangeThrough[Int64] ``` Builds a partial range `..=self` (through self, inclusive). **Convertible** #### initializer From Source ```kestrel init(from: From) ``` Creates an instance from `value`. **SeqIndex** #### typealias SeqOutput ```kestrel type SeqOutput = T ``` #### function readSeq ```kestrel public func readSeq(from: ArraySlice[T]) -> T ``` #### function readSeqChecked ```kestrel public func readSeqChecked(from: ArraySlice[T]) -> T? ``` #### function readSeqUnchecked ```kestrel public func readSeqUnchecked(from: ArraySlice[T]) -> T ``` #### function writeSeq ```kestrel public func writeSeq(to: ArraySlice[T], with: T) ``` #### function writeSeqUnchecked ```kestrel public func writeSeqUnchecked(to: ArraySlice[T], with: T) ``` **SeqClampable** #### typealias SeqClampedOutput ```kestrel type SeqClampedOutput = T? ``` #### function readSeqClamped ```kestrel public func readSeqClamped(from: ArraySlice[T]) -> T? ``` #### function writeSeqClamped ```kestrel public func writeSeqClamped(to: ArraySlice[T], with: T?) ``` **SeqWrappable** #### typealias SeqWrappedOutput ```kestrel type SeqWrappedOutput = T? ``` #### function readSeqWrapped ```kestrel public func readSeqWrapped(from: ArraySlice[T]) -> T? ``` #### function writeSeqWrapped ```kestrel public func writeSeqWrapped(to: ArraySlice[T], with: T?) ``` **BytesIndex** #### typealias BytesYield ```kestrel type BytesYield = UInt8 ``` #### function readBytes ```kestrel public func readBytes(from: BytesView) -> UInt8 ``` #### function readBytesChecked ```kestrel public func readBytesChecked(from: BytesView) -> UInt8? ``` #### function readBytesUnchecked ```kestrel public func readBytesUnchecked(from: BytesView) -> UInt8 ``` **BytesClampable** #### typealias BytesClampedYield ```kestrel type BytesClampedYield = UInt8? ``` #### function readBytesClamped ```kestrel public func readBytesClamped(from: BytesView) -> UInt8? ``` **BytesWrappable** #### typealias BytesWrappedYield ```kestrel type BytesWrappedYield = UInt8? ``` #### function readBytesWrapped ```kestrel public func readBytesWrapped(from: BytesView) -> UInt8? ``` **CharsIndex** #### typealias CharsYield ```kestrel type CharsYield = Char ``` #### function readChars ```kestrel public func readChars(from: CharsView) -> Char ``` #### function readCharsChecked ```kestrel public func readCharsChecked(from: CharsView) -> Char? ``` **CharsClampable** #### typealias CharsClampedYield ```kestrel type CharsClampedYield = Char? ``` #### function readCharsClamped ```kestrel public func readCharsClamped(from: CharsView) -> Char? ``` **CharsWrappable** #### typealias CharsWrappedYield ```kestrel type CharsWrappedYield = Char? ``` #### function readCharsWrapped ```kestrel public func readCharsWrapped(from: CharsView) -> Char? ``` **GraphemesIndex** #### typealias GraphemesYield ```kestrel type GraphemesYield = Grapheme ``` #### function readGraphemes ```kestrel public func readGraphemes(from: GraphemesView) -> Grapheme ``` #### function readGraphemesChecked ```kestrel public func readGraphemesChecked(from: GraphemesView) -> Grapheme? ``` **GraphemesClampable** #### typealias GraphemesClampedYield ```kestrel type GraphemesClampedYield = Grapheme? ``` #### function readGraphemesClamped ```kestrel public func readGraphemesClamped(from: GraphemesView) -> Grapheme? ``` **GraphemesWrappable** #### typealias GraphemesWrappedYield ```kestrel type GraphemesWrappedYield = Grapheme? ``` #### function readGraphemesWrapped ```kestrel public func readGraphemesWrapped(from: GraphemesView) -> Grapheme? ``` **LinesIndex** #### typealias LinesYield ```kestrel type LinesYield = String ``` #### function readLines ```kestrel public func readLines(from: LinesView) -> String ``` #### function readLinesChecked ```kestrel public func readLinesChecked(from: LinesView) -> String? ``` **LinesClampable** #### typealias LinesClampedYield ```kestrel type LinesClampedYield = String? ``` #### function readLinesClamped ```kestrel public func readLinesClamped(from: LinesView) -> String? ``` **LinesWrappable** #### typealias LinesWrappedYield ```kestrel type LinesWrappedYield = String? ``` #### function readLinesWrapped ```kestrel public func readLinesWrapped(from: LinesView) -> String? ``` ### struct Int8 ```kestrel public struct Int8 { /* private fields */ } ``` A 8-bit signed integer. Int8 is the 8-bit member of the integer family. The same surface area is provided across all widths; switch widths to trade range for memory or to match an FFI ABI. Arithmetic wraps on overflow by default — use the `*Checked` variants for overflow detection or `*Saturating` to clamp to `minValue`/`maxValue`. The type is `FFISafe` and lays out as a single `lang.i8` so it can cross C boundaries unchanged. # Examples ``` let a: Int64 = 100; let b = a + 50; // 150 let c = a * 2; // 200 let d = a.addChecked(Int64.maxValue); // None (overflow detected) ``` ``` // Bit twiddling (0b1010).countOnes // 2 (1).shiftLeft(by: 4) // 16 (-1).leadingZeros // 0 (all bits set) ``` # Representation A single `lang.i8` field. No padding, no headers — bit-identical to the corresponding C type. #### initializer Default ```kestrel public init() ``` Creates the zero value, satisfying `Defaultable`. # Examples ``` let n = Int64(); // 0 ``` #### initializer From Bytes ```kestrel public init[S](fromBytes: S) where S: Slice[UInt8] ``` Reassembles a `Int8` from 1 bytes in native byte order. Returns `null` if the input is not exactly 1 bytes long. #### initializer From Bytes Big Endian ```kestrel public init[S](fromBytesBigEndian: S) where S: Slice[UInt8] ``` Reassembles a `Int8` from 1 bytes in big-endian order. Returns `null` if the input is not exactly 1 bytes long. #### initializer From Bytes Little Endian ```kestrel public init[S](fromBytesLittleEndian: S) where S: Slice[UInt8] ``` Reassembles a `Int8` from 1 bytes in little-endian order. Returns `null` if the input is not exactly 1 bytes long. #### initializer From Integer ```kestrel public init(from: Int16) ``` Converts from `Int16`. Narrowing conversions truncate the high bits; signed→unsigned reinterprets the bit pattern. #### initializer From Integer ```kestrel public init(from: Int32) ``` Converts from `Int32`. Narrowing conversions truncate the high bits; signed→unsigned reinterprets the bit pattern. #### initializer From Integer ```kestrel public init(from: Int64) ``` Converts from `Int64`. Narrowing conversions truncate the high bits; signed→unsigned reinterprets the bit pattern. #### initializer From Integer ```kestrel public init(from: UInt8) ``` Converts from `UInt8`. Narrowing conversions truncate the high bits; signed→unsigned reinterprets the bit pattern. #### initializer From Integer ```kestrel public init(from: UInt16) ``` Converts from `UInt16`. Narrowing conversions truncate the high bits; signed→unsigned reinterprets the bit pattern. #### initializer From Integer ```kestrel public init(from: UInt32) ``` Converts from `UInt32`. Narrowing conversions truncate the high bits; signed→unsigned reinterprets the bit pattern. #### initializer From Integer ```kestrel public init(from: UInt64) ``` Converts from `UInt64`. Narrowing conversions truncate the high bits; signed→unsigned reinterprets the bit pattern. #### initializer From Raw ```kestrel init(raw: lang.i8) ``` Wraps an existing `lang.i8` without conversion. Internal constructor used by intrinsics; not part of the public API. #### initializer Int Literal ```kestrel public init(intLiteral: lang.i64) ``` Compiler-emitted bridge that turns an integer literal into a Int8. You will rarely call this directly — write the literal and let the `ExpressibleByIntLiteral` protocol pick it up. For widths smaller than 64 bits the literal is truncated with `lang.cast_i64_i8`. # Examples ``` let n: Int64 = 42; // implicit ``` #### initializer Parsing ```kestrel public init(parsing: String) ``` Parses a base-10 integer literal, optionally prefixed with `+` or `-`. Returns `null` for an empty string, a non-digit character, or a value that does not fit in `Int8`. # Examples ``` Int8(parsing: "42"); // Some(42) Int8(parsing: "-7"); // Some(-7) Int8(parsing: "abc"); // None ``` #### initializer Parsing with Radix ```kestrel public init(parsing: String, radix: Int64) ``` Parses an integer in `radix` (base 2-36 inclusive). Letters a-z are case-insensitive and represent digit values 10-35. # Examples ``` Int8(parsing: "ff", radix: 16); // Some(255 if it fits, else None) Int8(parsing: "101010", radix: 2); // Some(42) Int8(parsing: "z", radix: 36); // Some(35) ``` #### function absChecked ```kestrel public func absChecked() -> Int8? ``` Absolute value that returns `None` for `minValue` (whose absolute value overflows). #### function absSaturating ```kestrel public func absSaturating() -> Int8 ``` Absolute value that returns `maxValue` instead of wrapping `minValue`. #### function addChecked ```kestrel public func addChecked(Int8) -> Int8? ``` Wrapping addition that returns `None` instead of overflowing. #### function addSaturating ```kestrel public func addSaturating(Int8) -> Int8 ``` Addition that clamps to `maxValue`/`minValue` instead of wrapping. #### field bitWidth ```kestrel public static var bitWidth: Int64 { get } ``` The width in bits (8). Useful for shift bounds and bit-walks. #### field byteSwapped ```kestrel public var byteSwapped: Int8 { get } ``` Value with its byte order reversed. Use to convert between big- and little-endian; lowered to a `bswap` intrinsic. #### function clamp ```kestrel public func clamp(Int8, Int8) -> Int8 ``` Clamps `self` into `[min, max]`. Caller is responsible for ensuring `min <= max`; otherwise the result is undefined. # Examples ``` (5).clamp(0, 10); // 5 (-5).clamp(0, 10); // 0 (15).clamp(0, 10); // 10 ``` #### field countOnes ```kestrel public var countOnes: Int64 { get } ``` Population count — the number of `1` bits in the binary representation. Lowered to a `popcount` intrinsic where the target supports it. # Examples ``` (0b1010).countOnes; // 2 (0b1111).countOnes; // 4 (0).countOnes; // 0 ``` #### field countZeros ```kestrel public var countZeros: Int64 { get } ``` Complement of `countOnes`: equal to `bitWidth - countOnes`. #### function divideChecked ```kestrel public func divideChecked(Int8) -> Int8? ``` Division that returns `None` for divide-by-zero or for the `minValue / -1` overflow case. #### function gcd ```kestrel public func gcd(Int8) -> Int8 ``` Greatest common divisor via Euclidean algorithm. For signed types the inputs are taken absolute first; the result is always non-negative. # Examples ``` (12).gcd(8); // 4 (17).gcd(5); // 1 (coprime) (-12).gcd(8); // 4 ``` #### field isNegative ```kestrel public var isNegative: Bool { get } ``` True when `self < 0`. #### field isPositive ```kestrel public var isPositive: Bool { get } ``` True when `self > 0`. #### field isPowerOfTwo ```kestrel public var isPowerOfTwo: Bool { get } ``` True when the value is a positive power of two (`2^k` for `k >= 0`). Zero and negatives are excluded. Cheap branchless test built on `x & (x - 1) == 0`. # Examples ``` (1).isPowerOfTwo; // true (2^0) (4).isPowerOfTwo; // true (2^2) (3).isPowerOfTwo; // false (0).isPowerOfTwo; // false ``` #### field isZero ```kestrel public var isZero: Bool { get } ``` True when `self == 0`. #### function lcm ```kestrel public func lcm(Int8) -> Int8 ``` Least common multiple, computed as `|self| / gcd(self, other) * |other|` to avoid intermediate overflow. Returns zero if either input is zero. # Examples ``` (4).lcm(6); // 12 (3).lcm(5); // 15 (0).lcm(7); // 0 ``` #### field leadingZeros ```kestrel public var leadingZeros: Int64 { get } ``` Number of leading zero bits, counting from the most-significant end. For zero, returns `bitWidth`. # Examples ``` (1).leadingZeros; // bitWidth - 1 (0).leadingZeros; // bitWidth ``` #### field maxValue ```kestrel public static var maxValue: Int8 { get } ``` The largest representable value. This is 2^7 - 1 (127). #### field minValue ```kestrel public static var minValue: Int8 { get } ``` The smallest representable value. This is -2^7 (-128). Note that for signed types `minValue.negate()` overflows back to itself; use `negateChecked()` if you need to detect that. #### function multiplyChecked ```kestrel public func multiplyChecked(Int8) -> Int8? ``` Wrapping multiplication that returns `None` instead of overflowing. Implemented by multiplying then dividing back; replace with an overflow-detecting intrinsic when one is available. #### function multiplySaturating ```kestrel public func multiplySaturating(Int8) -> Int8 ``` Multiplication that clamps to `maxValue`/`minValue` instead of wrapping. The clamp direction follows the algebraic sign of the would-be result. #### function negateChecked ```kestrel public func negateChecked() -> Int8? ``` Negation that returns `None` for `minValue` (whose negation overflows). #### function negateSaturating ```kestrel public func negateSaturating() -> Int8 ``` Negation that returns `maxValue` instead of wrapping `minValue`. #### function pow ```kestrel public func pow(Int64) -> Int8 ``` Raises `self` to `exponent` via binary exponentiation. Wraps on overflow. Negative exponents return zero (integer truncation of the would-be fraction). # Examples ``` (2).pow(10); // 1024 (3).pow(4); // 81 (5).pow(-1); // 0 ``` #### field raw ```kestrel public var raw: lang.i8 ``` The underlying primitive `lang.i8` value. Exposed for FFI and intrinsic use; prefer the typed surface for everything else. #### function rotateLeft ```kestrel public func rotateLeft(by: Int64) -> Int8 ``` Rotates bits left by `count`, modulo `bitWidth`. Bits shifted past the MSB re-enter at the LSB. #### function rotateRight ```kestrel public func rotateRight(by: Int64) -> Int8 ``` Rotates bits right by `count`, modulo `bitWidth`. Mirror of `rotateLeft`. #### field sign ```kestrel public var sign: Int8 { get } ``` Sign as a `Int8`: `-1`, `0`, or `1`. #### function subtractChecked ```kestrel public func subtractChecked(Int8) -> Int8? ``` Wrapping subtraction that returns `None` instead of overflowing. #### function subtractSaturating ```kestrel public func subtractSaturating(Int8) -> Int8 ``` Subtraction that clamps to `maxValue`/`minValue` instead of wrapping. #### function toBytes ```kestrel public func toBytes() -> std.collections.Array[UInt8] ``` Splits this integer into 1 bytes in *native* (host) byte order. Use `toBytesBigEndian` / `toBytesLittleEndian` when serialising for a fixed wire format. # Examples ``` let bytes = Int8.maxValue.toBytes(); // 1 bytes, host order ``` #### function toBytesBigEndian ```kestrel public func toBytesBigEndian() -> std.collections.Array[UInt8] ``` Splits this integer into 1 bytes in big-endian order (most significant byte first — i.e. network byte order). #### function toBytesLittleEndian ```kestrel public func toBytesLittleEndian() -> std.collections.Array[UInt8] ``` Splits this integer into 1 bytes in little-endian order (least significant byte first). #### field trailingZeros ```kestrel public var trailingZeros: Int64 { get } ``` Number of trailing zero bits. Equal to `log2(self & -self)` for non-zero values; returns `bitWidth` for zero. Useful for finding the largest power of two dividing the value. **SignedInteger** #### function abs ```kestrel public func abs() -> Int8 ``` Absolute value. Wraps at the minimum value (`Int8.minValue.abs() == Int8.minValue`); use `absChecked` if that's a problem. **Steppable** #### function predecessor ```kestrel public func predecessor() -> Int8 ``` Predecessor — `self - 1`. Wraps at `minValue`. #### function successor ```kestrel public func successor() -> Int8 ``` Successor — `self + 1`. Wraps at `maxValue`. Used by `for-in` over integer ranges. **Comparable** #### typealias Output ```kestrel type Output = Bool ``` #### function compare ```kestrel public func compare(Int8) -> Ordering ``` Three-way comparison returning an `Ordering`. Signed types compare using two's-complement ordering; unsigned types use natural ordering. # Examples ``` (1).compare(2); // .Less (2).compare(2); // .Equal (3).compare(2); // .Greater ``` #### function greaterThan ```kestrel public func greaterThan(Self) -> Bool ``` `>` derived from `compare`. #### function greaterThanOrEqual ```kestrel public func greaterThanOrEqual(Self) -> Bool ``` `>=` derived from `compare`. #### function isAtLeast ```kestrel public func isAtLeast(Self) -> Bool ``` `start..` lower-bound check, derived from `compare`. #### function isAtMost ```kestrel public func isAtMost(Self) -> Bool ``` `..=end` upper-bound check, derived from `compare`. #### function isBelow ```kestrel public func isBelow(Self) -> Bool ``` `.. Bool ``` `<` derived from `compare`. #### function lessThanOrEqual ```kestrel public func lessThanOrEqual(Self) -> Bool ``` `<=` derived from `compare`. **Equatable** #### typealias Output ```kestrel type Output = Bool ``` #### function equal ```kestrel public func equal(to: Self) -> Bool ``` Bridges `Equal.equal(to:)` to `Equatable.isEqual(to:)`. #### function isEqual ```kestrel public func isEqual(to: Int8) -> Bool ``` Bit-for-bit equality. Backs the `==` operator. # Examples ``` (42).isEqual(to: 42); // true 42 == 42; // true ``` #### function notEqual ```kestrel public func notEqual(to: Self) -> Bool ``` Default `!=`: delegates to `==` so there's a single source of truth. **Matchable** #### function matches ```kestrel public func matches(Int8) -> Bool ``` Pattern-matching hook for `Matchable`. Identical to `isEqual`. **Formattable** #### function format ```kestrel public func format(into: mutating StringBuilder, FormatOptions) ``` Formats the integer directly into `writer`, honouring the supplied `FormatOptions`. Implements the `Formattable` protocol. # Examples ``` (42).format(); // "42" (255).format(.{radix: 16}); // "ff" (255).format(.{radix: 16, uppercase: true}); // "FF" (255).format(.{radix: 16, alternate: true}); // "0xff" (42).format(.{radix: 2, alternate: true}); // "0b101010" (42).format(.{width: .Some(5), fill: '0'}); // "00042" (-42).format(.{sign: .Always}); // "-42" ``` #### function formatted ```kestrel public func formatted(FormatOptions) -> String ``` Returns this value rendered as a `String`. Convenience wrapper: creates a `StringBuilder`, calls `format(into:)`, and returns the built string. Uses a distinct name to avoid overload-resolution ambiguity with `format(into:)`. **Hashable** #### function hash ```kestrel public func hash[H](into: mutating H) where H: Hasher ``` Feeds the raw bytes of this value into `hasher`. Endianness-agnostic only within a single process — do not persist hashes across builds. **Addable** #### typealias Output ```kestrel type Output = Int8 ``` #### typealias Output ```kestrel type Output = Int8 ``` #### typealias Output ```kestrel type Output = Int8 ``` #### typealias Output ```kestrel type Output = Int8 ``` #### typealias Output ```kestrel type Output = Int8 ``` #### typealias Output ```kestrel type Output = Int8 ``` #### typealias Output ```kestrel type Output = Int8 ``` #### typealias Output ```kestrel type Output = Int8 ``` #### typealias Output ```kestrel type Output = Int8 ``` #### typealias Output ```kestrel type Output = Int8 ``` #### typealias Output ```kestrel type Output = Int8 ``` #### typealias Output ```kestrel type Output = Int8 ``` #### typealias Output ```kestrel type Output = Range[Int8] ``` #### typealias Output ```kestrel type Output = ClosedRange[Int8] ``` #### typealias Output ```kestrel type Output = RangeFrom[Int8] ``` #### typealias Output ```kestrel type Output = RangeUpTo[Int8] ``` #### typealias Output ```kestrel type Output = RangeThrough[Int8] ``` #### function add ```kestrel public consuming func add(consuming Int8) -> Int8 ``` `self + other`, wrapping on overflow. Use `addChecked` to detect or `addSaturating` to clamp. #### field zero ```kestrel public static var zero: Int8 { get } ``` The additive identity, `0`. **Subtractable** #### typealias Output ```kestrel type Output ``` #### function subtract ```kestrel public consuming func subtract(consuming Int8) -> Int8 ``` `self - other`, wrapping on overflow. **Multipliable** #### typealias Output ```kestrel type Output ``` #### function multiply ```kestrel public consuming func multiply(consuming Int8) -> Int8 ``` `self * other`, wrapping on overflow. #### field one ```kestrel public static var one: Int8 { get } ``` The multiplicative identity, `1`. **Divisible** #### typealias Output ```kestrel type Output ``` #### function divide ```kestrel public consuming func divide(consuming Int8) -> Int8 ``` Truncating integer division (`self / other`). For signed types, `minValue / -1` wraps; use `divideChecked` to detect. # Errors Traps on division by zero (LLVM `udiv`/`sdiv` are UB on zero — the process aborts before producing a result). **Modulo** #### typealias Output ```kestrel type Output ``` #### function modulo ```kestrel public consuming func modulo(consuming Int8) -> Int8 ``` `self % other` — truncated remainder; the result has the sign of `self` for signed types. # Errors Traps on division by zero, like `divide`. **Negatable** #### typealias Output ```kestrel type Output ``` #### function negate ```kestrel public consuming func negate() -> Int8 ``` Two's-complement negation. Wraps at the minimum value: `Int8.minValue.negate() == Int8.minValue`. Use `negateChecked` to surface the overflow. **BitwiseAnd** #### typealias Output ```kestrel type Output ``` #### function bitwiseAnd ```kestrel public consuming func bitwiseAnd(consuming Int8) -> Int8 ``` Bitwise AND. `0b1010 & 0b1100 == 0b1000`. **BitwiseOr** #### typealias Output ```kestrel type Output ``` #### function bitwiseOr ```kestrel public consuming func bitwiseOr(consuming Int8) -> Int8 ``` Bitwise OR. `0b1010 | 0b1100 == 0b1110`. **BitwiseXor** #### typealias Output ```kestrel type Output ``` #### function bitwiseXor ```kestrel public consuming func bitwiseXor(consuming Int8) -> Int8 ``` Bitwise XOR. `0b1010 ^ 0b1100 == 0b0110`. **BitwiseNot** #### typealias Output ```kestrel type Output ``` #### function bitwiseNot ```kestrel public consuming func bitwiseNot() -> Int8 ``` Bitwise NOT — flips all bits. For signed types this is `-self - 1`. **LeftShift** #### typealias Output ```kestrel type Output ``` #### function shiftLeft ```kestrel public consuming func shiftLeft(by: consuming Int64) -> Int8 ``` Left shift by `count`. Behavior is undefined when `count >= bitWidth` — pre-mask the count if you can't guarantee the bound. **RightShift** #### typealias Output ```kestrel type Output ``` #### function shiftRight ```kestrel public consuming func shiftRight(by: consuming Int64) -> Int8 ``` Right shift by `count`. Arithmetic (sign-extending) for signed types, logical (zero-filling) for unsigned. Same `count` precondition as `shiftLeft`. **AddAssign** #### function addAssign ```kestrel public mutating func addAssign(Int8) ``` `self += other` **SubtractAssign** #### function subtractAssign ```kestrel public mutating func subtractAssign(Int8) ``` `self -= other` **MultiplyAssign** #### function multiplyAssign ```kestrel public mutating func multiplyAssign(Int8) ``` `self *= other` **DivideAssign** #### function divideAssign ```kestrel public mutating func divideAssign(Int8) ``` `self /= other` **ModuloAssign** #### function modAssign ```kestrel public mutating func modAssign(Int8) ``` `self %= other` **BitwiseAndAssign** #### function bitwiseAndAssign ```kestrel public mutating func bitwiseAndAssign(Int8) ``` `self &= other` **BitwiseOrAssign** #### function bitwiseOrAssign ```kestrel public mutating func bitwiseOrAssign(Int8) ``` `self |= other` **BitwiseXorAssign** #### function bitwiseXorAssign ```kestrel public mutating func bitwiseXorAssign(Int8) ``` `self ^= other` **LeftShiftAssign** #### function shiftLeftAssign ```kestrel public mutating func shiftLeftAssign(by: Int64) ``` `self <<= count` **RightShiftAssign** #### function shiftRightAssign ```kestrel public mutating func shiftRightAssign(by: Int64) ``` `self >>= count` **ExpressibleByIntLiteral** #### initializer Int Literal ```kestrel init(intLiteral: lang.i64) ``` Builds an instance from an integer literal. **Defaultable** #### initializer Default ```kestrel init() ``` Builds the default-valued instance. **RangeConstructible** #### typealias Output ```kestrel type Output ``` #### function exclusiveRange ```kestrel public func exclusiveRange(to: Int8) -> Range[Int8] ``` Builds a half-open range `self.. ClosedRange[Int8] ``` Builds a closed range `self..=end`. Sugar for the `..=` operator. **RangeFromConstructible** #### typealias Output ```kestrel type Output ``` #### function rangeFrom ```kestrel public func rangeFrom() -> RangeFrom[Int8] ``` Builds a partial range `self..` (from self, no upper bound). **RangeUpToConstructible** #### typealias Output ```kestrel type Output ``` #### function rangeUpTo ```kestrel public func rangeUpTo() -> RangeUpTo[Int8] ``` Builds a partial range `.. RangeThrough[Int8] ``` Builds a partial range `..=self` (through self, inclusive). **Convertible** #### initializer From Source ```kestrel init(from: From) ``` Creates an instance from `value`. ### struct Lcg64 ```kestrel public struct Lcg64 { /* private fields */ } ``` A 64-bit linear congruential generator. Cheap, allocation-free, and adequate for shuffling, fuzz seeds, and simulation noise — *not* for cryptographic use, key generation, or anything an adversary observes. Constants come from Numerical Recipes and give a full period of `2^64`: - multiplier `a = 6364136223846793005` - increment `c = 1442695040888963407` The state update is `state = state * a + c`, returning the new state. # Examples ``` var rng = Lcg64(seed: 12345); let v1 = rng.nextUInt64(); let v2 = rng.nextUInt64(); // distinct from v1 ``` # Representation One `UInt64` field — the mutable generator state. #### initializer Default ```kestrel public init() ``` Creates a generator with a hard-coded default seed (`88172645463325252`). Always produces the same stream — provide an explicit seed via `init(seed:)` when you need variation between runs. #### initializer Seeded ```kestrel public init(seed: UInt64) ``` Creates a generator initialised with `seed`. Different seeds produce independent streams; the same seed always reproduces the same stream (useful for deterministic tests). # Examples ``` var rng = Lcg64(seed: 42); ``` **RandomNumberGenerator** #### function nextInt ```kestrel public mutating func nextInt(below: Int64) -> Int64 ``` Returns a uniformly distributed integer in `[0, upperBound)`. Returns `0` when `upperBound <= 0` rather than panicking. Uses naive modulo for simplicity — for `upperBound` close to `UInt64.maxValue` the result has slight bias toward smaller values. If you need exact uniformity, sample `nextUInt64()` and reject. # Examples ``` var rng = Lcg64(seed: 42); let roll = rng.nextInt(below: 6); // 0..5 ``` #### function nextUInt64 ```kestrel public mutating func nextUInt64() -> UInt64 ``` Advances the state once and returns the new value. `O(1)` and allocation-free. **Defaultable** #### initializer Default ```kestrel init() ``` Builds the default-valued instance. ### protocol RandomNumberGenerator ```kestrel public protocol RandomNumberGenerator ``` A source of pseudo-random `UInt64` values. Implementers expose a single raw-uniform primitive; the extension on this protocol layers ergonomic helpers on top. Conformers are free to choose any algorithm they like — the protocol makes no statement about cryptographic strength, period, or bias. Pick `Lcg64` for cheap non-cryptographic randomness; bring your own type for anything stronger. # Examples ``` struct MyRng: RandomNumberGenerator { var state: UInt64; mutating func nextUInt64() -> UInt64 { // mix state, return a fresh value } } ``` #### function nextInt ```kestrel public mutating func nextInt(below: Int64) -> Int64 ``` Returns a uniformly distributed integer in `[0, upperBound)`. Returns `0` when `upperBound <= 0` rather than panicking. Uses naive modulo for simplicity — for `upperBound` close to `UInt64.maxValue` the result has slight bias toward smaller values. If you need exact uniformity, sample `nextUInt64()` and reject. # Examples ``` var rng = Lcg64(seed: 42); let roll = rng.nextInt(below: 6); // 0..5 ``` #### function nextUInt64 ```kestrel mutating func nextUInt64() -> UInt64 ``` Returns the next `UInt64` from the stream and advances internal state. Each call should be independent and uniformly distributed over the full `UInt64` range — implementers that can't promise uniformity (e.g. very small periods) should document the bias. ### protocol SignedInteger ```kestrel public protocol SignedInteger ``` Marker protocol for signed integer types. The `abs()` requirement is what justifies treating these uniformly in generic code — unsigned integers can't satisfy it without changing semantics. #### function abs ```kestrel func abs() -> Self ``` Absolute value. For two's-complement types this can overflow at `minValue`; consumers that need a total function should use `absChecked()` from the concrete type instead. ### protocol Steppable ```kestrel public protocol Steppable ``` A type whose values can be stepped one position at a time. Underpins `for-in` over integer ranges and any other "next/previous" walk where the step size is implicit (`1` for integers). `successor` and `predecessor` should be inverses for every interior value; behaviour at the type's edges (`Int64.maxValue.successor()`, for example) follows the same wrapping rules as `add`/`subtract`. #### function predecessor ```kestrel func predecessor() -> Self ``` The previous value in the sequence. For integers this is `self - 1`. #### function successor ```kestrel func successor() -> Self ``` The next value in the sequence. For integers this is `self + 1`. ### typealias UInt ```kestrel public type UInt = UInt64 ``` Platform-sized unsigned integer — currently always `UInt64`. ### struct UInt16 ```kestrel public struct UInt16 { /* private fields */ } ``` A 16-bit unsigned integer. UInt16 is the 16-bit member of the integer family. The same surface area is provided across all widths; switch widths to trade range for memory or to match an FFI ABI. Arithmetic wraps on overflow by default — use the `*Checked` variants for overflow detection or `*Saturating` to clamp to `minValue`/`maxValue`. The type is `FFISafe` and lays out as a single `lang.i16` so it can cross C boundaries unchanged. # Examples ``` let a: Int64 = 100; let b = a + 50; // 150 let c = a * 2; // 200 let d = a.addChecked(Int64.maxValue); // None (overflow detected) ``` ``` // Bit twiddling (0b1010).countOnes // 2 (1).shiftLeft(by: 4) // 16 (-1).leadingZeros // 0 (all bits set) ``` # Representation A single `lang.i16` field. No padding, no headers — bit-identical to the corresponding C type. #### initializer Default ```kestrel public init() ``` Creates the zero value, satisfying `Defaultable`. # Examples ``` let n = Int64(); // 0 ``` #### initializer From Bytes ```kestrel public init[S](fromBytes: S) where S: Slice[UInt8] ``` Reassembles a `UInt16` from 2 bytes in native byte order. Returns `null` if the input is not exactly 2 bytes long. #### initializer From Bytes Big Endian ```kestrel public init[S](fromBytesBigEndian: S) where S: Slice[UInt8] ``` Reassembles a `UInt16` from 2 bytes in big-endian order. Returns `null` if the input is not exactly 2 bytes long. #### initializer From Bytes Little Endian ```kestrel public init[S](fromBytesLittleEndian: S) where S: Slice[UInt8] ``` Reassembles a `UInt16` from 2 bytes in little-endian order. Returns `null` if the input is not exactly 2 bytes long. #### initializer From Integer ```kestrel public init(from: Int8) ``` Converts from `Int8`. Narrowing conversions truncate the high bits; signed→unsigned reinterprets the bit pattern. #### initializer From Integer ```kestrel public init(from: Int16) ``` Converts from `Int16`. Narrowing conversions truncate the high bits; signed→unsigned reinterprets the bit pattern. #### initializer From Integer ```kestrel public init(from: Int32) ``` Converts from `Int32`. Narrowing conversions truncate the high bits; signed→unsigned reinterprets the bit pattern. #### initializer From Integer ```kestrel public init(from: Int64) ``` Converts from `Int64`. Narrowing conversions truncate the high bits; signed→unsigned reinterprets the bit pattern. #### initializer From Integer ```kestrel public init(from: UInt8) ``` Converts from `UInt8`. Narrowing conversions truncate the high bits; signed→unsigned reinterprets the bit pattern. #### initializer From Integer ```kestrel public init(from: UInt32) ``` Converts from `UInt32`. Narrowing conversions truncate the high bits; signed→unsigned reinterprets the bit pattern. #### initializer From Integer ```kestrel public init(from: UInt64) ``` Converts from `UInt64`. Narrowing conversions truncate the high bits; signed→unsigned reinterprets the bit pattern. #### initializer From Raw ```kestrel init(raw: lang.i16) ``` Wraps an existing `lang.i16` without conversion. Internal constructor used by intrinsics; not part of the public API. #### initializer Int Literal ```kestrel public init(intLiteral: lang.i64) ``` Compiler-emitted bridge that turns an integer literal into a UInt16. You will rarely call this directly — write the literal and let the `ExpressibleByIntLiteral` protocol pick it up. For widths smaller than 64 bits the literal is truncated with `lang.cast_i64_i16`. # Examples ``` let n: Int64 = 42; // implicit ``` #### initializer Parse ```kestrel public init(parsing: String) ``` Parses a base-10 unsigned integer literal, optionally prefixed with `+`. A leading `-` is rejected. Returns `null` for an empty string, a non-digit character, or a value that does not fit in `UInt16`. # Examples ``` let n = UInt16(parsing: "42"); // Some(42) let bad = UInt16(parsing: "-1"); // null (no sign for unsigned) ``` #### initializer Parse Radix ```kestrel public init(parsing: String, radix: Int64) ``` Parses an unsigned integer in `radix` (base 2-36 inclusive). Letters a-z are case-insensitive and represent digit values 10-35. A leading `+` is allowed but a leading `-` is rejected. Returns `null` for an out-of-range radix, an empty string, an unrecognised digit, or a value that overflows `UInt16`. # Examples ``` let n = UInt16(parsing: "ff", radix: 16); // Some(255 if it fits, else None) let m = UInt16(parsing: "101010", radix: 2); // Some(42) ``` #### function addChecked ```kestrel public func addChecked(UInt16) -> UInt16? ``` Wrapping addition that returns `None` on overflow. For unsigned types overflow is detected via `result < self`. #### function addSaturating ```kestrel public func addSaturating(UInt16) -> UInt16 ``` Addition that clamps to `maxValue` on overflow. #### field bitWidth ```kestrel public static var bitWidth: Int64 { get } ``` The width in bits (16). Useful for shift bounds and bit-walks. #### field byteSwapped ```kestrel public var byteSwapped: UInt16 { get } ``` Value with its byte order reversed. Use to convert between big- and little-endian; lowered to a `bswap` intrinsic. #### function clamp ```kestrel public func clamp(UInt16, UInt16) -> UInt16 ``` Clamps `self` into `[min, max]`. Caller is responsible for ensuring `min <= max`; otherwise the result is undefined. # Examples ``` (5).clamp(0, 10); // 5 (-5).clamp(0, 10); // 0 (15).clamp(0, 10); // 10 ``` #### field countOnes ```kestrel public var countOnes: Int64 { get } ``` Population count — the number of `1` bits in the binary representation. Lowered to a `popcount` intrinsic where the target supports it. # Examples ``` (0b1010).countOnes; // 2 (0b1111).countOnes; // 4 (0).countOnes; // 0 ``` #### field countZeros ```kestrel public var countZeros: Int64 { get } ``` Complement of `countOnes`: equal to `bitWidth - countOnes`. #### function divideChecked ```kestrel public func divideChecked(UInt16) -> UInt16? ``` Division that returns `None` for divide-by-zero. #### function gcd ```kestrel public func gcd(UInt16) -> UInt16 ``` Greatest common divisor via Euclidean algorithm. For signed types the inputs are taken absolute first; the result is always non-negative. # Examples ``` (12).gcd(8); // 4 (17).gcd(5); // 1 (coprime) (-12).gcd(8); // 4 ``` #### field isNegative ```kestrel public var isNegative: Bool { get } ``` Always `false` — unsigned types cannot be negative. #### field isPositive ```kestrel public var isPositive: Bool { get } ``` True when `self > 0`. #### field isPowerOfTwo ```kestrel public var isPowerOfTwo: Bool { get } ``` True when the value is a positive power of two (`2^k` for `k >= 0`). Zero and negatives are excluded. Cheap branchless test built on `x & (x - 1) == 0`. # Examples ``` (1).isPowerOfTwo; // true (2^0) (4).isPowerOfTwo; // true (2^2) (3).isPowerOfTwo; // false (0).isPowerOfTwo; // false ``` #### field isZero ```kestrel public var isZero: Bool { get } ``` True when `self == 0`. #### function lcm ```kestrel public func lcm(UInt16) -> UInt16 ``` Least common multiple, computed as `|self| / gcd(self, other) * |other|` to avoid intermediate overflow. Returns zero if either input is zero. # Examples ``` (4).lcm(6); // 12 (3).lcm(5); // 15 (0).lcm(7); // 0 ``` #### field leadingZeros ```kestrel public var leadingZeros: Int64 { get } ``` Number of leading zero bits, counting from the most-significant end. For zero, returns `bitWidth`. # Examples ``` (1).leadingZeros; // bitWidth - 1 (0).leadingZeros; // bitWidth ``` #### field maxValue ```kestrel public static var maxValue: UInt16 { get } ``` The largest representable value. This is 2^16 - 1 (65_535). #### field minValue ```kestrel public static var minValue: UInt16 { get } ``` The smallest representable value. This is always 0 for unsigned types. Note that for signed types `minValue.negate()` overflows back to itself; use `negateChecked()` if you need to detect that. #### function multiplyChecked ```kestrel public func multiplyChecked(UInt16) -> UInt16? ``` Wrapping multiplication that returns `None` on overflow. Implemented by multiplying then dividing back. #### function multiplySaturating ```kestrel public func multiplySaturating(UInt16) -> UInt16 ``` Multiplication that clamps to `maxValue` on overflow. #### function pow ```kestrel public func pow(Int64) -> UInt16 ``` Raises `self` to `exponent` via binary exponentiation. Wraps on overflow. Negative exponents return zero (integer truncation of the would-be fraction). # Examples ``` (2).pow(10); // 1024 (3).pow(4); // 81 (5).pow(-1); // 0 ``` #### field raw ```kestrel public var raw: lang.i16 ``` The underlying primitive `lang.i16` value. Exposed for FFI and intrinsic use; prefer the typed surface for everything else. #### function rotateLeft ```kestrel public func rotateLeft(by: Int64) -> UInt16 ``` Rotates bits left by `count`, modulo `bitWidth`. Bits shifted past the MSB re-enter at the LSB. #### function rotateRight ```kestrel public func rotateRight(by: Int64) -> UInt16 ``` Rotates bits right by `count`, modulo `bitWidth`. Mirror of `rotateLeft`. #### field sign ```kestrel public var sign: UInt16 { get } ``` Sign as a `UInt16`: `0` for zero, `1` otherwise (unsigned types have no negative values). #### function subtractChecked ```kestrel public func subtractChecked(UInt16) -> UInt16? ``` Subtraction that returns `None` on underflow (`other > self`). #### function subtractSaturating ```kestrel public func subtractSaturating(UInt16) -> UInt16 ``` Subtraction that clamps to `0` on underflow (unsigned types cannot represent negative results). #### function toBytes ```kestrel public func toBytes() -> std.collections.Array[UInt8] ``` Splits this integer into 2 bytes in *native* (host) byte order. Use `toBytesBigEndian` / `toBytesLittleEndian` when serialising for a fixed wire format. # Examples ``` let bytes = UInt16.maxValue.toBytes(); // 2 bytes, host order ``` #### function toBytesBigEndian ```kestrel public func toBytesBigEndian() -> std.collections.Array[UInt8] ``` Splits this integer into 2 bytes in big-endian order (most significant byte first — i.e. network byte order). #### function toBytesLittleEndian ```kestrel public func toBytesLittleEndian() -> std.collections.Array[UInt8] ``` Splits this integer into 2 bytes in little-endian order (least significant byte first). #### field trailingZeros ```kestrel public var trailingZeros: Int64 { get } ``` Number of trailing zero bits. Equal to `log2(self & -self)` for non-zero values; returns `bitWidth` for zero. Useful for finding the largest power of two dividing the value. **Steppable** #### function predecessor ```kestrel public func predecessor() -> UInt16 ``` Predecessor — `self - 1`. Wraps at `minValue`. #### function successor ```kestrel public func successor() -> UInt16 ``` Successor — `self + 1`. Wraps at `maxValue`. Used by `for-in` over integer ranges. **Comparable** #### typealias Output ```kestrel type Output = Bool ``` #### function compare ```kestrel public func compare(UInt16) -> Ordering ``` Three-way comparison returning an `Ordering`. Signed types compare using two's-complement ordering; unsigned types use natural ordering. # Examples ``` (1).compare(2); // .Less (2).compare(2); // .Equal (3).compare(2); // .Greater ``` #### function greaterThan ```kestrel public func greaterThan(Self) -> Bool ``` `>` derived from `compare`. #### function greaterThanOrEqual ```kestrel public func greaterThanOrEqual(Self) -> Bool ``` `>=` derived from `compare`. #### function isAtLeast ```kestrel public func isAtLeast(Self) -> Bool ``` `start..` lower-bound check, derived from `compare`. #### function isAtMost ```kestrel public func isAtMost(Self) -> Bool ``` `..=end` upper-bound check, derived from `compare`. #### function isBelow ```kestrel public func isBelow(Self) -> Bool ``` `.. Bool ``` `<` derived from `compare`. #### function lessThanOrEqual ```kestrel public func lessThanOrEqual(Self) -> Bool ``` `<=` derived from `compare`. **Equatable** #### typealias Output ```kestrel type Output = Bool ``` #### function equal ```kestrel public func equal(to: Self) -> Bool ``` Bridges `Equal.equal(to:)` to `Equatable.isEqual(to:)`. #### function isEqual ```kestrel public func isEqual(to: UInt16) -> Bool ``` Bit-for-bit equality. Backs the `==` operator. # Examples ``` (42).isEqual(to: 42); // true 42 == 42; // true ``` #### function notEqual ```kestrel public func notEqual(to: Self) -> Bool ``` Default `!=`: delegates to `==` so there's a single source of truth. **Matchable** #### function matches ```kestrel public func matches(UInt16) -> Bool ``` Pattern-matching hook for `Matchable`. Identical to `isEqual`. **Formattable** #### function format ```kestrel public func format(into: mutating StringBuilder, FormatOptions) ``` Formats the integer directly into `writer`, honouring the supplied `FormatOptions`. Implements the `Formattable` protocol. # Examples ``` (42).format(); // "42" (255).format(.{radix: 16}); // "ff" (255).format(.{radix: 16, uppercase: true}); // "FF" (255).format(.{radix: 16, alternate: true}); // "0xff" (42).format(.{radix: 2, alternate: true}); // "0b101010" (42).format(.{width: .Some(5), fill: '0'}); // "00042" (-42).format(.{sign: .Always}); // "-42" ``` #### function formatted ```kestrel public func formatted(FormatOptions) -> String ``` Returns this value rendered as a `String`. Convenience wrapper: creates a `StringBuilder`, calls `format(into:)`, and returns the built string. Uses a distinct name to avoid overload-resolution ambiguity with `format(into:)`. **Hashable** #### function hash ```kestrel public func hash[H](into: mutating H) where H: Hasher ``` Feeds the raw bytes of this value into `hasher`. Endianness-agnostic only within a single process — do not persist hashes across builds. **Addable** #### typealias Output ```kestrel type Output = UInt16 ``` #### typealias Output ```kestrel type Output = UInt16 ``` #### typealias Output ```kestrel type Output = UInt16 ``` #### typealias Output ```kestrel type Output = UInt16 ``` #### typealias Output ```kestrel type Output = UInt16 ``` #### typealias Output ```kestrel type Output = UInt16 ``` #### typealias Output ```kestrel type Output = UInt16 ``` #### typealias Output ```kestrel type Output = UInt16 ``` #### typealias Output ```kestrel type Output = UInt16 ``` #### typealias Output ```kestrel type Output = UInt16 ``` #### typealias Output ```kestrel type Output = UInt16 ``` #### typealias Output ```kestrel type Output = Range[UInt16] ``` #### typealias Output ```kestrel type Output = ClosedRange[UInt16] ``` #### typealias Output ```kestrel type Output = RangeFrom[UInt16] ``` #### typealias Output ```kestrel type Output = RangeUpTo[UInt16] ``` #### typealias Output ```kestrel type Output = RangeThrough[UInt16] ``` #### function add ```kestrel public consuming func add(consuming UInt16) -> UInt16 ``` `self + other`, wrapping on overflow. Use `addChecked` to detect or `addSaturating` to clamp. #### field zero ```kestrel public static var zero: UInt16 { get } ``` The additive identity, `0`. **Subtractable** #### typealias Output ```kestrel type Output ``` #### function subtract ```kestrel public consuming func subtract(consuming UInt16) -> UInt16 ``` `self - other`, wrapping on overflow. **Multipliable** #### typealias Output ```kestrel type Output ``` #### function multiply ```kestrel public consuming func multiply(consuming UInt16) -> UInt16 ``` `self * other`, wrapping on overflow. #### field one ```kestrel public static var one: UInt16 { get } ``` The multiplicative identity, `1`. **Divisible** #### typealias Output ```kestrel type Output ``` #### function divide ```kestrel public consuming func divide(consuming UInt16) -> UInt16 ``` Truncating integer division (`self / other`). For signed types, `minValue / -1` wraps; use `divideChecked` to detect. # Errors Traps on division by zero (LLVM `udiv`/`sdiv` are UB on zero — the process aborts before producing a result). **Modulo** #### typealias Output ```kestrel type Output ``` #### function modulo ```kestrel public consuming func modulo(consuming UInt16) -> UInt16 ``` `self % other` — truncated remainder; the result has the sign of `self` for signed types. # Errors Traps on division by zero, like `divide`. **BitwiseAnd** #### typealias Output ```kestrel type Output ``` #### function bitwiseAnd ```kestrel public consuming func bitwiseAnd(consuming UInt16) -> UInt16 ``` Bitwise AND. `0b1010 & 0b1100 == 0b1000`. **BitwiseOr** #### typealias Output ```kestrel type Output ``` #### function bitwiseOr ```kestrel public consuming func bitwiseOr(consuming UInt16) -> UInt16 ``` Bitwise OR. `0b1010 | 0b1100 == 0b1110`. **BitwiseXor** #### typealias Output ```kestrel type Output ``` #### function bitwiseXor ```kestrel public consuming func bitwiseXor(consuming UInt16) -> UInt16 ``` Bitwise XOR. `0b1010 ^ 0b1100 == 0b0110`. **BitwiseNot** #### typealias Output ```kestrel type Output ``` #### function bitwiseNot ```kestrel public consuming func bitwiseNot() -> UInt16 ``` Bitwise NOT — flips all bits. For signed types this is `-self - 1`. **LeftShift** #### typealias Output ```kestrel type Output ``` #### function shiftLeft ```kestrel public consuming func shiftLeft(by: consuming Int64) -> UInt16 ``` Left shift by `count`. Behavior is undefined when `count >= bitWidth` — pre-mask the count if you can't guarantee the bound. **RightShift** #### typealias Output ```kestrel type Output ``` #### function shiftRight ```kestrel public consuming func shiftRight(by: consuming Int64) -> UInt16 ``` Right shift by `count`. Arithmetic (sign-extending) for signed types, logical (zero-filling) for unsigned. Same `count` precondition as `shiftLeft`. **AddAssign** #### function addAssign ```kestrel public mutating func addAssign(UInt16) ``` `self += other` **SubtractAssign** #### function subtractAssign ```kestrel public mutating func subtractAssign(UInt16) ``` `self -= other` **MultiplyAssign** #### function multiplyAssign ```kestrel public mutating func multiplyAssign(UInt16) ``` `self *= other` **DivideAssign** #### function divideAssign ```kestrel public mutating func divideAssign(UInt16) ``` `self /= other` **ModuloAssign** #### function modAssign ```kestrel public mutating func modAssign(UInt16) ``` `self %= other` **BitwiseAndAssign** #### function bitwiseAndAssign ```kestrel public mutating func bitwiseAndAssign(UInt16) ``` `self &= other` **BitwiseOrAssign** #### function bitwiseOrAssign ```kestrel public mutating func bitwiseOrAssign(UInt16) ``` `self |= other` **BitwiseXorAssign** #### function bitwiseXorAssign ```kestrel public mutating func bitwiseXorAssign(UInt16) ``` `self ^= other` **LeftShiftAssign** #### function shiftLeftAssign ```kestrel public mutating func shiftLeftAssign(by: Int64) ``` `self <<= count` **RightShiftAssign** #### function shiftRightAssign ```kestrel public mutating func shiftRightAssign(by: Int64) ``` `self >>= count` **ExpressibleByIntLiteral** #### initializer Int Literal ```kestrel init(intLiteral: lang.i64) ``` Builds an instance from an integer literal. **Defaultable** #### initializer Default ```kestrel init() ``` Builds the default-valued instance. **RangeConstructible** #### typealias Output ```kestrel type Output ``` #### function exclusiveRange ```kestrel public func exclusiveRange(to: UInt16) -> Range[UInt16] ``` Builds a half-open range `self.. ClosedRange[UInt16] ``` Builds a closed range `self..=end`. Sugar for the `..=` operator. **RangeFromConstructible** #### typealias Output ```kestrel type Output ``` #### function rangeFrom ```kestrel public func rangeFrom() -> RangeFrom[UInt16] ``` Builds a partial range `self..` (from self, no upper bound). **RangeUpToConstructible** #### typealias Output ```kestrel type Output ``` #### function rangeUpTo ```kestrel public func rangeUpTo() -> RangeUpTo[UInt16] ``` Builds a partial range `.. RangeThrough[UInt16] ``` Builds a partial range `..=self` (through self, inclusive). **Convertible** #### initializer From Source ```kestrel init(from: From) ``` Creates an instance from `value`. ### struct UInt32 ```kestrel public struct UInt32 { /* private fields */ } ``` A 32-bit unsigned integer. UInt32 is the 32-bit member of the integer family. The same surface area is provided across all widths; switch widths to trade range for memory or to match an FFI ABI. Arithmetic wraps on overflow by default — use the `*Checked` variants for overflow detection or `*Saturating` to clamp to `minValue`/`maxValue`. The type is `FFISafe` and lays out as a single `lang.i32` so it can cross C boundaries unchanged. # Examples ``` let a: Int64 = 100; let b = a + 50; // 150 let c = a * 2; // 200 let d = a.addChecked(Int64.maxValue); // None (overflow detected) ``` ``` // Bit twiddling (0b1010).countOnes // 2 (1).shiftLeft(by: 4) // 16 (-1).leadingZeros // 0 (all bits set) ``` # Representation A single `lang.i32` field. No padding, no headers — bit-identical to the corresponding C type. #### initializer Default ```kestrel public init() ``` Creates the zero value, satisfying `Defaultable`. # Examples ``` let n = Int64(); // 0 ``` #### initializer From Bytes ```kestrel public init[S](fromBytes: S) where S: Slice[UInt8] ``` Reassembles a `UInt32` from 4 bytes in native byte order. Returns `null` if the input is not exactly 4 bytes long. #### initializer From Bytes Big Endian ```kestrel public init[S](fromBytesBigEndian: S) where S: Slice[UInt8] ``` Reassembles a `UInt32` from 4 bytes in big-endian order. Returns `null` if the input is not exactly 4 bytes long. #### initializer From Bytes Little Endian ```kestrel public init[S](fromBytesLittleEndian: S) where S: Slice[UInt8] ``` Reassembles a `UInt32` from 4 bytes in little-endian order. Returns `null` if the input is not exactly 4 bytes long. #### initializer From Integer ```kestrel public init(from: Int8) ``` Converts from `Int8`. Narrowing conversions truncate the high bits; signed→unsigned reinterprets the bit pattern. #### initializer From Integer ```kestrel public init(from: Int16) ``` Converts from `Int16`. Narrowing conversions truncate the high bits; signed→unsigned reinterprets the bit pattern. #### initializer From Integer ```kestrel public init(from: Int32) ``` Converts from `Int32`. Narrowing conversions truncate the high bits; signed→unsigned reinterprets the bit pattern. #### initializer From Integer ```kestrel public init(from: Int64) ``` Converts from `Int64`. Narrowing conversions truncate the high bits; signed→unsigned reinterprets the bit pattern. #### initializer From Integer ```kestrel public init(from: UInt8) ``` Converts from `UInt8`. Narrowing conversions truncate the high bits; signed→unsigned reinterprets the bit pattern. #### initializer From Integer ```kestrel public init(from: UInt16) ``` Converts from `UInt16`. Narrowing conversions truncate the high bits; signed→unsigned reinterprets the bit pattern. #### initializer From Integer ```kestrel public init(from: UInt64) ``` Converts from `UInt64`. Narrowing conversions truncate the high bits; signed→unsigned reinterprets the bit pattern. #### initializer From Raw ```kestrel init(raw: lang.i32) ``` Wraps an existing `lang.i32` without conversion. Internal constructor used by intrinsics; not part of the public API. #### initializer Int Literal ```kestrel public init(intLiteral: lang.i64) ``` Compiler-emitted bridge that turns an integer literal into a UInt32. You will rarely call this directly — write the literal and let the `ExpressibleByIntLiteral` protocol pick it up. For widths smaller than 64 bits the literal is truncated with `lang.cast_i64_i32`. # Examples ``` let n: Int64 = 42; // implicit ``` #### initializer Parse ```kestrel public init(parsing: String) ``` Parses a base-10 unsigned integer literal, optionally prefixed with `+`. A leading `-` is rejected. Returns `null` for an empty string, a non-digit character, or a value that does not fit in `UInt32`. # Examples ``` let n = UInt32(parsing: "42"); // Some(42) let bad = UInt32(parsing: "-1"); // null (no sign for unsigned) ``` #### initializer Parse Radix ```kestrel public init(parsing: String, radix: Int64) ``` Parses an unsigned integer in `radix` (base 2-36 inclusive). Letters a-z are case-insensitive and represent digit values 10-35. A leading `+` is allowed but a leading `-` is rejected. Returns `null` for an out-of-range radix, an empty string, an unrecognised digit, or a value that overflows `UInt32`. # Examples ``` let n = UInt32(parsing: "ff", radix: 16); // Some(255 if it fits, else None) let m = UInt32(parsing: "101010", radix: 2); // Some(42) ``` #### function addChecked ```kestrel public func addChecked(UInt32) -> UInt32? ``` Wrapping addition that returns `None` on overflow. For unsigned types overflow is detected via `result < self`. #### function addSaturating ```kestrel public func addSaturating(UInt32) -> UInt32 ``` Addition that clamps to `maxValue` on overflow. #### field bitWidth ```kestrel public static var bitWidth: Int64 { get } ``` The width in bits (32). Useful for shift bounds and bit-walks. #### field byteSwapped ```kestrel public var byteSwapped: UInt32 { get } ``` Value with its byte order reversed. Use to convert between big- and little-endian; lowered to a `bswap` intrinsic. #### function clamp ```kestrel public func clamp(UInt32, UInt32) -> UInt32 ``` Clamps `self` into `[min, max]`. Caller is responsible for ensuring `min <= max`; otherwise the result is undefined. # Examples ``` (5).clamp(0, 10); // 5 (-5).clamp(0, 10); // 0 (15).clamp(0, 10); // 10 ``` #### field countOnes ```kestrel public var countOnes: Int64 { get } ``` Population count — the number of `1` bits in the binary representation. Lowered to a `popcount` intrinsic where the target supports it. # Examples ``` (0b1010).countOnes; // 2 (0b1111).countOnes; // 4 (0).countOnes; // 0 ``` #### field countZeros ```kestrel public var countZeros: Int64 { get } ``` Complement of `countOnes`: equal to `bitWidth - countOnes`. #### function divideChecked ```kestrel public func divideChecked(UInt32) -> UInt32? ``` Division that returns `None` for divide-by-zero. #### function gcd ```kestrel public func gcd(UInt32) -> UInt32 ``` Greatest common divisor via Euclidean algorithm. For signed types the inputs are taken absolute first; the result is always non-negative. # Examples ``` (12).gcd(8); // 4 (17).gcd(5); // 1 (coprime) (-12).gcd(8); // 4 ``` #### field isNegative ```kestrel public var isNegative: Bool { get } ``` Always `false` — unsigned types cannot be negative. #### field isPositive ```kestrel public var isPositive: Bool { get } ``` True when `self > 0`. #### field isPowerOfTwo ```kestrel public var isPowerOfTwo: Bool { get } ``` True when the value is a positive power of two (`2^k` for `k >= 0`). Zero and negatives are excluded. Cheap branchless test built on `x & (x - 1) == 0`. # Examples ``` (1).isPowerOfTwo; // true (2^0) (4).isPowerOfTwo; // true (2^2) (3).isPowerOfTwo; // false (0).isPowerOfTwo; // false ``` #### field isZero ```kestrel public var isZero: Bool { get } ``` True when `self == 0`. #### function lcm ```kestrel public func lcm(UInt32) -> UInt32 ``` Least common multiple, computed as `|self| / gcd(self, other) * |other|` to avoid intermediate overflow. Returns zero if either input is zero. # Examples ``` (4).lcm(6); // 12 (3).lcm(5); // 15 (0).lcm(7); // 0 ``` #### field leadingZeros ```kestrel public var leadingZeros: Int64 { get } ``` Number of leading zero bits, counting from the most-significant end. For zero, returns `bitWidth`. # Examples ``` (1).leadingZeros; // bitWidth - 1 (0).leadingZeros; // bitWidth ``` #### field maxValue ```kestrel public static var maxValue: UInt32 { get } ``` The largest representable value. This is 2^32 - 1 (4_294_967_295). #### field minValue ```kestrel public static var minValue: UInt32 { get } ``` The smallest representable value. This is always 0 for unsigned types. Note that for signed types `minValue.negate()` overflows back to itself; use `negateChecked()` if you need to detect that. #### function multiplyChecked ```kestrel public func multiplyChecked(UInt32) -> UInt32? ``` Wrapping multiplication that returns `None` on overflow. Implemented by multiplying then dividing back. #### function multiplySaturating ```kestrel public func multiplySaturating(UInt32) -> UInt32 ``` Multiplication that clamps to `maxValue` on overflow. #### function pow ```kestrel public func pow(Int64) -> UInt32 ``` Raises `self` to `exponent` via binary exponentiation. Wraps on overflow. Negative exponents return zero (integer truncation of the would-be fraction). # Examples ``` (2).pow(10); // 1024 (3).pow(4); // 81 (5).pow(-1); // 0 ``` #### field raw ```kestrel public var raw: lang.i32 ``` The underlying primitive `lang.i32` value. Exposed for FFI and intrinsic use; prefer the typed surface for everything else. #### function rotateLeft ```kestrel public func rotateLeft(by: Int64) -> UInt32 ``` Rotates bits left by `count`, modulo `bitWidth`. Bits shifted past the MSB re-enter at the LSB. #### function rotateRight ```kestrel public func rotateRight(by: Int64) -> UInt32 ``` Rotates bits right by `count`, modulo `bitWidth`. Mirror of `rotateLeft`. #### field sign ```kestrel public var sign: UInt32 { get } ``` Sign as a `UInt32`: `0` for zero, `1` otherwise (unsigned types have no negative values). #### function subtractChecked ```kestrel public func subtractChecked(UInt32) -> UInt32? ``` Subtraction that returns `None` on underflow (`other > self`). #### function subtractSaturating ```kestrel public func subtractSaturating(UInt32) -> UInt32 ``` Subtraction that clamps to `0` on underflow (unsigned types cannot represent negative results). #### function toBytes ```kestrel public func toBytes() -> std.collections.Array[UInt8] ``` Splits this integer into 4 bytes in *native* (host) byte order. Use `toBytesBigEndian` / `toBytesLittleEndian` when serialising for a fixed wire format. # Examples ``` let bytes = UInt32.maxValue.toBytes(); // 4 bytes, host order ``` #### function toBytesBigEndian ```kestrel public func toBytesBigEndian() -> std.collections.Array[UInt8] ``` Splits this integer into 4 bytes in big-endian order (most significant byte first — i.e. network byte order). #### function toBytesLittleEndian ```kestrel public func toBytesLittleEndian() -> std.collections.Array[UInt8] ``` Splits this integer into 4 bytes in little-endian order (least significant byte first). #### field trailingZeros ```kestrel public var trailingZeros: Int64 { get } ``` Number of trailing zero bits. Equal to `log2(self & -self)` for non-zero values; returns `bitWidth` for zero. Useful for finding the largest power of two dividing the value. **Steppable** #### function predecessor ```kestrel public func predecessor() -> UInt32 ``` Predecessor — `self - 1`. Wraps at `minValue`. #### function successor ```kestrel public func successor() -> UInt32 ``` Successor — `self + 1`. Wraps at `maxValue`. Used by `for-in` over integer ranges. **Comparable** #### typealias Output ```kestrel type Output = Bool ``` #### function compare ```kestrel public func compare(UInt32) -> Ordering ``` Three-way comparison returning an `Ordering`. Signed types compare using two's-complement ordering; unsigned types use natural ordering. # Examples ``` (1).compare(2); // .Less (2).compare(2); // .Equal (3).compare(2); // .Greater ``` #### function greaterThan ```kestrel public func greaterThan(Self) -> Bool ``` `>` derived from `compare`. #### function greaterThanOrEqual ```kestrel public func greaterThanOrEqual(Self) -> Bool ``` `>=` derived from `compare`. #### function isAtLeast ```kestrel public func isAtLeast(Self) -> Bool ``` `start..` lower-bound check, derived from `compare`. #### function isAtMost ```kestrel public func isAtMost(Self) -> Bool ``` `..=end` upper-bound check, derived from `compare`. #### function isBelow ```kestrel public func isBelow(Self) -> Bool ``` `.. Bool ``` `<` derived from `compare`. #### function lessThanOrEqual ```kestrel public func lessThanOrEqual(Self) -> Bool ``` `<=` derived from `compare`. **Equatable** #### typealias Output ```kestrel type Output = Bool ``` #### function equal ```kestrel public func equal(to: Self) -> Bool ``` Bridges `Equal.equal(to:)` to `Equatable.isEqual(to:)`. #### function isEqual ```kestrel public func isEqual(to: UInt32) -> Bool ``` Bit-for-bit equality. Backs the `==` operator. # Examples ``` (42).isEqual(to: 42); // true 42 == 42; // true ``` #### function notEqual ```kestrel public func notEqual(to: Self) -> Bool ``` Default `!=`: delegates to `==` so there's a single source of truth. **Matchable** #### function matches ```kestrel public func matches(UInt32) -> Bool ``` Pattern-matching hook for `Matchable`. Identical to `isEqual`. **Formattable** #### function format ```kestrel public func format(into: mutating StringBuilder, FormatOptions) ``` Formats the integer directly into `writer`, honouring the supplied `FormatOptions`. Implements the `Formattable` protocol. # Examples ``` (42).format(); // "42" (255).format(.{radix: 16}); // "ff" (255).format(.{radix: 16, uppercase: true}); // "FF" (255).format(.{radix: 16, alternate: true}); // "0xff" (42).format(.{radix: 2, alternate: true}); // "0b101010" (42).format(.{width: .Some(5), fill: '0'}); // "00042" (-42).format(.{sign: .Always}); // "-42" ``` #### function formatted ```kestrel public func formatted(FormatOptions) -> String ``` Returns this value rendered as a `String`. Convenience wrapper: creates a `StringBuilder`, calls `format(into:)`, and returns the built string. Uses a distinct name to avoid overload-resolution ambiguity with `format(into:)`. **Hashable** #### function hash ```kestrel public func hash[H](into: mutating H) where H: Hasher ``` Feeds the raw bytes of this value into `hasher`. Endianness-agnostic only within a single process — do not persist hashes across builds. **Addable** #### typealias Output ```kestrel type Output = UInt32 ``` #### typealias Output ```kestrel type Output = UInt32 ``` #### typealias Output ```kestrel type Output = UInt32 ``` #### typealias Output ```kestrel type Output = UInt32 ``` #### typealias Output ```kestrel type Output = UInt32 ``` #### typealias Output ```kestrel type Output = UInt32 ``` #### typealias Output ```kestrel type Output = UInt32 ``` #### typealias Output ```kestrel type Output = UInt32 ``` #### typealias Output ```kestrel type Output = UInt32 ``` #### typealias Output ```kestrel type Output = UInt32 ``` #### typealias Output ```kestrel type Output = UInt32 ``` #### typealias Output ```kestrel type Output = Range[UInt32] ``` #### typealias Output ```kestrel type Output = ClosedRange[UInt32] ``` #### typealias Output ```kestrel type Output = RangeFrom[UInt32] ``` #### typealias Output ```kestrel type Output = RangeUpTo[UInt32] ``` #### typealias Output ```kestrel type Output = RangeThrough[UInt32] ``` #### function add ```kestrel public consuming func add(consuming UInt32) -> UInt32 ``` `self + other`, wrapping on overflow. Use `addChecked` to detect or `addSaturating` to clamp. #### field zero ```kestrel public static var zero: UInt32 { get } ``` The additive identity, `0`. **Subtractable** #### typealias Output ```kestrel type Output ``` #### function subtract ```kestrel public consuming func subtract(consuming UInt32) -> UInt32 ``` `self - other`, wrapping on overflow. **Multipliable** #### typealias Output ```kestrel type Output ``` #### function multiply ```kestrel public consuming func multiply(consuming UInt32) -> UInt32 ``` `self * other`, wrapping on overflow. #### field one ```kestrel public static var one: UInt32 { get } ``` The multiplicative identity, `1`. **Divisible** #### typealias Output ```kestrel type Output ``` #### function divide ```kestrel public consuming func divide(consuming UInt32) -> UInt32 ``` Truncating integer division (`self / other`). For signed types, `minValue / -1` wraps; use `divideChecked` to detect. # Errors Traps on division by zero (LLVM `udiv`/`sdiv` are UB on zero — the process aborts before producing a result). **Modulo** #### typealias Output ```kestrel type Output ``` #### function modulo ```kestrel public consuming func modulo(consuming UInt32) -> UInt32 ``` `self % other` — truncated remainder; the result has the sign of `self` for signed types. # Errors Traps on division by zero, like `divide`. **BitwiseAnd** #### typealias Output ```kestrel type Output ``` #### function bitwiseAnd ```kestrel public consuming func bitwiseAnd(consuming UInt32) -> UInt32 ``` Bitwise AND. `0b1010 & 0b1100 == 0b1000`. **BitwiseOr** #### typealias Output ```kestrel type Output ``` #### function bitwiseOr ```kestrel public consuming func bitwiseOr(consuming UInt32) -> UInt32 ``` Bitwise OR. `0b1010 | 0b1100 == 0b1110`. **BitwiseXor** #### typealias Output ```kestrel type Output ``` #### function bitwiseXor ```kestrel public consuming func bitwiseXor(consuming UInt32) -> UInt32 ``` Bitwise XOR. `0b1010 ^ 0b1100 == 0b0110`. **BitwiseNot** #### typealias Output ```kestrel type Output ``` #### function bitwiseNot ```kestrel public consuming func bitwiseNot() -> UInt32 ``` Bitwise NOT — flips all bits. For signed types this is `-self - 1`. **LeftShift** #### typealias Output ```kestrel type Output ``` #### function shiftLeft ```kestrel public consuming func shiftLeft(by: consuming Int64) -> UInt32 ``` Left shift by `count`. Behavior is undefined when `count >= bitWidth` — pre-mask the count if you can't guarantee the bound. **RightShift** #### typealias Output ```kestrel type Output ``` #### function shiftRight ```kestrel public consuming func shiftRight(by: consuming Int64) -> UInt32 ``` Right shift by `count`. Arithmetic (sign-extending) for signed types, logical (zero-filling) for unsigned. Same `count` precondition as `shiftLeft`. **AddAssign** #### function addAssign ```kestrel public mutating func addAssign(UInt32) ``` `self += other` **SubtractAssign** #### function subtractAssign ```kestrel public mutating func subtractAssign(UInt32) ``` `self -= other` **MultiplyAssign** #### function multiplyAssign ```kestrel public mutating func multiplyAssign(UInt32) ``` `self *= other` **DivideAssign** #### function divideAssign ```kestrel public mutating func divideAssign(UInt32) ``` `self /= other` **ModuloAssign** #### function modAssign ```kestrel public mutating func modAssign(UInt32) ``` `self %= other` **BitwiseAndAssign** #### function bitwiseAndAssign ```kestrel public mutating func bitwiseAndAssign(UInt32) ``` `self &= other` **BitwiseOrAssign** #### function bitwiseOrAssign ```kestrel public mutating func bitwiseOrAssign(UInt32) ``` `self |= other` **BitwiseXorAssign** #### function bitwiseXorAssign ```kestrel public mutating func bitwiseXorAssign(UInt32) ``` `self ^= other` **LeftShiftAssign** #### function shiftLeftAssign ```kestrel public mutating func shiftLeftAssign(by: Int64) ``` `self <<= count` **RightShiftAssign** #### function shiftRightAssign ```kestrel public mutating func shiftRightAssign(by: Int64) ``` `self >>= count` **ExpressibleByIntLiteral** #### initializer Int Literal ```kestrel init(intLiteral: lang.i64) ``` Builds an instance from an integer literal. **Defaultable** #### initializer Default ```kestrel init() ``` Builds the default-valued instance. **RangeConstructible** #### typealias Output ```kestrel type Output ``` #### function exclusiveRange ```kestrel public func exclusiveRange(to: UInt32) -> Range[UInt32] ``` Builds a half-open range `self.. ClosedRange[UInt32] ``` Builds a closed range `self..=end`. Sugar for the `..=` operator. **RangeFromConstructible** #### typealias Output ```kestrel type Output ``` #### function rangeFrom ```kestrel public func rangeFrom() -> RangeFrom[UInt32] ``` Builds a partial range `self..` (from self, no upper bound). **RangeUpToConstructible** #### typealias Output ```kestrel type Output ``` #### function rangeUpTo ```kestrel public func rangeUpTo() -> RangeUpTo[UInt32] ``` Builds a partial range `.. RangeThrough[UInt32] ``` Builds a partial range `..=self` (through self, inclusive). **Convertible** #### initializer From Source ```kestrel init(from: From) ``` Creates an instance from `value`. ### struct UInt64 ```kestrel public struct UInt64 { /* private fields */ } ``` A 64-bit unsigned integer. UInt64 is the 64-bit member of the integer family. The same surface area is provided across all widths; switch widths to trade range for memory or to match an FFI ABI. Arithmetic wraps on overflow by default — use the `*Checked` variants for overflow detection or `*Saturating` to clamp to `minValue`/`maxValue`. The type is `FFISafe` and lays out as a single `lang.i64` so it can cross C boundaries unchanged. # Examples ``` let a: Int64 = 100; let b = a + 50; // 150 let c = a * 2; // 200 let d = a.addChecked(Int64.maxValue); // None (overflow detected) ``` ``` // Bit twiddling (0b1010).countOnes // 2 (1).shiftLeft(by: 4) // 16 (-1).leadingZeros // 0 (all bits set) ``` # Representation A single `lang.i64` field. No padding, no headers — bit-identical to the corresponding C type. #### initializer Default ```kestrel public init() ``` Creates the zero value, satisfying `Defaultable`. # Examples ``` let n = Int64(); // 0 ``` #### initializer From Bytes ```kestrel public init[S](fromBytes: S) where S: Slice[UInt8] ``` Reassembles a `UInt64` from 8 bytes in native byte order. Returns `null` if the input is not exactly 8 bytes long. #### initializer From Bytes Big Endian ```kestrel public init[S](fromBytesBigEndian: S) where S: Slice[UInt8] ``` Reassembles a `UInt64` from 8 bytes in big-endian order. Returns `null` if the input is not exactly 8 bytes long. #### initializer From Bytes Little Endian ```kestrel public init[S](fromBytesLittleEndian: S) where S: Slice[UInt8] ``` Reassembles a `UInt64` from 8 bytes in little-endian order. Returns `null` if the input is not exactly 8 bytes long. #### initializer From Integer ```kestrel public init(from: Int8) ``` Converts from `Int8`. Narrowing conversions truncate the high bits; signed→unsigned reinterprets the bit pattern. #### initializer From Integer ```kestrel public init(from: Int16) ``` Converts from `Int16`. Narrowing conversions truncate the high bits; signed→unsigned reinterprets the bit pattern. #### initializer From Integer ```kestrel public init(from: Int32) ``` Converts from `Int32`. Narrowing conversions truncate the high bits; signed→unsigned reinterprets the bit pattern. #### initializer From Integer ```kestrel public init(from: Int64) ``` Converts from `Int64`. Narrowing conversions truncate the high bits; signed→unsigned reinterprets the bit pattern. #### initializer From Integer ```kestrel public init(from: UInt8) ``` Converts from `UInt8`. Narrowing conversions truncate the high bits; signed→unsigned reinterprets the bit pattern. #### initializer From Integer ```kestrel public init(from: UInt16) ``` Converts from `UInt16`. Narrowing conversions truncate the high bits; signed→unsigned reinterprets the bit pattern. #### initializer From Integer ```kestrel public init(from: UInt32) ``` Converts from `UInt32`. Narrowing conversions truncate the high bits; signed→unsigned reinterprets the bit pattern. #### initializer From Raw ```kestrel init(raw: lang.i64) ``` Wraps an existing `lang.i64` without conversion. Internal constructor used by intrinsics; not part of the public API. #### initializer Int Literal ```kestrel public init(intLiteral: lang.i64) ``` Compiler-emitted bridge that turns an integer literal into a UInt64. You will rarely call this directly — write the literal and let the `ExpressibleByIntLiteral` protocol pick it up. For widths smaller than 64 bits the literal is truncated with `lang.cast_i64_i64`. # Examples ``` let n: Int64 = 42; // implicit ``` #### initializer Parse ```kestrel public init(parsing: String) ``` Parses a base-10 unsigned integer literal, optionally prefixed with `+`. A leading `-` is rejected. Returns `null` for an empty string, a non-digit character, or a value that does not fit in `UInt64`. # Examples ``` let n = UInt64(parsing: "42"); // Some(42) let bad = UInt64(parsing: "-1"); // null (no sign for unsigned) ``` #### initializer Parse Radix ```kestrel public init(parsing: String, radix: Int64) ``` Parses an unsigned integer in `radix` (base 2-36 inclusive). Letters a-z are case-insensitive and represent digit values 10-35. A leading `+` is allowed but a leading `-` is rejected. Returns `null` for an out-of-range radix, an empty string, an unrecognised digit, or a value that overflows `UInt64`. # Examples ``` let n = UInt64(parsing: "ff", radix: 16); // Some(255 if it fits, else None) let m = UInt64(parsing: "101010", radix: 2); // Some(42) ``` #### function addChecked ```kestrel public func addChecked(UInt64) -> UInt64? ``` Wrapping addition that returns `None` on overflow. For unsigned types overflow is detected via `result < self`. #### function addSaturating ```kestrel public func addSaturating(UInt64) -> UInt64 ``` Addition that clamps to `maxValue` on overflow. #### field bitWidth ```kestrel public static var bitWidth: Int64 { get } ``` The width in bits (64). Useful for shift bounds and bit-walks. #### field byteSwapped ```kestrel public var byteSwapped: UInt64 { get } ``` Value with its byte order reversed. Use to convert between big- and little-endian; lowered to a `bswap` intrinsic. #### function clamp ```kestrel public func clamp(UInt64, UInt64) -> UInt64 ``` Clamps `self` into `[min, max]`. Caller is responsible for ensuring `min <= max`; otherwise the result is undefined. # Examples ``` (5).clamp(0, 10); // 5 (-5).clamp(0, 10); // 0 (15).clamp(0, 10); // 10 ``` #### field countOnes ```kestrel public var countOnes: Int64 { get } ``` Population count — the number of `1` bits in the binary representation. Lowered to a `popcount` intrinsic where the target supports it. # Examples ``` (0b1010).countOnes; // 2 (0b1111).countOnes; // 4 (0).countOnes; // 0 ``` #### field countZeros ```kestrel public var countZeros: Int64 { get } ``` Complement of `countOnes`: equal to `bitWidth - countOnes`. #### function divideChecked ```kestrel public func divideChecked(UInt64) -> UInt64? ``` Division that returns `None` for divide-by-zero. #### function gcd ```kestrel public func gcd(UInt64) -> UInt64 ``` Greatest common divisor via Euclidean algorithm. For signed types the inputs are taken absolute first; the result is always non-negative. # Examples ``` (12).gcd(8); // 4 (17).gcd(5); // 1 (coprime) (-12).gcd(8); // 4 ``` #### field isNegative ```kestrel public var isNegative: Bool { get } ``` Always `false` — unsigned types cannot be negative. #### field isPositive ```kestrel public var isPositive: Bool { get } ``` True when `self > 0`. #### field isPowerOfTwo ```kestrel public var isPowerOfTwo: Bool { get } ``` True when the value is a positive power of two (`2^k` for `k >= 0`). Zero and negatives are excluded. Cheap branchless test built on `x & (x - 1) == 0`. # Examples ``` (1).isPowerOfTwo; // true (2^0) (4).isPowerOfTwo; // true (2^2) (3).isPowerOfTwo; // false (0).isPowerOfTwo; // false ``` #### field isZero ```kestrel public var isZero: Bool { get } ``` True when `self == 0`. #### function lcm ```kestrel public func lcm(UInt64) -> UInt64 ``` Least common multiple, computed as `|self| / gcd(self, other) * |other|` to avoid intermediate overflow. Returns zero if either input is zero. # Examples ``` (4).lcm(6); // 12 (3).lcm(5); // 15 (0).lcm(7); // 0 ``` #### field leadingZeros ```kestrel public var leadingZeros: Int64 { get } ``` Number of leading zero bits, counting from the most-significant end. For zero, returns `bitWidth`. # Examples ``` (1).leadingZeros; // bitWidth - 1 (0).leadingZeros; // bitWidth ``` #### field maxValue ```kestrel public static var maxValue: UInt64 { get } ``` The largest representable value. This is 2^64 - 1 (18_446_744_073_709_551_615). #### field minValue ```kestrel public static var minValue: UInt64 { get } ``` The smallest representable value. This is always 0 for unsigned types. Note that for signed types `minValue.negate()` overflows back to itself; use `negateChecked()` if you need to detect that. #### function multiplyChecked ```kestrel public func multiplyChecked(UInt64) -> UInt64? ``` Wrapping multiplication that returns `None` on overflow. Implemented by multiplying then dividing back. #### function multiplySaturating ```kestrel public func multiplySaturating(UInt64) -> UInt64 ``` Multiplication that clamps to `maxValue` on overflow. #### function pow ```kestrel public func pow(Int64) -> UInt64 ``` Raises `self` to `exponent` via binary exponentiation. Wraps on overflow. Negative exponents return zero (integer truncation of the would-be fraction). # Examples ``` (2).pow(10); // 1024 (3).pow(4); // 81 (5).pow(-1); // 0 ``` #### field raw ```kestrel public var raw: lang.i64 ``` The underlying primitive `lang.i64` value. Exposed for FFI and intrinsic use; prefer the typed surface for everything else. #### function rotateLeft ```kestrel public func rotateLeft(by: Int64) -> UInt64 ``` Rotates bits left by `count`, modulo `bitWidth`. Bits shifted past the MSB re-enter at the LSB. #### function rotateRight ```kestrel public func rotateRight(by: Int64) -> UInt64 ``` Rotates bits right by `count`, modulo `bitWidth`. Mirror of `rotateLeft`. #### field sign ```kestrel public var sign: UInt64 { get } ``` Sign as a `UInt64`: `0` for zero, `1` otherwise (unsigned types have no negative values). #### function subtractChecked ```kestrel public func subtractChecked(UInt64) -> UInt64? ``` Subtraction that returns `None` on underflow (`other > self`). #### function subtractSaturating ```kestrel public func subtractSaturating(UInt64) -> UInt64 ``` Subtraction that clamps to `0` on underflow (unsigned types cannot represent negative results). #### function toBytes ```kestrel public func toBytes() -> std.collections.Array[UInt8] ``` Splits this integer into 8 bytes in *native* (host) byte order. Use `toBytesBigEndian` / `toBytesLittleEndian` when serialising for a fixed wire format. # Examples ``` let bytes = UInt64.maxValue.toBytes(); // 8 bytes, host order ``` #### function toBytesBigEndian ```kestrel public func toBytesBigEndian() -> std.collections.Array[UInt8] ``` Splits this integer into 8 bytes in big-endian order (most significant byte first — i.e. network byte order). #### function toBytesLittleEndian ```kestrel public func toBytesLittleEndian() -> std.collections.Array[UInt8] ``` Splits this integer into 8 bytes in little-endian order (least significant byte first). #### field trailingZeros ```kestrel public var trailingZeros: Int64 { get } ``` Number of trailing zero bits. Equal to `log2(self & -self)` for non-zero values; returns `bitWidth` for zero. Useful for finding the largest power of two dividing the value. **Steppable** #### function predecessor ```kestrel public func predecessor() -> UInt64 ``` Predecessor — `self - 1`. Wraps at `minValue`. #### function successor ```kestrel public func successor() -> UInt64 ``` Successor — `self + 1`. Wraps at `maxValue`. Used by `for-in` over integer ranges. **Comparable** #### typealias Output ```kestrel type Output = Bool ``` #### function compare ```kestrel public func compare(UInt64) -> Ordering ``` Three-way comparison returning an `Ordering`. Signed types compare using two's-complement ordering; unsigned types use natural ordering. # Examples ``` (1).compare(2); // .Less (2).compare(2); // .Equal (3).compare(2); // .Greater ``` #### function greaterThan ```kestrel public func greaterThan(Self) -> Bool ``` `>` derived from `compare`. #### function greaterThanOrEqual ```kestrel public func greaterThanOrEqual(Self) -> Bool ``` `>=` derived from `compare`. #### function isAtLeast ```kestrel public func isAtLeast(Self) -> Bool ``` `start..` lower-bound check, derived from `compare`. #### function isAtMost ```kestrel public func isAtMost(Self) -> Bool ``` `..=end` upper-bound check, derived from `compare`. #### function isBelow ```kestrel public func isBelow(Self) -> Bool ``` `.. Bool ``` `<` derived from `compare`. #### function lessThanOrEqual ```kestrel public func lessThanOrEqual(Self) -> Bool ``` `<=` derived from `compare`. **Equatable** #### typealias Output ```kestrel type Output = Bool ``` #### function equal ```kestrel public func equal(to: Self) -> Bool ``` Bridges `Equal.equal(to:)` to `Equatable.isEqual(to:)`. #### function isEqual ```kestrel public func isEqual(to: UInt64) -> Bool ``` Bit-for-bit equality. Backs the `==` operator. # Examples ``` (42).isEqual(to: 42); // true 42 == 42; // true ``` #### function notEqual ```kestrel public func notEqual(to: Self) -> Bool ``` Default `!=`: delegates to `==` so there's a single source of truth. **Matchable** #### function matches ```kestrel public func matches(UInt64) -> Bool ``` Pattern-matching hook for `Matchable`. Identical to `isEqual`. **Formattable** #### function format ```kestrel public func format(into: mutating StringBuilder, FormatOptions) ``` Formats the integer directly into `writer`, honouring the supplied `FormatOptions`. Implements the `Formattable` protocol. # Examples ``` (42).format(); // "42" (255).format(.{radix: 16}); // "ff" (255).format(.{radix: 16, uppercase: true}); // "FF" (255).format(.{radix: 16, alternate: true}); // "0xff" (42).format(.{radix: 2, alternate: true}); // "0b101010" (42).format(.{width: .Some(5), fill: '0'}); // "00042" (-42).format(.{sign: .Always}); // "-42" ``` #### function formatted ```kestrel public func formatted(FormatOptions) -> String ``` Returns this value rendered as a `String`. Convenience wrapper: creates a `StringBuilder`, calls `format(into:)`, and returns the built string. Uses a distinct name to avoid overload-resolution ambiguity with `format(into:)`. **Hashable** #### function hash ```kestrel public func hash[H](into: mutating H) where H: Hasher ``` Feeds the raw bytes of this value into `hasher`. Endianness-agnostic only within a single process — do not persist hashes across builds. **Addable** #### typealias Output ```kestrel type Output = UInt64 ``` #### typealias Output ```kestrel type Output = UInt64 ``` #### typealias Output ```kestrel type Output = UInt64 ``` #### typealias Output ```kestrel type Output = UInt64 ``` #### typealias Output ```kestrel type Output = UInt64 ``` #### typealias Output ```kestrel type Output = UInt64 ``` #### typealias Output ```kestrel type Output = UInt64 ``` #### typealias Output ```kestrel type Output = UInt64 ``` #### typealias Output ```kestrel type Output = UInt64 ``` #### typealias Output ```kestrel type Output = UInt64 ``` #### typealias Output ```kestrel type Output = UInt64 ``` #### typealias Output ```kestrel type Output = Range[UInt64] ``` #### typealias Output ```kestrel type Output = ClosedRange[UInt64] ``` #### typealias Output ```kestrel type Output = RangeFrom[UInt64] ``` #### typealias Output ```kestrel type Output = RangeUpTo[UInt64] ``` #### typealias Output ```kestrel type Output = RangeThrough[UInt64] ``` #### function add ```kestrel public consuming func add(consuming UInt64) -> UInt64 ``` `self + other`, wrapping on overflow. Use `addChecked` to detect or `addSaturating` to clamp. #### field zero ```kestrel public static var zero: UInt64 { get } ``` The additive identity, `0`. **Subtractable** #### typealias Output ```kestrel type Output ``` #### function subtract ```kestrel public consuming func subtract(consuming UInt64) -> UInt64 ``` `self - other`, wrapping on overflow. **Multipliable** #### typealias Output ```kestrel type Output ``` #### function multiply ```kestrel public consuming func multiply(consuming UInt64) -> UInt64 ``` `self * other`, wrapping on overflow. #### field one ```kestrel public static var one: UInt64 { get } ``` The multiplicative identity, `1`. **Divisible** #### typealias Output ```kestrel type Output ``` #### function divide ```kestrel public consuming func divide(consuming UInt64) -> UInt64 ``` Truncating integer division (`self / other`). For signed types, `minValue / -1` wraps; use `divideChecked` to detect. # Errors Traps on division by zero (LLVM `udiv`/`sdiv` are UB on zero — the process aborts before producing a result). **Modulo** #### typealias Output ```kestrel type Output ``` #### function modulo ```kestrel public consuming func modulo(consuming UInt64) -> UInt64 ``` `self % other` — truncated remainder; the result has the sign of `self` for signed types. # Errors Traps on division by zero, like `divide`. **BitwiseAnd** #### typealias Output ```kestrel type Output ``` #### function bitwiseAnd ```kestrel public consuming func bitwiseAnd(consuming UInt64) -> UInt64 ``` Bitwise AND. `0b1010 & 0b1100 == 0b1000`. **BitwiseOr** #### typealias Output ```kestrel type Output ``` #### function bitwiseOr ```kestrel public consuming func bitwiseOr(consuming UInt64) -> UInt64 ``` Bitwise OR. `0b1010 | 0b1100 == 0b1110`. **BitwiseXor** #### typealias Output ```kestrel type Output ``` #### function bitwiseXor ```kestrel public consuming func bitwiseXor(consuming UInt64) -> UInt64 ``` Bitwise XOR. `0b1010 ^ 0b1100 == 0b0110`. **BitwiseNot** #### typealias Output ```kestrel type Output ``` #### function bitwiseNot ```kestrel public consuming func bitwiseNot() -> UInt64 ``` Bitwise NOT — flips all bits. For signed types this is `-self - 1`. **LeftShift** #### typealias Output ```kestrel type Output ``` #### function shiftLeft ```kestrel public consuming func shiftLeft(by: consuming Int64) -> UInt64 ``` Left shift by `count`. Behavior is undefined when `count >= bitWidth` — pre-mask the count if you can't guarantee the bound. **RightShift** #### typealias Output ```kestrel type Output ``` #### function shiftRight ```kestrel public consuming func shiftRight(by: consuming Int64) -> UInt64 ``` Right shift by `count`. Arithmetic (sign-extending) for signed types, logical (zero-filling) for unsigned. Same `count` precondition as `shiftLeft`. **AddAssign** #### function addAssign ```kestrel public mutating func addAssign(UInt64) ``` `self += other` **SubtractAssign** #### function subtractAssign ```kestrel public mutating func subtractAssign(UInt64) ``` `self -= other` **MultiplyAssign** #### function multiplyAssign ```kestrel public mutating func multiplyAssign(UInt64) ``` `self *= other` **DivideAssign** #### function divideAssign ```kestrel public mutating func divideAssign(UInt64) ``` `self /= other` **ModuloAssign** #### function modAssign ```kestrel public mutating func modAssign(UInt64) ``` `self %= other` **BitwiseAndAssign** #### function bitwiseAndAssign ```kestrel public mutating func bitwiseAndAssign(UInt64) ``` `self &= other` **BitwiseOrAssign** #### function bitwiseOrAssign ```kestrel public mutating func bitwiseOrAssign(UInt64) ``` `self |= other` **BitwiseXorAssign** #### function bitwiseXorAssign ```kestrel public mutating func bitwiseXorAssign(UInt64) ``` `self ^= other` **LeftShiftAssign** #### function shiftLeftAssign ```kestrel public mutating func shiftLeftAssign(by: Int64) ``` `self <<= count` **RightShiftAssign** #### function shiftRightAssign ```kestrel public mutating func shiftRightAssign(by: Int64) ``` `self >>= count` **ExpressibleByIntLiteral** #### initializer Int Literal ```kestrel init(intLiteral: lang.i64) ``` Builds an instance from an integer literal. **Defaultable** #### initializer Default ```kestrel init() ``` Builds the default-valued instance. **RangeConstructible** #### typealias Output ```kestrel type Output ``` #### function exclusiveRange ```kestrel public func exclusiveRange(to: UInt64) -> Range[UInt64] ``` Builds a half-open range `self.. ClosedRange[UInt64] ``` Builds a closed range `self..=end`. Sugar for the `..=` operator. **RangeFromConstructible** #### typealias Output ```kestrel type Output ``` #### function rangeFrom ```kestrel public func rangeFrom() -> RangeFrom[UInt64] ``` Builds a partial range `self..` (from self, no upper bound). **RangeUpToConstructible** #### typealias Output ```kestrel type Output ``` #### function rangeUpTo ```kestrel public func rangeUpTo() -> RangeUpTo[UInt64] ``` Builds a partial range `.. RangeThrough[UInt64] ``` Builds a partial range `..=self` (through self, inclusive). **Convertible** #### initializer From Source ```kestrel init(from: From) ``` Creates an instance from `value`. ### struct UInt8 ```kestrel public struct UInt8 { /* private fields */ } ``` A 8-bit unsigned integer. UInt8 is the 8-bit member of the integer family. The same surface area is provided across all widths; switch widths to trade range for memory or to match an FFI ABI. Arithmetic wraps on overflow by default — use the `*Checked` variants for overflow detection or `*Saturating` to clamp to `minValue`/`maxValue`. The type is `FFISafe` and lays out as a single `lang.i8` so it can cross C boundaries unchanged. # Examples ``` let a: Int64 = 100; let b = a + 50; // 150 let c = a * 2; // 200 let d = a.addChecked(Int64.maxValue); // None (overflow detected) ``` ``` // Bit twiddling (0b1010).countOnes // 2 (1).shiftLeft(by: 4) // 16 (-1).leadingZeros // 0 (all bits set) ``` # Representation A single `lang.i8` field. No padding, no headers — bit-identical to the corresponding C type. #### initializer Default ```kestrel public init() ``` Creates the zero value, satisfying `Defaultable`. # Examples ``` let n = Int64(); // 0 ``` #### initializer From Bytes ```kestrel public init[S](fromBytes: S) where S: Slice[UInt8] ``` Reassembles a `UInt8` from 1 bytes in native byte order. Returns `null` if the input is not exactly 1 bytes long. #### initializer From Bytes Big Endian ```kestrel public init[S](fromBytesBigEndian: S) where S: Slice[UInt8] ``` Reassembles a `UInt8` from 1 bytes in big-endian order. Returns `null` if the input is not exactly 1 bytes long. #### initializer From Bytes Little Endian ```kestrel public init[S](fromBytesLittleEndian: S) where S: Slice[UInt8] ``` Reassembles a `UInt8` from 1 bytes in little-endian order. Returns `null` if the input is not exactly 1 bytes long. #### initializer From Integer ```kestrel public init(from: Int8) ``` Converts from `Int8`. Narrowing conversions truncate the high bits; signed→unsigned reinterprets the bit pattern. #### initializer From Integer ```kestrel public init(from: Int16) ``` Converts from `Int16`. Narrowing conversions truncate the high bits; signed→unsigned reinterprets the bit pattern. #### initializer From Integer ```kestrel public init(from: Int32) ``` Converts from `Int32`. Narrowing conversions truncate the high bits; signed→unsigned reinterprets the bit pattern. #### initializer From Integer ```kestrel public init(from: Int64) ``` Converts from `Int64`. Narrowing conversions truncate the high bits; signed→unsigned reinterprets the bit pattern. #### initializer From Integer ```kestrel public init(from: UInt16) ``` Converts from `UInt16`. Narrowing conversions truncate the high bits; signed→unsigned reinterprets the bit pattern. #### initializer From Integer ```kestrel public init(from: UInt32) ``` Converts from `UInt32`. Narrowing conversions truncate the high bits; signed→unsigned reinterprets the bit pattern. #### initializer From Integer ```kestrel public init(from: UInt64) ``` Converts from `UInt64`. Narrowing conversions truncate the high bits; signed→unsigned reinterprets the bit pattern. #### initializer From Raw ```kestrel init(raw: lang.i8) ``` Wraps an existing `lang.i8` without conversion. Internal constructor used by intrinsics; not part of the public API. #### initializer Int Literal ```kestrel public init(intLiteral: lang.i64) ``` Compiler-emitted bridge that turns an integer literal into a UInt8. You will rarely call this directly — write the literal and let the `ExpressibleByIntLiteral` protocol pick it up. For widths smaller than 64 bits the literal is truncated with `lang.cast_i64_i8`. # Examples ``` let n: Int64 = 42; // implicit ``` #### initializer Parse ```kestrel public init(parsing: String) ``` Parses a base-10 unsigned integer literal, optionally prefixed with `+`. A leading `-` is rejected. Returns `null` for an empty string, a non-digit character, or a value that does not fit in `UInt8`. # Examples ``` let n = UInt8(parsing: "42"); // Some(42) let bad = UInt8(parsing: "-1"); // null (no sign for unsigned) ``` #### initializer Parse Radix ```kestrel public init(parsing: String, radix: Int64) ``` Parses an unsigned integer in `radix` (base 2-36 inclusive). Letters a-z are case-insensitive and represent digit values 10-35. A leading `+` is allowed but a leading `-` is rejected. Returns `null` for an out-of-range radix, an empty string, an unrecognised digit, or a value that overflows `UInt8`. # Examples ``` let n = UInt8(parsing: "ff", radix: 16); // Some(255 if it fits, else None) let m = UInt8(parsing: "101010", radix: 2); // Some(42) ``` #### function addChecked ```kestrel public func addChecked(UInt8) -> UInt8? ``` Wrapping addition that returns `None` on overflow. For unsigned types overflow is detected via `result < self`. #### function addSaturating ```kestrel public func addSaturating(UInt8) -> UInt8 ``` Addition that clamps to `maxValue` on overflow. #### field bitWidth ```kestrel public static var bitWidth: Int64 { get } ``` The width in bits (8). Useful for shift bounds and bit-walks. #### field byteSwapped ```kestrel public var byteSwapped: UInt8 { get } ``` Value with its byte order reversed. Use to convert between big- and little-endian; lowered to a `bswap` intrinsic. #### function clamp ```kestrel public func clamp(UInt8, UInt8) -> UInt8 ``` Clamps `self` into `[min, max]`. Caller is responsible for ensuring `min <= max`; otherwise the result is undefined. # Examples ``` (5).clamp(0, 10); // 5 (-5).clamp(0, 10); // 0 (15).clamp(0, 10); // 10 ``` #### field countOnes ```kestrel public var countOnes: Int64 { get } ``` Population count — the number of `1` bits in the binary representation. Lowered to a `popcount` intrinsic where the target supports it. # Examples ``` (0b1010).countOnes; // 2 (0b1111).countOnes; // 4 (0).countOnes; // 0 ``` #### field countZeros ```kestrel public var countZeros: Int64 { get } ``` Complement of `countOnes`: equal to `bitWidth - countOnes`. #### function divideChecked ```kestrel public func divideChecked(UInt8) -> UInt8? ``` Division that returns `None` for divide-by-zero. #### function gcd ```kestrel public func gcd(UInt8) -> UInt8 ``` Greatest common divisor via Euclidean algorithm. For signed types the inputs are taken absolute first; the result is always non-negative. # Examples ``` (12).gcd(8); // 4 (17).gcd(5); // 1 (coprime) (-12).gcd(8); // 4 ``` #### field isNegative ```kestrel public var isNegative: Bool { get } ``` Always `false` — unsigned types cannot be negative. #### field isPositive ```kestrel public var isPositive: Bool { get } ``` True when `self > 0`. #### field isPowerOfTwo ```kestrel public var isPowerOfTwo: Bool { get } ``` True when the value is a positive power of two (`2^k` for `k >= 0`). Zero and negatives are excluded. Cheap branchless test built on `x & (x - 1) == 0`. # Examples ``` (1).isPowerOfTwo; // true (2^0) (4).isPowerOfTwo; // true (2^2) (3).isPowerOfTwo; // false (0).isPowerOfTwo; // false ``` #### field isZero ```kestrel public var isZero: Bool { get } ``` True when `self == 0`. #### function lcm ```kestrel public func lcm(UInt8) -> UInt8 ``` Least common multiple, computed as `|self| / gcd(self, other) * |other|` to avoid intermediate overflow. Returns zero if either input is zero. # Examples ``` (4).lcm(6); // 12 (3).lcm(5); // 15 (0).lcm(7); // 0 ``` #### field leadingZeros ```kestrel public var leadingZeros: Int64 { get } ``` Number of leading zero bits, counting from the most-significant end. For zero, returns `bitWidth`. # Examples ``` (1).leadingZeros; // bitWidth - 1 (0).leadingZeros; // bitWidth ``` #### field maxValue ```kestrel public static var maxValue: UInt8 { get } ``` The largest representable value. This is 2^8 - 1 (255). #### field minValue ```kestrel public static var minValue: UInt8 { get } ``` The smallest representable value. This is always 0 for unsigned types. Note that for signed types `minValue.negate()` overflows back to itself; use `negateChecked()` if you need to detect that. #### function multiplyChecked ```kestrel public func multiplyChecked(UInt8) -> UInt8? ``` Wrapping multiplication that returns `None` on overflow. Implemented by multiplying then dividing back. #### function multiplySaturating ```kestrel public func multiplySaturating(UInt8) -> UInt8 ``` Multiplication that clamps to `maxValue` on overflow. #### function pow ```kestrel public func pow(Int64) -> UInt8 ``` Raises `self` to `exponent` via binary exponentiation. Wraps on overflow. Negative exponents return zero (integer truncation of the would-be fraction). # Examples ``` (2).pow(10); // 1024 (3).pow(4); // 81 (5).pow(-1); // 0 ``` #### field raw ```kestrel public var raw: lang.i8 ``` The underlying primitive `lang.i8` value. Exposed for FFI and intrinsic use; prefer the typed surface for everything else. #### function rotateLeft ```kestrel public func rotateLeft(by: Int64) -> UInt8 ``` Rotates bits left by `count`, modulo `bitWidth`. Bits shifted past the MSB re-enter at the LSB. #### function rotateRight ```kestrel public func rotateRight(by: Int64) -> UInt8 ``` Rotates bits right by `count`, modulo `bitWidth`. Mirror of `rotateLeft`. #### field sign ```kestrel public var sign: UInt8 { get } ``` Sign as a `UInt8`: `0` for zero, `1` otherwise (unsigned types have no negative values). #### function subtractChecked ```kestrel public func subtractChecked(UInt8) -> UInt8? ``` Subtraction that returns `None` on underflow (`other > self`). #### function subtractSaturating ```kestrel public func subtractSaturating(UInt8) -> UInt8 ``` Subtraction that clamps to `0` on underflow (unsigned types cannot represent negative results). #### function toBytes ```kestrel public func toBytes() -> std.collections.Array[UInt8] ``` Splits this integer into 1 bytes in *native* (host) byte order. Use `toBytesBigEndian` / `toBytesLittleEndian` when serialising for a fixed wire format. # Examples ``` let bytes = UInt8.maxValue.toBytes(); // 1 bytes, host order ``` #### function toBytesBigEndian ```kestrel public func toBytesBigEndian() -> std.collections.Array[UInt8] ``` Splits this integer into 1 bytes in big-endian order (most significant byte first — i.e. network byte order). #### function toBytesLittleEndian ```kestrel public func toBytesLittleEndian() -> std.collections.Array[UInt8] ``` Splits this integer into 1 bytes in little-endian order (least significant byte first). #### field trailingZeros ```kestrel public var trailingZeros: Int64 { get } ``` Number of trailing zero bits. Equal to `log2(self & -self)` for non-zero values; returns `bitWidth` for zero. Useful for finding the largest power of two dividing the value. **Steppable** #### function predecessor ```kestrel public func predecessor() -> UInt8 ``` Predecessor — `self - 1`. Wraps at `minValue`. #### function successor ```kestrel public func successor() -> UInt8 ``` Successor — `self + 1`. Wraps at `maxValue`. Used by `for-in` over integer ranges. **Comparable** #### typealias Output ```kestrel type Output = Bool ``` #### function compare ```kestrel public func compare(UInt8) -> Ordering ``` Three-way comparison returning an `Ordering`. Signed types compare using two's-complement ordering; unsigned types use natural ordering. # Examples ``` (1).compare(2); // .Less (2).compare(2); // .Equal (3).compare(2); // .Greater ``` #### function greaterThan ```kestrel public func greaterThan(Self) -> Bool ``` `>` derived from `compare`. #### function greaterThanOrEqual ```kestrel public func greaterThanOrEqual(Self) -> Bool ``` `>=` derived from `compare`. #### function isAtLeast ```kestrel public func isAtLeast(Self) -> Bool ``` `start..` lower-bound check, derived from `compare`. #### function isAtMost ```kestrel public func isAtMost(Self) -> Bool ``` `..=end` upper-bound check, derived from `compare`. #### function isBelow ```kestrel public func isBelow(Self) -> Bool ``` `.. Bool ``` `<` derived from `compare`. #### function lessThanOrEqual ```kestrel public func lessThanOrEqual(Self) -> Bool ``` `<=` derived from `compare`. **Equatable** #### typealias Output ```kestrel type Output = Bool ``` #### function equal ```kestrel public func equal(to: Self) -> Bool ``` Bridges `Equal.equal(to:)` to `Equatable.isEqual(to:)`. #### function isEqual ```kestrel public func isEqual(to: UInt8) -> Bool ``` Bit-for-bit equality. Backs the `==` operator. # Examples ``` (42).isEqual(to: 42); // true 42 == 42; // true ``` #### function notEqual ```kestrel public func notEqual(to: Self) -> Bool ``` Default `!=`: delegates to `==` so there's a single source of truth. **Matchable** #### function matches ```kestrel public func matches(UInt8) -> Bool ``` Pattern-matching hook for `Matchable`. Identical to `isEqual`. **Formattable** #### function format ```kestrel public func format(into: mutating StringBuilder, FormatOptions) ``` Formats the integer directly into `writer`, honouring the supplied `FormatOptions`. Implements the `Formattable` protocol. # Examples ``` (42).format(); // "42" (255).format(.{radix: 16}); // "ff" (255).format(.{radix: 16, uppercase: true}); // "FF" (255).format(.{radix: 16, alternate: true}); // "0xff" (42).format(.{radix: 2, alternate: true}); // "0b101010" (42).format(.{width: .Some(5), fill: '0'}); // "00042" (-42).format(.{sign: .Always}); // "-42" ``` #### function formatted ```kestrel public func formatted(FormatOptions) -> String ``` Returns this value rendered as a `String`. Convenience wrapper: creates a `StringBuilder`, calls `format(into:)`, and returns the built string. Uses a distinct name to avoid overload-resolution ambiguity with `format(into:)`. **Hashable** #### function hash ```kestrel public func hash[H](into: mutating H) where H: Hasher ``` Feeds the raw bytes of this value into `hasher`. Endianness-agnostic only within a single process — do not persist hashes across builds. **Addable** #### typealias Output ```kestrel type Output = UInt8 ``` #### typealias Output ```kestrel type Output = UInt8 ``` #### typealias Output ```kestrel type Output = UInt8 ``` #### typealias Output ```kestrel type Output = UInt8 ``` #### typealias Output ```kestrel type Output = UInt8 ``` #### typealias Output ```kestrel type Output = UInt8 ``` #### typealias Output ```kestrel type Output = UInt8 ``` #### typealias Output ```kestrel type Output = UInt8 ``` #### typealias Output ```kestrel type Output = UInt8 ``` #### typealias Output ```kestrel type Output = UInt8 ``` #### typealias Output ```kestrel type Output = UInt8 ``` #### typealias Output ```kestrel type Output = Range[UInt8] ``` #### typealias Output ```kestrel type Output = ClosedRange[UInt8] ``` #### typealias Output ```kestrel type Output = RangeFrom[UInt8] ``` #### typealias Output ```kestrel type Output = RangeUpTo[UInt8] ``` #### typealias Output ```kestrel type Output = RangeThrough[UInt8] ``` #### function add ```kestrel public consuming func add(consuming UInt8) -> UInt8 ``` `self + other`, wrapping on overflow. Use `addChecked` to detect or `addSaturating` to clamp. #### field zero ```kestrel public static var zero: UInt8 { get } ``` The additive identity, `0`. **Subtractable** #### typealias Output ```kestrel type Output ``` #### function subtract ```kestrel public consuming func subtract(consuming UInt8) -> UInt8 ``` `self - other`, wrapping on overflow. **Multipliable** #### typealias Output ```kestrel type Output ``` #### function multiply ```kestrel public consuming func multiply(consuming UInt8) -> UInt8 ``` `self * other`, wrapping on overflow. #### field one ```kestrel public static var one: UInt8 { get } ``` The multiplicative identity, `1`. **Divisible** #### typealias Output ```kestrel type Output ``` #### function divide ```kestrel public consuming func divide(consuming UInt8) -> UInt8 ``` Truncating integer division (`self / other`). For signed types, `minValue / -1` wraps; use `divideChecked` to detect. # Errors Traps on division by zero (LLVM `udiv`/`sdiv` are UB on zero — the process aborts before producing a result). **Modulo** #### typealias Output ```kestrel type Output ``` #### function modulo ```kestrel public consuming func modulo(consuming UInt8) -> UInt8 ``` `self % other` — truncated remainder; the result has the sign of `self` for signed types. # Errors Traps on division by zero, like `divide`. **BitwiseAnd** #### typealias Output ```kestrel type Output ``` #### function bitwiseAnd ```kestrel public consuming func bitwiseAnd(consuming UInt8) -> UInt8 ``` Bitwise AND. `0b1010 & 0b1100 == 0b1000`. **BitwiseOr** #### typealias Output ```kestrel type Output ``` #### function bitwiseOr ```kestrel public consuming func bitwiseOr(consuming UInt8) -> UInt8 ``` Bitwise OR. `0b1010 | 0b1100 == 0b1110`. **BitwiseXor** #### typealias Output ```kestrel type Output ``` #### function bitwiseXor ```kestrel public consuming func bitwiseXor(consuming UInt8) -> UInt8 ``` Bitwise XOR. `0b1010 ^ 0b1100 == 0b0110`. **BitwiseNot** #### typealias Output ```kestrel type Output ``` #### function bitwiseNot ```kestrel public consuming func bitwiseNot() -> UInt8 ``` Bitwise NOT — flips all bits. For signed types this is `-self - 1`. **LeftShift** #### typealias Output ```kestrel type Output ``` #### function shiftLeft ```kestrel public consuming func shiftLeft(by: consuming Int64) -> UInt8 ``` Left shift by `count`. Behavior is undefined when `count >= bitWidth` — pre-mask the count if you can't guarantee the bound. **RightShift** #### typealias Output ```kestrel type Output ``` #### function shiftRight ```kestrel public consuming func shiftRight(by: consuming Int64) -> UInt8 ``` Right shift by `count`. Arithmetic (sign-extending) for signed types, logical (zero-filling) for unsigned. Same `count` precondition as `shiftLeft`. **AddAssign** #### function addAssign ```kestrel public mutating func addAssign(UInt8) ``` `self += other` **SubtractAssign** #### function subtractAssign ```kestrel public mutating func subtractAssign(UInt8) ``` `self -= other` **MultiplyAssign** #### function multiplyAssign ```kestrel public mutating func multiplyAssign(UInt8) ``` `self *= other` **DivideAssign** #### function divideAssign ```kestrel public mutating func divideAssign(UInt8) ``` `self /= other` **ModuloAssign** #### function modAssign ```kestrel public mutating func modAssign(UInt8) ``` `self %= other` **BitwiseAndAssign** #### function bitwiseAndAssign ```kestrel public mutating func bitwiseAndAssign(UInt8) ``` `self &= other` **BitwiseOrAssign** #### function bitwiseOrAssign ```kestrel public mutating func bitwiseOrAssign(UInt8) ``` `self |= other` **BitwiseXorAssign** #### function bitwiseXorAssign ```kestrel public mutating func bitwiseXorAssign(UInt8) ``` `self ^= other` **LeftShiftAssign** #### function shiftLeftAssign ```kestrel public mutating func shiftLeftAssign(by: Int64) ``` `self <<= count` **RightShiftAssign** #### function shiftRightAssign ```kestrel public mutating func shiftRightAssign(by: Int64) ``` `self >>= count` **ExpressibleByIntLiteral** #### initializer Int Literal ```kestrel init(intLiteral: lang.i64) ``` Builds an instance from an integer literal. **Defaultable** #### initializer Default ```kestrel init() ``` Builds the default-valued instance. **RangeConstructible** #### typealias Output ```kestrel type Output ``` #### function exclusiveRange ```kestrel public func exclusiveRange(to: UInt8) -> Range[UInt8] ``` Builds a half-open range `self.. ClosedRange[UInt8] ``` Builds a closed range `self..=end`. Sugar for the `..=` operator. **RangeFromConstructible** #### typealias Output ```kestrel type Output ``` #### function rangeFrom ```kestrel public func rangeFrom() -> RangeFrom[UInt8] ``` Builds a partial range `self..` (from self, no upper bound). **RangeUpToConstructible** #### typealias Output ```kestrel type Output ``` #### function rangeUpTo ```kestrel public func rangeUpTo() -> RangeUpTo[UInt8] ``` Builds a partial range `.. RangeThrough[UInt8] ``` Builds a partial range `..=self` (through self, inclusive). **Convertible** #### initializer From Source ```kestrel init(from: From) ``` Creates an instance from `value`. ### protocol UnsignedInteger ```kestrel public protocol UnsignedInteger ``` Marker protocol for unsigned integer types. Carries no requirements — it exists so generic code can constrain on signedness without naming every concrete `UInt*` type. --- ## std.os ### function captureOutput ```kestrel public func captureOutput(String) -> String ``` Runs `command` through the system shell and returns its captured stdout. Reads from `popen(command, "r")` 1 KiB at a time until EOF, then trims a single run of trailing ASCII whitespace (space, tab, LF, CR) so callers don't have to chomp the newline themselves. Stderr is **not** captured — it goes to the parent's stderr. Returns the empty string if `popen` fails. # Examples ``` let branch = captureOutput("git rev-parse --abbrev-ref HEAD"); // "main" ``` ### function chmod ```kestrel public func chmod(String, Int32) -> Result[(), IoError] ``` Changes the mode bits of `path` to `mode`. Wraps `chmod(2)`. `mode` is the raw POSIX mode bits (e.g. `0o755`); pass it as `Int32`. Resolves symlinks (use `lchmod` equivalent if you need to change a link itself — not currently exposed). # Errors Returns `Err(IoError)` on any libc failure; `errno` is captured. # Examples ``` chmod("/tmp/script.sh", Int32(intLiteral: 0o755)); ``` ### function exit ```kestrel public func exit(Int32) ``` Terminates the calling process immediately with the given exit code. Wraps `libc::exit`. Runs `atexit` handlers and flushes stdio buffers; does **not** unwind Kestrel's stack or run deinits on values still in scope. Conventionally `0` means success and any non-zero value means failure; a few codes have specific meanings (`2` is shells' "misuse of builtins", `126`/`127` are `exec` errors, `>128` typically encodes a fatal signal). # Examples ``` exit(0); // success — does not return ``` ### function fileExists ```kestrel public func fileExists(String) -> Bool ``` Returns true if any filesystem entry exists at `path`. Wraps `access(path, F_OK)`. Does not distinguish files from directories or symlinks (a dangling symlink reports as nonexistent because `access` follows symlinks). For the type, follow up with `isFile` / `isDirectory`. # Examples ``` if fileExists("/tmp/foo") { // ... } ``` ### function getcwd ```kestrel public func getcwd() -> String ``` Returns the calling process's current working directory. Wraps `getcwd(2)` with a 1 KiB buffer. Returns the empty string if the cwd has been deleted, is longer than 1 KiB, or any other `getcwd` failure occurs — the function does not surface the error code. # Examples ``` let here = getcwd(); ``` ### function getenv ```kestrel public func getenv(String) -> Optional[String] ``` Looks up the value of the environment variable `name`. Returns `Some(value)` if the variable is set (including the empty string), `None` if it is unset. Wraps `libc::getenv`, which returns a pointer into the `environ` block — this function copies the bytes into a Kestrel `String` immediately, so the result is safe to keep across subsequent `setenv` / `unsetenv` calls. # Examples ``` match getenv(name: "HOME") { .Some(path) => print(path), .None => print("HOME not set") } ``` ### function isDirectory ```kestrel public func isDirectory(String) -> Bool ``` Returns true if `path` exists and is a directory. Resolves symlinks (uses `stat`, not `lstat`). Returns `false` for nonexistent paths or any non-directory file type. # Examples ``` isDirectory("/tmp"); // true isDirectory("/etc/hosts"); // false ``` ### function isFile ```kestrel public func isFile(String) -> Bool ``` Returns true if `path` exists and is a regular file. Resolves symlinks. Returns `false` for directories, sockets, FIFOs, devices, and nonexistent paths. ### function listDir ```kestrel public func listDir(String) -> Array[String] ``` Returns the names of the entries inside `path`, excluding `.` and `..`. Wraps `opendir`/`readdir`/`closedir`. The returned names are relative to `path`; join with `path` yourself if you need full paths. On failure to open the directory (missing path, permission denied, etc.), returns an empty array — the function does not distinguish "empty directory" from "open failed". # Examples ``` for entry in listDir("/tmp") { print(entry); } ``` ### function mkdir ```kestrel public func mkdir(String) -> Result[(), IoError] ``` Creates a single directory at `path` with mode `0o755`. Wraps `mkdir(2)`. Fails if `path` already exists or any parent component is missing — use `mkdirAll` to create intermediate directories. # Errors Returns `Err(IoError)` on any libc failure; `errno` is captured and surfaced via the error's `kind`. Common cases: `EEXIST` (path exists), `ENOENT` (missing parent), `EACCES` (permission denied). # Examples ``` match mkdir("/tmp/foo") { .Ok(_) => print("created"), .Err(e) => print(e.message) } ``` ### function mkdirAll ```kestrel public func mkdirAll(String) -> Result[(), IoError] ``` Creates `path` and any missing parent directories. Walks back from the deepest non-existent component, recursing on the parent first. If `path` already exists and is a directory, the call is a no-op success; if it exists and is **not** a directory, returns `Err(IoError(kind: .AlreadyExists))` (`EEXIST`) without disturbing the file. Each created intermediate uses the default mode `0o755`. # Errors Forwards any `mkdir` failure verbatim. Specific to this function: `Err(IoError(kind: .AlreadyExists))` when `path` exists as a non-directory. # Examples ``` mkdirAll("/tmp/foo/bar/baz"); // creates all three levels ``` ### function platform ```kestrel public func platform() -> String ``` Returns a short identifier for the host operating system. One of `"darwin"` or `"linux"` — the string is fixed at compile time via `@platform` selection of two distinct definitions, so the call is effectively a constant. Use this for one-off platform branches; for repeated checks consider `@platform` on your own functions instead. # Examples ``` if platform() == "darwin" { // macOS-specific path } ``` ### function readlink ```kestrel public func readlink(String) -> Result[String, IoError] ``` Returns the target stored in the symlink at `path`. Wraps `readlink(2)` with a 1 KiB buffer. `readlink` does not null- terminate, so this function copies exactly the returned byte count into the result string. Targets longer than 1 KiB are silently truncated — the syscall returns a partial result rather than failing. # Errors Returns `Err(IoError)` if `path` is not a symlink (`EINVAL`), missing (`ENOENT`), or any other libc failure. ### function remove ```kestrel public func remove(String) -> Result[(), IoError] ``` Deletes the file at `path`. Wraps `unlink(2)`. Does not work on directories — use `removeDir` for those. If `path` is the last link to an open file, the file's blocks remain allocated until every descriptor is closed. # Errors Returns `Err(IoError)` on any libc failure; `errno` is captured. ### function removeDir ```kestrel public func removeDir(String) -> Result[(), IoError] ``` Removes an empty directory at `path`. Wraps `rmdir(2)`. Fails with `ENOTEMPTY` if the directory still has entries — list and remove its contents first if you need a recursive remove. # Errors Returns `Err(IoError)` on any libc failure; `errno` is captured. ### function rename ```kestrel public func rename(String, String) -> Result[(), IoError] ``` Renames or moves `from` to `to`. Wraps `rename(2)`. Atomic within a single filesystem; cross- filesystem moves return `EXDEV` and require a copy + delete instead. If `to` exists, it is replaced (subject to type-match rules — file replaces file, directory replaces empty directory). # Errors Returns `Err(IoError)` on any libc failure; `errno` is captured. ### function spawn ```kestrel public func spawn(String) -> Int32 ``` Runs `command` through the system shell and returns its exit code. Wraps `libc::system`, which on POSIX runs `/bin/sh -c ` and returns a packed status word; this function shifts off the signal/coredump bits and returns just the exit code (0–255 in normal cases). The child's stdout and stderr are inherited from the parent process — they go straight to the terminal. For captured output, use `captureOutput`. # Examples ``` let code = spawn("ls -la"); if code != 0 { print("ls failed"); } ``` ### function symlink ```kestrel public func symlink(String, String) -> Result[(), IoError] ``` Creates a symbolic link at `path` pointing to `target`. Wraps `symlink(2)`. The target is stored verbatim — it is not resolved or validated, so dangling links are allowed and relative targets resolve relative to the directory containing the link. # Errors Returns `Err(IoError)` on any libc failure; `errno` is captured. --- ## std.result ### enum Optional ```kestrel public enum Optional[T] ``` A type-safe stand-in for nullable references — either `Some(value)` or `None`. `T?` desugars to `Optional[T]`, and the `null` literal constructs `.None` for any optional type. The compiler refuses to let you read the inner value without handling the `None` case, which is the whole point — there is no implicit unwrap. The `try` operator (and the `??` coalescing operator) propagate `None` through call chains so you can write linear code without nested `match` blocks. # Examples ``` func find(id: Int64) -> User? { if let user = users.get(id) { return user }; null } match find(42) { .Some(let u) => print(u.name), .None => print("Not found") } ``` ``` // `try` short-circuits on None func combine() -> Int64? { let a = try getA(); // returns None early if getA() is None let b = try getB(); a + b } ``` # Representation A two-case tagged union — one byte (or whatever the backend picks) of discriminant plus the payload of `T`. The compiler will use a niche when one is available (e.g. a non-zero pointer), so `Optional[Pointer]` is the same size as `Pointer`. #### case None ```kestrel case None ``` The absent state — same shape as a null reference, but checked at the type level. #### initializer Null Literal ```kestrel public init() ``` Compiler-emitted bridge for the `null` literal. Always constructs `.None`. #### case Some ```kestrel case Some(T) ``` Wraps a present value of `T`. #### function clone ```kestrel public func clone() -> Optional[T] ``` Returns an independent copy. For value types this is a shallow copy of the payload; for COW types, the underlying buffer is shared until first mutation. # Examples ``` let opt = Some([1, 2, 3]); let copy = opt.clone(); // independent copy ``` #### function contains ```kestrel public func contains(T) -> Bool ``` True when `self` is `Some` and the wrapped value equals `value`. Slightly cheaper than `== Some(value)` when you already have the bare value. # Examples ``` Some(42).contains(42); // true Some(42).contains(0); // false None.contains(42); // false ``` #### function expect ```kestrel public func expect(String) -> T ``` Like `unwrap`, but the panic carries `message` instead of the generic text. Use this where the absence of a value should crash loudly with context. # Errors Panics with `message` on `.None` via `fatalError`. # Examples ``` let cfg = loadConfig().expect("Config file required"); ``` #### function filter ```kestrel public func filter((T) -> Bool) -> Optional[T] ``` Returns `Some(value)` when the predicate accepts the value, `None` otherwise. # Examples ``` Some(4).filter { it % 2 == 0 }; // Some(4) Some(3).filter { it % 2 == 0 }; // None None.filter { it % 2 == 0 }; // None ``` #### function flatMap ```kestrel public func flatMap[U]((T) -> Optional[U]) -> Optional[U] ``` Monadic bind — apply a transform that itself returns an `Optional`, without nesting. Equivalent to `map(...).flatten()`. # Examples ``` func parse(s: String) -> Int64? { ... } Some("42").flatMap(parse); // Some(42) Some("abc").flatMap(parse); // None (parse failed) None.flatMap(parse); // None ``` #### function flatten ```kestrel public func flatten[U]() -> Optional[U] where T == Optional[U] ``` Collapses an `Optional[Optional[T]]` one level. Available only when `T` is itself an `Optional`. # Examples ``` Some(Some(42)).flatten(); // Some(42) Some(None).flatten(); // None None.flatten(); // None ``` #### function inspect ```kestrel public func inspect((T) -> ()) -> Optional[T] ``` Side-effecting tap — runs `fn` on the wrapped value (if any) and returns `self` unchanged. Useful for logging or assertions inside a chain. # Examples ``` getUser(id) .inspect { print("Found: \{it.name}") } .map { it.email }; ``` #### function isNone ```kestrel public func isNone() -> Bool ``` True when this is `.None`. The complement of `isSome`. #### function isSome ```kestrel public func isSome() -> Bool ``` True when this is `.Some`. Cheap discriminator-only check. # Examples ``` Some(42).isSome(); // true None.isSome(); // false ``` #### function isSomeAnd ```kestrel public func isSomeAnd((T) -> Bool) -> Bool ``` True when `.Some(value)` and `predicate(value)` returns `true`. `None` always answers `false` without invoking the predicate. # Examples ``` Some(42).isSomeAnd { it > 0 }; // true Some(-1).isSomeAnd { it > 0 }; // false None.isSomeAnd { it > 0 }; // false ``` #### function iter ```kestrel public func iter() -> OptionalIterator[T] ``` Returns an `OptionalIterator` that yields one element if `Some` or zero elements if `None`. Lets an optional plug into any `for-in` or iterator-combinator pipeline. # Examples ``` for value in Some(42).iter() { print(value) // prints 42 }; for value in None.iter() { print(value) // never executes }; ``` #### function map ```kestrel public func map[U]((T) -> U) -> Optional[U] ``` Functor map — applies `transform` to the wrapped value, leaving `None` untouched. # Examples ``` Some(2).map { it * 2 }; // Some(4) None.map { it * 2 }; // None Some("hello").map { it.len }; // Some(5) ``` #### function none ```kestrel public static func none() -> Optional[T] ``` Returns `.None`. Prefer the `null` literal — it works in any optional context without naming the type parameter. # Examples ``` let a = Optional[Int64].none(); // None let b: Int64? = null; // identical, preferred ``` #### function okOr ```kestrel public func okOr[E](E) -> Result[T, E] ``` Promotes to `Result`, supplying `error` for the `None` branch. `error` is eagerly evaluated — use `okOrElse` to defer it. # Examples ``` Some(42).okOr("missing"); // Ok(42) None.okOr("missing"); // Err("missing") ``` #### function okOrElse ```kestrel public func okOrElse[E](() -> E) -> Result[T, E] ``` Like `okOr`, but `error()` is only invoked on `None`. # Examples ``` Some(42).okOrElse { NotFoundError() }; // Ok(42), fn not called None.okOrElse { NotFoundError() }; // Err(NotFoundError()) ``` #### function orElse ```kestrel public func orElse(() -> Optional[T]) -> Optional[T] ``` Returns `self` when `Some`, otherwise the result of `alternative()`. For "use a default scalar" prefer the `??` operator; reach for `orElse` when the fallback itself is an `Optional`. # Examples ``` Some(1).orElse { Some(2) }; // Some(1), fn not called None.orElse { Some(2) }; // Some(2) None.orElse { loadFromCache() }; // calls fn // For unwrapping with a default, prefer ??: let value = optionalInt ?? 0; ``` #### function replace ```kestrel public mutating func replace(T) -> Optional[T] ``` Stores `value` and returns whatever was there before. Mirror of `take` for the assignment direction. # Examples ``` var opt = Some(1); opt.replace(2); // Some(1); opt is now Some(2) var none: Int64? = null; none.replace(1); // None; none is now Some(1) ``` #### function take ```kestrel public mutating func take() -> Optional[T] ``` Removes and returns the current value, leaving `self` as `None`. Idiomatic for "consume once" optional fields. # Examples ``` var opt = Some(42); opt.take(); // Some(42); opt is now None opt.take(); // None; opt is still None ``` #### function take ```kestrel public mutating func take(where: (T) -> Bool) -> Optional[T] ``` Conditional `take` — empties `self` and returns the value only when `predicate(value)` accepts it. Otherwise leaves `self` untouched and returns `None`. # Examples ``` var opt = Some(42); opt.take(where: { it > 0 }); // Some(42); opt is now None var opt2 = Some(42); opt2.take(where: { it < 0 }); // None; opt2 is still Some(42) ``` #### function then ```kestrel public func then[U](Optional[U]) -> Optional[U] ``` Returns `other` when `self` is `Some`, otherwise `None`. `other` is evaluated eagerly — use `flatMap` for lazy chaining. # Examples ``` Some(1).then(Some("a")); // Some("a") Some(1).then(None); // None None.then(Some("a")); // None ``` #### function unwrap ```kestrel public func unwrap() -> T ``` Returns the wrapped value, panicking if `None`. Reach for `unwrap(or:)`, the `??` operator, or pattern matching unless you can prove the value is `Some`. # Errors Panics with `"called unwrap() on None"` when invoked on `.None`. # Examples ``` Some(42).unwrap(); // 42 None.unwrap(); // PANIC ``` #### function unwrap ```kestrel public func unwrap(or: T) -> T ``` Returns the wrapped value or `default` when `None`. `default` is always evaluated — use `unwrap(orElse:)` if computing it is expensive. # Examples ``` Some(42).unwrap(or: 0); // 42 None.unwrap(or: 0); // 0 ``` #### function unwrap ```kestrel public func unwrap(orElse: () -> T) -> T ``` Like `unwrap(or:)`, but `defaultFn` is only called on `None`. Use this when the default is expensive to compute or has side effects. # Examples ``` Some(42).unwrap(orElse: { expensiveDefault() }); // 42, no call None.unwrap(orElse: { expensiveDefault() }); // calls fn ``` #### function wrap ```kestrel public static func wrap(T) -> Optional[T] ``` Wraps `value` in `.Some`. Rarely needed in practice — bare values are promoted via `FromValue`, and `let x: Int64? = 42` does the right thing. # Examples ``` let opt = Optional.wrap(42); // Some(42) let opt: Int64? = 42; // identical, preferred ``` #### function xor ```kestrel public func xor(Optional[T]) -> Optional[T] ``` Exclusive-or of presence — returns the unique `Some` when exactly one of `self`/`other` is set, else `None`. # Examples ``` Some(1).xor(None); // Some(1) None.xor(Some(2)); // Some(2) Some(1).xor(Some(2)); // None None.xor(None); // None ``` #### function zip ```kestrel public func zip[U](with: Optional[U]) -> Optional[(T, U)] ``` Pairs two optionals into an optional tuple. `Some` only when both inputs are `Some`. # Examples ``` Some(1).zip(with: Some("a")); // Some((1, "a")) Some(1).zip(with: None); // None None.zip(with: Some("a")); // None ``` **Equatable** #### typealias Output ```kestrel type Output = Bool ``` #### function equal ```kestrel public func equal(to: Self) -> Bool ``` Bridges `Equal.equal(to:)` to `Equatable.isEqual(to:)`. #### function isEqual ```kestrel public func isEqual(to: Optional[T]) -> Bool ``` Structural equality on the optional. Backs `==`. # Examples ``` Some(1) == Some(1); // true Some(1) == Some(2); // false Some(1) == None; // false None == None; // true ``` #### function notEqual ```kestrel public func notEqual(to: Self) -> Bool ``` Default `!=`: delegates to `==` so there's a single source of truth. **Comparable** #### typealias Output ```kestrel type Output = Bool ``` #### function compare ```kestrel public func compare(Optional[T]) -> Ordering ``` Three-way compare. `None < Some(_)`; two `Some`s defer to the inner `compare`. # Examples ``` None < Some(1); // true Some(1) < Some(2); // true Some(2) < Some(1); // false ``` #### function greaterThan ```kestrel public func greaterThan(Self) -> Bool ``` `>` derived from `compare`. #### function greaterThanOrEqual ```kestrel public func greaterThanOrEqual(Self) -> Bool ``` `>=` derived from `compare`. #### function isAtLeast ```kestrel public func isAtLeast(Self) -> Bool ``` `start..` lower-bound check, derived from `compare`. #### function isAtMost ```kestrel public func isAtMost(Self) -> Bool ``` `..=end` upper-bound check, derived from `compare`. #### function isBelow ```kestrel public func isBelow(Self) -> Bool ``` `.. Bool ``` `<` derived from `compare`. #### function lessThanOrEqual ```kestrel public func lessThanOrEqual(Self) -> Bool ``` `<=` derived from `compare`. **Hashable** #### function hash ```kestrel public func hash[H](into: mutating H) where H: Hasher ``` Mixes a one-byte tag (`0` for `None`, `1` for `Some`) into the hasher, then defers to `T.hash` for the payload. **Tryable** #### typealias Output ```kestrel type Output = T ``` #### typealias Output ```kestrel type Output = T ``` #### typealias Residual ```kestrel type Residual = () ``` #### function tryExtract ```kestrel public consuming func tryExtract() -> ControlFlow[T, ()] ``` Drives `try` — `Continue(value)` for `Some`, `Break(())` for `None`. **FromResidual** #### function fromResidual ```kestrel public static func fromResidual(()) -> Optional[T] ``` Builds `.None` from the residual produced by a `try` short-circuit. **FromValue** #### function from ```kestrel public static func from(T) -> Optional[T] ``` Wraps `value` in `.Some`. Called by the compiler at the promotion site, not usually by user code. **Formattable** #### function format ```kestrel public func format(into: mutating StringBuilder, FormatOptions) ``` Renders `Some(...)` or `None`, forwarding `options` to the inner `format` for the payload. #### function formatted ```kestrel public func formatted(FormatOptions) -> String ``` Returns this value rendered as a `String`. Convenience wrapper: creates a `StringBuilder`, calls `format(into:)`, and returns the built string. Uses a distinct name to avoid overload-resolution ambiguity with `format(into:)`. **ExpressibleByNullLiteral** #### initializer Null Literal ```kestrel init() ``` Builds the absent/none instance. **Coalesce** #### typealias Output ```kestrel type Output ``` #### function coalesce ```kestrel public func coalesce(() -> T) -> T ``` Returns the wrapped value or evaluates `default()`. The default is only invoked on `None`, which is what makes `??` cheap on the happy path. ### struct OptionalIterator ```kestrel public struct OptionalIterator[T] { /* private fields */ } ``` Single-shot iterator yielding zero or one elements. Returned by `Optional.iter()`. # Examples ``` let items: [Int64] = Some(42).iter().collect(); // [42] let empty: [Int64] = None.iter().collect(); // [] ``` # Representation One `Optional[T]` field. `next()` empties it on first call. #### initializer From Optional ```kestrel public init(Optional[T]) ``` Builds an iterator that will yield the contents of `value` on its first `next()` call (or terminate immediately if `value` is `None`). **Iterator** #### typealias Item ```kestrel type Item = T ``` #### typealias TargetIterator ```kestrel type TargetIterator = Self ``` #### function all ```kestrel 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) ``` #### function any ```kestrel 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 ``` #### function chain ```kestrel 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] ``` #### function collect ```kestrel 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] ``` #### function compactMap ```kestrel public func compactMap[T]() -> FilterMapIterator[Self, T] where Item == Optional[T] ``` Drops `None`s and unwraps `Some`s — 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] ``` #### function contains ```kestrel 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 ``` #### function count ```kestrel 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 ``` #### function cycle ```kestrel 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] ``` #### function enumerate ```kestrel 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}") }; ``` #### function filter ```kestrel public func filter(where: (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] ``` #### function filterMap ```kestrel public func filterMap[U](as: (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] ``` #### function first ```kestrel 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 ``` #### function firstIndex ```kestrel 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 ``` #### function flatMap ```kestrel public func flatMap[U](as: (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] ``` #### function flatten ```kestrel 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] ``` #### function fold ```kestrel 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 ``` #### function forEach ```kestrel 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) }; ``` #### function fuse ```kestrel 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. #### function inspect ```kestrel public func inspect((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(); ``` #### function intersperse ```kestrel 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] ``` #### function intersperseWith ```kestrel public func intersperseWith(with: () -> 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] ``` #### function isSorted ```kestrel 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) ``` #### function isSortedDescending ```kestrel public consuming func isSortedDescending() -> Bool ``` True if elements come out in descending order. Mirror of `isSorted`. #### function iter ```kestrel func iter() -> Self ``` Returns `self`. The blanket conformance pivot — iterators *are* iterables. #### function last ```kestrel 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. #### function map ```kestrel public func map[U](as: (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] ``` #### function max ```kestrel public consuming func max() -> Item? ``` Largest element, or `None` for an empty iterator. Ties go to the first occurrence. #### function min ```kestrel 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 ``` #### function next ```kestrel public mutating func next() -> Optional[T] ``` Returns and clears the stored value, then returns `None` forever. `O(1)` and allocation-free. #### function nth ```kestrel 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) ``` #### function peekable ```kestrel 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) ``` #### function product ```kestrel 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 ``` #### function reduce ```kestrel 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 ``` #### function scan ```kestrel public func scan[Acc](from: Acc, by: (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] ``` #### function skip ```kestrel 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(); // [] ``` #### function skipWhile ```kestrel public func skipWhile(where: (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] ``` #### function sorted ```kestrel 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] ``` #### function stepBy ```kestrel 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] ``` #### function sum ```kestrel 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 ``` #### function take ```kestrel 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] ``` #### function takeWhile ```kestrel public func takeWhile(where: (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] ``` #### function tryFold ```kestrel 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") ``` #### function tryForEach ```kestrel public mutating func tryForEach[E]((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 ``` #### function unzip ```kestrel 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"] ``` #### function zip ```kestrel 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)] ``` ### typealias OptionalTypeOperator ```kestrel public type OptionalTypeOperator[T] = Optional[T] ``` Compiler hook — `T?` desugars to `Optional[T]` via this alias. End users should write the sugar; this declaration exists so the operator can resolve to a concrete type. # Examples ``` var name: String? = null; // same as Optional[String] func find(id: Int64) -> User?; // returns Optional[User] let nested: Int64?? = null; // Optional[Optional[Int64]] ``` ### enum Result ```kestrel public enum Result[T, E] ``` The fallible-operation enum: either `Ok(value)` or `Err(error)`. The project's exception-free error story. `T throws E` desugars to `Result[T, E]`, and the `try` operator short-circuits on `Err` so failure propagation reads like normal straight-line code. The compiler refuses to let you read the success value without first handling the error case. `Result` composes with `Optional` via `ok()` / `err()`, and with the `?` operator via `Tryable`. Pick `Result` when callers should be able to inspect *why* something failed; pick `Optional` when "absent" is the only failure mode. # Examples ``` func parseAndDouble(s: String) -> Int64 throws ParseError { let n = try Int64.parse(s).okOr(ParseError()); n * 2 } match parseAndDouble("21") { .Ok(let v) => print("got \{v}"), .Err(let e) => print("failed: \{e}") } ``` # Representation A two-case tagged union — discriminant plus the larger of `T` / `E`. Niche optimisation applies the same way it does to `Optional`. #### case Err ```kestrel case Err(E) ``` The failure branch — wraps an `E`. #### case Ok ```kestrel case Ok(T) ``` The success branch — wraps a `T`. #### function andThen ```kestrel public func andThen[U]((T) -> Result[U, E]) -> Result[U, E] ``` Alias for `flatMap` — chains a fallible step onto an `Ok` branch. Reads more naturally in long pipelines (`parseInput().andThen(validate).andThen(persist)`). #### function andValue ```kestrel public func andValue[U](Result[U, E]) -> Result[U, E] ``` Returns `other` when `self` is `Ok`, otherwise propagates the existing `Err`. Named `andValue` (not `and`) because `and` is a reserved keyword. #### function err ```kestrel public static func err(E) -> Result[T, E] ``` Wraps `error` in `.Err`. Useful when constructing a `Result` from a known error in non-promotion contexts. #### function err ```kestrel public func err() -> Optional[E] ``` Discards the success value, returning `Some(error)` for `.Err` and `None` for `.Ok`. Mirror of `ok()`. #### function flatMap ```kestrel public func flatMap[U]((T) -> Result[U, E]) -> Result[U, E] ``` Monadic bind on the success branch — apply a transform that itself returns a `Result`, without nesting. #### function flatMapErr ```kestrel public func flatMapErr[F]((E) -> Result[T, F]) -> Result[T, F] ``` Monadic bind on the error branch — apply a recovery function that itself returns a `Result`, without nesting. Mirror of `flatMap`. #### function isErr ```kestrel public func isErr() -> Bool ``` True when this is `.Err`. Complement of `isOk`. #### function isOk ```kestrel public func isOk() -> Bool ``` True when this is `.Ok`. Cheap discriminator-only check. # Examples ``` Ok(42).isOk(); // true Err("oops").isOk(); // false ``` #### function iter ```kestrel public func iter() -> ResultIterator[T, E] ``` Returns a `ResultIterator` yielding the success value (one element for `.Ok`, zero for `.Err`). Lets a `Result` plug into iterator pipelines that only care about the happy path. #### function map ```kestrel public func map[U]((T) -> U) -> Result[U, E] ``` Functor map on the success branch. `.Err` passes through unchanged. # Examples ``` Ok(2).map { it * 2 }; // Ok(4) Err("oops").map { it * 2 }; // Err("oops") ``` #### function mapErr ```kestrel public func mapErr[F]((E) -> F) -> Result[T, F] ``` Functor map on the error branch — typically used to widen a specific error type into a more general one. # Examples ``` parse(s).mapErr { AppError.Parse(it) }; ``` #### function ok ```kestrel public static func ok(T) -> Result[T, E] ``` Wraps `value` in `.Ok`. Rarely needed in practice — `FromValue` promotes bare values where the context expects a `Result`. #### function ok ```kestrel public func ok() -> Optional[T] ``` Discards the error, returning `Some(value)` for `.Ok` and `None` for `.Err`. #### function orElse ```kestrel public func orElse[F]((E) -> Result[T, F]) -> Result[T, F] ``` Returns `self` when `Ok`, otherwise calls `alternative(error)`. Use this for recovery logic that depends on which error occurred — e.g. retrying on a transient error but bubbling a permanent one. #### function orValue ```kestrel public func orValue(Result[T, E]) -> Result[T, E] ``` Returns `self` when `Ok`, otherwise returns `other`. Named `orValue` because `or` is a reserved keyword. #### function unwrap ```kestrel public func unwrap() -> T ``` Returns the success value, panicking if `Err`. Use `unwrap(or:)` or pattern matching unless you can prove the result is `Ok`. # Errors Panics with `"called unwrap() on Err"` when invoked on `.Err`. #### function unwrap ```kestrel public func unwrap(or: T) -> T ``` Returns the success value or `default` on `Err`. `default` is always evaluated — use `unwrap(orElse:)` if computing it is expensive or depends on the error. #### function unwrap ```kestrel public func unwrap(orElse: (E) -> T) -> T ``` Like `unwrap(or:)`, but `defaultFn` receives the error value and is only invoked on `Err`. Useful when the recovery value depends on what went wrong. #### function unwrapErr ```kestrel public func unwrapErr() -> E ``` Returns the error value, panicking if `Ok`. Mostly used in tests to assert that a call failed. # Errors Panics with `"called unwrapErr() on Ok"` when invoked on `.Ok`. **Tryable** #### typealias Output ```kestrel type Output = T ``` #### typealias Residual ```kestrel type Residual = E ``` #### function tryExtract ```kestrel public consuming func tryExtract() -> ControlFlow[T, E] ``` Drives `try` — `Continue(value)` for `.Ok`, `Break(error)` for `.Err`. Defined inline because `Tryable` is declared in the enum's conformance list above. **FromResidual** #### function fromResidual ```kestrel public static func fromResidual(E) -> Result[T, E] ``` Builds `.Err(residual)` from the residual produced by a `try` short-circuit. **FromValue** #### function from ```kestrel public static func from(T) -> Result[T, E] ``` Wraps `value` in `.Ok`. Called by the compiler at the promotion site, not usually by user code. **Equatable** #### typealias Output ```kestrel type Output = Bool ``` #### function equal ```kestrel public func equal(to: Self) -> Bool ``` Bridges `Equal.equal(to:)` to `Equatable.isEqual(to:)`. #### function isEqual ```kestrel public func isEqual(to: Result[T, E]) -> Bool ``` Structural equality on the result. Backs `==`. # Examples ``` Ok(1) == Ok(1); // true Ok(1) == Ok(2); // false Err("x") == Err("x"); // true Ok(1) == Err("x"); // false ``` #### function notEqual ```kestrel public func notEqual(to: Self) -> Bool ``` Default `!=`: delegates to `==` so there's a single source of truth. **Formattable** #### function format ```kestrel public func format(into: mutating StringBuilder, FormatOptions) ``` Renders `Ok(...)` or `Err(...)`, forwarding `options` to the inner `format` for the payload. #### function formatted ```kestrel public func formatted(FormatOptions) -> String ``` Returns this value rendered as a `String`. Convenience wrapper: creates a `StringBuilder`, calls `format(into:)`, and returns the built string. Uses a distinct name to avoid overload-resolution ambiguity with `format(into:)`. ### struct ResultIterator ```kestrel public struct ResultIterator[T, E] { /* private fields */ } ``` Single-shot iterator yielding zero or one elements (the `Ok` value). Returned by `Result.iter()`. Errors are silently skipped — use `mapErr` / `match` if you need them. # Representation Stores the success value in an `Optional[T]` field; `next()` empties it on first call. #### initializer From Result ```kestrel public init(Result[T, E]) ``` Builds an iterator from a `Result`, projecting `.Ok` to a single element and `.Err` to an empty stream. #### typealias Item ```kestrel type Item = T ``` #### function next ```kestrel public mutating func next() -> Optional[T] ``` Returns and clears the stored value, then returns `None` forever. `O(1)` and allocation-free. ### typealias ResultTypeOperator ```kestrel public type ResultTypeOperator[T, E] = Result[T, E] ``` Compiler hook — `T throws E` desugars to `Result[T, E]` via this alias. Write the sugar in user code; this exists so the operator can resolve to a concrete type. --- ## std.text ### enum Alignment ```kestrel public enum Alignment ``` Horizontal alignment of formatted output within a fixed field width. Pairs with `FormatOptions.width` and `FormatOptions.fill` to position shorter values inside the requested column. When the value is already at least as wide as the field, alignment has no visible effect. The formatter for `String` is the canonical consumer; numeric and boolean formatters honour the same convention. # Examples ``` var opts = FormatOptions(); opts.width = .Some(8); opts.alignment = .Right; "ab".format(options: opts); // " ab" opts.alignment = .Center; "ab".format(options: opts); // " ab " ``` #### case Center ```kestrel case Center ``` Pad on both sides; if the padding is odd, the extra space goes on the right. #### case Left ```kestrel case Left ``` Pad on the right; the value sits flush against the left edge of the field. #### case Right ```kestrel case Right ``` Pad on the left; the value sits flush against the right edge of the field. **Equatable** #### typealias Output ```kestrel type Output = Bool ``` #### function equal ```kestrel public func equal(to: Self) -> Bool ``` Bridges `Equal.equal(to:)` to `Equatable.isEqual(to:)`. #### function isEqual ```kestrel public func isEqual(to: Alignment) -> Bool ``` Returns true if both cases are the same variant. Equality is structural — there are no payloads. Used by the `Equatable` conformance so `FormatOptions.isEqual` can fall through without payload comparisons. # Examples ``` Alignment.Left.isEqual(to: .Left); // true Alignment.Left.isEqual(to: .Center); // false ``` #### function notEqual ```kestrel public func notEqual(to: Self) -> Bool ``` Default `!=`: delegates to `==` so there's a single source of truth. **Matchable** #### function matches ```kestrel public func matches(Alignment) -> Bool ``` Pattern-match form of equality — delegates to `isEqual`. Lets `Alignment` appear in `match` patterns against another value. # Examples ``` Alignment.Right.matches(.Right); // true ``` ### struct ByteIndex ```kestrel public struct ByteIndex { /* private fields */ } ``` A typed wrapper for a byte position within a `String`. `ByteIndex` exists so that APIs taking string positions can refuse raw `Int64`s, which removes the "is this a byte offset or a char offset?" ambiguity at the call site. The wrapped `value` is a plain UTF-8 byte offset; arithmetic is the caller's responsibility. # Representation A single `Int64` field. #### initializer From Value ```kestrel public init(Int64) ``` Wraps a raw byte offset. #### function advance ```kestrel public func advance(by: Int64) -> ByteIndex ``` Advances by `n` bytes. Pure arithmetic — no string needed. #### field value ```kestrel public var value: Int64 ``` The wrapped byte offset. **Equatable** #### typealias Output ```kestrel type Output = Bool ``` #### function equal ```kestrel public func equal(to: Self) -> Bool ``` Bridges `Equal.equal(to:)` to `Equatable.isEqual(to:)`. #### function isEqual ```kestrel public func isEqual(to: ByteIndex) -> Bool ``` Returns true if the two indices wrap the same byte offset. #### function notEqual ```kestrel public func notEqual(to: Self) -> Bool ``` Default `!=`: delegates to `==` so there's a single source of truth. **Comparable** #### typealias Output ```kestrel type Output = Bool ``` #### function compare ```kestrel public func compare(ByteIndex) -> Ordering ``` Compares two byte indices by their wrapped offsets. #### function greaterThan ```kestrel public func greaterThan(Self) -> Bool ``` `>` derived from `compare`. #### function greaterThanOrEqual ```kestrel public func greaterThanOrEqual(Self) -> Bool ``` `>=` derived from `compare`. #### function isAtLeast ```kestrel public func isAtLeast(Self) -> Bool ``` `start..` lower-bound check, derived from `compare`. #### function isAtMost ```kestrel public func isAtMost(Self) -> Bool ``` `..=end` upper-bound check, derived from `compare`. #### function isBelow ```kestrel public func isBelow(Self) -> Bool ``` `.. Bool ``` `<` derived from `compare`. #### function lessThanOrEqual ```kestrel public func lessThanOrEqual(Self) -> Bool ``` `<=` derived from `compare`. **BytesIndex** #### typealias BytesYield ```kestrel type BytesYield = UInt8 ``` #### function readBytes ```kestrel public func readBytes(from: BytesView) -> UInt8 ``` #### function readBytesChecked ```kestrel public func readBytesChecked(from: BytesView) -> UInt8? ``` #### function readBytesUnchecked ```kestrel public func readBytesUnchecked(from: BytesView) -> UInt8 ``` ### struct BytesIterator ```kestrel public struct BytesIterator { /* private fields */ } ``` Single-pass forward iterator over the raw UTF-8 bytes of a string. Yielded by `BytesView.iter()`. Walks the underlying buffer one byte at a time and returns each as a `UInt8`. The iterator holds a raw pointer into the source string's storage; do not mutate the source while iterating. # Examples ``` var it = "hi".bytes.iter(); it.next(); // Some(104) // 'h' it.next(); // Some(105) // 'i' it.next(); // None ``` # Representation A `(ptr, length, index)` triple: a raw pointer to the buffer plus the cursor and total-length pair the iterator advances through. # Memory Model Value type. The pointer aliases string storage; do not retain the iterator across mutations of the source `String`. #### initializer From Pointer ```kestrel public init(ptr: lang.ptr[lang.i8], length: Int64, index: Int64) ``` Constructs a bytes iterator from a raw pointer, total byte count, and starting offset. Prefer `String.bytes.iter()` over calling this directly. # Safety `ptr` must point to at least `length` valid bytes; `index` must be in `0..=length`. **Iterator** #### typealias Item ```kestrel type Item = UInt8 ``` The element type yielded by `next()` — always `UInt8`. #### typealias TargetIterator ```kestrel type TargetIterator = Self ``` #### function all ```kestrel 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) ``` #### function any ```kestrel 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 ``` #### function chain ```kestrel 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] ``` #### function collect ```kestrel 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] ``` #### function compactMap ```kestrel public func compactMap[T]() -> FilterMapIterator[Self, T] where Item == Optional[T] ``` Drops `None`s and unwraps `Some`s — 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] ``` #### function contains ```kestrel 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 ``` #### function count ```kestrel 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 ``` #### function cycle ```kestrel 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] ``` #### function enumerate ```kestrel 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}") }; ``` #### function filter ```kestrel public func filter(where: (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] ``` #### function filterMap ```kestrel public func filterMap[U](as: (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] ``` #### function first ```kestrel 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 ``` #### function firstIndex ```kestrel 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 ``` #### function flatMap ```kestrel public func flatMap[U](as: (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] ``` #### function flatten ```kestrel 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] ``` #### function fold ```kestrel 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 ``` #### function forEach ```kestrel 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) }; ``` #### function fuse ```kestrel 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. #### function inspect ```kestrel public func inspect((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(); ``` #### function intersperse ```kestrel 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] ``` #### function intersperseWith ```kestrel public func intersperseWith(with: () -> 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] ``` #### function isSorted ```kestrel 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) ``` #### function isSortedDescending ```kestrel public consuming func isSortedDescending() -> Bool ``` True if elements come out in descending order. Mirror of `isSorted`. #### function iter ```kestrel func iter() -> Self ``` Returns `self`. The blanket conformance pivot — iterators *are* iterables. #### function last ```kestrel 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. #### function map ```kestrel public func map[U](as: (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] ``` #### function max ```kestrel public consuming func max() -> Item? ``` Largest element, or `None` for an empty iterator. Ties go to the first occurrence. #### function min ```kestrel 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 ``` #### function next ```kestrel public mutating func next() -> UInt8? ``` Returns the next byte, or `None` once `index` reaches `length`. Each call reads one byte and advances the cursor by 1. #### function nth ```kestrel 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) ``` #### function peekable ```kestrel 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) ``` #### function product ```kestrel 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 ``` #### function reduce ```kestrel 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 ``` #### function scan ```kestrel public func scan[Acc](from: Acc, by: (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] ``` #### function skip ```kestrel 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(); // [] ``` #### function skipWhile ```kestrel public func skipWhile(where: (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] ``` #### function sorted ```kestrel 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] ``` #### function stepBy ```kestrel 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] ``` #### function sum ```kestrel 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 ``` #### function take ```kestrel 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] ``` #### function takeWhile ```kestrel public func takeWhile(where: (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] ``` #### function tryFold ```kestrel 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") ``` #### function tryForEach ```kestrel public mutating func tryForEach[E]((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 ``` #### function unzip ```kestrel 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"] ``` #### function zip ```kestrel 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)] ``` ### protocol BytesSubstringIndex ```kestrel public protocol BytesSubstringIndex ``` Range-only index for `BytesView.substring`. Conformed by every range type so a single generic `substring` can dispatch over all of them. Single-element indexes (`Int64`) deliberately don't conform — `substring` is range-flavored only. #### function readBytesSubstring ```kestrel func readBytesSubstring(from: BytesView) -> String ``` ### struct BytesView ```kestrel public struct BytesView { /* private fields */ } ``` A read-only view over the raw UTF-8 bytes of a `String`. Returned by `String.bytes`. Provides O(1) byte indexing and iteration; the bytes are returned as `UInt8` exactly as they sit in memory. The most common reason to reach for `BytesView` is to perform byte-level operations (substring searches, hashing) without paying the cost of UTF-8 decoding. For code-point or grapheme iteration, see `CharsView` / `GraphemesView`. # Examples ``` let s = "hi"; s.bytes.count; // 2 s.bytes(checked: 0); // Some(104) s.bytes(checked: 5); // None (out of bounds) ``` # Representation A `(ptr, length)` pair pointing at the source string's UTF-8 buffer. # Memory Model Borrows the source string's storage; the view is invalidated by any mutation that reallocates that buffer. Copy out to a new `String` (e.g. via `substring`) if you need an independent value. #### subscript Checked Index ```kestrel public subscript[I](checked: I) -> I.BytesYield? { get } ``` Reads at `index`, returning `.None` on out-of-bounds. #### subscript Clamping ```kestrel public subscript[I](clamped: I) -> I.BytesClampedYield { get } ``` Reads at `index` with bounds saturated to `[0, count)`. Single- byte indexes yield `UInt8?` (`None` on empty view); range indexes yield `BytesView` (always valid, possibly empty). #### initializer From Slice ```kestrel public init(slice: StringSlice) ``` Constructs a bytes view backed by the given string slice. The view retains shared ownership of the underlying bytes. #### subscript Indexed Byte / Sub-view ```kestrel public subscript[I](I) -> I.BytesYield { get } ``` Reads a single byte (`UInt8`) for `Int64` indexes, or a zero-copy sub-view (`BytesView`) for `Range[Int64]` / `ClosedRange[Int64]`. Panics on out-of-bounds. Range slicing does not validate UTF-8 boundaries — call `.toString()` on the sub-view if you need an owned `String` (which validates). #### subscript Unchecked Index ```kestrel public subscript[I](unchecked: I) -> I.BytesYield { get } ``` Reads at `index` with no bounds check. # Safety Caller must guarantee `0 <= index < count`. For ranges, the endpoints must be in `0..=count`; otherwise the resulting sub-view aliases out-of-bounds memory. #### subscript Wrapping ```kestrel public subscript[I](wrapped: I) -> I.BytesWrappedYield { get } ``` Reads at `index` with modulo wrap-around. Negative indices wrap from the end: `view.bytes(wrapped: -1)` reads the last byte. Returns `None` on an empty view. #### function asRaw ```kestrel public func asRaw() -> lang.ptr[lang.i8] ``` Returns the raw pointer to the underlying byte buffer. Intended for FFI bridges; the pointer is only valid as long as the source string remains live and unmutated. #### field count ```kestrel public var count: Int64 { get } ``` Number of bytes in the view. O(1). This is **byte** count, not character count — see `CharsView.count` for the latter (which is O(n)). #### field endIndex ```kestrel public var endIndex: ByteIndex { get } ``` Byte index one past the last byte. #### function firstIndex ```kestrel public func firstIndex(of: UInt8) -> ByteIndex? ``` Returns the index of the first occurrence of `byte`, or `.None`. #### field isEmpty ```kestrel public var isEmpty: Bool { get } ``` `true` if the view spans zero bytes. #### function lastIndex ```kestrel public func lastIndex(of: UInt8) -> ByteIndex? ``` Returns the index of the last occurrence of `byte`, or `.None`. #### function slice ```kestrel public func slice(from: ByteIndex, to: ByteIndex) -> StringSlice ``` Returns a `StringSlice` covering the byte range `[start, end)`. #### field startIndex ```kestrel public var startIndex: ByteIndex { get } ``` Byte index of the first byte. #### function substring ```kestrel public func substring[__opaque_0](__opaque_0) -> String where __opaque_0: BytesSubstringIndex ``` Convenience: dispatches to a `BytesSubstringIndex` to produce an owned `String` covering the requested byte range. Equivalent to `self(range).toString()` for both `Range[Int64]` and `ClosedRange[Int64]`. #### function toString ```kestrel public func toString() -> String ``` Materializes the view as an owned `String`. Copies all bytes into a fresh buffer; the result is independent of the source. Bytes are copied verbatim — no UTF-8 validation is performed. **Iterable** #### typealias Item ```kestrel type Item = UInt8 ``` The element type yielded by iteration — always `UInt8`. #### typealias TargetIterator ```kestrel type TargetIterator = BytesIterator ``` The iterator type returned by `iter()`. #### function iter ```kestrel public func iter() -> BytesIterator ``` Returns a `BytesIterator` positioned at byte 0. Required by `Iterable`. Each call produces a fresh iterator — the view is reusable. **Cloneable** #### function clone ```kestrel public func clone() -> BytesView ``` ### struct Char ```kestrel public struct Char { /* private fields */ } ``` A single Unicode scalar value (code point in `0..=0x10FFFF`, surrogates excluded). `Char` is the unit yielded by `String.chars` / `CharsView`; iterating graphemes (`String.graphemes`) instead returns `Grapheme` clusters that may comprise multiple `Char`s. The character-literal syntax constructs values directly: `'a'`, `'\n'`, `'\u{1F600}'`. For the raw byte representation, see `utf8Length()` and the free `encodeUtf8` / `decodeUtf8` functions. # Examples ``` let a: Char = 'a'; a.isAsciiLetter; // true a.utf8Length(); // 1 let smile: Char = '\u{1F600}'; smile.utf8Length(); // 4 ``` # Representation A single `UInt32` holding the scalar value. Comparison and hashing operate on that integer directly. #### initializer Char Literal ```kestrel public init(charLiteral: lang.i32) ``` Compiler-emitted constructor for character literals. Called when you write `'a'`, `'\n'`, `'\u{1F600}'`. Not intended for direct use — `Char(value:)` is the user-facing constructor. # Examples ``` let c: Char = 'a'; // lowers to Char(charLiteral: ...) ``` #### initializer From Digit ```kestrel public init(fromDigit: UInt32) ``` Returns the ASCII digit `Char` for a numeric value `0`–`9`, `null` otherwise. Inverse of `digitValue`. Values outside `0..=9` return `null`. # Examples ``` Char(fromDigit: 7); // Some('7') Char(fromDigit: 12); // None ``` #### initializer From Value ```kestrel public init(UInt32) ``` Returns a `Char` if the value is a valid Unicode scalar, `null` otherwise. Rejects values > U+10FFFF and the surrogate range U+D800..U+DFFF. # Examples ``` let c = Char(65); // Some('A') let bad = Char(0xD800); // None (surrogate) ``` #### initializer Unchecked ```kestrel public init(unchecked: UInt32) ``` Wraps a raw `UInt32` scalar value as a `Char` without validation. # Safety The caller must ensure `value` is a valid Unicode scalar (0..=0x10FFFF, excluding surrogates U+D800..U+DFFF). #### function digitValue ```kestrel public func digitValue() -> UInt32? ``` Returns the numeric value `0`–`9` for ASCII digits, otherwise `None`. Inverse of `fromDigit`. Non-ASCII digit characters return `None` — match `isAsciiDigit` semantics. # Examples ``` '7'.digitValue(); // Some(7) 'a'.digitValue(); // None ``` #### function hasLowercaseExpansion ```kestrel public func hasLowercaseExpansion() -> Bool ``` Returns true if the lowercase form is multi-char. Rare in practice but exists for full Unicode round-tripping. #### function hasTitlecaseExpansion ```kestrel public func hasTitlecaseExpansion() -> Bool ``` Returns true if the titlecase form is multi-char. #### function hasUppercaseExpansion ```kestrel public func hasUppercaseExpansion() -> Bool ``` Returns true if the uppercase form is multi-char (e.g. `ß` → `SS`). When `true`, prefer `uppercaseExpansion()` over `uppercased()` to avoid silently dropping characters. # Examples ``` '\u{00DF}'.hasUppercaseExpansion(); // true (ß) 'a'.hasUppercaseExpansion(); // false ``` #### field isAscii ```kestrel public var isAscii: Bool { get } ``` Returns true if the scalar is in the ASCII range (`< 0x80`). Cheap byte-range test; does not consult Unicode tables. For "alphabetic by Unicode" use `unicode.toLowercase` round-tripping or the property tables directly. # Examples ``` 'A'.isAscii; // true '\u{00E9}'.isAscii; // false (é) ``` #### field isAsciiAlphanumeric ```kestrel public var isAsciiAlphanumeric: Bool { get } ``` Returns true for ASCII letters and ASCII digits. Composition of `isAsciiLetter` and `isAsciiDigit`; same ASCII-only caveats apply. # Examples ``` 'a'.isAsciiAlphanumeric; // true '7'.isAsciiAlphanumeric; // true '_'.isAsciiAlphanumeric; // false ``` #### field isAsciiDigit ```kestrel public var isAsciiDigit: Bool { get } ``` Returns true for the ASCII digits `0`–`9`. **ASCII-only.** Other Unicode digit categories (Arabic-Indic, Devanagari, etc.) return `false`. See `digitValue()` for parsing to numeric value. # Examples ``` '7'.isAsciiDigit; // true 'a'.isAsciiDigit; // false ``` #### field isAsciiLetter ```kestrel public var isAsciiLetter: Bool { get } ``` Returns true for ASCII letters `A`–`Z` / `a`–`z`. **ASCII-only.** Non-ASCII letters (e.g. `é`, `Ω`, `日`) return `false` even though they are letters in Unicode. For the full Unicode test, use the property tables in `std.text.unicode`. # Examples ``` 'A'.isAsciiLetter; // true '\u{00E9}'.isAsciiLetter; // false (é — non-ASCII) '7'.isAsciiLetter; // false ``` #### field isAsciiLowercase ```kestrel public var isAsciiLowercase: Bool { get } ``` Returns true for ASCII lowercase letters `a`–`z`. **ASCII-only.** Use `unicode.toLowercase` round-tripping for general Unicode case tests. # Examples ``` 'a'.isAsciiLowercase; // true 'A'.isAsciiLowercase; // false ``` #### field isAsciiUppercase ```kestrel public var isAsciiUppercase: Bool { get } ``` Returns true for ASCII uppercase letters `A`–`Z`. **ASCII-only.** Use `unicode.toUppercase` round-tripping for general Unicode case tests. # Examples ``` 'A'.isAsciiUppercase; // true 'a'.isAsciiUppercase; // false '\u{00C9}'.isAsciiUppercase; // false (É — non-ASCII) ``` #### field isControl ```kestrel public var isControl: Bool { get } ``` Returns true for the C0 controls (`< U+0020`) and DEL (`U+007F`). Does not include the C1 controls (`U+0080`–`U+009F`); add a dedicated test if you need them. # Examples ``` '\n'.isControl; // true '\x7F'.isControl; // true 'a'.isControl; // false ``` #### field isWhitespace ```kestrel public var isWhitespace: Bool { get } ``` Returns true for the common ASCII whitespace set: space, tab, LF, CR, form feed. Does not include Unicode whitespace such as `U+00A0` (no-break space) or `U+2028` (line separator). For Unicode-aware whitespace, consult the property tables. # Examples ``` ' '.isWhitespace; // true '\t'.isWhitespace; // true '\n'.isWhitespace; // true 'a'.isWhitespace; // false ``` #### function lowercaseExpansion ```kestrel public func lowercaseExpansion() -> String ``` Returns the multi-char lowercase form as a `String`. Empty string if no expansion exists. #### function lowercased ```kestrel public func lowercased() -> Char ``` Returns the lowercase form, using full Unicode case-mapping tables. Locale-independent. For characters with multi-char lowercase expansions, see `lowercaseExpansion()`. # Examples ``` 'A'.lowercased(); // 'a' '\u{0130}'.lowercased(); // 'i' (Turkish dotted I — first char only) ``` #### function titlecaseExpansion ```kestrel public func titlecaseExpansion() -> String ``` Returns the multi-char titlecase form as a `String`. Empty string if no expansion exists. #### function titlecased ```kestrel public func titlecased() -> Char ``` Returns the titlecase form, using full Unicode case-mapping tables. Titlecase differs from uppercase for some characters — e.g. ligatures like `dz` titlecase to `Dz` (capital plus small) rather than `DZ` (full uppercase). # Examples ``` 'a'.titlecased(); // 'A' ``` #### function toString ```kestrel public func toString() -> String ``` Converts this code point to an owned `String`. #### function uppercaseExpansion ```kestrel public func uppercaseExpansion() -> String ``` Returns the multi-char uppercase form as a `String`. For characters without an expansion this returns the empty string; use `hasUppercaseExpansion()` first to distinguish. # Examples ``` '\u{00DF}'.uppercaseExpansion(); // "SS" 'a'.uppercaseExpansion(); // "" ``` #### function uppercased ```kestrel public func uppercased() -> Char ``` Returns the uppercase form, using full Unicode case-mapping tables. For characters whose uppercase form is multiple `Char`s (e.g. German `ß` → `SS`), this returns only the first `Char`. Use `hasUppercaseExpansion()` plus `uppercaseExpansion()` to handle those cases correctly. Locale-independent — does not perform Turkish / Azeri tailoring. # Examples ``` 'a'.uppercased(); // 'A' '\u{00DF}'.uppercased(); // 'S' (first char of "SS"; see hasUppercaseExpansion) ``` #### function utf8Length ```kestrel public func utf8Length() -> Int64 ``` Returns how many UTF-8 bytes are required to encode this character (1–4). Constant time — branches on the scalar value alone. Use this to size buffers before calling `encodeUtf8`. # Examples ``` 'a'.utf8Length(); // 1 '\u{00E9}'.utf8Length(); // 2 (é) '\u{20AC}'.utf8Length(); // 3 (€) '\u{1F600}'.utf8Length(); // 4 (😀) ``` #### function value ```kestrel public func value() -> UInt32 ``` Returns the raw Unicode scalar as a `UInt32`. Useful for arithmetic on code points (e.g. `digitValue`'s offset trick) or interop with APIs that take a numeric code point. # Examples ``` 'A'.value(); // 65 '\u{1F600}'.value(); // 128512 ``` **Equatable** #### typealias Output ```kestrel type Output = Bool ``` #### function equal ```kestrel public func equal(to: Self) -> Bool ``` Bridges `Equal.equal(to:)` to `Equatable.isEqual(to:)`. #### function isEqual ```kestrel public func isEqual(to: Char) -> Bool ``` Returns true if both characters are the same Unicode scalar. Pure scalar-value equality — no case folding, no normalization. # Examples ``` 'a'.isEqual(to: 'a'); // true 'a'.isEqual(to: 'A'); // false ``` #### function notEqual ```kestrel public func notEqual(to: Self) -> Bool ``` Default `!=`: delegates to `==` so there's a single source of truth. **Comparable** #### typealias Output ```kestrel type Output = Bool ``` #### function compare ```kestrel public func compare(Char) -> Ordering ``` Compares two characters by scalar value. Yields code-point order, which agrees with byte order in UTF-8 (UTF-8 is order-preserving). Not the same as locale-aware collation. # Examples ``` 'a'.compare('b'); // Less 'b'.compare('a'); // Greater 'a'.compare('a'); // Equal ``` #### function greaterThan ```kestrel public func greaterThan(Self) -> Bool ``` `>` derived from `compare`. #### function greaterThanOrEqual ```kestrel public func greaterThanOrEqual(Self) -> Bool ``` `>=` derived from `compare`. #### function isAtLeast ```kestrel public func isAtLeast(Self) -> Bool ``` `start..` lower-bound check, derived from `compare`. #### function isAtMost ```kestrel public func isAtMost(Self) -> Bool ``` `..=end` upper-bound check, derived from `compare`. #### function isBelow ```kestrel public func isBelow(Self) -> Bool ``` `.. Bool ``` `<` derived from `compare`. #### function lessThanOrEqual ```kestrel public func lessThanOrEqual(Self) -> Bool ``` `<=` derived from `compare`. **Matchable** #### function matches ```kestrel public func matches(Char) -> Bool ``` Pattern-match form of equality — delegates to `isEqual`. **ExpressibleByCharLiteral** #### initializer Char Literal ```kestrel init(charLiteral: lang.i32) ``` Builds an instance from a character literal. **Hashable** #### function hash ```kestrel public func hash[H](into: mutating H) where H: Hasher ``` Hashes this character by writing its 4-byte scalar value to the hasher. Uses native byte order — fine for in-process hash maps; do not use the result for content-addressed storage. **RangeMatchable** #### function isAtLeast ```kestrel public func isAtLeast(Char) -> Bool ``` Returns true if `self >= bound`. Used by `RangeMatchable` for `case 'a'...'z'`. #### function isAtMost ```kestrel public func isAtMost(Char) -> Bool ``` Returns true if `self <= bound`. Used by `RangeMatchable` for `case 'a'...'z'`. #### function isBelow ```kestrel public func isBelow(Char) -> Bool ``` Returns true if `self < bound`. Used by `RangeMatchable` for half-open patterns. **Formattable** #### function format ```kestrel public func format(into: mutating StringBuilder, FormatOptions) ``` #### function formatted ```kestrel public func formatted(FormatOptions) -> String ``` Returns this value rendered as a `String`. Convenience wrapper: creates a `StringBuilder`, calls `format(into:)`, and returns the built string. Uses a distinct name to avoid overload-resolution ambiguity with `format(into:)`. ### struct CharIndex ```kestrel public struct CharIndex { /* private fields */ } ``` A typed wrapper for a character position within a `String`. Unlike `ByteIndex`, `CharIndex` carries the byte offset of the underlying character — code-point indexing is O(n), so this pre-resolved offset is what gets stored. Construct one by walking the string yourself; the type is purely a tag for clarity. # Representation A single `Int64` field holding the byte offset of the character. #### initializer From Offset ```kestrel public init(Int64) ``` Wraps a pre-resolved byte offset for a character position. #### function advance ```kestrel public func advance(by: Int64, from: StringSlice) -> CharIndex ``` Advances by `n` code points. Requires the source string to decode UTF-8 boundaries. O(n) in chars advanced. #### field byteOffset ```kestrel public var byteOffset: Int64 ``` The byte offset where the indexed character begins. **Equatable** #### typealias Output ```kestrel type Output = Bool ``` #### function equal ```kestrel public func equal(to: Self) -> Bool ``` Bridges `Equal.equal(to:)` to `Equatable.isEqual(to:)`. #### function isEqual ```kestrel public func isEqual(to: CharIndex) -> Bool ``` Returns true if the two indices point at the same byte offset. #### function notEqual ```kestrel public func notEqual(to: Self) -> Bool ``` Default `!=`: delegates to `==` so there's a single source of truth. **Comparable** #### typealias Output ```kestrel type Output = Bool ``` #### function compare ```kestrel public func compare(CharIndex) -> Ordering ``` #### function greaterThan ```kestrel public func greaterThan(Self) -> Bool ``` `>` derived from `compare`. #### function greaterThanOrEqual ```kestrel public func greaterThanOrEqual(Self) -> Bool ``` `>=` derived from `compare`. #### function isAtLeast ```kestrel public func isAtLeast(Self) -> Bool ``` `start..` lower-bound check, derived from `compare`. #### function isAtMost ```kestrel public func isAtMost(Self) -> Bool ``` `..=end` upper-bound check, derived from `compare`. #### function isBelow ```kestrel public func isBelow(Self) -> Bool ``` `.. Bool ``` `<` derived from `compare`. #### function lessThanOrEqual ```kestrel public func lessThanOrEqual(Self) -> Bool ``` `<=` derived from `compare`. **CharsIndex** #### typealias CharsYield ```kestrel type CharsYield = Char ``` #### function readChars ```kestrel public func readChars(from: CharsView) -> Char ``` #### function readCharsChecked ```kestrel public func readCharsChecked(from: CharsView) -> Char? ``` ### struct CharsIterator ```kestrel public struct CharsIterator { /* private fields */ } ``` Single-pass forward iterator over Unicode code points (`Char`). Yielded by `CharsView.iter()` and consumed by `GraphemesIterator`. On each `next()` call, decodes one UTF-8 character starting at the current cursor and advances by its byte length. Invalid bytes are skipped one at a time and surfaced as `U+FFFD` (the Unicode replacement character) so the iteration always makes progress. # Examples ``` var it = "hi".chars.iter(); it.next(); // Some('h') it.next(); // Some('i') it.next(); // None ``` # Representation A `(ptr, length, byteIndex)` triple. `byteIndex` walks the buffer in variable-width steps according to the UTF-8 encoding. # Memory Model Value type that aliases the source string's buffer. Do not retain across mutations of the source `String`. #### initializer From Pointer ```kestrel public init(ptr: lang.ptr[lang.i8], length: Int64, byteIndex: Int64) ``` Constructs a chars iterator from a raw pointer, byte length, and starting byte offset. Prefer `String.chars.iter()` over calling this directly. # Safety `ptr` must point to `length` valid UTF-8 bytes; `byteIndex` must be `0` or land on a UTF-8 boundary. **Iterator** #### typealias Item ```kestrel type Item = Char ``` The element type yielded by `next()` — always `Char`. #### typealias TargetIterator ```kestrel type TargetIterator = Self ``` #### function all ```kestrel 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) ``` #### function any ```kestrel 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 ``` #### function chain ```kestrel 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] ``` #### function collect ```kestrel 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] ``` #### function compactMap ```kestrel public func compactMap[T]() -> FilterMapIterator[Self, T] where Item == Optional[T] ``` Drops `None`s and unwraps `Some`s — 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] ``` #### function contains ```kestrel 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 ``` #### function count ```kestrel 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 ``` #### function cycle ```kestrel 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] ``` #### function enumerate ```kestrel 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}") }; ``` #### function filter ```kestrel public func filter(where: (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] ``` #### function filterMap ```kestrel public func filterMap[U](as: (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] ``` #### function first ```kestrel 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 ``` #### function firstIndex ```kestrel 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 ``` #### function flatMap ```kestrel public func flatMap[U](as: (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] ``` #### function flatten ```kestrel 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] ``` #### function fold ```kestrel 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 ``` #### function forEach ```kestrel 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) }; ``` #### function fuse ```kestrel 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. #### function inspect ```kestrel public func inspect((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(); ``` #### function intersperse ```kestrel 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] ``` #### function intersperseWith ```kestrel public func intersperseWith(with: () -> 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] ``` #### function isSorted ```kestrel 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) ``` #### function isSortedDescending ```kestrel public consuming func isSortedDescending() -> Bool ``` True if elements come out in descending order. Mirror of `isSorted`. #### function iter ```kestrel func iter() -> Self ``` Returns `self`. The blanket conformance pivot — iterators *are* iterables. #### function last ```kestrel 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. #### function map ```kestrel public func map[U](as: (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] ``` #### function max ```kestrel public consuming func max() -> Item? ``` Largest element, or `None` for an empty iterator. Ties go to the first occurrence. #### function min ```kestrel 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 ``` #### function next ```kestrel public mutating func next() -> Char? ``` Returns the next code point, or `None` when the buffer is exhausted. On invalid UTF-8 the iterator yields the replacement character `U+FFFD` and advances by one byte; this guarantees forward progress without aborting. #### function nth ```kestrel 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) ``` #### function peekable ```kestrel 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) ``` #### function product ```kestrel 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 ``` #### function reduce ```kestrel 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 ``` #### function scan ```kestrel public func scan[Acc](from: Acc, by: (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] ``` #### function skip ```kestrel 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(); // [] ``` #### function skipWhile ```kestrel public func skipWhile(where: (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] ``` #### function sorted ```kestrel 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] ``` #### function stepBy ```kestrel 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] ``` #### function sum ```kestrel 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 ``` #### function take ```kestrel 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] ``` #### function takeWhile ```kestrel public func takeWhile(where: (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] ``` #### function tryFold ```kestrel 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") ``` #### function tryForEach ```kestrel public mutating func tryForEach[E]((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 ``` #### function unzip ```kestrel 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"] ``` #### function zip ```kestrel 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)] ``` ### protocol CharsSubstringIndex ```kestrel public protocol CharsSubstringIndex ``` Range-only index for `CharsView.substring`. See `BytesSubstringIndex`. #### function readCharsSubstring ```kestrel func readCharsSubstring(from: CharsView) -> String ``` ### struct CharsView ```kestrel public struct CharsView { /* private fields */ } ``` A view over the Unicode code points in a `String`. Returned by `String.chars`. Iteration is O(1) per code point but `count()` is O(n) because UTF-8 is variable-width. Range subscripts are O(n) (the segment-walk dominates) but yield a zero-copy `CharsView` sub-view — call `.toString()` to materialize an owned `String`. To index in O(1), use `BytesView` and convert byte offsets back yourself. # Examples ``` let s = "héllo"; s.chars.count; // 5 (code points) s.bytes.count; // 6 (bytes — 'é' is 2 bytes) s.chars(0..<4).toString(); // "héll" s.chars.substring(0..<4); // "héll" ``` # Representation A `(ptr, length)` pair, plus the on-demand UTF-8 decoder. # Memory Model Borrows the source string's buffer. Invalidated by any mutation that reallocates the storage. #### subscript Checked Index ```kestrel public subscript[I](checked: I) -> I.CharsYield? { get } ``` Reads at `index`, returning `.None` on out-of-bounds. #### subscript Clamping ```kestrel public subscript[I](clamped: I) -> I.CharsClampedYield { get } ``` Reads at `index` with bounds saturated to `[0, count)`. Single- char indexes yield `Char?` (`None` on empty view); range indexes yield `CharsView` (always valid, possibly empty). #### initializer From Slice ```kestrel public init(slice: StringSlice) ``` Constructs a chars view backed by the given string slice. The view retains shared ownership of the underlying bytes. #### subscript Indexed Char / Sub-view ```kestrel public subscript[I](I) -> I.CharsYield { get } ``` Reads a single code point (`Char`) for `Int64` indexes, or a zero-copy `CharsView` sub-view for `Range[Int64]` / `ClosedRange[Int64]`. All access is O(n) because UTF-8 is variable-width. Panics on out-of-bounds. #### subscript Wrapping ```kestrel public subscript[I](wrapped: I) -> I.CharsWrappedYield { get } ``` Reads at `index` with modulo wrap-around. Negative indices wrap from the end: `view.chars(wrapped: -1)` reads the last char. Returns `None` on an empty view. #### field count ```kestrel public var count: Int64 { get } ``` #### field endIndex ```kestrel public var endIndex: CharIndex { get } ``` Char index at the end (one past the last byte). #### field first ```kestrel public var first: Char? { get } ``` The first code point, or `None` if the view is empty. #### function firstIndex ```kestrel public func firstIndex(of: Char) -> CharIndex? ``` Returns the index of the first occurrence of `c`, or `.None`. #### function firstIndex ```kestrel public func firstIndex(where: (Char) -> Bool) -> CharIndex? ``` Returns the index of the first code point matching `predicate`, or `.None`. #### function index ```kestrel public func index(at: Int64) -> CharIndex? ``` Resolves the n-th code point to its byte offset. O(n). #### function indexedIter ```kestrel public func indexedIter() -> IndexedCharsIterator ``` Returns an iterator yielding `(CharIndex, Char)` pairs. #### field isEmpty ```kestrel public var isEmpty: Bool { get } ``` `true` when the view spans zero bytes (no code points). O(1) — checks `byteCount`, not `count`. #### field last ```kestrel public var last: Char? { get } ``` The last code point, or `None` if the view is empty. #### function lastIndex ```kestrel public func lastIndex(of: Char) -> CharIndex? ``` Returns the index of the last occurrence of `c`, or `.None`. #### function lastIndex ```kestrel public func lastIndex(where: (Char) -> Bool) -> CharIndex? ``` Returns the index of the last code point matching `predicate`, or `.None`. #### field reversed ```kestrel public var reversed: ReversedCharsView { get } ``` A reversed view that iterates code points back-to-front. #### function slice ```kestrel public func slice(from: CharIndex, to: CharIndex) -> StringSlice ``` Returns a `StringSlice` covering `[start, end)` by byte offset. #### field startIndex ```kestrel public var startIndex: CharIndex { get } ``` Char index at byte 0 (the first code point). #### function substring ```kestrel public func substring[__opaque_0](__opaque_0) -> String where __opaque_0: CharsSubstringIndex ``` Convenience: dispatches to a `CharsSubstringIndex` to produce an owned `String` covering the requested code-point range. Equivalent to `self(range).toString()` for both `Range[Int64]` and `ClosedRange[Int64]`. #### function toString ```kestrel public func toString() -> String ``` Materializes the view as an owned `String`. O(n) — copies bytes. **Iterable** #### typealias Item ```kestrel type Item = Char ``` The element type yielded by iteration — always `Char`. #### typealias TargetIterator ```kestrel type TargetIterator = CharsIterator ``` The iterator type returned by `iter()`. #### function iter ```kestrel public func iter() -> CharsIterator ``` Returns a `CharsIterator` positioned at byte 0. Each call returns a fresh iterator; the view itself is reusable. **Cloneable** #### function clone ```kestrel public func clone() -> CharsView ``` ### struct DefaultStringInterpolation ```kestrel public struct DefaultStringInterpolation { /* private fields */ } ``` The default `Interpolatable` accumulator used for `String` interpolation. Stores each literal and each formatted interpolation as a separate `String` part, then concatenates them in `build()`. The two-pass design lets `build()` size the result buffer exactly, avoiding the repeated reallocation cost a single-buffer accumulator would pay. # Examples ``` var acc = DefaultStringInterpolation(literalCapacity: 7, interpolationCount: 1); acc.appendLiteral("hello, "); acc.appendInterpolation("world", options: FormatOptions.default()); acc.build(); // "hello, world" ``` # Representation A single `StringBuilder` that accumulates all literal and formatted bytes in one buffer. Pre-sized using the compiler's capacity hints. #### initializer With Capacity ```kestrel public init(literalCapacity: Int64, interpolationCount: Int64) ``` Constructs an empty accumulator pre-sized from compile-time hints. `literalCapacity` is the exact byte count of static segments; `interpolationCount` estimates ~16 bytes per hole. # Examples ``` var acc = DefaultStringInterpolation(literalCapacity: 0, interpolationCount: 0); acc.build(); // "" ``` #### function appendInterpolation ```kestrel public mutating func appendInterpolation[__opaque_0](__opaque_0, FormatOptions) where __opaque_0: Formattable ``` Formats one interpolation hole directly into the buffer. #### function build ```kestrel public mutating func build() -> String ``` Transfers the buffer into a `String` without copying. # Examples ``` var acc = DefaultStringInterpolation(literalCapacity: 0, interpolationCount: 0); acc.appendLiteral("a"); acc.appendLiteral("b"); acc.build(); // "ab" ``` **Interpolatable** #### initializer With Capacity ```kestrel init(literalCapacity: Int64, interpolationCount: Int64) ``` Constructs an empty accumulator with capacity hints derived from the literal at compile time. `literalCapacity` is the total byte count of the static segments; `interpolationCount` is the number of `\{...}` holes. Implementors can use these to preallocate. #### function appendLiteral ```kestrel public mutating func appendLiteral(String) ``` Appends a static literal segment directly into the buffer. **Cloneable** #### function clone ```kestrel public func clone() -> DefaultStringInterpolation ``` Returns a copy with a cloned builder buffer. ### protocol ExpressibleByStringInterpolation ```kestrel public protocol ExpressibleByStringInterpolation ``` Marker protocol for types constructible from a completed string interpolation. Refines `ExpressibleByStringLiteral` so a single conformance covers both pure-literal `"abc"` and interpolated `"a\{x}b"` forms. The compiler picks `Interpolation` as the accumulator type, drives it via `Interpolatable`, then hands it to `init(interpolation:)`. #### initializer From Interpolation ```kestrel init(Interpolation) ``` Constructs `Self` from a fully built interpolation accumulator. #### typealias Interpolation ```kestrel type Interpolation ``` The accumulator type used to build interpolated values of `Self`. **ExpressibleByStringLiteral** #### initializer String Literal ```kestrel init(stringLiteral: lang.ptr[lang.i8], lang.i64) ``` Builds an instance from a string literal. ### enum FloatStyle ```kestrel public enum FloatStyle ``` How a floating-point value should be rendered. Selected by the `:f` / `:e` / `:E` / `:%` type slots in the format mini-language and read by the `Float32` / `Float64` formatters. Choice of style is independent of `precision` — `Auto` honours precision as "max significant digits", `Fixed` and `Scientific` treat it as "decimal places". The non-`Auto` variants always emit a decimal point. # Examples ``` var opts = FormatOptions(); opts.precision = .Some(2); opts.floatStyle = .Fixed; (3.14159).format(options: opts); // "3.14" opts.floatStyle = .Scientific; (3.14159).format(options: opts); // "3.14e0" opts.floatStyle = .Percent; (0.5).format(options: opts); // "50.00%" ``` #### case Auto ```kestrel case Auto ``` Shortest round-trippable representation; switches to scientific for very large or very small magnitudes. #### case Fixed ```kestrel case Fixed ``` Fixed-point — `precision` controls decimal places. #### case Percent ```kestrel case Percent ``` Multiplies by 100 and appends `%`. #### case Scientific ```kestrel case Scientific ``` Scientific notation with lowercase `e` exponent marker. #### case ScientificUpper ```kestrel case ScientificUpper ``` Scientific notation with uppercase `E` exponent marker. **Equatable** #### typealias Output ```kestrel type Output = Bool ``` #### function equal ```kestrel public func equal(to: Self) -> Bool ``` Bridges `Equal.equal(to:)` to `Equatable.isEqual(to:)`. #### function isEqual ```kestrel public func isEqual(to: FloatStyle) -> Bool ``` Returns true if both cases are the same variant. All cases are payload-less, so equality is purely structural. # Examples ``` FloatStyle.Fixed.isEqual(to: .Fixed); // true FloatStyle.Fixed.isEqual(to: .Scientific); // false ``` #### function notEqual ```kestrel public func notEqual(to: Self) -> Bool ``` Default `!=`: delegates to `==` so there's a single source of truth. **Matchable** #### function matches ```kestrel public func matches(FloatStyle) -> Bool ``` Pattern-match form of equality — delegates to `isEqual`. # Examples ``` FloatStyle.Auto.matches(.Auto); // true ``` ### struct FormatOptions ```kestrel public struct FormatOptions { /* private fields */ } ``` Mutable bag of formatting knobs threaded through every `Formattable.format` call. `FormatOptions` is the parsed form of the format-spec mini-language. String interpolation `"\{expr:spec}"` constructs one of these from the trailing spec, then hands it to the formatter for `expr`'s type. Each formatter reads only the fields that apply to it: integers ignore `floatStyle`, strings ignore `radix`, and so on. # Format spec mini-language `[[fill]align][sign][#][0][width][.precision][type]` Where `type` is one of: - Integers: `b` (binary), `o` (octal), `x` (hex lower), `X` (hex upper) - Floats: `f` (fixed), `e` (scientific), `E` (scientific upper), `%` (percent) - Any: `?` (debug) # Examples ``` "\{n:>8}"; // right-align, width 8 "\{n:08x}"; // zero-pad, width 8, hex "\{n:#X}"; // hex upper with 0x prefix "\{pi:.2}"; // precision 2 decimal places "\{pi:.2e}"; // scientific with 2 decimal places "\{ratio:%}"; // as percentage (0.5 -> "50%") "\{name:^10}"; // center, width 10 "\{value:?}"; // debug format ``` # Representation A flat record of independent fields — no validation across them. Each formatter is responsible for ignoring fields outside its domain and applying its own defaults when an option is absent. #### initializer Default ```kestrel public init() ``` Creates a `FormatOptions` with every field at its default value. Defaults: no `width` or `precision`, left alignment, space fill, decimal radix, lowercase hex, negative-only sign, no alternate form, `Auto` float style, debug off. # Examples ``` var opts = FormatOptions(); opts.width = .Some(6); opts.alignment = .Right; "hi".format(options: opts); // " hi" ``` #### field alignment ```kestrel public var alignment: Alignment ``` How to position the value inside `width` when padding is required. #### field alternate ```kestrel public var alternate: Bool ``` Alternate form: emit the conventional radix prefix (`0b`, `0o`, `0x`/`0X`) for non-decimal integers. #### field debug ```kestrel public var debug: Bool ``` When `true`, formatters should produce a structural / debug representation rather than a user-facing one. #### function default ```kestrel public static func default() -> FormatOptions ``` Returns a fresh `FormatOptions` with all fields at their default values. Equivalent to calling `FormatOptions()`; provided as a static so callers that want defaults without spelling out the constructor (e.g. default-arg expressions) have a clean call site. # Examples ``` let opts = FormatOptions.default(); (42).format(options: opts); // "42" ``` #### field fill ```kestrel public var fill: Char ``` Padding character — defaults to `' '`. Only applies when `width` is set and the value is shorter. #### field floatStyle ```kestrel public var floatStyle: FloatStyle ``` Float rendering style (fixed, scientific, percent, auto). #### field precision ```kestrel public var precision: Int64? ``` For floats: number of decimal places (or significant digits in `Auto` mode). For strings: maximum character count. #### field radix ```kestrel public var radix: Int64 ``` Numeric base for integer formatting: 2 (binary), 8 (octal), 10 (decimal), 16 (hex). #### field sign ```kestrel public var sign: Sign ``` Sign-display strategy for numeric formatters. #### field uppercase ```kestrel public var uppercase: Bool ``` When `true`, integer hex digits are emitted as `A`–`F` rather than `a`–`f`. #### field width ```kestrel public var width: Int64? ``` Minimum field width in characters; shorter values are padded with `fill` according to `alignment`. **Equatable** #### typealias Output ```kestrel type Output = Bool ``` #### function equal ```kestrel public func equal(to: Self) -> Bool ``` Bridges `Equal.equal(to:)` to `Equatable.isEqual(to:)`. #### function isEqual ```kestrel public func isEqual(to: FormatOptions) -> Bool ``` Returns true if all fields are equal between the two options. `width` and `precision` are not compared — they typically reflect per-call overrides rather than logical identity. Compare them explicitly if needed. # Examples ``` let a = FormatOptions(); let b = FormatOptions(); a.isEqual(to: b); // true var c = FormatOptions(); c.alternate = true; a.isEqual(to: c); // false ``` #### function notEqual ```kestrel public func notEqual(to: Self) -> Bool ``` Default `!=`: delegates to `==` so there's a single source of truth. ### protocol Formattable ```kestrel public protocol Formattable ``` Protocol for types that can render themselves as a `String` under a `FormatOptions`. Print routines and string interpolation `"\{expr}"` and `"\{expr:spec}"` both ultimately bottom out in `format`. Implementors should honour every `FormatOptions` field that is meaningful for their domain (alignment and width are universal; `radix` only applies to integers, `floatStyle` only to floats) and silently ignore fields that aren't. # Examples ``` "\{name}"; // "Alice" (default formatting) "\{name:>10}"; // " Alice" (right-align, width 10) "\{n:08x}"; // "0000002a" (zero-pad, hex, width 8) "\{pi:.2}"; // "3.14" (precision 2) "\{value:?}"; // debug representation ``` #### function format ```kestrel func format(into: mutating StringBuilder, FormatOptions) ``` Writes this value's formatted representation directly into `writer`. This is the kernel method — all formatting ultimately bottoms out here. The convenience `format(options:) -> String` in the protocol extension calls this under the hood. #### function formatted ```kestrel public func formatted(FormatOptions) -> String ``` Returns this value rendered as a `String`. Convenience wrapper: creates a `StringBuilder`, calls `format(into:)`, and returns the built string. Uses a distinct name to avoid overload-resolution ambiguity with `format(into:)`. ### struct Grapheme ```kestrel public struct Grapheme { /* private fields */ } ``` An extended grapheme cluster — what users perceive as a single character. A grapheme may comprise one `Char` (e.g. `'a'`) or several (combining marks, regional-indicator country flags, ZWJ-joined emoji sequences). `String.graphemes` is the canonical producer; iteration uses UAX #29 segmentation. Treat `Grapheme` as the right unit for any user-visible operation (cursor movement, selection, truncation for display). # Examples ``` let g = Grapheme(char: 'a'); g.charCount(); // 1 g.isAscii; // true g.utf8Length(); // 1 ``` # Representation An `Array[Char]` of the constituent code points in scalar order. #### initializer From Chars ```kestrel public init(chars: Array[Char]) ``` Constructs a grapheme from a sequence of `Char`s. The caller is responsible for the chars actually forming a single UAX #29 cluster — the constructor does not segment or validate. `GraphemesIterator` is the canonical producer of valid clusters. Single-char input avoids allocating; multi-char input keeps the trailing code points in a separate array. # Examples ``` var chars = Array[Char](); chars.append('e'); chars.append('\u{0301}'); // combining acute let g = Grapheme(chars: chars); g.charCount(); // 2 ``` #### initializer Single Char ```kestrel public init(char: Char) ``` Constructs a one-`Char` grapheme. Allocation-free — the common path for ASCII iteration through `GraphemesView`. # Examples ``` let g = Grapheme(char: 'a'); g.charCount(); // 1 ``` #### function charCount ```kestrel public func charCount() -> Int64 ``` Returns the number of `Char`s in this cluster — `1` for plain ASCII, more for combining sequences and ZWJ-joined emoji. #### field chars ```kestrel public var chars: Array[Char] { get } ``` The constituent code points in scalar order. Materializes a fresh `Array[Char]` on every access. #### field firstChar ```kestrel public var firstChar: Char { get } ``` Returns the first `Char` of the cluster. The first code point of this grapheme cluster. #### field isAscii ```kestrel public var isAscii: Bool { get } ``` Returns true iff the cluster is exactly one ASCII `Char`. A single-`Char` non-ASCII grapheme (e.g. `é` as the precomposed `U+00E9`) returns `false`. Multi-`Char` clusters always return `false` even if every component is ASCII. #### function utf8Length ```kestrel public func utf8Length() -> Int64 ``` Returns the total UTF-8 byte length of all constituent `Char`s. Sum of each `Char.utf8Length()`. Use this to size a buffer before re-encoding the cluster. **Equatable** #### typealias Output ```kestrel type Output = Bool ``` #### function equal ```kestrel public func equal(to: Self) -> Bool ``` Bridges `Equal.equal(to:)` to `Equatable.isEqual(to:)`. #### function isEqual ```kestrel public func isEqual(to: Grapheme) -> Bool ``` Returns true if the two graphemes are the same length and every `Char` is equal pairwise. **Not** Unicode normalization-aware: precomposed `é` (`U+00E9`) and decomposed `e` + `U+0301` are not equal under this check even though they represent the same user-perceived character. Normalize both sides first if you need that. # Examples ``` let a = Grapheme(char: 'a'); let b = Grapheme(char: 'a'); a.isEqual(to: b); // true ``` #### function notEqual ```kestrel public func notEqual(to: Self) -> Bool ``` Default `!=`: delegates to `==` so there's a single source of truth. **Cloneable** #### function clone ```kestrel public func clone() -> Grapheme ``` Returns a deep copy of this grapheme. **Comparable** #### typealias Output ```kestrel type Output = Bool ``` #### function compare ```kestrel public func compare(Grapheme) -> Ordering ``` #### function greaterThan ```kestrel public func greaterThan(Self) -> Bool ``` `>` derived from `compare`. #### function greaterThanOrEqual ```kestrel public func greaterThanOrEqual(Self) -> Bool ``` `>=` derived from `compare`. #### function isAtLeast ```kestrel public func isAtLeast(Self) -> Bool ``` `start..` lower-bound check, derived from `compare`. #### function isAtMost ```kestrel public func isAtMost(Self) -> Bool ``` `..=end` upper-bound check, derived from `compare`. #### function isBelow ```kestrel public func isBelow(Self) -> Bool ``` `.. Bool ``` `<` derived from `compare`. #### function lessThanOrEqual ```kestrel public func lessThanOrEqual(Self) -> Bool ``` `<=` derived from `compare`. **Hashable** #### function hash ```kestrel public func hash[H](into: mutating H) where H: Hasher ``` **Formattable** #### function format ```kestrel public func format(into: mutating StringBuilder, FormatOptions) ``` #### function formatted ```kestrel public func formatted(FormatOptions) -> String ``` Returns this value rendered as a `String`. Convenience wrapper: creates a `StringBuilder`, calls `format(into:)`, and returns the built string. Uses a distinct name to avoid overload-resolution ambiguity with `format(into:)`. ### struct GraphemeIndex ```kestrel public struct GraphemeIndex { /* private fields */ } ``` A typed wrapper for a grapheme-cluster position within a `String`. Like `CharIndex` but ranges over UAX #29 clusters rather than code points. Stores the byte offset of the cluster's first byte; resolving requires walking the segmenter. # Representation A single `Int64` field holding the byte offset of the grapheme. #### initializer From Offset ```kestrel public init(Int64) ``` Wraps a pre-resolved byte offset for a grapheme position. #### function advance ```kestrel public func advance(by: Int64, from: StringSlice) -> GraphemeIndex ``` Advances by `n` grapheme clusters. Requires the source slice to run the UAX #29 segmenter forward. O(n) in graphemes advanced. # Examples ``` let s = "héllo"; let idx = s.graphemes.startIndex; // byte 0 let next = idx.advance(by: 2, from: s.asSlice()); // Skipped 'h' (1 byte) and 'é' (2 bytes) → byte 3 ``` #### field byteOffset ```kestrel public var byteOffset: Int64 ``` The byte offset where the indexed grapheme begins. **Equatable** #### typealias Output ```kestrel type Output = Bool ``` #### function equal ```kestrel public func equal(to: Self) -> Bool ``` Bridges `Equal.equal(to:)` to `Equatable.isEqual(to:)`. #### function isEqual ```kestrel public func isEqual(to: GraphemeIndex) -> Bool ``` Returns true if the two indices point at the same byte offset. #### function notEqual ```kestrel public func notEqual(to: Self) -> Bool ``` Default `!=`: delegates to `==` so there's a single source of truth. **Comparable** #### typealias Output ```kestrel type Output = Bool ``` #### function compare ```kestrel public func compare(GraphemeIndex) -> Ordering ``` #### function greaterThan ```kestrel public func greaterThan(Self) -> Bool ``` `>` derived from `compare`. #### function greaterThanOrEqual ```kestrel public func greaterThanOrEqual(Self) -> Bool ``` `>=` derived from `compare`. #### function isAtLeast ```kestrel public func isAtLeast(Self) -> Bool ``` `start..` lower-bound check, derived from `compare`. #### function isAtMost ```kestrel public func isAtMost(Self) -> Bool ``` `..=end` upper-bound check, derived from `compare`. #### function isBelow ```kestrel public func isBelow(Self) -> Bool ``` `.. Bool ``` `<` derived from `compare`. #### function lessThanOrEqual ```kestrel public func lessThanOrEqual(Self) -> Bool ``` `<=` derived from `compare`. ### struct GraphemesIterator ```kestrel public struct GraphemesIterator { /* private fields */ } ``` Iterator over extended grapheme clusters under UAX #29 segmentation. Wraps a `CharsIterator` and consults the Unicode grapheme-break property tables on each step. Buffers one look-ahead `Char` so it can decide whether the next code point starts a new cluster; that pending char is yielded as the start of the *next* cluster on the following call. Handles ZWJ-joined sequences and regional-indicator flag pairs. # Examples ``` var it = "a\u{0301}b".graphemes.iter(); it.next(); // Some(Grapheme: ['a', U+0301]) it.next(); // Some(Grapheme: ['b']) it.next(); // None ``` # Representation Wraps a `CharsIterator` plus a small amount of state machine: the pending look-ahead char, the previous break property, the "previous-previous was Regional Indicator" flag (for flag pairs), and a `started` marker. #### initializer From Chars ```kestrel public init(CharsIterator) ``` Wraps a `CharsIterator` to produce graphemes via UAX #29 segmentation. Prefer `someString.graphemes.iter()` over calling this directly. **Iterator** #### typealias Item ```kestrel type Item = Grapheme ``` The element type yielded by `next()` — always `Grapheme`. #### typealias TargetIterator ```kestrel type TargetIterator = Self ``` #### function all ```kestrel 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) ``` #### function any ```kestrel 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 ``` #### function chain ```kestrel 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] ``` #### function collect ```kestrel 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] ``` #### function compactMap ```kestrel public func compactMap[T]() -> FilterMapIterator[Self, T] where Item == Optional[T] ``` Drops `None`s and unwraps `Some`s — 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] ``` #### function contains ```kestrel 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 ``` #### function count ```kestrel 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 ``` #### function cycle ```kestrel 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] ``` #### function enumerate ```kestrel 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}") }; ``` #### function filter ```kestrel public func filter(where: (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] ``` #### function filterMap ```kestrel public func filterMap[U](as: (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] ``` #### function first ```kestrel 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 ``` #### function firstIndex ```kestrel 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 ``` #### function flatMap ```kestrel public func flatMap[U](as: (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] ``` #### function flatten ```kestrel 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] ``` #### function fold ```kestrel 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 ``` #### function forEach ```kestrel 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) }; ``` #### function fuse ```kestrel 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. #### function inspect ```kestrel public func inspect((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(); ``` #### function intersperse ```kestrel 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] ``` #### function intersperseWith ```kestrel public func intersperseWith(with: () -> 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] ``` #### function isSorted ```kestrel 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) ``` #### function isSortedDescending ```kestrel public consuming func isSortedDescending() -> Bool ``` True if elements come out in descending order. Mirror of `isSorted`. #### function iter ```kestrel func iter() -> Self ``` Returns `self`. The blanket conformance pivot — iterators *are* iterables. #### function last ```kestrel 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. #### function map ```kestrel public func map[U](as: (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] ``` #### function max ```kestrel public consuming func max() -> Item? ``` Largest element, or `None` for an empty iterator. Ties go to the first occurrence. #### function min ```kestrel 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 ``` #### function next ```kestrel public mutating func next() -> Grapheme? ``` Returns the next grapheme cluster, or `None` when the source is exhausted. Accumulates code points until `shouldBreakBetween` reports a boundary, then returns them as a `Grapheme`. The look-ahead char that triggered the break is held back for the next call. #### function nth ```kestrel 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) ``` #### function peekable ```kestrel 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) ``` #### function product ```kestrel 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 ``` #### function reduce ```kestrel 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 ``` #### function scan ```kestrel public func scan[Acc](from: Acc, by: (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] ``` #### function skip ```kestrel 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(); // [] ``` #### function skipWhile ```kestrel public func skipWhile(where: (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] ``` #### function sorted ```kestrel 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] ``` #### function stepBy ```kestrel 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] ``` #### function sum ```kestrel 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 ``` #### function take ```kestrel 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] ``` #### function takeWhile ```kestrel public func takeWhile(where: (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] ``` #### function tryFold ```kestrel 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") ``` #### function tryForEach ```kestrel public mutating func tryForEach[E]((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 ``` #### function unzip ```kestrel 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"] ``` #### function zip ```kestrel 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)] ``` ### protocol GraphemesSubstringIndex ```kestrel public protocol GraphemesSubstringIndex ``` Range-only index for `GraphemesView.substring`. See `BytesSubstringIndex`. #### function readGraphemesSubstring ```kestrel func readGraphemesSubstring(from: GraphemesView) -> String ``` ### struct GraphemesView ```kestrel public struct GraphemesView { /* private fields */ } ``` A view over the user-perceived characters (extended grapheme clusters) of a `String`. Returned by `String.graphemes`. Use this — not `chars` — when you need the unit a user thinks of as a single character: emoji sequences, accented forms, country flags, etc. Both iteration and `count()` are O(n) because each cluster requires consulting the UAX #29 break tables. # Examples ``` let flag = "\u{1F1FA}\u{1F1F8}"; // 🇺🇸 flag.chars.count; // 2 (regional indicators) flag.graphemes.count; // 1 (one flag) ``` # Representation A `(ptr, length)` pair; iteration is delegated to a wrapped `CharsIterator` plus the UAX #29 segmenter state machine. #### subscript Checked Index ```kestrel public subscript[I](checked: I) -> I.GraphemesYield? { get } ``` Reads at `index`, returning `.None` on out-of-bounds. #### subscript Clamping ```kestrel public subscript[I](clamped: I) -> I.GraphemesClampedYield { get } ``` Reads at `index` saturated to `[0, count)`. Single-grapheme indexes yield `Grapheme?` (`.None` only when the view is empty); range indexes yield `GraphemesView` (always valid, possibly empty). #### initializer From Slice ```kestrel public init(slice: StringSlice) ``` Constructs a graphemes view backed by the given string slice. The view retains shared ownership of the underlying bytes. #### subscript Indexed Grapheme / Sub-view ```kestrel public subscript[I](I) -> I.GraphemesYield { get } ``` `Int64` reads a single cluster; `Range[Int64]` / `ClosedRange[Int64]` yield a zero-copy `GraphemesView` sub-view covering those clusters. **O(n)** — walks the segmenter from the start. Panics on out-of-bounds. #### subscript Wrapping ```kestrel public subscript[I](wrapped: I) -> I.GraphemesWrappedYield { get } ``` Reads at `index` with modulo wrap-around. Negative indices wrap from the end: `view.graphemes(wrapped: -1)` reads the last grapheme cluster. Returns `None` on an empty view. #### field count ```kestrel public var count: Int64 { get } ``` Number of grapheme clusters. **O(n)** — walks the entire string through the UAX #29 segmenter. Cache the result if you need it more than once; each access re-walks the string. #### field endIndex ```kestrel public var endIndex: GraphemeIndex { get } ``` Grapheme index at the end (one past the last byte). #### field first ```kestrel public var first: Grapheme? { get } ``` The first grapheme cluster, or `None` if the view is empty. O(1) in practice — decodes one cluster from the start. #### function firstIndex ```kestrel public func firstIndex(where: (Grapheme) -> Bool) -> GraphemeIndex? ``` Returns the index of the first grapheme matching `predicate`, or `.None`. #### function index ```kestrel public func index(at: Int64) -> GraphemeIndex? ``` Resolves the n-th grapheme cluster to its byte offset. O(n) — walks the segmenter from the start. #### function indexedIter ```kestrel public func indexedIter() -> IndexedGraphemesIterator ``` Returns an iterator yielding `(GraphemeIndex, Grapheme)` pairs. #### field isEmpty ```kestrel public var isEmpty: Bool { get } ``` `true` when the view spans zero bytes (no graphemes). O(1) — checks `byteCount`, not `count`. #### field last ```kestrel public var last: Grapheme? { get } ``` The last grapheme cluster, or `None` if the view is empty. O(n) — walks the entire string through the segmenter. #### function slice ```kestrel public func slice(from: GraphemeIndex, to: GraphemeIndex) -> StringSlice ``` Returns a `StringSlice` covering `[start, end)` by byte offset. #### field startIndex ```kestrel public var startIndex: GraphemeIndex { get } ``` Grapheme index at byte 0. #### function substring ```kestrel public func substring[__opaque_0](__opaque_0) -> String where __opaque_0: GraphemesSubstringIndex ``` Convenience: dispatches to a `GraphemesSubstringIndex` to produce an owned `String` covering the requested cluster range. Equivalent to `self(range).toString()` for both `Range[Int64]` and `ClosedRange[Int64]`. #### function toString ```kestrel public func toString() -> String ``` Materializes the view as an owned `String`. O(n) — copies bytes. **Iterable** #### typealias Item ```kestrel type Item = Grapheme ``` The element type yielded by iteration — always `Grapheme`. #### typealias TargetIterator ```kestrel type TargetIterator = GraphemesIterator ``` The iterator type returned by `iter()`. #### function iter ```kestrel public func iter() -> GraphemesIterator ``` Returns a `GraphemesIterator` positioned at byte 0. **Cloneable** #### function clone ```kestrel public func clone() -> GraphemesView ``` ### struct IndexedCharsIterator ```kestrel public struct IndexedCharsIterator { /* private fields */ } ``` Iterator yielding `(CharIndex, Char)` pairs — the byte offset of each code point alongside the decoded character. Useful when you need to know where each char starts in the buffer. #### initializer init ```kestrel public init(ptr: lang.ptr[lang.i8], length: Int64) ``` **Iterator** #### typealias Item ```kestrel type Item = (CharIndex, Char) ``` #### typealias TargetIterator ```kestrel type TargetIterator = Self ``` #### function all ```kestrel 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) ``` #### function any ```kestrel 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 ``` #### function chain ```kestrel 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] ``` #### function collect ```kestrel 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] ``` #### function compactMap ```kestrel public func compactMap[T]() -> FilterMapIterator[Self, T] where Item == Optional[T] ``` Drops `None`s and unwraps `Some`s — 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] ``` #### function contains ```kestrel 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 ``` #### function count ```kestrel 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 ``` #### function cycle ```kestrel 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] ``` #### function enumerate ```kestrel 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}") }; ``` #### function filter ```kestrel public func filter(where: (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] ``` #### function filterMap ```kestrel public func filterMap[U](as: (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] ``` #### function first ```kestrel 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 ``` #### function firstIndex ```kestrel 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 ``` #### function flatMap ```kestrel public func flatMap[U](as: (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] ``` #### function flatten ```kestrel 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] ``` #### function fold ```kestrel 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 ``` #### function forEach ```kestrel 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) }; ``` #### function fuse ```kestrel 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. #### function inspect ```kestrel public func inspect((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(); ``` #### function intersperse ```kestrel 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] ``` #### function intersperseWith ```kestrel public func intersperseWith(with: () -> 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] ``` #### function isSorted ```kestrel 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) ``` #### function isSortedDescending ```kestrel public consuming func isSortedDescending() -> Bool ``` True if elements come out in descending order. Mirror of `isSorted`. #### function iter ```kestrel func iter() -> Self ``` Returns `self`. The blanket conformance pivot — iterators *are* iterables. #### function last ```kestrel 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. #### function map ```kestrel public func map[U](as: (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] ``` #### function max ```kestrel public consuming func max() -> Item? ``` Largest element, or `None` for an empty iterator. Ties go to the first occurrence. #### function min ```kestrel 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 ``` #### function next ```kestrel public mutating func next() -> (CharIndex, Char)? ``` #### function nth ```kestrel 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) ``` #### function peekable ```kestrel 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) ``` #### function product ```kestrel 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 ``` #### function reduce ```kestrel 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 ``` #### function scan ```kestrel public func scan[Acc](from: Acc, by: (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] ``` #### function skip ```kestrel 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(); // [] ``` #### function skipWhile ```kestrel public func skipWhile(where: (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] ``` #### function sorted ```kestrel 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] ``` #### function stepBy ```kestrel 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] ``` #### function sum ```kestrel 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 ``` #### function take ```kestrel 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] ``` #### function takeWhile ```kestrel public func takeWhile(where: (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] ``` #### function tryFold ```kestrel 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") ``` #### function tryForEach ```kestrel public mutating func tryForEach[E]((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 ``` #### function unzip ```kestrel 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"] ``` #### function zip ```kestrel 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)] ``` ### struct IndexedGraphemesIterator ```kestrel public struct IndexedGraphemesIterator { /* private fields */ } ``` Iterator yielding `(GraphemeIndex, Grapheme)` pairs — the byte offset of each grapheme cluster alongside the grapheme value. #### initializer init ```kestrel public init(inner: GraphemesIterator) ``` **Iterator** #### typealias Item ```kestrel type Item = (GraphemeIndex, Grapheme) ``` #### typealias TargetIterator ```kestrel type TargetIterator = Self ``` #### function all ```kestrel 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) ``` #### function any ```kestrel 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 ``` #### function chain ```kestrel 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] ``` #### function collect ```kestrel 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] ``` #### function compactMap ```kestrel public func compactMap[T]() -> FilterMapIterator[Self, T] where Item == Optional[T] ``` Drops `None`s and unwraps `Some`s — 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] ``` #### function contains ```kestrel 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 ``` #### function count ```kestrel 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 ``` #### function cycle ```kestrel 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] ``` #### function enumerate ```kestrel 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}") }; ``` #### function filter ```kestrel public func filter(where: (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] ``` #### function filterMap ```kestrel public func filterMap[U](as: (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] ``` #### function first ```kestrel 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 ``` #### function firstIndex ```kestrel 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 ``` #### function flatMap ```kestrel public func flatMap[U](as: (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] ``` #### function flatten ```kestrel 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] ``` #### function fold ```kestrel 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 ``` #### function forEach ```kestrel 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) }; ``` #### function fuse ```kestrel 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. #### function inspect ```kestrel public func inspect((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(); ``` #### function intersperse ```kestrel 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] ``` #### function intersperseWith ```kestrel public func intersperseWith(with: () -> 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] ``` #### function isSorted ```kestrel 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) ``` #### function isSortedDescending ```kestrel public consuming func isSortedDescending() -> Bool ``` True if elements come out in descending order. Mirror of `isSorted`. #### function iter ```kestrel func iter() -> Self ``` Returns `self`. The blanket conformance pivot — iterators *are* iterables. #### function last ```kestrel 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. #### function map ```kestrel public func map[U](as: (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] ``` #### function max ```kestrel public consuming func max() -> Item? ``` Largest element, or `None` for an empty iterator. Ties go to the first occurrence. #### function min ```kestrel 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 ``` #### function next ```kestrel public mutating func next() -> (GraphemeIndex, Grapheme)? ``` #### function nth ```kestrel 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) ``` #### function peekable ```kestrel 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) ``` #### function product ```kestrel 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 ``` #### function reduce ```kestrel 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 ``` #### function scan ```kestrel public func scan[Acc](from: Acc, by: (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] ``` #### function skip ```kestrel 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(); // [] ``` #### function skipWhile ```kestrel public func skipWhile(where: (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] ``` #### function sorted ```kestrel 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] ``` #### function stepBy ```kestrel 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] ``` #### function sum ```kestrel 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 ``` #### function take ```kestrel 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] ``` #### function takeWhile ```kestrel public func takeWhile(where: (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] ``` #### function tryFold ```kestrel 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") ``` #### function tryForEach ```kestrel public mutating func tryForEach[E]((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 ``` #### function unzip ```kestrel 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"] ``` #### function zip ```kestrel 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)] ``` ### struct IndexedLinesIterator ```kestrel public struct IndexedLinesIterator { /* private fields */ } ``` Iterator yielding `(LineIndex, String)` pairs — the byte offset of each line's start alongside the line content (without terminator). #### initializer init ```kestrel public init(ptr: lang.ptr[lang.i8], length: Int64) ``` **Iterator** #### typealias Item ```kestrel type Item = (LineIndex, String) ``` #### typealias TargetIterator ```kestrel type TargetIterator = Self ``` #### function all ```kestrel 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) ``` #### function any ```kestrel 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 ``` #### function chain ```kestrel 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] ``` #### function collect ```kestrel 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] ``` #### function compactMap ```kestrel public func compactMap[T]() -> FilterMapIterator[Self, T] where Item == Optional[T] ``` Drops `None`s and unwraps `Some`s — 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] ``` #### function contains ```kestrel 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 ``` #### function count ```kestrel 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 ``` #### function cycle ```kestrel 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] ``` #### function enumerate ```kestrel 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}") }; ``` #### function filter ```kestrel public func filter(where: (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] ``` #### function filterMap ```kestrel public func filterMap[U](as: (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] ``` #### function first ```kestrel 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 ``` #### function firstIndex ```kestrel 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 ``` #### function flatMap ```kestrel public func flatMap[U](as: (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] ``` #### function flatten ```kestrel 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] ``` #### function fold ```kestrel 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 ``` #### function forEach ```kestrel 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) }; ``` #### function fuse ```kestrel 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. #### function inspect ```kestrel public func inspect((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(); ``` #### function intersperse ```kestrel 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] ``` #### function intersperseWith ```kestrel public func intersperseWith(with: () -> 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] ``` #### function isSorted ```kestrel 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) ``` #### function isSortedDescending ```kestrel public consuming func isSortedDescending() -> Bool ``` True if elements come out in descending order. Mirror of `isSorted`. #### function iter ```kestrel func iter() -> Self ``` Returns `self`. The blanket conformance pivot — iterators *are* iterables. #### function last ```kestrel 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. #### function map ```kestrel public func map[U](as: (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] ``` #### function max ```kestrel public consuming func max() -> Item? ``` Largest element, or `None` for an empty iterator. Ties go to the first occurrence. #### function min ```kestrel 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 ``` #### function next ```kestrel public mutating func next() -> (LineIndex, String)? ``` #### function nth ```kestrel 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) ``` #### function peekable ```kestrel 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) ``` #### function product ```kestrel 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 ``` #### function reduce ```kestrel 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 ``` #### function scan ```kestrel public func scan[Acc](from: Acc, by: (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] ``` #### function skip ```kestrel 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(); // [] ``` #### function skipWhile ```kestrel public func skipWhile(where: (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] ``` #### function sorted ```kestrel 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] ``` #### function stepBy ```kestrel 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] ``` #### function sum ```kestrel 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 ``` #### function take ```kestrel 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] ``` #### function takeWhile ```kestrel public func takeWhile(where: (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] ``` #### function tryFold ```kestrel 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") ``` #### function tryForEach ```kestrel public mutating func tryForEach[E]((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 ``` #### function unzip ```kestrel 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"] ``` #### function zip ```kestrel 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)] ``` ### protocol Interpolatable ```kestrel public protocol Interpolatable ``` Protocol for the accumulator type that string interpolation builds into. The compiler lowers `"hello, \{name}!"` to a sequence of `appendLiteral` and `appendInterpolation` calls on a fresh value of the implementor's type, then reads the final string out (typically via a `build()` method on the concrete accumulator). `String` ships `DefaultStringInterpolation` as its accumulator; custom string-like types can supply their own to intercept literal pieces or coerce formatted parts. #### initializer With Capacity ```kestrel init(literalCapacity: Int64, interpolationCount: Int64) ``` Constructs an empty accumulator with capacity hints derived from the literal at compile time. `literalCapacity` is the total byte count of the static segments; `interpolationCount` is the number of `\{...}` holes. Implementors can use these to preallocate. #### function appendLiteral ```kestrel mutating func appendLiteral(String) ``` Appends a static literal segment. Called once per run of literal text between `\{...}` holes. May be called with the empty string; implementors should be cheap in that case. ### struct LineIndex ```kestrel public struct LineIndex { /* private fields */ } ``` A typed wrapper for a line position within a string. Stores the byte offset of the line's first byte. #### function advance ```kestrel public func advance(by: Int64, from: StringSlice) -> LineIndex ``` Advances by `n` lines. Scans for line terminators (`\n`, `\r\n`, `\r`) from the current byte offset. O(n) in lines advanced. # Examples ``` let s = "a\nb\nc"; let idx = s.lines.startIndex; // byte 0 let second = idx.advance(by: 1, from: s.asSlice()); // second.byteOffset == 2 (past "a\n") ``` #### field byteOffset ```kestrel public var byteOffset: Int64 ``` #### initializer init ```kestrel public init(Int64) ``` **Equatable** #### typealias Output ```kestrel type Output = Bool ``` #### function equal ```kestrel public func equal(to: Self) -> Bool ``` Bridges `Equal.equal(to:)` to `Equatable.isEqual(to:)`. #### function isEqual ```kestrel public func isEqual(to: LineIndex) -> Bool ``` #### function notEqual ```kestrel public func notEqual(to: Self) -> Bool ``` Default `!=`: delegates to `==` so there's a single source of truth. **Comparable** #### typealias Output ```kestrel type Output = Bool ``` #### function compare ```kestrel public func compare(LineIndex) -> Ordering ``` #### function greaterThan ```kestrel public func greaterThan(Self) -> Bool ``` `>` derived from `compare`. #### function greaterThanOrEqual ```kestrel public func greaterThanOrEqual(Self) -> Bool ``` `>=` derived from `compare`. #### function isAtLeast ```kestrel public func isAtLeast(Self) -> Bool ``` `start..` lower-bound check, derived from `compare`. #### function isAtMost ```kestrel public func isAtMost(Self) -> Bool ``` `..=end` upper-bound check, derived from `compare`. #### function isBelow ```kestrel public func isBelow(Self) -> Bool ``` `.. Bool ``` `<` derived from `compare`. #### function lessThanOrEqual ```kestrel public func lessThanOrEqual(Self) -> Bool ``` `<=` derived from `compare`. ### struct LinesIterator ```kestrel public struct LinesIterator { /* private fields */ } ``` Iterator that yields each line of a string as a `String`. Recognises both `\n` (LF) and `\r\n` (CRLF) as line terminators and a lone `\r` (CR) as a terminator on its own. The terminator itself is **not** included in the yielded line. A trailing line without a terminator is still emitted; an empty input emits no lines. # Examples ``` var it = "a\nb\r\nc".lines.iter(); it.next(); // Some("a") it.next(); // Some("b") it.next(); // Some("c") it.next(); // None ``` # Representation A `(ptr, length, byteIndex, done)` quadruple. `done` flips to true after the trailing-no-terminator case has been emitted, so further calls return `None`. #### initializer From Pointer ```kestrel public init(ptr: lang.ptr[lang.i8], length: Int64, byteIndex: Int64, done: Bool) ``` Constructs a lines iterator from a raw pointer, total byte count, starting byte offset, and `done` flag. Prefer `someString.lines.iter()` over calling this directly. # Safety `ptr` must point to `length` valid UTF-8 bytes; `byteIndex` must be `0` or sit at a UTF-8 boundary. **Iterator** #### typealias Item ```kestrel type Item = String ``` The element type yielded by `next()` — always `String`. #### typealias TargetIterator ```kestrel type TargetIterator = Self ``` #### function all ```kestrel 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) ``` #### function any ```kestrel 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 ``` #### function chain ```kestrel 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] ``` #### function collect ```kestrel 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] ``` #### function compactMap ```kestrel public func compactMap[T]() -> FilterMapIterator[Self, T] where Item == Optional[T] ``` Drops `None`s and unwraps `Some`s — 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] ``` #### function contains ```kestrel 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 ``` #### function count ```kestrel 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 ``` #### function cycle ```kestrel 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] ``` #### function enumerate ```kestrel 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}") }; ``` #### function filter ```kestrel public func filter(where: (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] ``` #### function filterMap ```kestrel public func filterMap[U](as: (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] ``` #### function first ```kestrel 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 ``` #### function firstIndex ```kestrel 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 ``` #### function flatMap ```kestrel public func flatMap[U](as: (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] ``` #### function flatten ```kestrel 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] ``` #### function fold ```kestrel 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 ``` #### function forEach ```kestrel 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) }; ``` #### function fuse ```kestrel 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. #### function inspect ```kestrel public func inspect((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(); ``` #### function intersperse ```kestrel 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] ``` #### function intersperseWith ```kestrel public func intersperseWith(with: () -> 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] ``` #### function isSorted ```kestrel 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) ``` #### function isSortedDescending ```kestrel public consuming func isSortedDescending() -> Bool ``` True if elements come out in descending order. Mirror of `isSorted`. #### function iter ```kestrel func iter() -> Self ``` Returns `self`. The blanket conformance pivot — iterators *are* iterables. #### function last ```kestrel 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. #### function map ```kestrel public func map[U](as: (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] ``` #### function max ```kestrel public consuming func max() -> Item? ``` Largest element, or `None` for an empty iterator. Ties go to the first occurrence. #### function min ```kestrel 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 ``` #### function next ```kestrel public mutating func next() -> String? ``` Returns the next line, or `None` once exhausted. Scans byte-by-byte for `\n` or `\r`, treating `\r\n` as a single terminator. The yielded string contains the bytes up to but not including the terminator. #### function nth ```kestrel 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) ``` #### function peekable ```kestrel 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) ``` #### function product ```kestrel 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 ``` #### function reduce ```kestrel 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 ``` #### function scan ```kestrel public func scan[Acc](from: Acc, by: (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] ``` #### function skip ```kestrel 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(); // [] ``` #### function skipWhile ```kestrel public func skipWhile(where: (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] ``` #### function sorted ```kestrel 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] ``` #### function stepBy ```kestrel 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] ``` #### function sum ```kestrel 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 ``` #### function take ```kestrel 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] ``` #### function takeWhile ```kestrel public func takeWhile(where: (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] ``` #### function tryFold ```kestrel 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") ``` #### function tryForEach ```kestrel public mutating func tryForEach[E]((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 ``` #### function unzip ```kestrel 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"] ``` #### function zip ```kestrel 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)] ``` ### protocol LinesSubstringIndex ```kestrel public protocol LinesSubstringIndex ``` Range-only index for `LinesView.substring`. See `BytesSubstringIndex`. #### function readLinesSubstring ```kestrel func readLinesSubstring(from: LinesView) -> String ``` ### struct LinesView ```kestrel public struct LinesView { /* private fields */ } ``` A view over the lines of a `String`, split on `\n`, `\r\n`, or `\r`. Returned by `String.lines`. The yielded strings (from iteration or single-line subscripting) do not include the terminator; a trailing line without a terminator is still emitted. Range subscripts (`lines(0.. I.LinesYield? { get } ``` Reads at `index`, returning `.None` on out-of-bounds. #### subscript Clamping ```kestrel public subscript[I](clamped: I) -> I.LinesClampedYield { get } ``` Reads at `index` saturated to `[0, count)`. Single-line indexes yield `String?` (`.None` only when the view holds no lines); range indexes yield `LinesView` (always valid, possibly empty). #### initializer From Slice ```kestrel public init(slice: StringSlice) ``` Constructs a lines view backed by the given string slice. The view retains shared ownership of the underlying bytes. #### subscript Indexed Line / Sub-view ```kestrel public subscript[I](I) -> I.LinesYield { get } ``` `Int64` reads a single line as a `String` (without terminator). `Range[Int64]` / `ClosedRange[Int64]` yield a zero-copy `LinesView` sub-view covering those lines (terminators preserved in the underlying bytes). **O(n)** — walks the buffer from the start. Panics on out-of-bounds. #### subscript Wrapping ```kestrel public subscript[I](wrapped: I) -> I.LinesWrappedYield { get } ``` Reads at `index` with modulo wrap-around. Negative indices wrap from the end: `view.lines(wrapped: -1)` reads the last line. Returns `None` on an empty view. #### field count ```kestrel public var count: Int64 { get } ``` Number of lines in the view. **O(n)** — walks the buffer scanning for terminators. Cache the result if you need it more than once. #### field endIndex ```kestrel public var endIndex: LineIndex { get } ``` Line index at the end (one past the last byte). #### field first ```kestrel public var first: String? { get } ``` The first line (without terminator), or `None` if the view is empty. O(first line length) — scans for the first terminator. #### function index ```kestrel public func index(at: Int64) -> LineIndex? ``` Resolves the n-th line to its byte offset. O(n) — scans for line terminators from the start. #### function indexedIter ```kestrel public func indexedIter() -> IndexedLinesIterator ``` Returns an iterator yielding `(LineIndex, String)` pairs. #### field isEmpty ```kestrel public var isEmpty: Bool { get } ``` `true` when the view spans zero bytes (no lines). O(1) — checks `byteCount`, not `count`. #### function slice ```kestrel public func slice(from: LineIndex, to: LineIndex) -> StringSlice ``` Returns a `StringSlice` covering `[start, end)` by byte offset. #### field startIndex ```kestrel public var startIndex: LineIndex { get } ``` Line index at byte 0. #### function substring ```kestrel public func substring[__opaque_0](__opaque_0) -> String where __opaque_0: LinesSubstringIndex ``` Convenience: dispatches to a `LinesSubstringIndex` to produce an owned `String` covering the requested line range, with their original terminators preserved. Equivalent to `self(range).toString()` for both `Range[Int64]` and `ClosedRange[Int64]`. #### function toString ```kestrel public func toString() -> String ``` Materializes the view as an owned `String` covering the entire underlying buffer (terminators included). O(n) — copies bytes. **Iterable** #### typealias Item ```kestrel type Item = String ``` The element type yielded by iteration — always `String`. #### typealias TargetIterator ```kestrel type TargetIterator = LinesIterator ``` The iterator type returned by `iter()`. #### function iter ```kestrel public func iter() -> LinesIterator ``` Returns a `LinesIterator` positioned at byte 0. **Cloneable** #### function clone ```kestrel public func clone() -> LinesView ``` ### struct ReversedCharsIterator ```kestrel public struct ReversedCharsIterator { /* private fields */ } ``` Iterator that yields code points back-to-front by walking backward through UTF-8 continuation bytes to find each leading byte, then decoding forward. #### initializer init ```kestrel public init(ptr: lang.ptr[lang.i8], length: Int64) ``` **Iterator** #### typealias Item ```kestrel type Item = Char ``` #### typealias TargetIterator ```kestrel type TargetIterator = Self ``` #### function all ```kestrel 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) ``` #### function any ```kestrel 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 ``` #### function chain ```kestrel 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] ``` #### function collect ```kestrel 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] ``` #### function compactMap ```kestrel public func compactMap[T]() -> FilterMapIterator[Self, T] where Item == Optional[T] ``` Drops `None`s and unwraps `Some`s — 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] ``` #### function contains ```kestrel 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 ``` #### function count ```kestrel 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 ``` #### function cycle ```kestrel 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] ``` #### function enumerate ```kestrel 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}") }; ``` #### function filter ```kestrel public func filter(where: (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] ``` #### function filterMap ```kestrel public func filterMap[U](as: (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] ``` #### function first ```kestrel 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 ``` #### function firstIndex ```kestrel 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 ``` #### function flatMap ```kestrel public func flatMap[U](as: (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] ``` #### function flatten ```kestrel 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] ``` #### function fold ```kestrel 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 ``` #### function forEach ```kestrel 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) }; ``` #### function fuse ```kestrel 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. #### function inspect ```kestrel public func inspect((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(); ``` #### function intersperse ```kestrel 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] ``` #### function intersperseWith ```kestrel public func intersperseWith(with: () -> 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] ``` #### function isSorted ```kestrel 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) ``` #### function isSortedDescending ```kestrel public consuming func isSortedDescending() -> Bool ``` True if elements come out in descending order. Mirror of `isSorted`. #### function iter ```kestrel func iter() -> Self ``` Returns `self`. The blanket conformance pivot — iterators *are* iterables. #### function last ```kestrel 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. #### function map ```kestrel public func map[U](as: (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] ``` #### function max ```kestrel public consuming func max() -> Item? ``` Largest element, or `None` for an empty iterator. Ties go to the first occurrence. #### function min ```kestrel 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 ``` #### function next ```kestrel public mutating func next() -> Char? ``` #### function nth ```kestrel 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) ``` #### function peekable ```kestrel 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) ``` #### function product ```kestrel 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 ``` #### function reduce ```kestrel 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 ``` #### function scan ```kestrel public func scan[Acc](from: Acc, by: (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] ``` #### function skip ```kestrel 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(); // [] ``` #### function skipWhile ```kestrel public func skipWhile(where: (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] ``` #### function sorted ```kestrel 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] ``` #### function stepBy ```kestrel 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] ``` #### function sum ```kestrel 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 ``` #### function take ```kestrel 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] ``` #### function takeWhile ```kestrel public func takeWhile(where: (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] ``` #### function tryFold ```kestrel 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") ``` #### function tryForEach ```kestrel public mutating func tryForEach[E]((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 ``` #### function unzip ```kestrel 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"] ``` #### function zip ```kestrel 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)] ``` ### struct ReversedCharsView ```kestrel public struct ReversedCharsView { /* private fields */ } ``` A reversed view over the code points in a string. Iterates characters back-to-front without allocating. # Examples ``` let view = "abc".chars.reversed; view.first(); // Some('c') view.count; // 3 ``` #### field count ```kestrel public var count: Int64 { get } ``` Number of code points. O(n). #### field first ```kestrel public var first: Char? { get } ``` The first element of the reversed view (= last char of the source). #### initializer init ```kestrel public init(slice: StringSlice) ``` #### field isEmpty ```kestrel public var isEmpty: Bool { get } ``` **Iterable** #### typealias Item ```kestrel type Item = Char ``` #### typealias TargetIterator ```kestrel type TargetIterator = ReversedCharsIterator ``` #### function iter ```kestrel public func iter() -> ReversedCharsIterator ``` **Cloneable** #### function clone ```kestrel public func clone() -> ReversedCharsView ``` ### enum Sign ```kestrel public enum Sign ``` How the sign of a numeric value should be rendered. Read by integer and float formatters before emitting the magnitude. `Negative` is the conventional default — only `-` for negative values, nothing for non-negatives. `Always` is useful for diffs or coordinates where every value should carry an explicit sign; `Space` reserves a column so columns of mixed signs line up. # Examples ``` var opts = FormatOptions(); opts.sign = .Always; (3).format(options: opts); // "+3" (-3).format(options: opts); // "-3" opts.sign = .Space; (3).format(options: opts); // " 3" ``` #### case Always ```kestrel case Always ``` Always show a sign — `+` for non-negative, `-` for negative. #### case Negative ```kestrel case Negative ``` Show `-` for negative values, no prefix for zero or positive (default). #### case Space ```kestrel case Space ``` Use a leading space for non-negative, `-` for negative; keeps mixed-sign columns aligned. **Equatable** #### typealias Output ```kestrel type Output = Bool ``` #### function equal ```kestrel public func equal(to: Self) -> Bool ``` Bridges `Equal.equal(to:)` to `Equatable.isEqual(to:)`. #### function isEqual ```kestrel public func isEqual(to: Sign) -> Bool ``` Returns true if both cases are the same variant. Used by `Equatable` to lift case identity into a `Bool` for composite comparisons (see `FormatOptions.isEqual`). # Examples ``` Sign.Always.isEqual(to: .Always); // true Sign.Negative.isEqual(to: .Always); // false ``` #### function notEqual ```kestrel public func notEqual(to: Self) -> Bool ``` Default `!=`: delegates to `==` so there's a single source of truth. **Matchable** #### function matches ```kestrel public func matches(Sign) -> Bool ``` Pattern-match form of equality — delegates to `isEqual`. # Examples ``` Sign.Space.matches(.Space); // true ``` ### struct SplitView ```kestrel public struct SplitView { /* private fields */ } ``` Lazy view over the segments of a string split on a fixed separator. Each segment is a zero-copy `StringSlice` into the original buffer. Use `iter()` for one-pass iteration, or `first()`/`last()`/`collect()` for targeted access. # Examples ``` let view = "a,b,c".asSlice().split(","); view.first(); // Some("a") view.count; // 3 view.collect(); // [StringSlice("a"), StringSlice("b"), StringSlice("c")] ``` #### function collect ```kestrel public func collect() -> Array[StringSlice] ``` Collects all segments into an array. #### field count ```kestrel public var count: Int64 { get } ``` Number of segments. O(n) — iterates once to count. #### field first ```kestrel public var first: StringSlice? { get } ``` The first segment, or `.None` if empty. #### initializer init ```kestrel public init(slice: StringSlice, separator: String) ``` #### field isEmpty ```kestrel public var isEmpty: Bool { get } ``` True when the source slice is empty. #### field last ```kestrel public var last: StringSlice? { get } ``` The last segment, or `.None` if empty. **Iterable** #### typealias Item ```kestrel type Item = StringSlice ``` #### typealias TargetIterator ```kestrel type TargetIterator = SplitViewIterator ``` #### function iter ```kestrel public func iter() -> SplitViewIterator ``` **Cloneable** #### function clone ```kestrel public func clone() -> SplitView ``` ### struct SplitViewIterator ```kestrel public struct SplitViewIterator { /* private fields */ } ``` Iterator that yields `StringSlice` segments produced by splitting on a fixed separator. Zero-copy: each yielded slice is a window into the original source buffer. #### initializer init ```kestrel public init(slice: StringSlice, separator: String) ``` **Iterator** #### typealias Item ```kestrel type Item = StringSlice ``` #### typealias TargetIterator ```kestrel type TargetIterator = Self ``` #### function all ```kestrel 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) ``` #### function any ```kestrel 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 ``` #### function chain ```kestrel 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] ``` #### function collect ```kestrel 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] ``` #### function compactMap ```kestrel public func compactMap[T]() -> FilterMapIterator[Self, T] where Item == Optional[T] ``` Drops `None`s and unwraps `Some`s — 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] ``` #### function contains ```kestrel 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 ``` #### function count ```kestrel 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 ``` #### function cycle ```kestrel 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] ``` #### function enumerate ```kestrel 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}") }; ``` #### function filter ```kestrel public func filter(where: (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] ``` #### function filterMap ```kestrel public func filterMap[U](as: (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] ``` #### function first ```kestrel 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 ``` #### function firstIndex ```kestrel 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 ``` #### function flatMap ```kestrel public func flatMap[U](as: (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] ``` #### function flatten ```kestrel 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] ``` #### function fold ```kestrel 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 ``` #### function forEach ```kestrel 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) }; ``` #### function fuse ```kestrel 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. #### function inspect ```kestrel public func inspect((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(); ``` #### function intersperse ```kestrel 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] ``` #### function intersperseWith ```kestrel public func intersperseWith(with: () -> 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] ``` #### function isSorted ```kestrel 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) ``` #### function isSortedDescending ```kestrel public consuming func isSortedDescending() -> Bool ``` True if elements come out in descending order. Mirror of `isSorted`. #### function iter ```kestrel func iter() -> Self ``` Returns `self`. The blanket conformance pivot — iterators *are* iterables. #### function last ```kestrel 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. #### function map ```kestrel public func map[U](as: (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] ``` #### function max ```kestrel public consuming func max() -> Item? ``` Largest element, or `None` for an empty iterator. Ties go to the first occurrence. #### function min ```kestrel 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 ``` #### function next ```kestrel public mutating func next() -> StringSlice? ``` #### function nth ```kestrel 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) ``` #### function peekable ```kestrel 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) ``` #### function product ```kestrel 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 ``` #### function reduce ```kestrel 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 ``` #### function scan ```kestrel public func scan[Acc](from: Acc, by: (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] ``` #### function skip ```kestrel 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(); // [] ``` #### function skipWhile ```kestrel public func skipWhile(where: (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] ``` #### function sorted ```kestrel 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] ``` #### function stepBy ```kestrel 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] ``` #### function sum ```kestrel 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 ``` #### function take ```kestrel 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] ``` #### function takeWhile ```kestrel public func takeWhile(where: (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] ``` #### function tryFold ```kestrel 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") ``` #### function tryForEach ```kestrel public mutating func tryForEach[E]((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 ``` #### function unzip ```kestrel 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"] ``` #### function zip ```kestrel 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)] ``` **Cloneable** #### function clone ```kestrel public func clone() -> SplitViewIterator ``` ### struct SplitWhereView ```kestrel public struct SplitWhereView { /* private fields */ } ``` Lazy view over the segments of a string split at every code point matching a predicate. The matching characters are excluded from segments. # Examples ``` let view = "hello world".asSlice().split { (c) in c == Char(" ") }; view.first(); // Some("hello") view.count; // 2 ``` #### function collect ```kestrel public func collect() -> Array[StringSlice] ``` Collects all segments into an array. #### field count ```kestrel public var count: Int64 { get } ``` Number of segments. O(n) — iterates once to count. #### field first ```kestrel public var first: StringSlice? { get } ``` The first segment, or `.None` if empty. #### initializer init ```kestrel public init(slice: StringSlice, where: (Char) -> Bool) ``` #### field isEmpty ```kestrel public var isEmpty: Bool { get } ``` True when the source slice is empty. #### field last ```kestrel public var last: StringSlice? { get } ``` The last segment, or `.None` if empty. **Iterable** #### typealias Item ```kestrel type Item = StringSlice ``` #### typealias TargetIterator ```kestrel type TargetIterator = SplitWhereViewIterator ``` #### function iter ```kestrel public func iter() -> SplitWhereViewIterator ``` **Cloneable** #### function clone ```kestrel public func clone() -> SplitWhereView ``` ### struct SplitWhereViewIterator ```kestrel public struct SplitWhereViewIterator { /* private fields */ } ``` Iterator that yields `StringSlice` segments produced by splitting at every code point matching a predicate. The matching character is not included in any segment. #### initializer init ```kestrel public init(slice: StringSlice, where: (Char) -> Bool) ``` **Iterator** #### typealias Item ```kestrel type Item = StringSlice ``` #### typealias TargetIterator ```kestrel type TargetIterator = Self ``` #### function all ```kestrel 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) ``` #### function any ```kestrel 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 ``` #### function chain ```kestrel 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] ``` #### function collect ```kestrel 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] ``` #### function compactMap ```kestrel public func compactMap[T]() -> FilterMapIterator[Self, T] where Item == Optional[T] ``` Drops `None`s and unwraps `Some`s — 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] ``` #### function contains ```kestrel 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 ``` #### function count ```kestrel 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 ``` #### function cycle ```kestrel 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] ``` #### function enumerate ```kestrel 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}") }; ``` #### function filter ```kestrel public func filter(where: (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] ``` #### function filterMap ```kestrel public func filterMap[U](as: (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] ``` #### function first ```kestrel 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 ``` #### function firstIndex ```kestrel 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 ``` #### function flatMap ```kestrel public func flatMap[U](as: (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] ``` #### function flatten ```kestrel 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] ``` #### function fold ```kestrel 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 ``` #### function forEach ```kestrel 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) }; ``` #### function fuse ```kestrel 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. #### function inspect ```kestrel public func inspect((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(); ``` #### function intersperse ```kestrel 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] ``` #### function intersperseWith ```kestrel public func intersperseWith(with: () -> 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] ``` #### function isSorted ```kestrel 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) ``` #### function isSortedDescending ```kestrel public consuming func isSortedDescending() -> Bool ``` True if elements come out in descending order. Mirror of `isSorted`. #### function iter ```kestrel func iter() -> Self ``` Returns `self`. The blanket conformance pivot — iterators *are* iterables. #### function last ```kestrel 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. #### function map ```kestrel public func map[U](as: (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] ``` #### function max ```kestrel public consuming func max() -> Item? ``` Largest element, or `None` for an empty iterator. Ties go to the first occurrence. #### function min ```kestrel 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 ``` #### function next ```kestrel public mutating func next() -> StringSlice? ``` #### function nth ```kestrel 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) ``` #### function peekable ```kestrel 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) ``` #### function product ```kestrel 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 ``` #### function reduce ```kestrel 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 ``` #### function scan ```kestrel public func scan[Acc](from: Acc, by: (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] ``` #### function skip ```kestrel 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(); // [] ``` #### function skipWhile ```kestrel public func skipWhile(where: (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] ``` #### function sorted ```kestrel 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] ``` #### function stepBy ```kestrel 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] ``` #### function sum ```kestrel 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 ``` #### function take ```kestrel 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] ``` #### function takeWhile ```kestrel public func takeWhile(where: (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] ``` #### function tryFold ```kestrel 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") ``` #### function tryForEach ```kestrel public mutating func tryForEach[E]((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 ``` #### function unzip ```kestrel 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"] ``` #### function zip ```kestrel 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)] ``` **Cloneable** #### function clone ```kestrel public func clone() -> SplitWhereViewIterator ``` ### protocol Str ```kestrel public protocol Str ``` Shared read-only protocol for `String` and `StringSlice`. Requires exactly one method from conformers: `asSlice()`. All read-only methods are defined once in `extend Str` and inherited by both types automatically. #### function asSlice ```kestrel func asSlice() -> StringSlice ``` #### field byteCount ```kestrel public var byteCount: Int64 { get } ``` Number of UTF-8 bytes. O(1). # Examples ``` "hello".byteCount; // 5 "\u{00E9}".byteCount; // 2 (é is two UTF-8 bytes) ``` #### field bytes ```kestrel public var bytes: BytesView { get } ``` View over the raw UTF-8 bytes. # Examples ``` "hi".bytes.count; // 2 ``` #### function caseFolded ```kestrel public func caseFolded() -> String ``` Returns a new string with Unicode case folding applied to each code point. Case folding maps characters to a canonical form suitable for case-insensitive comparison. Currently single-char folds only (e.g. `A` → `a`); multi-char expansions like `ß` → `ss` are not yet supported. # Examples ``` "Hello".caseFolded(); // "hello" ``` #### field chars ```kestrel public var chars: CharsView { get } ``` View over Unicode code points. # Examples ``` "caf\u{00E9}".chars.count; // 4 ``` #### function contains ```kestrel public func contains(String) -> Bool ``` Returns true if `substring` appears anywhere in this string. # Examples ``` "hello world".contains(substring: "world"); // true "hello world".contains(substring: "xyz"); // false ``` #### function contains ```kestrel public func contains(where: (Char) -> Bool) -> Bool ``` Returns true if any code point matches `predicate`. # Examples ``` "abc123".contains(where: { (c) in c.isAsciiDigit }); // true ``` #### function ends ```kestrel public func ends(with: String) -> Bool ``` Returns true if this string ends with `suffix`. Empty suffix always returns true. Comparison is byte-wise. # Examples ``` "hello".ends(with: "llo"); // true "hello".ends(with: "xyz"); // false ``` #### function equalsCaseInsensitive ```kestrel public func equalsCaseInsensitive(String) -> Bool ``` Compares two strings for equality after Unicode case folding. Folds each string to its case-folded form and compares the results byte-wise. Not normalization-aware — `é` (`U+00E9`) and `e\u{0301}` are still considered different. # Examples ``` "Hello".equalsCaseInsensitive("HELLO"); // true "Hello".equalsCaseInsensitive("World"); // false ``` #### function firstIndex ```kestrel public func firstIndex(of: String) -> ByteIndex? ``` Returns the byte index of the first occurrence of `substring`, or `None` if not found. The empty substring matches at the start. Uses `memmem` for efficient byte-level search. # Examples ``` "hello world".firstIndex(of: "world"); // Some(ByteIndex(6)) "hello world".firstIndex(of: "xyz"); // None ``` #### field graphemes ```kestrel public var graphemes: GraphemesView { get } ``` View over grapheme clusters (user-perceived characters). # Examples ``` "caf\u{00E9}".graphemes.count; // 4 ``` #### field isEmpty ```kestrel public var isEmpty: Bool { get } ``` True when the string contains no bytes. # Examples ``` "".isEmpty; // true "hello".isEmpty; // false ``` #### function lastIndex ```kestrel public func lastIndex(of: String) -> ByteIndex? ``` Returns the byte index of the last occurrence of `substring`, or `None` if not found. Scans from the left using repeated `memmem` calls, keeping the last match position. # Examples ``` "abcabc".lastIndex(of: "abc"); // Some(ByteIndex(3)) "abcabc".lastIndex(of: "xyz"); // None ``` #### field lines ```kestrel public var lines: LinesView { get } ``` View over lines, recognising `\n`, `\r\n`, and `\r`. # Examples ``` "a\nb\nc".lines.count; // 3 ``` #### function lowercased ```kestrel public func lowercased() -> String ``` Returns the lowercase form using full Unicode case mapping. Locale-independent. Handles multi-character expansions (e.g. Turkish dotted I). All-ASCII strings with no uppercase letters short-circuit to `toOwned()` (no per-char decode). # Examples ``` "Hello".lowercased(); // "hello" "\u{0130}".lowercased(); // "i\u{0307}" ``` #### function lowercasedAscii ```kestrel public func lowercasedAscii() -> String ``` Returns a copy with only ASCII letters lowercased; non-ASCII bytes pass through unchanged. Cheap byte-level scan with no Unicode tables. For full Unicode case mapping, use `lowercased()`. # Examples ``` "H\u{00E9}LLO".lowercasedAscii(); // "h\u{00E9}llo" ``` #### function pad ```kestrel public func pad(leading: Int64, with: Char) -> String ``` Returns the string padded at the start with `char` so the total *code-point* count is at least `length`. If the string is already at least `length` code points long, returns a copy unchanged. # Examples ``` "42".pad(leading: 5, with: '0'); // "00042" ``` #### function pad ```kestrel public func pad(trailing: Int64, with: Char) -> String ``` Returns the string padded at the end with `char` so the total *code-point* count is at least `length`. If the string is already at least `length` code points long, returns a copy unchanged. # Examples ``` "42".pad(trailing: 5, with: '.'); // "42..." ``` #### function repeated ```kestrel public func repeated(Int64) -> String ``` Returns this string concatenated with itself `count` times. Non-positive `count` returns the empty string. Pre-allocates the result buffer for the exact final length. # Examples ``` "ab".repeated(3); // "ababab" "ab".repeated(0); // "" ``` #### function replaced ```kestrel public func replaced(String, with: String) -> String ``` Returns a copy with every occurrence of `pattern` replaced by `replacement`. Empty `pattern` is a no-op (returns a copy). Searches greedily from the left and skips past each replacement so substituted text is not re-matched. # Examples ``` "hello world".replaced("o", with: "0"); // "hell0 w0rld" "abcabc".replaced("ab", with: "ABCD"); // "ABCDcABCDc" ``` #### function split ```kestrel public func split(String) -> SplitView ``` Returns a lazy view that splits on `separator`, yielding zero-copy `StringSlice` segments. The empty separator is special-cased to split per code point. Adjacent separators produce empty segments. # Examples ``` "a,b,c".split(",").collect(); // ["a", "b", "c"] "a,,b".split(",").count; // 3 (empty segment preserved) ``` #### function split ```kestrel public func split(where: (Char) -> Bool) -> SplitWhereView ``` Returns a lazy view that splits at every code point matching `predicate`, yielding zero-copy `StringSlice` segments. The matching characters are not included in any segment. # Examples ``` "hello world".split(where: { (c) in c.isWhitespace }).count; // 2 ``` #### function starts ```kestrel public func starts(with: String) -> Bool ``` Returns true if this string starts with `prefix`. Empty prefix always returns true. Comparison is byte-wise. # Examples ``` "hello".starts(with: "hel"); // true "hello".starts(with: "xyz"); // false ``` #### function titlecased ```kestrel public func titlecased() -> String ``` Returns the titlecase form using full Unicode case mapping. Word boundaries are detected by `Char.isWhitespace`; the first non-space character of each run is titlecased and the rest lowercased. # Examples ``` "hello world".titlecased(); // "Hello World" "FOO BAR".titlecased(); // "Foo Bar" ``` #### function toOwned ```kestrel public func toOwned() -> String ``` Copies this string's bytes into a new independent `String`. For `String`, this is equivalent to `clone()`. For `StringSlice`, it copies only the slice's bytes, releasing the reference to the source buffer. # Examples ``` let slice = "hello world".asSlice(); let owned = slice.toOwned(); // independent copy ``` #### function trimmed ```kestrel public func trimmed() -> StringSlice ``` Returns a zero-copy slice with leading and trailing ASCII whitespace removed. Whitespace characters: space (`' '`), tab (`'\t'`), newline (`'\n'`), carriage return (`'\r'`), and form feed (`'\x0C'`). The returned `StringSlice` shares the source buffer — no allocation occurs. # Examples ``` " hello ".trimmed().toOwned(); // "hello" "\t\n".trimmed().isEmpty; // true ``` #### function trimmed ```kestrel public func trimmed(where: (Char) -> Bool) -> StringSlice ``` Returns a zero-copy slice with leading and trailing code points matching `predicate` removed. Decodes the source one `Char` at a time. Leading characters that satisfy the predicate are skipped; the trailing boundary is the last character that does *not* match. # Examples ``` "00042".trimmed(where: { (c) in c.isEqual(to: '0') }).toOwned(); // "42" ``` #### function trimmedEnd ```kestrel public func trimmedEnd() -> StringSlice ``` Returns a zero-copy slice with trailing whitespace removed. See `trimmed()` for the whitespace set. Leading whitespace is preserved. # Examples ``` " hello ".trimmedEnd().toOwned(); // " hello" ``` #### function trimmedEnd ```kestrel public func trimmedEnd(where: (Char) -> Bool) -> StringSlice ``` Returns a zero-copy slice with trailing code points matching `predicate` removed. Leading matches are preserved. # Examples ``` "abc000".trimmedEnd(where: { (c) in c.isEqual(to: '0') }).toOwned(); // "abc" ``` #### function trimmedStart ```kestrel public func trimmedStart() -> StringSlice ``` Returns a zero-copy slice with leading whitespace removed. See `trimmed()` for the whitespace set. Trailing whitespace is preserved. # Examples ``` " hello ".trimmedStart().toOwned(); // "hello " ``` #### function trimmedStart ```kestrel public func trimmedStart(where: (Char) -> Bool) -> StringSlice ``` Returns a zero-copy slice with leading code points matching `predicate` removed. Trailing matches are preserved. # Examples ``` "000abc".trimmedStart(where: { (c) in c.isEqual(to: '0') }).toOwned(); // "abc" ``` #### function uppercased ```kestrel public func uppercased() -> String ``` Returns the uppercase form using full Unicode case mapping. Locale-independent. Handles multi-character expansions (e.g. `ß` → `SS`). All-ASCII strings with no lowercase letters short-circuit to `toOwned()`. # Examples ``` "hello".uppercased(); // "HELLO" "stra\u{00DF}e".uppercased(); // "STRASSE" ``` #### function uppercasedAscii ```kestrel public func uppercasedAscii() -> String ``` Returns a copy with only ASCII letters uppercased; non-ASCII bytes pass through unchanged. Cheap byte-level scan with no Unicode tables. For full Unicode case mapping, use `uppercased()`. # Examples ``` "h\u{00E9}llo".uppercasedAscii(); // "H\u{00E9}LLO" ``` **Iterable** #### typealias Item ```kestrel type Item ``` The element type that iteration yields. #### typealias TargetIterator ```kestrel type TargetIterator ``` The concrete iterator type returned by `iter()`. Constrained so `TargetIterator.Item` matches `Self.Item`. #### function iter ```kestrel public func iter() -> CharsIterator ``` Returns a `CharsIterator` over the code points. Required by `Iterable`. Each call returns a fresh iterator; the source is reusable. # Examples ``` for c in "abc" { ... } // iterates 'a', 'b', 'c' ``` **Equatable** #### typealias Output ```kestrel type Output = Bool ``` #### function equal ```kestrel public func equal(to: Self) -> Bool ``` Bridges `Equal.equal(to:)` to `Equatable.isEqual(to:)`. #### function isEqual ```kestrel public func isEqual(to: Self) -> Bool ``` Returns true if both strings have the same byte sequence. Pure byte-wise equality — not normalization-aware. For case-insensitive comparison, see `equalsCaseInsensitive`. # Examples ``` "abc".isEqual(to: "abc"); // true "abc".isEqual(to: "ABC"); // false ``` #### function notEqual ```kestrel public func notEqual(to: Self) -> Bool ``` Default `!=`: delegates to `==` so there's a single source of truth. **Comparable** #### typealias Output ```kestrel type Output = Bool ``` #### function compare ```kestrel public func compare(Self) -> Ordering ``` Lexicographic byte-wise comparison. Returns `Less` / `Equal` / `Greater` according to the first differing byte; if one string is a prefix of the other, the shorter is less. # Examples ``` "abc".compare("abd"); // Less "abc".compare("ab"); // Greater ``` #### function greaterThan ```kestrel public func greaterThan(Self) -> Bool ``` `>` derived from `compare`. #### function greaterThanOrEqual ```kestrel public func greaterThanOrEqual(Self) -> Bool ``` `>=` derived from `compare`. #### function isAtLeast ```kestrel public func isAtLeast(Self) -> Bool ``` `start..` lower-bound check, derived from `compare`. #### function isAtMost ```kestrel public func isAtMost(Self) -> Bool ``` `..=end` upper-bound check, derived from `compare`. #### function isBelow ```kestrel public func isBelow(Self) -> Bool ``` `.. Bool ``` `<` derived from `compare`. #### function lessThanOrEqual ```kestrel public func lessThanOrEqual(Self) -> Bool ``` `<=` derived from `compare`. **Hashable** #### function hash ```kestrel public func hash[H](into: mutating H) where H: Hasher ``` Hashes the byte content into `hasher`. **Formattable** #### function format ```kestrel public func format(into: mutating StringBuilder, FormatOptions) ``` Formats the string using the given options. # Examples ``` "hi".format(FormatOptions(width: 5)); // "hi " ``` #### function formatted ```kestrel public func formatted(FormatOptions) -> String ``` Returns this value rendered as a `String`. Convenience wrapper: creates a `StringBuilder`, calls `format(into:)`, and returns the built string. Uses a distinct name to avoid overload-resolution ambiguity with `format(into:)`. ### struct String ```kestrel public struct String { /* private fields */ } ``` A UTF-8 encoded, dynamically sized string with copy-on-write semantics. `String` is the standard text type. The bytes are always valid UTF-8. Storage is shared between clones via an `RcBox`; mutating a `String` whose storage is referenced elsewhere triggers a copy. Three different views (`bytes`, `chars`, `graphemes`) plus a `lines` view expose different units of iteration over the same buffer. # Examples ``` var s = "hello"; s.append(", world"); s.byteCount; // 12 s.contains(","); // true for line in "a\nb".lines { /* ... */ } ``` # UTF-8 All public mutators preserve UTF-8 validity. The `bytes` view returns raw `UInt8`s for hashing and FFI; the `chars` view decodes code points; the `graphemes` view applies UAX #29 segmentation for user-perceived characters. Choose the view that matches your unit: byte-level work uses `bytes`, scalar-level work uses `chars`, and anything user-visible (cursor movement, truncation) uses `graphemes`. # Representation A single `CowBox[StringStorage]` field. The storage record carries `(ptr, len, cap)`; the empty string uses a null pointer with both counts zero. # Memory Model Reference-counted, copy-on-write. Cloning is O(1); the first mutation after a shared clone allocates and copies the bytes. The raw byte pointer returned from `bytes` aliases the live buffer; retain strings, not pointers. # Guarantees - Bytes are valid UTF-8 after every public mutator. - `byteCount`, `capacity`, and `isEmpty` are O(1); `count` (code points) is O(n). - Clones do not share mutation; `s.clone()` and `s` will diverge as soon as either is mutated. #### initializer Empty ```kestrel public init() ``` Constructs an empty string. Allocates no buffer; the empty string is represented by a null pointer with zero length and capacity. Required by `Defaultable`. # Examples ``` let s = String(); s.isEmpty; // true s.byteCount; // 0 ``` #### initializer From CString ```kestrel public init(from: CString) ``` Builds a `String` by copying the bytes out of `cstring`, excluding the null terminator. O(n) — `cstring.length` walks to the terminator and the byte copy is linear. Empty `CString`s (length zero) yield the default empty `String` without touching the pointer. # Safety `cstring.raw` must be valid for at least `length` readable bytes plus a terminator. The conversion does not free the `CString`'s buffer — caller still owns it. # Examples ``` let cstr = CString(raw: somePtr); let s = String(from: cstr); ``` #### initializer From Char Iterable ```kestrel public init[I](from: I) where I: Iterable, I.Item == Char ``` Builds a string by encoding each character of `chars` as UTF-8. Mirrors `Array.init(from:)` and `Set.init(from:)` — accepts any `Iterable` whose `Item` is `Char`. Useful for materializing the result of an iterator chain back into a `String`: ``` let upper = String(from: "hello".chars.iter().map { it.toUpper() }); // "HELLO" ``` #### initializer From Storage ```kestrel init(storage: CowBox[StringStorage]) ``` Wraps an existing `CowBox[StringStorage]` as a new `String`. Module-internal — used by `clone()`, `StringBuilder.build()`, and other std.text code that constructs strings from raw storage. #### initializer From UTF-8 ```kestrel public init[S](fromUtf8: S) where S: Slice[UInt8] ``` Constructs a string from validated UTF-8 bytes, returning `null` if the input is not valid UTF-8. # Examples ``` let s = String(fromUtf8: "héllo".bytes); // Some("héllo") ``` #### initializer From UTF-8 Lossy ```kestrel public init[S](fromUtf8Lossy: S) where S: Slice[UInt8] ``` Constructs a string from bytes, replacing invalid UTF-8 sequences with the Unicode replacement character (U+FFFD). # Examples ``` let s = String(fromUtf8Lossy: mixedBytes); // invalid bytes become '�' ``` #### initializer From UTF-8 Unchecked ```kestrel public init[S](fromUtf8Unchecked: S) where S: Slice[UInt8] ``` Constructs a string by copying bytes without UTF-8 validation. # Safety The caller must ensure the bytes are valid UTF-8. #### initializer String Literal ```kestrel public init(stringLiteral: lang.ptr[lang.i8], lang.i64) ``` Compiler-emitted constructor for string literals. Receives a static byte pointer and length, then memcpys into a fresh heap allocation so the resulting `String` owns its bytes (and can be mutated independently of the literal pool). # Errors Panics with `"String allocation failed"` if the system allocator returns null. #### initializer With Capacity ```kestrel public init(capacity: Int64) ``` Constructs an empty string with at least `capacity` bytes preallocated. Useful before a series of appends whose total byte count is known: avoids the geometric-growth reallocations the default constructor would incur. A non-positive `capacity` is treated as zero. # Errors Panics with `"String allocation failed"` if the system allocator returns null. # Examples ``` var s = String(capacity: 64); s.byteCount; // 0 s.capacity; // 64 ``` #### function _appendBytes ```kestrel mutating func _appendBytes(Pointer[UInt8], Int64) ``` Appends `n` bytes from `ptr` via `memcpy`. Internal — caller ensures the bytes preserve UTF-8 validity. # Safety `ptr` must reference at least `n` valid UTF-8 bytes that, when concatenated to the current buffer, yield valid UTF-8. #### function append ```kestrel public mutating func append[__opaque_0](__opaque_0) where __opaque_0: Str ``` Appends `other`'s bytes to this string. COW. Triggers a copy if storage is shared. Empty appends are a fast no-op. # Examples ``` var s = "hello"; s.append(", world"); s; // "hello, world" ``` #### function append ```kestrel public mutating func append(char: Char) ``` Appends a single code point, encoding it as UTF-8. Sizes the buffer for the encoded length (1–4 bytes) before writing. # Examples ``` var s = "h"; s.append(char: 'i'); s.append(char: '\u{1F600}'); s; // "hi😀" ``` #### function appendByte ```kestrel internal mutating func appendByte(UInt8) ``` Appends a raw byte. Internal — caller ensures UTF-8 validity. Do not use to append ASCII characters: prefer `appendChar(c)` or `append(other)`. This exists only for low-level UTF-8 plumbing inside the stdlib (e.g. an encoder that already produced bytes). #### field byteCount ```kestrel public var byteCount: Int64 { get } ``` The number of UTF-8 bytes in the string. O(1). This is **not** the character count — see `count` for that. Pure ASCII strings have `byteCount == count`. #### field bytes ```kestrel public var bytes: BytesView { get } ``` `s.bytes` — view over the raw UTF-8 bytes. O(1) byte indexing, byte-level iteration. Index via the view's subscripts: `s.bytes(i)`, `s.bytes(checked: i)`, `s.bytes(0.. String ``` Internal helper: copies `count` bytes from `ptr` without validation. #### function fromRawBytes ```kestrel static func fromRawBytes(lang.ptr[lang.i8], Int64) -> String ``` Internal helper: copies `count` bytes from a raw `lang.ptr[lang.i8]`. #### field graphemes ```kestrel public var graphemes: GraphemesView { get } ``` `s.graphemes` — view over user-perceived characters (UAX #29 grapheme clusters). Iterate or count, no random access. #### field isEmpty ```kestrel public var isEmpty: Bool { get } ``` True if the string holds zero bytes. O(1). #### field lines ```kestrel public var lines: LinesView { get } ``` A view over the lines of the string, recognising `\n`, `\r\n`, and `\r`. #### function lowercase ```kestrel public mutating func lowercase() ``` Replaces this string with its lowercase form using full Unicode case mapping. #### function lowercaseAscii ```kestrel public mutating func lowercaseAscii() ``` Lowercases ASCII letters in place; non-ASCII bytes are left untouched. Cheap byte-level scan with no Unicode tables. For locale- independent Unicode case folding, use `lowercase`. # Examples ``` var s = "HéLLO"; s.lowercaseAscii(); s; // "héllo" — only ASCII letters touched ``` #### function replace ```kestrel public mutating func replace(String, with: String) ``` Replaces every occurrence of `pattern` with `replacement`, in place. #### function substringBytes ```kestrel internal func substringBytes(from: Int64, to: Int64) -> String ``` Internal substring by byte range. Returns empty for invalid ranges. Do not use for per-character slicing in a loop — each call copies `end - start` bytes, so walking the string yields O(N²) behaviour. For iteration, use `decodeUtf8` with a running byte offset, or the `chars()` / `bytes()` views. #### function toCString ```kestrel public func toCString() -> CString ``` Allocates a fresh null-terminated copy of this string and returns it as a `CString`. Sizes the buffer to `byteCount + 1`, copies the source bytes via `memcpy`, and writes the trailing `\0`. The caller takes ownership and must release the buffer with `cstr.free()`. # Safety The returned `CString` aliases freshly allocated memory; do not pass it to a C function that takes ownership of the pointer (it will then be double-freed) and do not forget to free it. # Examples ``` let cstr = "Hello, C!".toCString(); let _ = puts(cstr); cstr.free(); ``` #### function trim ```kestrel public mutating func trim() ``` Removes leading and trailing ASCII whitespace in place. Recognises the same whitespace set as `Char.isWhitespace`: space, tab, LF, CR, form feed. For Unicode-aware trimming, use the `(where:)` overloads with a custom predicate. Non-mutating mirrors live under `trimmed*`. # Examples ``` var s = " hi "; s.trim(); s; // "hi" ``` #### function trim ```kestrel public mutating func trim(where: (Char) -> Bool) ``` Removes leading and trailing code points matching `predicate`, in place. # Examples ``` var s = "***hi***"; s.trim { (c) in c == '*' }; s; // "hi" ``` #### function trimEnd ```kestrel public mutating func trimEnd() ``` Removes trailing ASCII whitespace in place. #### function trimEnd ```kestrel public mutating func trimEnd(where: (Char) -> Bool) ``` Removes trailing code points matching `predicate`, in place. #### function trimStart ```kestrel public mutating func trimStart() ``` Removes leading ASCII whitespace in place. #### function trimStart ```kestrel public mutating func trimStart(where: (Char) -> Bool) ``` Removes leading code points matching `predicate`, in place. #### function uppercase ```kestrel public mutating func uppercase() ``` Replaces this string with its uppercase form using full Unicode case mapping. Locale-independent. Handles multi-character expansions — e.g. German `ß` → `SS`. #### function uppercaseAscii ```kestrel public mutating func uppercaseAscii() ``` Uppercases ASCII letters in place; non-ASCII bytes are left untouched. **Str** #### function asSlice ```kestrel public func asSlice() -> StringSlice ``` Returns a `StringSlice` covering this string's entire buffer. Shares storage via refcount — zero-copy. #### field byteCount ```kestrel public var byteCount: Int64 { get } ``` Number of UTF-8 bytes. O(1). # Examples ``` "hello".byteCount; // 5 "\u{00E9}".byteCount; // 2 (é is two UTF-8 bytes) ``` #### field bytes ```kestrel public var bytes: BytesView { get } ``` View over the raw UTF-8 bytes. # Examples ``` "hi".bytes.count; // 2 ``` #### function caseFolded ```kestrel public func caseFolded() -> String ``` Returns a new string with Unicode case folding applied to each code point. Case folding maps characters to a canonical form suitable for case-insensitive comparison. Currently single-char folds only (e.g. `A` → `a`); multi-char expansions like `ß` → `ss` are not yet supported. # Examples ``` "Hello".caseFolded(); // "hello" ``` #### field chars ```kestrel public var chars: CharsView { get } ``` View over Unicode code points. # Examples ``` "caf\u{00E9}".chars.count; // 4 ``` #### function compare ```kestrel public func compare(Self) -> Ordering ``` Lexicographic byte-wise comparison. Returns `Less` / `Equal` / `Greater` according to the first differing byte; if one string is a prefix of the other, the shorter is less. # Examples ``` "abc".compare("abd"); // Less "abc".compare("ab"); // Greater ``` #### function contains ```kestrel public func contains(String) -> Bool ``` Returns true if `substring` appears anywhere in this string. # Examples ``` "hello world".contains(substring: "world"); // true "hello world".contains(substring: "xyz"); // false ``` #### function ends ```kestrel public func ends(with: String) -> Bool ``` Returns true if this string ends with `suffix`. Empty suffix always returns true. Comparison is byte-wise. # Examples ``` "hello".ends(with: "llo"); // true "hello".ends(with: "xyz"); // false ``` #### function equalsCaseInsensitive ```kestrel public func equalsCaseInsensitive(String) -> Bool ``` Compares two strings for equality after Unicode case folding. Folds each string to its case-folded form and compares the results byte-wise. Not normalization-aware — `é` (`U+00E9`) and `e\u{0301}` are still considered different. # Examples ``` "Hello".equalsCaseInsensitive("HELLO"); // true "Hello".equalsCaseInsensitive("World"); // false ``` #### function firstIndex ```kestrel public func firstIndex(of: String) -> ByteIndex? ``` Returns the byte index of the first occurrence of `substring`, or `None` if not found. The empty substring matches at the start. Uses `memmem` for efficient byte-level search. # Examples ``` "hello world".firstIndex(of: "world"); // Some(ByteIndex(6)) "hello world".firstIndex(of: "xyz"); // None ``` #### function format ```kestrel public func format(into: mutating StringBuilder, FormatOptions) ``` Formats the string using the given options. # Examples ``` "hi".format(FormatOptions(width: 5)); // "hi " ``` #### field graphemes ```kestrel public var graphemes: GraphemesView { get } ``` View over grapheme clusters (user-perceived characters). # Examples ``` "caf\u{00E9}".graphemes.count; // 4 ``` #### function hash ```kestrel public func hash[H](into: mutating H) where H: Hasher ``` Hashes the byte content into `hasher`. #### field isEmpty ```kestrel public var isEmpty: Bool { get } ``` True when the string contains no bytes. # Examples ``` "".isEmpty; // true "hello".isEmpty; // false ``` #### function isEqual ```kestrel public func isEqual(to: Self) -> Bool ``` Returns true if both strings have the same byte sequence. Pure byte-wise equality — not normalization-aware. For case-insensitive comparison, see `equalsCaseInsensitive`. # Examples ``` "abc".isEqual(to: "abc"); // true "abc".isEqual(to: "ABC"); // false ``` #### function iter ```kestrel public func iter() -> CharsIterator ``` Returns a `CharsIterator` over the code points. Required by `Iterable`. Each call returns a fresh iterator; the source is reusable. # Examples ``` for c in "abc" { ... } // iterates 'a', 'b', 'c' ``` #### function lastIndex ```kestrel public func lastIndex(of: String) -> ByteIndex? ``` Returns the byte index of the last occurrence of `substring`, or `None` if not found. Scans from the left using repeated `memmem` calls, keeping the last match position. # Examples ``` "abcabc".lastIndex(of: "abc"); // Some(ByteIndex(3)) "abcabc".lastIndex(of: "xyz"); // None ``` #### field lines ```kestrel public var lines: LinesView { get } ``` View over lines, recognising `\n`, `\r\n`, and `\r`. # Examples ``` "a\nb\nc".lines.count; // 3 ``` #### function lowercased ```kestrel public func lowercased() -> String ``` Returns the lowercase form using full Unicode case mapping. Locale-independent. Handles multi-character expansions (e.g. Turkish dotted I). All-ASCII strings with no uppercase letters short-circuit to `toOwned()` (no per-char decode). # Examples ``` "Hello".lowercased(); // "hello" "\u{0130}".lowercased(); // "i\u{0307}" ``` #### function lowercasedAscii ```kestrel public func lowercasedAscii() -> String ``` Returns a copy with only ASCII letters lowercased; non-ASCII bytes pass through unchanged. Cheap byte-level scan with no Unicode tables. For full Unicode case mapping, use `lowercased()`. # Examples ``` "H\u{00E9}LLO".lowercasedAscii(); // "h\u{00E9}llo" ``` #### function pad ```kestrel public func pad(leading: Int64, with: Char) -> String ``` Returns the string padded at the start with `char` so the total *code-point* count is at least `length`. If the string is already at least `length` code points long, returns a copy unchanged. # Examples ``` "42".pad(leading: 5, with: '0'); // "00042" ``` #### function repeated ```kestrel public func repeated(Int64) -> String ``` Returns this string concatenated with itself `count` times. Non-positive `count` returns the empty string. Pre-allocates the result buffer for the exact final length. # Examples ``` "ab".repeated(3); // "ababab" "ab".repeated(0); // "" ``` #### function replaced ```kestrel public func replaced(String, with: String) -> String ``` Returns a copy with every occurrence of `pattern` replaced by `replacement`. Empty `pattern` is a no-op (returns a copy). Searches greedily from the left and skips past each replacement so substituted text is not re-matched. # Examples ``` "hello world".replaced("o", with: "0"); // "hell0 w0rld" "abcabc".replaced("ab", with: "ABCD"); // "ABCDcABCDc" ``` #### function split ```kestrel public func split(String) -> SplitView ``` Returns a lazy view that splits on `separator`, yielding zero-copy `StringSlice` segments. The empty separator is special-cased to split per code point. Adjacent separators produce empty segments. # Examples ``` "a,b,c".split(",").collect(); // ["a", "b", "c"] "a,,b".split(",").count; // 3 (empty segment preserved) ``` #### function starts ```kestrel public func starts(with: String) -> Bool ``` Returns true if this string starts with `prefix`. Empty prefix always returns true. Comparison is byte-wise. # Examples ``` "hello".starts(with: "hel"); // true "hello".starts(with: "xyz"); // false ``` #### function titlecased ```kestrel public func titlecased() -> String ``` Returns the titlecase form using full Unicode case mapping. Word boundaries are detected by `Char.isWhitespace`; the first non-space character of each run is titlecased and the rest lowercased. # Examples ``` "hello world".titlecased(); // "Hello World" "FOO BAR".titlecased(); // "Foo Bar" ``` #### function toOwned ```kestrel public func toOwned() -> String ``` Copies this string's bytes into a new independent `String`. For `String`, this is equivalent to `clone()`. For `StringSlice`, it copies only the slice's bytes, releasing the reference to the source buffer. # Examples ``` let slice = "hello world".asSlice(); let owned = slice.toOwned(); // independent copy ``` #### function trimmed ```kestrel public func trimmed() -> StringSlice ``` Returns a zero-copy slice with leading and trailing ASCII whitespace removed. Whitespace characters: space (`' '`), tab (`'\t'`), newline (`'\n'`), carriage return (`'\r'`), and form feed (`'\x0C'`). The returned `StringSlice` shares the source buffer — no allocation occurs. # Examples ``` " hello ".trimmed().toOwned(); // "hello" "\t\n".trimmed().isEmpty; // true ``` #### function trimmedEnd ```kestrel public func trimmedEnd() -> StringSlice ``` Returns a zero-copy slice with trailing whitespace removed. See `trimmed()` for the whitespace set. Leading whitespace is preserved. # Examples ``` " hello ".trimmedEnd().toOwned(); // " hello" ``` #### function trimmedStart ```kestrel public func trimmedStart() -> StringSlice ``` Returns a zero-copy slice with leading whitespace removed. See `trimmed()` for the whitespace set. Trailing whitespace is preserved. # Examples ``` " hello ".trimmedStart().toOwned(); // "hello " ``` #### function uppercased ```kestrel public func uppercased() -> String ``` Returns the uppercase form using full Unicode case mapping. Locale-independent. Handles multi-character expansions (e.g. `ß` → `SS`). All-ASCII strings with no lowercase letters short-circuit to `toOwned()`. # Examples ``` "hello".uppercased(); // "HELLO" "stra\u{00DF}e".uppercased(); // "STRASSE" ``` #### function uppercasedAscii ```kestrel public func uppercasedAscii() -> String ``` Returns a copy with only ASCII letters uppercased; non-ASCII bytes pass through unchanged. Cheap byte-level scan with no Unicode tables. For full Unicode case mapping, use `uppercased()`. # Examples ``` "h\u{00E9}llo".uppercasedAscii(); // "H\u{00E9}LLO" ``` **Iterable** #### typealias Item ```kestrel type Item = Char ``` The element type yielded by iteration — always `Char`. #### typealias TargetIterator ```kestrel type TargetIterator = CharsIterator ``` The iterator type returned by `iter()`. #### function iter ```kestrel public func iter() -> CharsIterator ``` Returns a `CharsIterator` over the code points starting at byte 0. Required by `Iterable`. Each call returns a fresh iterator; the string itself is reusable. **Equatable** #### typealias Output ```kestrel type Output = Bool ``` #### function equal ```kestrel public func equal(to: Self) -> Bool ``` Bridges `Equal.equal(to:)` to `Equatable.isEqual(to:)`. #### function isEqual ```kestrel public func isEqual(to: String) -> Bool ``` Returns true if both strings have the same byte sequence. Pure byte-wise equality — not normalization-aware. For case-insensitive comparison, see `equalsCaseInsensitive`. # Examples ``` "abc".isEqual(to: "abc"); // true "abc".isEqual(to: "ABC"); // false ``` #### function notEqual ```kestrel public func notEqual(to: Self) -> Bool ``` Default `!=`: delegates to `==` so there's a single source of truth. **Matchable** #### function matches ```kestrel public func matches(String) -> Bool ``` Pattern-match form of `isEqual`: each `case "literal" =>` arm dispatches through here. Cost is `O(len)` per arm because the compiler emits one call per literal — past a handful of arms, E316 will suggest an `if/else if` chain instead. **Comparable** #### typealias Output ```kestrel type Output = Bool ``` #### function compare ```kestrel public func compare(String) -> Ordering ``` Lexicographic byte-wise comparison. Returns `Less` / `Equal` / `Greater` according to the first differing byte; if one string is a prefix of the other, the shorter is less. Byte order coincides with code-point order because UTF-8 is order-preserving — this is *not* the same as locale-aware collation. # Examples ``` "abc".compare("abd"); // Less "abc".compare("ab"); // Greater "abc".compare("abc"); // Equal ``` #### function greaterThan ```kestrel public func greaterThan(Self) -> Bool ``` `>` derived from `compare`. #### function greaterThanOrEqual ```kestrel public func greaterThanOrEqual(Self) -> Bool ``` `>=` derived from `compare`. #### function isAtLeast ```kestrel public func isAtLeast(Self) -> Bool ``` `start..` lower-bound check, derived from `compare`. #### function isAtMost ```kestrel public func isAtMost(Self) -> Bool ``` `..=end` upper-bound check, derived from `compare`. #### function isBelow ```kestrel public func isBelow(Self) -> Bool ``` `.. Bool ``` `<` derived from `compare`. #### function lessThanOrEqual ```kestrel public func lessThanOrEqual(Self) -> Bool ``` `<=` derived from `compare`. **Cloneable** #### function clone ```kestrel public func clone() -> String ``` Returns a shallow clone — storage is shared until either side mutates. O(1). Mutation triggers a deep copy via `CowBox.write()`. **Formattable** #### function format ```kestrel public func format(into: mutating StringBuilder, FormatOptions) ``` Renders this string under the supplied `FormatOptions`. Honours `width`, `alignment`, and `fill`. `precision` / `radix` / `floatStyle` / `sign` are ignored — they don't apply to strings. Aligned padding is measured in *code points*, not bytes, so multi-byte characters count as one column for alignment purposes (display width still depends on font). # Examples ``` var opts = FormatOptions(); opts.width = .Some(10); opts.alignment = .Left; "test".format(opts); // "test " opts.alignment = .Right; "test".format(opts); // " test" opts.alignment = .Center; "test".format(opts); // " test " ``` #### function formatted ```kestrel public func formatted(FormatOptions) -> String ``` Returns this value rendered as a `String`. Convenience wrapper: creates a `StringBuilder`, calls `format(into:)`, and returns the built string. Uses a distinct name to avoid overload-resolution ambiguity with `format(into:)`. **Addable** #### typealias Output ```kestrel type Output = String ``` The output type of `+` (concatenation) — always `String`. #### function add ```kestrel public consuming func add(consuming String) -> String ``` Returns the concatenation `self + other`. Required by `Addable`. When `self` is uniquely owned (refcount 1), appends in place — no allocation. Otherwise builds a fresh string with both halves. #### field zero ```kestrel public static var zero: String { get } ``` The additive identity for strings — the empty string `""`. **ExpressibleByStringLiteral** #### initializer String Literal ```kestrel init(stringLiteral: lang.ptr[lang.i8], lang.i64) ``` Builds an instance from a string literal. **Hashable** #### function hash ```kestrel public func hash[H](into: mutating H) where H: Hasher ``` Hashes the raw byte sequence into the supplied hasher. Sends the whole buffer in a single `write` so the hasher gets to choose how to consume it. **Defaultable** #### initializer Default ```kestrel init() ``` Builds the default-valued instance. **Convertible** #### initializer From Source ```kestrel init(from: From) ``` Creates an instance from `value`. ### struct StringBuilder ```kestrel public struct StringBuilder { /* private fields */ } ``` Write-only buffer for efficient string construction. No COW, no RcBox, no `isUnique` checks — every append writes directly. `build()` transfers ownership of the buffer into a new `String` without copying. The builder resets to empty and can be reused. # Examples ``` var b = StringBuilder(); b.append("hello"); b.append(char: ' '); b.append("world"); let s = b.build(); // "hello world", zero-copy ``` # Representation `(ptr: Pointer[UInt8], len: Int64, cap: Int64)`. # Memory Model Owns its buffer directly. `build()` donates the buffer to a `String`; the builder is left empty. `deinit` frees the buffer if `build()` was never called. #### initializer Empty ```kestrel public init() ``` Creates an empty builder with no allocation. #### initializer With Capacity ```kestrel public init(capacity: Int64) ``` Creates an empty builder with at least `capacity` bytes preallocated. #### function append ```kestrel public mutating func append[__opaque_0](__opaque_0) where __opaque_0: Str ``` Appends the UTF-8 bytes of `other` to this builder. Accepts any type conforming to `Str` — `String`, `StringSlice`, etc. #### function append ```kestrel public mutating func append(char: Char) ``` Appends a single code point, encoding it as UTF-8. #### function appendByte ```kestrel internal mutating func appendByte(UInt8) ``` Appends a raw byte. Caller must ensure UTF-8 validity. #### function appendBytes ```kestrel internal mutating func appendBytes(ptr: Pointer[UInt8], count: Int64) ``` Appends `count` bytes from `ptr`. Caller must ensure UTF-8 validity. #### function build ```kestrel public mutating func build() -> String ``` Transfers the buffer into a new `String` without copying. The builder resets to empty and can be reused. #### field byteCount ```kestrel public var byteCount: Int64 { get } ``` Number of bytes written so far. #### function clear ```kestrel public mutating func clear() ``` Resets length to zero, keeping the allocated buffer for reuse. #### field isEmpty ```kestrel public var isEmpty: Bool { get } ``` True when nothing has been written. **Cloneable** #### function clone ```kestrel public func clone() -> StringBuilder ``` Returns a copy with its own buffer. ### protocol StringIndex ```kestrel public protocol StringIndex ``` Protocol for typed string indices. Each index wraps a pre-resolved byte offset; the type tag determines what unit the index addresses and what the subscript returns. #### typealias Yield ```kestrel type Yield ``` #### function read ```kestrel func read(from: StringSlice) -> Yield ``` **Equatable** #### typealias Output ```kestrel type Output = Bool ``` #### function equal ```kestrel public func equal(to: Self) -> Bool ``` Bridges `Equal.equal(to:)` to `Equatable.isEqual(to:)`. #### function isEqual ```kestrel func isEqual(to: Self) -> Bool ``` Returns `true` iff `self` and `other` are considered equal. Should be reflexive, symmetric, and transitive — `Hashable` requires equal values to hash equal, so don't drift from those laws. #### function notEqual ```kestrel public func notEqual(to: Self) -> Bool ``` Default `!=`: delegates to `==` so there's a single source of truth. **Comparable** #### typealias Output ```kestrel type Output = Bool ``` #### function compare ```kestrel func compare(Self) -> Ordering ``` Returns the ordering of `self` relative to `other`. Must be a total order — for any `a`, `b`, `c` exactly one of `Less`, `Equal`, `Greater` holds, and the order is transitive. #### function greaterThan ```kestrel public func greaterThan(Self) -> Bool ``` `>` derived from `compare`. #### function greaterThanOrEqual ```kestrel public func greaterThanOrEqual(Self) -> Bool ``` `>=` derived from `compare`. #### function isAtLeast ```kestrel public func isAtLeast(Self) -> Bool ``` `start..` lower-bound check, derived from `compare`. #### function isAtMost ```kestrel public func isAtMost(Self) -> Bool ``` `..=end` upper-bound check, derived from `compare`. #### function isBelow ```kestrel public func isBelow(Self) -> Bool ``` `.. Bool ``` `<` derived from `compare`. #### function lessThanOrEqual ```kestrel public func lessThanOrEqual(Self) -> Bool ``` `<=` derived from `compare`. ### struct StringSlice ```kestrel public struct StringSlice { /* private fields */ } ``` An immutable window into a `String`'s UTF-8 bytes with shared ownership. The central read-only abstraction of the text library. Zero-cost to create from a String (share the RcBox, cover the whole range). Zero-cost to narrow (adjust start/end). Keeps the source alive as long as the slice exists. # Examples ``` let s = "hello, world"; let slice = s.asSlice(); slice.byteCount; // 12 slice.toOwned(); // "hello, world" ``` # Representation `(source: RcBox[StringStorage], start: Int64, end: Int64)`. # Memory Model Shared ownership via `RcBox`. The source string's buffer stays alive as long as any slice references it. Call `.toOwned()` to copy just the slice's bytes into an independent `String`. #### initializer From Source ```kestrel public init(source: RcBox[StringStorage], start: Int64, end: Int64) ``` Creates a slice covering `[start, end)` in the given storage. #### function _rawPtr ```kestrel func _rawPtr() -> Pointer[UInt8] ``` #### function _readByte ```kestrel func _readByte(at: Int64) -> UInt8 ``` #### field byteCount ```kestrel public var byteCount: Int64 { get } ``` Number of UTF-8 bytes in this slice. O(1). #### field end ```kestrel public var end: Int64 ``` #### field isEmpty ```kestrel public var isEmpty: Bool { get } ``` True when the slice covers zero bytes. #### field source ```kestrel var source: RcBox[StringStorage] ``` #### field start ```kestrel public var start: Int64 ``` #### function subslice ```kestrel public func subslice(from: Int64, to: Int64) -> StringSlice ``` Returns a sub-slice covering `[newStart, newEnd)` relative to the source buffer (absolute byte offsets, not relative to this slice's start). #### function toOwned ```kestrel public func toOwned() -> String ``` Copies just this slice's bytes into a new independent `String`. **Str** #### function asSlice ```kestrel public func asSlice() -> StringSlice ``` Returns self — StringSlice is already a slice. #### field byteCount ```kestrel public var byteCount: Int64 { get } ``` Number of UTF-8 bytes. O(1). # Examples ``` "hello".byteCount; // 5 "\u{00E9}".byteCount; // 2 (é is two UTF-8 bytes) ``` #### field bytes ```kestrel public var bytes: BytesView { get } ``` View over the raw UTF-8 bytes. # Examples ``` "hi".bytes.count; // 2 ``` #### function caseFolded ```kestrel public func caseFolded() -> String ``` Returns a new string with Unicode case folding applied to each code point. Case folding maps characters to a canonical form suitable for case-insensitive comparison. Currently single-char folds only (e.g. `A` → `a`); multi-char expansions like `ß` → `ss` are not yet supported. # Examples ``` "Hello".caseFolded(); // "hello" ``` #### field chars ```kestrel public var chars: CharsView { get } ``` View over Unicode code points. # Examples ``` "caf\u{00E9}".chars.count; // 4 ``` #### function compare ```kestrel public func compare(Self) -> Ordering ``` Lexicographic byte-wise comparison. Returns `Less` / `Equal` / `Greater` according to the first differing byte; if one string is a prefix of the other, the shorter is less. # Examples ``` "abc".compare("abd"); // Less "abc".compare("ab"); // Greater ``` #### function contains ```kestrel public func contains(String) -> Bool ``` Returns true if `substring` appears anywhere in this string. # Examples ``` "hello world".contains(substring: "world"); // true "hello world".contains(substring: "xyz"); // false ``` #### function ends ```kestrel public func ends(with: String) -> Bool ``` Returns true if this string ends with `suffix`. Empty suffix always returns true. Comparison is byte-wise. # Examples ``` "hello".ends(with: "llo"); // true "hello".ends(with: "xyz"); // false ``` #### function equalsCaseInsensitive ```kestrel public func equalsCaseInsensitive(String) -> Bool ``` Compares two strings for equality after Unicode case folding. Folds each string to its case-folded form and compares the results byte-wise. Not normalization-aware — `é` (`U+00E9`) and `e\u{0301}` are still considered different. # Examples ``` "Hello".equalsCaseInsensitive("HELLO"); // true "Hello".equalsCaseInsensitive("World"); // false ``` #### function firstIndex ```kestrel public func firstIndex(of: String) -> ByteIndex? ``` Returns the byte index of the first occurrence of `substring`, or `None` if not found. The empty substring matches at the start. Uses `memmem` for efficient byte-level search. # Examples ``` "hello world".firstIndex(of: "world"); // Some(ByteIndex(6)) "hello world".firstIndex(of: "xyz"); // None ``` #### function format ```kestrel public func format(into: mutating StringBuilder, FormatOptions) ``` Formats the string using the given options. # Examples ``` "hi".format(FormatOptions(width: 5)); // "hi " ``` #### field graphemes ```kestrel public var graphemes: GraphemesView { get } ``` View over grapheme clusters (user-perceived characters). # Examples ``` "caf\u{00E9}".graphemes.count; // 4 ``` #### function hash ```kestrel public func hash[H](into: mutating H) where H: Hasher ``` Hashes the byte content into `hasher`. #### field isEmpty ```kestrel public var isEmpty: Bool { get } ``` True when the string contains no bytes. # Examples ``` "".isEmpty; // true "hello".isEmpty; // false ``` #### function isEqual ```kestrel public func isEqual(to: Self) -> Bool ``` Returns true if both strings have the same byte sequence. Pure byte-wise equality — not normalization-aware. For case-insensitive comparison, see `equalsCaseInsensitive`. # Examples ``` "abc".isEqual(to: "abc"); // true "abc".isEqual(to: "ABC"); // false ``` #### function iter ```kestrel public func iter() -> CharsIterator ``` Returns a `CharsIterator` over the code points. Required by `Iterable`. Each call returns a fresh iterator; the source is reusable. # Examples ``` for c in "abc" { ... } // iterates 'a', 'b', 'c' ``` #### function lastIndex ```kestrel public func lastIndex(of: String) -> ByteIndex? ``` Returns the byte index of the last occurrence of `substring`, or `None` if not found. Scans from the left using repeated `memmem` calls, keeping the last match position. # Examples ``` "abcabc".lastIndex(of: "abc"); // Some(ByteIndex(3)) "abcabc".lastIndex(of: "xyz"); // None ``` #### field lines ```kestrel public var lines: LinesView { get } ``` View over lines, recognising `\n`, `\r\n`, and `\r`. # Examples ``` "a\nb\nc".lines.count; // 3 ``` #### function lowercased ```kestrel public func lowercased() -> String ``` Returns the lowercase form using full Unicode case mapping. Locale-independent. Handles multi-character expansions (e.g. Turkish dotted I). All-ASCII strings with no uppercase letters short-circuit to `toOwned()` (no per-char decode). # Examples ``` "Hello".lowercased(); // "hello" "\u{0130}".lowercased(); // "i\u{0307}" ``` #### function lowercasedAscii ```kestrel public func lowercasedAscii() -> String ``` Returns a copy with only ASCII letters lowercased; non-ASCII bytes pass through unchanged. Cheap byte-level scan with no Unicode tables. For full Unicode case mapping, use `lowercased()`. # Examples ``` "H\u{00E9}LLO".lowercasedAscii(); // "h\u{00E9}llo" ``` #### function pad ```kestrel public func pad(leading: Int64, with: Char) -> String ``` Returns the string padded at the start with `char` so the total *code-point* count is at least `length`. If the string is already at least `length` code points long, returns a copy unchanged. # Examples ``` "42".pad(leading: 5, with: '0'); // "00042" ``` #### function repeated ```kestrel public func repeated(Int64) -> String ``` Returns this string concatenated with itself `count` times. Non-positive `count` returns the empty string. Pre-allocates the result buffer for the exact final length. # Examples ``` "ab".repeated(3); // "ababab" "ab".repeated(0); // "" ``` #### function replaced ```kestrel public func replaced(String, with: String) -> String ``` Returns a copy with every occurrence of `pattern` replaced by `replacement`. Empty `pattern` is a no-op (returns a copy). Searches greedily from the left and skips past each replacement so substituted text is not re-matched. # Examples ``` "hello world".replaced("o", with: "0"); // "hell0 w0rld" "abcabc".replaced("ab", with: "ABCD"); // "ABCDcABCDc" ``` #### function split ```kestrel public func split(String) -> SplitView ``` Returns a lazy view that splits on `separator`, yielding zero-copy `StringSlice` segments. The empty separator is special-cased to split per code point. Adjacent separators produce empty segments. # Examples ``` "a,b,c".split(",").collect(); // ["a", "b", "c"] "a,,b".split(",").count; // 3 (empty segment preserved) ``` #### function starts ```kestrel public func starts(with: String) -> Bool ``` Returns true if this string starts with `prefix`. Empty prefix always returns true. Comparison is byte-wise. # Examples ``` "hello".starts(with: "hel"); // true "hello".starts(with: "xyz"); // false ``` #### function titlecased ```kestrel public func titlecased() -> String ``` Returns the titlecase form using full Unicode case mapping. Word boundaries are detected by `Char.isWhitespace`; the first non-space character of each run is titlecased and the rest lowercased. # Examples ``` "hello world".titlecased(); // "Hello World" "FOO BAR".titlecased(); // "Foo Bar" ``` #### function toOwned ```kestrel public func toOwned() -> String ``` Copies this string's bytes into a new independent `String`. For `String`, this is equivalent to `clone()`. For `StringSlice`, it copies only the slice's bytes, releasing the reference to the source buffer. # Examples ``` let slice = "hello world".asSlice(); let owned = slice.toOwned(); // independent copy ``` #### function trimmed ```kestrel public func trimmed() -> StringSlice ``` Returns a zero-copy slice with leading and trailing ASCII whitespace removed. Whitespace characters: space (`' '`), tab (`'\t'`), newline (`'\n'`), carriage return (`'\r'`), and form feed (`'\x0C'`). The returned `StringSlice` shares the source buffer — no allocation occurs. # Examples ``` " hello ".trimmed().toOwned(); // "hello" "\t\n".trimmed().isEmpty; // true ``` #### function trimmedEnd ```kestrel public func trimmedEnd() -> StringSlice ``` Returns a zero-copy slice with trailing whitespace removed. See `trimmed()` for the whitespace set. Leading whitespace is preserved. # Examples ``` " hello ".trimmedEnd().toOwned(); // " hello" ``` #### function trimmedStart ```kestrel public func trimmedStart() -> StringSlice ``` Returns a zero-copy slice with leading whitespace removed. See `trimmed()` for the whitespace set. Trailing whitespace is preserved. # Examples ``` " hello ".trimmedStart().toOwned(); // "hello " ``` #### function uppercased ```kestrel public func uppercased() -> String ``` Returns the uppercase form using full Unicode case mapping. Locale-independent. Handles multi-character expansions (e.g. `ß` → `SS`). All-ASCII strings with no lowercase letters short-circuit to `toOwned()`. # Examples ``` "hello".uppercased(); // "HELLO" "stra\u{00DF}e".uppercased(); // "STRASSE" ``` #### function uppercasedAscii ```kestrel public func uppercasedAscii() -> String ``` Returns a copy with only ASCII letters uppercased; non-ASCII bytes pass through unchanged. Cheap byte-level scan with no Unicode tables. For full Unicode case mapping, use `uppercased()`. # Examples ``` "h\u{00E9}llo".uppercasedAscii(); // "H\u{00E9}LLO" ``` **Equatable** #### typealias Output ```kestrel type Output = Bool ``` #### function equal ```kestrel public func equal(to: Self) -> Bool ``` Bridges `Equal.equal(to:)` to `Equatable.isEqual(to:)`. #### function isEqual ```kestrel public func isEqual(to: StringSlice) -> Bool ``` #### function notEqual ```kestrel public func notEqual(to: Self) -> Bool ``` Default `!=`: delegates to `==` so there's a single source of truth. **Comparable** #### typealias Output ```kestrel type Output = Bool ``` #### function compare ```kestrel public func compare(StringSlice) -> Ordering ``` #### function greaterThan ```kestrel public func greaterThan(Self) -> Bool ``` `>` derived from `compare`. #### function greaterThanOrEqual ```kestrel public func greaterThanOrEqual(Self) -> Bool ``` `>=` derived from `compare`. #### function isAtLeast ```kestrel public func isAtLeast(Self) -> Bool ``` `start..` lower-bound check, derived from `compare`. #### function isAtMost ```kestrel public func isAtMost(Self) -> Bool ``` `..=end` upper-bound check, derived from `compare`. #### function isBelow ```kestrel public func isBelow(Self) -> Bool ``` `.. Bool ``` `<` derived from `compare`. #### function lessThanOrEqual ```kestrel public func lessThanOrEqual(Self) -> Bool ``` `<=` derived from `compare`. **Hashable** #### function hash ```kestrel public func hash[H](into: mutating H) where H: Hasher ``` **Cloneable** #### function clone ```kestrel public func clone() -> StringSlice ``` **Formattable** #### function format ```kestrel public func format(into: mutating StringBuilder, FormatOptions) ``` #### function formatted ```kestrel public func formatted(FormatOptions) -> String ``` Returns this value rendered as a `String`. Convenience wrapper: creates a `StringBuilder`, calls `format(into:)`, and returns the built string. Uses a distinct name to avoid overload-resolution ambiguity with `format(into:)`. **Iterable** #### typealias Item ```kestrel type Item = Char ``` #### typealias TargetIterator ```kestrel type TargetIterator = CharsIterator ``` #### function iter ```kestrel public func iter() -> CharsIterator ``` Iterates code points in this slice. ### struct Utf8DecodeResult ```kestrel public struct Utf8DecodeResult { /* private fields */ } ``` The output of decoding one UTF-8 character from a byte buffer. Carries both the decoded `Char` and the number of bytes consumed, so the caller can advance their cursor without re-running `utf8Length()`. Returned as `Some` from `decodeUtf8`; `None` indicates an invalid or truncated sequence. # Examples ``` let r = Utf8DecodeResult(char: 'a', bytesConsumed: 1); r.char; // 'a' r.bytesConsumed; // 1 ``` # Representation A plain pair `(char: Char, bytesConsumed: Int64)`. Both fields are public to keep the type cheap to inspect. #### initializer From Fields ```kestrel public init(char: Char, bytesConsumed: Int64) ``` Constructs a decode result from an already-decoded char and byte length. Mainly used by `decodeUtf8` itself; user code rarely needs to build one directly. #### field bytesConsumed ```kestrel public var bytesConsumed: Int64 ``` How many bytes the encoded form occupied (1–4). #### field char ```kestrel public var char: Char ``` The decoded character. ### function _writePadded ```kestrel public func _writePadded(into: mutating StringBuilder, String, FormatOptions) ``` Writes `content` into `writer` with width/alignment/fill padding applied. Used by String, integer, and float `format(into:)` implementations. ### function decodeUtf8 ```kestrel public func decodeUtf8(lang.ptr[lang.i8], Int64, at: Int64) -> Utf8DecodeResult? ``` Decodes one UTF-8 character starting at `index` inside the buffer of `length` bytes pointed to by `ptr`. Returns `Some(Utf8DecodeResult)` on success, where `bytesConsumed` is `1`–`4`. Returns `None` for any of the malformed-input cases: truncated multi-byte sequence, continuation byte where a leading byte was expected, or invalid leading byte (`0xF8`–`0xFF`). **Does not** validate against overlong encodings or surrogate-range scalars — feed only well-formed UTF-8 if those matter. # Safety `ptr` must be valid for `length` bytes. The function bounds-checks `index` and any continuation bytes against `length`. # Examples ``` var result = String("hé"); // Conceptually: // decodeUtf8(rawPtr, 3, at: 0) // Some(char: 'h', bytesConsumed: 1) // decodeUtf8(rawPtr, 3, at: 1) // Some(char: 'é', bytesConsumed: 2) // decodeUtf8(rawPtr, 3, at: 3) // None (past the end) ``` ### function encodeUtf8 ```kestrel public func encodeUtf8(Char, lang.ptr[lang.i8], at: Int64) -> Int64 ``` Encodes `c` as UTF-8 starting at `ptr + index`, returning the number of bytes written (1–4). Companion of `decodeUtf8`. `c.utf8Length()` predicts the same byte count without writing — call it first to ensure the buffer has room. # Safety `ptr + index` through `ptr + index + utf8Length() - 1` must lie within an allocated, writable region. No bounds checking happens here. # Examples ``` // Conceptually, given a buffer `buf` of length 4: // encodeUtf8('a', buf, at: 0); // 1 // encodeUtf8('\u{1F600}', buf, at: 0); // 4 ``` --- ## std.text.unicode ### enum GraphemeBreakProperty ```kestrel public enum GraphemeBreakProperty ``` One of the UAX #29 Grapheme_Cluster_Break property values. Returned by `graphemeBreakProperty(c:)` and consumed by `shouldBreakBetween(...)`. Variant names match the Unicode property labels — see UAX #29 for the precise definitions and the boundary rules (GB1–GB999) that consume them. # Representation A 14-state tag enum (no payload). `ordinal()` gives the numeric encoding used by the stage-2 lookup table. #### case CR ```kestrel case CR ``` Carriage Return (`U+000D`). #### case Control ```kestrel case Control ``` Other control characters that always force a break. #### case Extend ```kestrel case Extend ``` Combining marks and other extending characters. #### case L ```kestrel case L ``` Hangul leading consonant jamo (L). #### case LF ```kestrel case LF ``` Line Feed (`U+000A`). #### case LV ```kestrel case LV ``` Hangul precomposed LV syllable. #### case LVT ```kestrel case LVT ``` Hangul precomposed LVT syllable. #### case Other ```kestrel case Other ``` Default class — anything not in another category. #### case Prepend ```kestrel case Prepend ``` Prepended concatenation marks. #### case RegionalIndicator ```kestrel case RegionalIndicator ``` Regional Indicator codepoints (used to form flag emoji in pairs). #### case SpacingMark ```kestrel case SpacingMark ``` Spacing combining marks. #### case T ```kestrel case T ``` Hangul trailing consonant jamo (T). #### case V ```kestrel case V ``` Hangul vowel jamo (V). #### case ZWJ ```kestrel case ZWJ ``` Zero Width Joiner (`U+200D`). #### function ordinal ```kestrel func ordinal() -> Int32 ``` **Equatable** #### typealias Output ```kestrel type Output = Bool ``` #### function equal ```kestrel public func equal(to: Self) -> Bool ``` Bridges `Equal.equal(to:)` to `Equatable.isEqual(to:)`. #### function isEqual ```kestrel public func isEqual(to: GraphemeBreakProperty) -> Bool ``` Equality by ordinal — same variant, same value. #### function notEqual ```kestrel public func notEqual(to: Self) -> Bool ``` Default `!=`: delegates to `==` so there's a single source of truth. **Matchable** #### function matches ```kestrel public func matches(GraphemeBreakProperty) -> Bool ``` Match form of `isEqual` for use in pattern matching. ### function caseFold ```kestrel public func caseFold(Char) -> Char ``` Single-codepoint case fold for `c`. Use when comparing characters case-insensitively: `caseFold(a) == caseFold(b)` is the canonical per-character equality test. For codepoints whose Unicode fold is multi-codepoint (e.g. `ß → ss`), this returns only the first folded codepoint — see `caseFoldExpansion` for the full sequence. # Examples ``` caseFold('A') // 'a' caseFold('İ') // 'i' — see caseFoldExpansion for "i\u{307}" caseFold('a') == caseFold('A') // true ``` ### function caseFoldExpansion ```kestrel public func caseFoldExpansion(Char) -> String ``` Full Unicode case fold of `c` as a `String`. Returns `""` when `c` has no multi-codepoint fold — pair with `hasCaseFoldExpansion`, or fall back to `caseFold` for the single-codepoint form. # Examples ``` caseFoldExpansion('ß') // "ss" caseFoldExpansion('ffi') // "ffi" caseFoldExpansion('a') // "" (no expansion; caseFold('a') == 'a') ``` ### function graphemeBreakProperty ```kestrel public func graphemeBreakProperty(Char) -> GraphemeBreakProperty ``` Looks up the UAX #29 Grapheme_Cluster_Break property for `c`. O(1) — two array indexings into the trie. Codepoints above `U+10FFFF` (which are not valid Unicode scalars) yield `.Other`. # Examples ``` graphemeBreakProperty('a') // .Other graphemeBreakProperty('\r') // .CR graphemeBreakProperty('\u{200D}') // .ZWJ ``` ### function hasCaseFoldExpansion ```kestrel public func hasCaseFoldExpansion(Char) -> Bool ``` `true` iff folding `c` produces more than one codepoint. Linear scan over `FOLD_EXPANSIONS` (~100 entries) — fine per-character but quadratic if applied across a large set. ### function hasLowercaseExpansion ```kestrel public func hasLowercaseExpansion(Char) -> Bool ``` `true` iff lowercasing `c` produces more than one codepoint. Same scan caveats as `hasUppercaseExpansion`. ### function hasTitlecaseExpansion ```kestrel public func hasTitlecaseExpansion(Char) -> Bool ``` `true` iff titlecasing `c` produces more than one codepoint. ### function hasUppercaseExpansion ```kestrel public func hasUppercaseExpansion(Char) -> Bool ``` `true` iff uppercasing `c` produces more than one codepoint. Linear scan over `UPPER_EXPANSIONS` (~100 entries); fine for per-character calls in normal text but quadratic if applied to a large codepoint set. ### function lowercaseExpansion ```kestrel public func lowercaseExpansion(Char) -> String ``` Full Unicode lowercase expansion for `c`. Empty string when no multi-codepoint expansion applies — see `uppercaseExpansion` for the same shape. ### function shouldBreakBetween ```kestrel public func shouldBreakBetween(GraphemeBreakProperty, GraphemeBreakProperty, Bool, Bool) -> Bool ``` Decides whether a grapheme cluster boundary lies between two adjacent codepoints with the given break properties. Implements the UAX #29 boundary rules GB3–GB13/GB999. The caller must thread two scalar bits across calls to capture rules that look further back than one codepoint: - `prevPrevWasRI`: was the codepoint *before* `prev` a Regional_Indicator? Needed to keep regional-indicator pairs together while still breaking between successive pairs (GB12/13). - `prevWasZWJ`: was the codepoint before `prev` a ZWJ? Needed for the simplified emoji ZWJ-sequence rule (GB11). Returns `true` to break (start a new cluster at `curr`), `false` to keep `prev` and `curr` in the same cluster. ### function titlecaseExpansion ```kestrel public func titlecaseExpansion(Char) -> String ``` Full Unicode titlecase expansion for `c`. Empty string when no multi-codepoint expansion applies. ### function toLowercase ```kestrel public func toLowercase(Char) -> Char ``` Single-codepoint lowercase mapping for `c`. Same caveats as `toUppercase`: codepoints with multi-char lowercase forms return only the first codepoint — see `lowercaseExpansion`. ### function toTitlecase ```kestrel public func toTitlecase(Char) -> Char ``` Single-codepoint titlecase mapping for `c`. Differs from `toUppercase` only for the codepoints (mostly Greek/Croatian digraphs) where Unicode defines a distinct "Title" form. Multi-char expansions live in `titlecaseExpansion`. ### function toUppercase ```kestrel public func toUppercase(Char) -> Char ``` Single-codepoint uppercase mapping for `c`. Falls back to `c` for characters with no mapping and for codepoints above `U+10FFFF`. For characters whose Unicode uppercase form expands to multiple codepoints (e.g. `ß → SS`, `fi → FI`), this returns only the first codepoint of the expansion. Use `hasUppercaseExpansion(c:)` to detect the multi-char case and `uppercaseExpansion(c:)` to retrieve the full `String`. # Examples ``` toUppercase('a') // 'A' toUppercase('ß') // 'S' — see uppercaseExpansion for "SS" toUppercase('1') // '1' — no mapping ``` ### field unicodeVersion ```kestrel public let unicodeVersion: String ``` Unicode version these tables track. Bump alongside the regeneration of the underlying `data/*.bin` files. ### function uppercaseExpansion ```kestrel public func uppercaseExpansion(Char) -> String ``` Full Unicode uppercase expansion for `c` as a `String`. Returns the empty string when `c` has no multi-codepoint expansion — pair with `hasUppercaseExpansion` (or call `toUppercase` instead) to avoid the scan when you only need the single-codepoint form. # Examples ``` uppercaseExpansion('ß') // "SS" uppercaseExpansion('fi') // "FI" uppercaseExpansion('a') // "" (use toUppercase for 'A') ``` # Packages ## kestrel/quill-toml 0.2.4 # Quill-TOML TOML support for the quill serialization framework. ## Installation ```toml [dependencies] kestrel/quill = "0.1.0" kestrel/quill-toml = "0.1.0" ``` ## Usage ```kestrel // Encode a Value to TOML let value = Value.Obj([ ("name", Value.Str("my-package")), ("version", Value.Str("0.1.0")) ]) let tomlStr = try Toml().encode(value: value) // Decode TOML to a Value let parsed = try Toml().decode(source: "name = \"my-package\"\nversion = \"0.1.0\"") // Convenience function for Serialize types let output = try toToml(value: mySerializableValue) ``` ## Key Types - **Toml** - implements the quill `Format` protocol for TOML - **TomlParseError** - parsing failure with line number - Content type: `application/toml` ## Functions - `toToml(value:)` - serialize any `Serialize` type to TOML ## Features - Standard `[section]` tables - Bare and quoted keys - Integers, floats (with `inf`/`nan`), booleans - Inline arrays and inline tables - Comment stripping - Underscore separators in numbers ## quill ## quill.toml.emitter ### function emitToml ```kestrel public func emitToml(Value) -> Result[String, SerializeError] ``` Converts a `Value` to a TOML string. The root must be `.Obj`; any other variant produces a `SerializeError`. Sub-objects become `[section]` tables; nested objects within those become dotted section headers (e.g., `[package.dependencies]`). # Examples ``` let v = Value.Obj([("name", Value.Str("hello")), ("version", Value.Str("1.0"))]); let s = try emitToml(v); // "name = \"hello\"\nversion = \"1.0\"\n" ``` # Errors Returns `.Err` if the root value is not `.Obj`. ## quill.toml.parser ### function parseToml ```kestrel public func parseToml(String) -> Result[Value, TomlParseError] ``` Parses a TOML document into a `Value.Obj`. Processes the source line-by-line. Lines beginning with `[` are table headers; other non-empty, non-comment lines are key-value pairs inserted into the current table. # Examples ``` let v = try parseToml("[package]\nname = \"hello\""); // v == Value.Obj([("package", Value.Obj([("name", Value.Str("hello"))]))]) ``` # Errors Returns `TomlParseError` for syntax violations, with a line number pointing at the problem line. ## quill.toml ### struct Toml ```kestrel public struct Toml { /* private fields */ } ``` TOML serialization format for use with the quill `Format` protocol. `Toml` is a stateless type whose static methods convert between `Value` and TOML text. The top-level value must be a `.Obj` — TOML documents are always key-value tables at the root. Encoding can fail if the root value is not an object. Decoding can fail on syntax errors; the error carries a line number. # Examples ``` let v = Value.Obj([("debug", Value.Boolean(true))]); let toml = try Toml.encode(value: v); // "debug = true\n" let back = try Toml.decode(source: toml); // v ``` #### function contentType ```kestrel public static func contentType() -> String ``` Returns the MIME content type for TOML: `"application/toml"`. #### function decode ```kestrel public static func decode(String) -> Result[Value, DeserializeError] ``` Decodes a TOML string into a `Value`. Returns a `DeserializeError` if the input contains unsupported TOML features or syntax violations. The underlying `TomlParseError` carries the line number; that detail is folded into the error description. #### function encode ```kestrel public static func encode(Value) -> Result[String, SerializeError] ``` Encodes a `Value` to a TOML string. The value must be `.Obj` at the top level (TOML requires a root table). Returns a `SerializeError` if the root is any other variant. ### function toToml ```kestrel public func toToml[T](T) -> Result[String, SerializeError] where T: Serialize ``` Serializes any `Serialize` value to a TOML string. Combines `value.toValue()` and `emitToml` in a single call. The serialized `Value` must be a root `.Obj`; other shapes produce an error. # Examples ``` let toml = try toToml(value: myConfig); ``` ## quill.toml.error ### struct TomlParseError ```kestrel public struct TomlParseError { /* private fields */ } ``` A syntax error encountered while parsing a TOML string. Carries a human-readable `message` describing what went wrong and the 1-based `line` number where the parser stopped. Use `description()` to format both into a single diagnostic string. # Representation Two fields: `message` (a short explanation like "expected '=' in key-value pair") and `line` (the 1-based source line number). # Examples ``` let err = TomlParseError("unterminated table header", 5); err.description(); // "TOML parse error at line 5: unterminated table header" ``` #### initializer Default ```kestrel public init(String, Int64) ``` Creates an error with the given message and line number. #### function clone ```kestrel public func clone() -> TomlParseError ``` Returns a deep copy of this error. #### function description ```kestrel public func description() -> String ``` Formats the error as `"TOML parse error at line : "`. #### field line ```kestrel public var line: Int64 ``` 1-based line number in the source where parsing failed. #### field message ```kestrel public var message: String ``` Short explanation of the syntax violation. --- ## kestrel/jessup 0.2.2 ## jessup.main ## jessup.github ### struct Release ```kestrel public struct Release { /* private fields */ } ``` A GitHub release with its tag and matching asset URL. #### field assetUrl ```kestrel public var assetUrl: String ``` #### function clone ```kestrel public func clone() -> Release ``` #### initializer init ```kestrel public init(tagName: String, assetUrl: String) ``` #### field tagName ```kestrel public var tagName: String ``` ### function fetchAllReleases ```kestrel public func fetchAllReleases() -> Result[Array[String], JessupError] ``` Fetches all available release tags from GitHub. ### function fetchJessupRelease ```kestrel public func fetchJessupRelease(platform: Platform) -> Result[String, JessupError] ``` Fetches the latest jessup binary URL for self-update. ### function fetchRelease ```kestrel public func fetchRelease(channel: String, platform: Platform) -> Result[Release, JessupError] ``` Fetches the latest release matching the given channel and platform. For "stable": finds the latest non-prerelease release. For "nightly": finds the latest release tagged "nightly". For a specific version like "1.0.0": finds that exact tag. ### function fetchVsixRelease ```kestrel public func fetchVsixRelease(channel: String, platform: Platform) -> Result[String, JessupError] ``` Fetches the VS Code extension (.vsix) URL for the given platform from the latest release. ## jessup.platform ### struct Platform ```kestrel public struct Platform { /* private fields */ } ``` Represents the current platform (OS + architecture). #### field arch ```kestrel public var arch: String ``` #### function assetTarget ```kestrel public func assetTarget() -> String ``` Returns the asset suffix for this platform. e.g., "aarch64-apple-darwin" or "x86_64-unknown-linux" #### function clone ```kestrel public func clone() -> Platform ``` #### initializer init ```kestrel public init(os: String, arch: String) ``` #### field os ```kestrel public var os: String ``` #### function vsceTarget ```kestrel public func vsceTarget() -> String ``` Returns the VS Code extension target name for this platform. e.g., "darwin-arm64" or "linux-x64" ### function detectPlatform ```kestrel public func detectPlatform() -> Result[Platform, JessupError] ``` Detects the current platform from uname. ## jessup.toolchain ### function installEditorExtension ```kestrel public func installEditorExtension(channel: String, platform: Platform) ``` Attempts to install the Kestrel VS Code extension (.vsix) into any detected editor (VS Code, Cursor, or codium). Silently skips if no supported editor CLI is found or the VSIX isn't available. ### function installToolchain ```kestrel public func installToolchain(channel: String) -> Result[String, JessupError] ``` Installs a toolchain for the given channel. channel can be "stable", "nightly", or a specific version like "1.0.0". ### function listToolchains ```kestrel public func listToolchains() -> Result[(), JessupError] ``` Lists all installed toolchains. Marks the active one. ### function removeToolchain ```kestrel public func removeToolchain(toolchainName: String) -> Result[(), JessupError] ``` Removes an installed toolchain. ### function selfUpdate ```kestrel public func selfUpdate() -> Result[(), JessupError] ``` Updates jessup itself to the latest version. ### function setDefault ```kestrel public func setDefault(toolchainName: String) -> Result[(), JessupError] ``` Sets the default toolchain by updating symlinks in ~/.jessup/bin/. ### function showActive ```kestrel public func showActive() -> Result[(), JessupError] ``` Shows the active toolchain and its path. ### function updateToolchains ```kestrel public func updateToolchains() -> Result[(), JessupError] ``` Updates all installed channel toolchains (stable, nightly) to their latest versions. ## jessup.config ### struct JessupConfig ```kestrel public struct JessupConfig { /* private fields */ } ``` Configuration stored in ~/.jessup/config.toml. #### function clone ```kestrel public func clone() -> JessupConfig ``` #### field defaultChannel ```kestrel public var defaultChannel: String ``` The default toolchain channel (e.g., "stable", "nightly"). #### initializer init ```kestrel public init(defaultChannel: String) ``` ### function binDir ```kestrel public func binDir() -> Result[String, JessupError] ``` Returns the path to the bin directory (~/.jessup/bin/). ### function configPath ```kestrel public func configPath() -> Result[String, JessupError] ``` Returns the path to config.toml (~/.jessup/config.toml). ### function ensureDirectories ```kestrel public func ensureDirectories() -> Result[(), JessupError] ``` Ensures all jessup directories exist. ### function jessupHome ```kestrel public func jessupHome() -> Result[String, JessupError] ``` Returns the jessup home directory. Uses JESSUP_HOME env var if set, otherwise defaults to ~/.jessup. ### function readConfig ```kestrel public func readConfig() -> JessupConfig ``` Reads the jessup config from disk. Returns a default config if the file doesn't exist or can't be parsed. ### function toolchainsDir ```kestrel public func toolchainsDir() -> Result[String, JessupError] ``` Returns the path to the toolchains directory (~/.jessup/toolchains/). ### function writeConfig ```kestrel public func writeConfig(config: JessupConfig) -> Result[(), JessupError] ``` Writes the config to disk. ## jessup.error ### enum JessupError ```kestrel public enum JessupError ``` All error conditions that can occur in jessup operations. #### case ConfigError ```kestrel case ConfigError(String) ``` #### case InstallError ```kestrel case InstallError(String) ``` #### case IoError ```kestrel case IoError(String) ``` #### case NetworkError ```kestrel case NetworkError(String) ``` #### case NotFound ```kestrel case NotFound(String) ``` #### case ParseError ```kestrel case ParseError(String) ``` #### function clone ```kestrel public func clone() -> JessupError ``` #### function description ```kestrel public func description() -> String ``` Returns a human-readable description of the error. ## jessup --- ## kestrel/flock 0.2.2 ## flock.registry ### struct RegistryConfig ```kestrel public struct RegistryConfig { /* private fields */ } ``` Configuration for connecting to a package registry. #### function clone ```kestrel public func clone() -> RegistryConfig ``` #### initializer init ```kestrel public init(url: String) ``` #### field url ```kestrel public var url: String ``` ### function isRegistryName ```kestrel public func isRegistryName(name: String) -> Bool ``` Returns true if the name contains a slash (i.e., is an org/pkg name). ### function resolveRegistryUrl ```kestrel public func resolveRegistryUrl(projectUrl: Optional[String]) -> String ``` Resolves the registry URL using three-tier lookup: 1. Project-level override (from flock.toml [registry] section) 2. Global config (~/.kestrel/config.toml) 3. Hardcoded default ### function splitPackageName ```kestrel public func splitPackageName(name: String) -> Optional[(String, String)] ``` Splits "org/pkg" into (org, pkg). Returns None if no slash found. ## flock.manifest ### struct BuildConfig ```kestrel public struct BuildConfig { /* private fields */ } ``` Build configuration from the [build] section of flock.toml. #### field cFlags ```kestrel public var cFlags: Array[String] ``` Flags passed to cc when compiling C sources. #### field cFlagsCmd ```kestrel public var cFlagsCmd: Optional[String] ``` Shell command whose stdout provides additional C flags. #### field cSources ```kestrel public var cSources: Array[String] ``` C source files to compile (relative to package root). #### function clone ```kestrel public func clone() -> BuildConfig ``` #### field frameworks ```kestrel public var frameworks: Array[String] ``` macOS frameworks (become --framework flags). #### initializer init ```kestrel public init() ``` #### field link ```kestrel public var link: Array[String] ``` Library names to link (become -l flags). #### field linkCmd ```kestrel public var linkCmd: Optional[String] ``` Shell command whose stdout provides additional link flags. #### field linkPaths ```kestrel public var linkPaths: Array[String] ``` Library search paths (become -L flags). ### struct Manifest ```kestrel public struct Manifest { /* private fields */ } ``` A parsed flock.toml file. #### field build ```kestrel public var build: BuildConfig ``` #### function clone ```kestrel public func clone() -> Manifest ``` #### field dependencies ```kestrel public var dependencies: Array[Dependency] ``` #### initializer init ```kestrel public init(package: PackageInfo, dependencies: Array[Dependency]) ``` #### initializer init ```kestrel public init(package: PackageInfo, dependencies: Array[Dependency], build: BuildConfig, registryUrl: Optional[String]) ``` #### field package ```kestrel public var package: PackageInfo ``` #### field registryUrl ```kestrel public var registryUrl: Optional[String] ``` Optional registry URL override from [registry] section. ### struct PackageInfo ```kestrel public struct PackageInfo { /* private fields */ } ``` Metadata from the [package] section of flock.toml. #### field author ```kestrel public var author: Optional[String] ``` #### function clone ```kestrel public func clone() -> PackageInfo ``` #### field description ```kestrel public var description: Optional[String] ``` #### field documentation ```kestrel public var documentation: Optional[String] ``` #### initializer init ```kestrel public init(name: String, version: Version, description: Optional[String], source: String) ``` #### field license ```kestrel public var license: Optional[String] ``` #### field name ```kestrel public var name: String ``` #### field repository ```kestrel public var repository: Optional[String] ``` #### field source ```kestrel public var source: String ``` Source directory relative to the package root. Defaults to "src". #### field version ```kestrel public var version: Version ``` #### field website ```kestrel public var website: Optional[String] ``` ### function parseManifest ```kestrel public func parseManifest(source: String) -> Result[Manifest, FlockError] ``` Parses a flock.toml source string into a Manifest. ## flock.compiler ### function invokeCompiler ```kestrel public func invokeCompiler(mode: String, sources: Array[String], output: Optional[String], linkLibs: Array[String], linkPaths: Array[String], frameworks: Array[String]) -> Result[(), FlockError] ``` Invokes the kestrel compiler with the given mode, sources, and optional output. mode: "build", "run", or "check" sources: all .ks files to compile (in dependency order) output: output binary name (only used with "build"; ignored for run/check) linkLibs: libraries and object files to link (-l flags) linkPaths: library search paths (-L flags) frameworks: macOS frameworks (--framework flags) ## flock.dependency ### struct Dependency ```kestrel public struct Dependency { /* private fields */ } ``` A single dependency declaration from [dependencies] in flock.toml. #### function clone ```kestrel public func clone() -> Dependency ``` #### initializer init ```kestrel public init(name: String, spec: DependencySpec) ``` #### field name ```kestrel public var name: String ``` #### field spec ```kestrel public var spec: DependencySpec ``` ### enum DependencySpec ```kestrel public enum DependencySpec ``` How a dependency is specified in flock.toml. #### case Path ```kestrel case Path(String) ``` Local path dependency: { path = "../quill" } #### case Registry ```kestrel case Registry(VersionConstraint) ``` Registry dependency with version constraint: "^1.0.0" (future) #### function clone ```kestrel public func clone() -> DependencySpec ``` ### function parseDependencies ```kestrel public func parseDependencies(depsValue: Value) -> Result[Array[Dependency], FlockError] ``` Parses the [dependencies] table from a quill Value. Each entry is either a string version or an object with a "path" key. ## flock.discover ### function discoverSources ```kestrel public func discoverSources(rootDir: String) -> Array[String] ``` Recursively discovers all .ks files in a package directory. Skips hidden directories (starting with ".") and "target" directories. ## flock.graph ### struct DepNode ```kestrel public struct DepNode { /* private fields */ } ``` A node in the dependency graph. #### field build ```kestrel public var build: BuildConfig ``` Build configuration (C sources, link flags, etc.). #### function clone ```kestrel public func clone() -> DepNode ``` #### field depNames ```kestrel public var depNames: Array[String] ``` #### initializer init ```kestrel public init(name: String, rootDir: String, sourceDir: String, depNames: Array[String], build: BuildConfig) ``` #### field name ```kestrel public var name: String ``` #### field rootDir ```kestrel public var rootDir: String ``` #### field sourceDir ```kestrel public var sourceDir: String ``` Source directory relative to rootDir (e.g. "src"). ### function buildGraph ```kestrel public func buildGraph(root: ResolvedPackage, pathSource: PathSource, registrySource: RegistrySource) -> Result[Array[DepNode], FlockError] ``` Builds a dependency graph starting from the root package. Uses BFS to resolve all transitive dependencies. Dispatches to PathSource or RegistrySource based on the dependency spec. ### function topologicalSort ```kestrel public func topologicalSort(nodes: Array[DepNode]) -> Result[Array[DepNode], FlockError] ``` Sorts dependency nodes in build order (dependencies before dependents). Returns an error if a cycle is detected. ## flock.version ### struct Version ```kestrel public struct Version { /* private fields */ } ``` A semantic version with major.minor.patch components. #### function clone ```kestrel public func clone() -> Version ``` #### function equals ```kestrel public func equals(other: Version) -> Bool ``` Returns true if this version equals another. #### initializer init ```kestrel public init(major: Int64, minor: Int64, patch: Int64) ``` #### function lessThan ```kestrel public func lessThan(other: Version) -> Bool ``` Returns true if this version is less than another. #### field major ```kestrel public var major: Int64 ``` #### field minor ```kestrel public var minor: Int64 ``` #### field patch ```kestrel public var patch: Int64 ``` #### function toString ```kestrel public func toString() -> String ``` Returns "major.minor.patch" string representation. ### enum VersionConstraint ```kestrel public enum VersionConstraint ``` A constraint on which versions are acceptable. #### case Any ```kestrel case Any ``` Any version matches #### case Compatible ```kestrel case Compatible(Version) ``` Compatible: "^1.2.3" (>=1.2.3, <2.0.0) #### case Exact ```kestrel case Exact(Version) ``` Exact match: "=1.2.3" or "1.2.3" #### case TildeCompat ```kestrel case TildeCompat(Version) ``` Tilde: "~1.2.3" (>=1.2.3, <1.3.0) #### function clone ```kestrel public func clone() -> VersionConstraint ``` ### function parseConstraint ```kestrel public func parseConstraint(s: String) -> Result[VersionConstraint, FlockError] ``` Parses a version constraint string like "^1.2.3", "~1.2.3", "1.2.3", or "*". ### function parseVersion ```kestrel public func parseVersion(s: String) -> Result[Version, FlockError] ``` Parses a version string like "1.2.3". ### function satisfies ```kestrel public func satisfies(Version, VersionConstraint) -> Bool ``` Returns true if the given version satisfies the constraint. ## flock.source ### protocol PackageSource ```kestrel public protocol PackageSource ``` Abstraction for resolving package dependencies from different sources. Implementations: - PathSource: resolves local path dependencies - (future) RegistrySource: resolves from a package registry #### function resolve ```kestrel func resolve(name: String, spec: DependencySpec, baseDir: String) -> Result[ResolvedPackage, FlockError] ``` ### struct PathSource ```kestrel public struct PathSource { /* private fields */ } ``` Resolves dependencies from local filesystem paths. #### initializer init ```kestrel public init() ``` **PackageSource** #### function resolve ```kestrel public func resolve(name: String, spec: DependencySpec, baseDir: String) -> Result[ResolvedPackage, FlockError] ``` ### struct ResolvedPackage ```kestrel public struct ResolvedPackage { /* private fields */ } ``` A fully resolved package with its manifest and location. #### function clone ```kestrel public func clone() -> ResolvedPackage ``` #### initializer init ```kestrel public init(name: String, version: Version, rootDir: String, manifest: Manifest) ``` #### field manifest ```kestrel public var manifest: Manifest ``` #### field name ```kestrel public var name: String ``` #### field rootDir ```kestrel public var rootDir: String ``` #### field version ```kestrel public var version: Version ``` ### function joinPath ```kestrel public func joinPath(base: String, rel: String) -> String ``` Joins a base path with a relative path. Handles trailing slashes and normalizes ".." segments. ## flock.main ## flock ## flock.registry_source ### struct RegistrySource ```kestrel public struct RegistrySource { /* private fields */ } ``` Resolves package dependencies from a remote registry. #### function clone ```kestrel public func clone() -> RegistrySource ``` #### field config ```kestrel var config: RegistryConfig ``` #### function downloadAndCache ```kestrel func downloadAndCache(org: String, pkg: String, version: Version) -> Result[ResolvedPackage, FlockError] ``` #### function fetchVersionMeta ```kestrel func fetchVersionMeta(org: String, pkg: String, version: Version) -> Result[VersionMeta, FlockError] ``` Fetches version metadata including checksum and download URL. API: GET /api/v1/packages/{org}/{pkg}/{version} Response: { "name": "org/pkg", "version": "1.2.3", "checksum": "sha256:...", "archive_url": "/api/v1/packages/{org}/{pkg}/{version}/download" } #### function fetchVersions ```kestrel func fetchVersions(org: String, pkg: String) -> Result[Array[Version], FlockError] ``` Fetches the list of available versions for a package from the registry. API: GET /api/v1/packages/{org}/{pkg} Response: { "name": "org/pkg", "versions": ["1.0.0", "1.1.0", ...] } #### initializer init ```kestrel public init(config: RegistryConfig) ``` #### function resolveRegistry ```kestrel func resolveRegistry(name: String, constraint: VersionConstraint) -> Result[ResolvedPackage, FlockError] ``` **PackageSource** #### function resolve ```kestrel public func resolve(name: String, spec: DependencySpec, baseDir: String) -> Result[ResolvedPackage, FlockError] ``` ## flock.error ### enum FlockError ```kestrel public enum FlockError ``` All error conditions that can occur in flock operations. #### case CacheError ```kestrel case CacheError(String) ``` #### case ChecksumMismatch ```kestrel case ChecksumMismatch(String) ``` #### case CompilerFailed ```kestrel case CompilerFailed(Int32) ``` #### case DependencyCycle ```kestrel case DependencyCycle(Array[String]) ``` #### case DependencyNotFound ```kestrel case DependencyNotFound(String) ``` #### case InvalidVersion ```kestrel case InvalidVersion(String) ``` #### case IoError ```kestrel case IoError(String) ``` #### case ManifestNotFound ```kestrel case ManifestNotFound(String) ``` #### case ManifestParse ```kestrel case ManifestParse(String) ``` #### case RegistryError ```kestrel case RegistryError(String) ``` #### function clone ```kestrel public func clone() -> FlockError ``` #### function description ```kestrel public func description() -> String ``` Returns a human-readable description of the error. ## flock.lock ### struct LockEntry ```kestrel public struct LockEntry { /* private fields */ } ``` A single resolved dependency in the lock file. #### field checksum ```kestrel public var checksum: Optional[String] ``` Checksum for registry packages (e.g., "sha256:abcdef...") #### function clone ```kestrel public func clone() -> LockEntry ``` #### initializer init ```kestrel public init(name: String, version: Version, source: String, checksum: Optional[String], path: Optional[String]) ``` #### field name ```kestrel public var name: String ``` #### field path ```kestrel public var path: Optional[String] ``` Relative path for path dependencies #### field source ```kestrel public var source: String ``` "registry" or "path" #### field version ```kestrel public var version: Version ``` ### struct LockFile ```kestrel public struct LockFile { /* private fields */ } ``` A parsed flock.lock file. #### function clone ```kestrel public func clone() -> LockFile ``` #### function find ```kestrel public func find(name: String) -> Optional[LockEntry] ``` Finds a locked entry by package name. #### initializer init ```kestrel public init() ``` #### initializer init ```kestrel public init(packages: Array[LockEntry]) ``` #### field packages ```kestrel public var packages: Array[LockEntry] ``` ### function generateLockFile ```kestrel public func generateLockFile(entries: Array[LockEntry]) -> String ``` Generates flock.lock TOML content from a list of lock entries. ### function parseLockFile ```kestrel public func parseLockFile(source: String) -> Result[LockFile, FlockError] ``` Parses a flock.lock file from its TOML source. ## flock.cache ### function cachePath ```kestrel public func cachePath(org: String, pkg: String, version: Version) -> Result[String, FlockError] ``` Returns the cache path for a specific package version. e.g., ~/.kestrel/packages/kestrel/swoop/1.0.0/ ### function cacheRoot ```kestrel public func cacheRoot() -> Result[String, FlockError] ``` Returns the cache root directory: ~/.kestrel/packages/ ### function downloadFile ```kestrel public func downloadFile(url: String, outputPath: String) -> Result[(), FlockError] ``` Downloads a file from a URL to a local path using curl. ### function ensureCacheDir ```kestrel public func ensureCacheDir(org: String, pkg: String, version: Version) -> Result[String, FlockError] ``` Ensures the cache directory exists for a given org/pkg/version. Creates all intermediate directories if needed. Returns the full cache path on success. ### function extractArchive ```kestrel public func extractArchive(archivePath: String, targetDir: String) -> Result[(), FlockError] ``` Extracts a .tar.gz archive into the target directory. ### function isCached ```kestrel public func isCached(org: String, pkg: String, version: Version) -> Bool ``` Checks if a package version is already cached (flock.toml exists in cache dir). --- ## kestrel/perch 0.3.0 # Perch Web server framework for Kestrel with routing, middleware, and parameterized context. ## Installation ```toml [dependencies] kestrel/perch = "0.2.1" ``` ## Usage ```kestrel var app = App[String]("Hello, World!") app.route(get: "/", func(req: Request, ctx: String) -> Response { return Response.ok(Text(ctx)) }) app.route(get: "/users/:id", func(req: Request, ctx: String) -> Response { let id = req.param("id") return Response.ok(Text("User " + id)) }) app.route(post: "/users", func(req: Request, ctx: String) -> Response { return Response.created(JsonBody(req.body)) }) let _ = app.listen(port: 8080) ``` ## Key Types - **App[T]** - web application with typed context - **Request** - incoming HTTP request with method, path segments, headers, body, and route params - **Response** - HTTP response builder with Content-based factories - **GroupBuilder[T]** - route group with shared prefix and middleware - **Content** - protocol for response/request body types (Text, JsonBody, Form, Bytes) - **Middleware[T]** - protocol for request processing middleware ## Routing Register handlers with `route(get:)`, `route(post:)`, `route(put:)`, `route(delete:)`, `route(patch:)`: ```kestrel app.route(get: "/api/users", handler) app.route(get: "/api/users/:id", handler) // :id is a path parameter ``` All types that conform to `Routes[T]` get these methods automatically — just implement `addRoute`. ## Route Groups ```kestrel var api = GroupBuilder[String]("/api") api.route(get: "/users", listUsers) api.route(post: "/users", createUser) app.addGroup(api) ``` ## Middleware Implement the `Middleware[T]` protocol to create reusable middleware: ```kestrel struct AuthCheck[T]: Middleware[T] { func handle(request: Request, ctx: T) -> MiddlewareResult { match request.header("Authorization") { .Some(_) => .Continue(request), .None => .Respond(Response.unauthorized()) } } func clone() -> AuthCheck[T] { AuthCheck[T]() } } app.use(AuthCheck[String]()) ``` ## Response Content Responses use the `Content` protocol for body data: ```kestrel Response.ok(Text("Hello")) Response.ok(JsonBody(payload)) Response.created(Form([("key", "value")])) Response.badRequest(Text("Missing field")) ``` ## perch.send ### function sendResponse ```kestrel public func sendResponse(Response, to: Int32) -> Result[(), IoError] ``` Serializes and sends an HTTP response over a socket file descriptor. Builds the full HTTP/1.1 wire format — status line, headers (including Content-Length and Connection: close), and body — then writes it to the socket in a single pass. # Errors Returns `IoError` when the socket write fails (broken pipe, connection reset) or a partial write cannot be completed. # Examples ``` let response = Response.ok(Text("hello")); let _ = sendResponse(response, to: socketFd); ``` ## perch.middleware ### struct Logger ```kestrel public struct Logger[T] { /* private fields */ } ``` Logging middleware that prints the HTTP method and path for each request. Logs one line per request in the format `GET /path`. # Examples ``` var app = App(context: ctx); app.use(Logger[Ctx]()); ``` #### function clone ```kestrel public func clone() -> Logger[T] ``` **Middleware** #### function handle ```kestrel public func handle(Request, T) -> MiddlewareResult ``` ## perch ## perch.json_body ### function byteCount ```kestrel public func byteCount() -> Int64 ``` ### function clone ```kestrel public func clone() -> JsonBody ``` ### function contentType ```kestrel public func contentType() -> String? ``` ### function toBytes ```kestrel public func toBytes() -> Array[UInt8] ``` ## perch.context ### protocol Middleware ```kestrel public protocol Middleware[T] ``` A type that can process requests in the middleware pipeline. Implement this protocol to create reusable middleware with named types and configurable state. # Examples ``` struct AuthCheck[T]: Middleware[T] { func handle(request: Request, ctx: T) -> MiddlewareResult { match request.header("Authorization") { .Some(_) => .Continue(request), .None => .Respond(Response.unauthorized()) } } func clone() -> AuthCheck[T] { AuthCheck[T]() } } ``` #### function handle ```kestrel func handle(Request, T) -> MiddlewareResult ``` ### enum MiddlewareResult ```kestrel public enum MiddlewareResult ``` The result of a middleware function. Middleware either continues the pipeline with a (possibly enriched) request, or short-circuits by returning a response immediately. The pipeline evaluates middleware in order: global first, then group-level, then route-level. The first `Respond` wins — no further middleware or handler runs. # Examples ``` // Middleware that requires an Authorization header func requireAuth[T]() -> (Request, T) -> MiddlewareResult { { (request: Request, ctx: T) in match request.header("Authorization") { .Some(_) => .Continue(request), .None => .Respond(Response.unauthorized()) } } } ``` #### case Continue ```kestrel case Continue(Request) ``` Continue to the next middleware or handler with this request. #### case Respond ```kestrel case Respond(Response) ``` Short-circuit the pipeline and return this response to the client. #### function clone ```kestrel public func clone() -> MiddlewareResult ``` ## perch.parse ### function parseHttpRequest ```kestrel public func parseHttpRequest(Int32) -> Result[Request, IoError] ``` Reads and parses an HTTP request from a raw socket file descriptor. Reads bytes until the header terminator (`\r\n\r\n`) is found, then parses the request line, headers, and optional body. # Errors Returns `IoError` when: - The socket returns zero bytes (client disconnected) - The header block exceeds 65536 bytes - The request line is malformed (missing method, path, or unrecognized method) # Examples ``` let request = try parseHttpRequest(socketFd); println(request.method.toString() + " " + request.path); ``` ## perch.router ### struct GroupBuilder ```kestrel public struct GroupBuilder[T] { /* private fields */ } ``` Builder for creating a route group with shared prefix and middleware. # Examples ``` var api = GroupBuilder[Ctx]("/api"); api.use(RequireAuth[Ctx]()); api.route(get: "/users", listUsers); api.route(get: "/users/:id", getUser); app.addGroup(api); ``` #### function clone ```kestrel public func clone() -> GroupBuilder[T] ``` #### initializer init ```kestrel public init(String) ``` Creates a new group builder with the given path prefix. #### field middleware ```kestrel var middleware: Array[(Request, T) -> MiddlewareResult] ``` #### field prefix ```kestrel var prefix: String ``` #### field routes ```kestrel var routes: Array[Route[T]] ``` #### function use ```kestrel public mutating func use[M](M) where M: Middleware[T] ``` Adds middleware to this group. **Routes** #### function addRoute ```kestrel public mutating func addRoute(HttpMethod, String, (Request, T) -> Response) ``` ### struct Route ```kestrel public struct Route[T] { /* private fields */ } ``` A route maps an HTTP method + path pattern to a handler. Path patterns support `:name` segments for parameter extraction. For example, `"/users/:id"` matches `"/users/42"` and binds `id` → `"42"` in the request's path params. #### function clone ```kestrel public func clone() -> Route[T] ``` #### field handler ```kestrel var handler: (Request, T) -> Response ``` #### field method ```kestrel var method: HttpMethod ``` #### field middleware ```kestrel var middleware: Array[(Request, T) -> MiddlewareResult] ``` #### field pattern ```kestrel var pattern: String ``` #### field patternSegments ```kestrel var patternSegments: Array[String] ``` ### struct RouteGroup ```kestrel public struct RouteGroup[T] { /* private fields */ } ``` A group of routes sharing a path prefix and middleware. #### function clone ```kestrel public func clone() -> RouteGroup[T] ``` #### field middleware ```kestrel var middleware: Array[(Request, T) -> MiddlewareResult] ``` #### field prefix ```kestrel var prefix: String ``` #### field prefixSegments ```kestrel var prefixSegments: Array[String] ``` #### field routes ```kestrel var routes: Array[Route[T]] ``` ### struct Router ```kestrel public struct Router[T] { /* private fields */ } ``` The main router holding global middleware, route groups, and standalone routes. Route matching checks groups first (in registration order), then standalone routes. The first match wins — later routes for the same method and pattern are shadowed. #### function addGroup ```kestrel public mutating func addGroup(GroupBuilder[T]) ``` Adds a route group. #### function clone ```kestrel public func clone() -> Router[T] ``` #### function findRoute ```kestrel func findRoute(HttpMethod, Array[String]) -> MatchResult[T]? ``` Finds a matching route for the given method and path segments. #### field globalMiddleware ```kestrel public var globalMiddleware: Array[(Request, T) -> MiddlewareResult] ``` #### field groups ```kestrel var groups: Array[RouteGroup[T]] ``` #### initializer init ```kestrel public init() ``` Creates an empty router. #### field routes ```kestrel var routes: Array[Route[T]] ``` #### function use ```kestrel public mutating func use[M](M) where M: Middleware[T] ``` Adds global middleware that runs on every request. **Routes** #### function addRoute ```kestrel public mutating func addRoute(HttpMethod, String, (Request, T) -> Response) ``` ### protocol Routes ```kestrel public protocol Routes[T] ``` A type that can register HTTP route handlers. Conform to this protocol by implementing `addRoute`. The seven verb methods — `route(get:)`, `route(post:)`, etc. — are provided automatically by the blanket extension. # Examples ``` app.route(get: "/users", listUsers); app.route(post: "/users", createUser); app.route(delete: "/users/:id", deleteUser); ``` #### function addRoute ```kestrel mutating func addRoute(HttpMethod, String, (Request, T) -> Response) ``` ### function route ```kestrel public func route(post: String, (Request, T) -> Response) ``` Registers a POST route. ### function route ```kestrel public func route(put: String, (Request, T) -> Response) ``` Registers a PUT route. ### function route ```kestrel public func route(delete: String, (Request, T) -> Response) ``` Registers a DELETE route. ### function route ```kestrel public func route(patch: String, (Request, T) -> Response) ``` Registers a PATCH route. ### function route ```kestrel public func route(head: String, (Request, T) -> Response) ``` Registers a HEAD route. ### function route ```kestrel public func route(options: String, (Request, T) -> Response) ``` Registers an OPTIONS route. ## perch.request ### struct Request ```kestrel public struct Request { /* private fields */ } ``` A parsed HTTP request with route parameters and middleware state. Combines the raw HTTP data (method, path, headers, body) with server-resolved state: path parameters extracted during route matching and a string key-value store that middleware can populate (e.g. an auth middleware sets `"userId"`). Query parameters and cookies are parsed eagerly at construction time and stored for O(1) repeated access. # Examples ``` func handleUser(request: Request, ctx: Ctx) -> Response { let id = match request.param("id") { .Some(id) => id, .None => return Response.badRequest(Text("Missing id")) }; Response.ok(Text("User " + id)) } ``` #### field body ```kestrel public var body: String ``` #### function clone ```kestrel public func clone() -> Request ``` #### field contentType ```kestrel public var contentType: String? { get } ``` The `Content-Type` header value, or `None` if not present. #### function cookie ```kestrel public func cookie(String) -> String? ``` Returns a specific cookie value by name, or `None`. Searches the eagerly-parsed cookies. O(n) in the number of cookies. #### field cookies ```kestrel public var cookies: Array[(String, String)] ``` #### function getValue ```kestrel public func getValue(forKey: String) -> String? ``` Returns a value from the middleware store, or `None`. #### function header ```kestrel public func header(String) -> String? ``` Returns the first value of a header by name (case-insensitive). #### field headers ```kestrel public var headers: Headers ``` #### field method ```kestrel public var method: HttpMethod ``` #### function param ```kestrel public func param(String) -> String? ``` Returns a path parameter by name, or `None`. Path parameters are extracted during route matching from `:name` segments in the route pattern. #### field path ```kestrel public var path: String ``` #### field pathParams ```kestrel public var pathParams: Dictionary[String, String] ``` #### function query ```kestrel public func query(String) -> String? ``` Returns a query parameter value by name, or `None`. Searches the eagerly-parsed query parameters. O(n) in the number of query parameters. #### field queryParams ```kestrel public var queryParams: Array[(String, String)] ``` #### field queryString ```kestrel public var queryString: String ``` #### field segments ```kestrel public var segments: Array[String] ``` #### field store ```kestrel public var store: Dictionary[String, String] ``` ## perch.app ### struct App ```kestrel public struct App[T] where T: Cloneable { /* private fields */ } ``` A Perch web application parameterized by a context type `T`. The context holds app-wide state — database connections, config, caches — anything your handlers need. It is created once at startup and passed to every handler and middleware by value. # Examples ``` struct Ctx {} var app = App(Ctx()); app.use(Logger[Ctx]()); app.route(get: "/", { (req: Request, ctx: Ctx) in Response.ok(Text("Hello, world!")) }); let _ = app.listen(8080); ``` #### function addGroup ```kestrel public mutating func addGroup(GroupBuilder[T]) ``` Adds a route group with shared prefix and middleware. #### function clone ```kestrel public func clone() -> App[T] ``` #### field context ```kestrel var context: T ``` #### function dispatch ```kestrel func dispatch(Request) -> Response ``` Dispatches a request through the middleware pipeline and route handler. Execution order: global middleware → group middleware → handler. The first middleware that returns `.Respond` short-circuits the chain. Returns 404 if no route matches. #### initializer init ```kestrel public init(T) ``` Creates a new app with the given context and no routes. #### function listen ```kestrel public func listen(UInt16) -> Result[(), IoError] ``` Starts the server, listening on the given port. Blocks forever, accepting connections and dispatching requests one at a time. Each connection is closed after the response is sent (`Connection: close`). # Errors Returns `IoError` if the TCP bind or accept fails (e.g. port already in use, permission denied). #### field router ```kestrel var router: Router[T] ``` #### function use ```kestrel public mutating func use[M](M) where M: Middleware[T] ``` Adds global middleware that runs on every request. **Routes** #### function addRoute ```kestrel public mutating func addRoute(HttpMethod, String, (Request, T) -> Response) ``` ## perch.response ### struct Response ```kestrel public struct Response { /* private fields */ } ``` An HTTP response with status code, headers, and body. Use the static factory methods for common responses — `Response.ok(content:)`, `Response.notFound()`, `Response.redirect(to:)`, etc. For custom status codes, use `Response.withStatus(code:, content:)`. Responses are value types. The `withHeader` and `withCookie` methods return new copies — the original is unchanged. # Examples ``` Response.ok(Text("Hello, world!")) Response.ok(JsonBody(payload)) Response.created(JsonBody(user)) .withCookie(Cookie("session", "abc123")) ``` #### initializer Default ```kestrel public init(StatusCode, Headers, String) ``` Creates a response with the given status, headers, and body. #### function badRequest ```kestrel public static func badRequest[C](C) -> Response where C: Content ``` Creates a 400 Bad Request response with the given content. #### field bodyContent ```kestrel public var bodyContent: String ``` #### function clone ```kestrel public func clone() -> Response ``` #### function conflict ```kestrel public static func conflict[C](C) -> Response where C: Content ``` Creates a 409 Conflict response with the given content. #### function created ```kestrel public static func created[C](C) -> Response where C: Content ``` Creates a 201 Created response with the given content. #### function forbidden ```kestrel public static func forbidden() -> Response ``` Creates a 403 Forbidden response. #### field headers ```kestrel public var headers: Headers ``` #### function internalServerError ```kestrel public static func internalServerError() -> Response ``` Creates a 500 Internal Server Error response. #### function methodNotAllowed ```kestrel public static func methodNotAllowed() -> Response ``` Creates a 405 Method Not Allowed response. #### function noContent ```kestrel public static func noContent() -> Response ``` Creates a 204 No Content response. #### function notFound ```kestrel public static func notFound() -> Response ``` Creates a 404 Not Found response. #### function ok ```kestrel public static func ok[C](C) -> Response where C: Content ``` Creates a 200 OK response with the given content. #### function redirect ```kestrel public static func redirect(to: String) -> Response ``` Creates a redirect response (302 Found by default). #### function redirect ```kestrel public static func redirect(to: String, Int64) -> Response ``` Creates a redirect response with a specific status code. #### field status ```kestrel public var status: StatusCode ``` #### function tooManyRequests ```kestrel public static func tooManyRequests() -> Response ``` Creates a 429 Too Many Requests response. #### function unauthorized ```kestrel public static func unauthorized() -> Response ``` Creates a 401 Unauthorized response. #### function unprocessableEntity ```kestrel public static func unprocessableEntity[C](C) -> Response where C: Content ``` Creates a 422 Unprocessable Entity response with the given content. #### function withCookie ```kestrel public func withCookie(Cookie) -> Response ``` Returns a new response with a `Set-Cookie` header appended. #### function withHeader ```kestrel public func withHeader(String, String) -> Response ``` Returns a new response with an additional header appended. #### function withStatus ```kestrel public static func withStatus[C](Int64, C) -> Response where C: Content ``` Creates a response with a custom status code and content. --- ## kestrel/swoop 0.3.0 # Swoop HTTP client library for Kestrel with a fluent, immutable API. ## Installation ```toml [dependencies] kestrel/swoop = "0.2.1" ``` Requires OpenSSL 3.x for HTTPS support. On macOS: `brew install openssl@3` ## Usage ```kestrel // Simple GET request let response = try Swoop().fetch("http://example.com/api/users") let _ = println(response.body) // Configure a reusable client let api = Swoop(baseUrl: "https://api.example.com") .header("Authorization", "Bearer my-token") .header("Accept", "application/json") let users = try api.fetch("/users") let user = try api.fetch("/users/42") // POST with JSON content let result = try api.post("/users", JsonBody("{\"name\":\"Alice\"}")) // POST with form data let result = try api.post("/login", Form([("username", "alice"), ("password", "secret")])) ``` ## Key Types - **Swoop** - immutable HTTP client (each config method returns a new instance) - **Response** - HTTP response with body, status code, and headers - **Content** - protocol for request body types - **Text** - plain text content - **Bytes** - raw binary content - **Form** - URL-encoded form data (auto-sets Content-Type) - **JsonBody** - JSON content (auto-sets Content-Type) ## HTTP Methods Instance methods on a configured client: - `fetch(url)` - GET - `post(url, content)` - POST - `put(url, content)` - PUT - `patch(url, content)` - PATCH - `delete(url)` - DELETE - `head(url)` - HEAD ## Features - Immutable, fluent configuration - Automatic TLS for `https://` URLs - Base URL with path resolution - Custom headers and timeouts - Extensible content types via `Content` protocol ## swoop.swoop ### struct Swoop ```kestrel public struct Swoop { /* private fields */ } ``` An immutable HTTP client configuration. Config methods return new instances; verb methods execute requests. All fields are private — configure via the fluent API. # Examples ``` let api = Swoop(baseUrl: "https://api.example.com") .header("Accept", "application/json"); let res = try api.fetch("/users"); ``` #### field _baseUrl ```kestrel var _baseUrl: String ``` #### field _headers ```kestrel var _headers: Headers ``` #### field _timeoutSeconds ```kestrel var _timeoutSeconds: Int64 ``` #### function clone ```kestrel public func clone() -> Swoop ``` #### function delete ```kestrel public func delete(String) -> Result[Response, SwoopError] ``` Performs an HTTP DELETE request. #### function execute ```kestrel func execute(HttpMethod, String) -> Result[Response, SwoopError] ``` #### function executeWith ```kestrel func executeWith[C](HttpMethod, String, C) -> Result[Response, SwoopError] where C: Content ``` #### function fetch ```kestrel public func fetch(String) -> Result[Response, SwoopError] ``` Performs an HTTP GET request. #### function head ```kestrel public func head(String) -> Result[Response, SwoopError] ``` Performs an HTTP HEAD request. #### function header ```kestrel public func header(String, String) -> Swoop ``` Returns a new Swoop with an additional header. #### initializer init ```kestrel public init() ``` #### initializer init ```kestrel public init(baseUrl: String) ``` Creates a client with a base URL. Relative paths passed to verb methods are resolved against this URL. #### initializer init ```kestrel init(String, Headers, Int64) ``` #### function patch ```kestrel public func patch[C](String, C) -> Result[Response, SwoopError] where C: Content ``` Performs an HTTP PATCH request with content. #### function post ```kestrel public func post[C](String, C) -> Result[Response, SwoopError] where C: Content ``` Performs an HTTP POST request with content. #### function put ```kestrel public func put[C](String, C) -> Result[Response, SwoopError] where C: Content ``` Performs an HTTP PUT request with content. #### function timeout ```kestrel public func timeout(Int64) -> Swoop ``` Returns a new Swoop with a timeout. ## swoop ## swoop.url ### struct ClientUrl ```kestrel public struct ClientUrl { /* private fields */ } ``` A parsed client URL with scheme, host, port, path, and query string. # Examples ``` let url = try parseClientUrl("https://api.example.com:8443/v1/users?page=1"); url.scheme; // "https" url.host; // "api.example.com" url.port; // 8443 url.path; // "/v1/users" url.queryString; // "page=1" ``` #### function clone ```kestrel public func clone() -> ClientUrl ``` #### field host ```kestrel public var host: String ``` #### function hostHeader ```kestrel public func hostHeader() -> String ``` Returns "host" or "host:port" for the Host header. Omits port when it matches the scheme default (80 for http, 443 for https). #### initializer init ```kestrel public init(String, String, UInt16, String, String) ``` #### field path ```kestrel public var path: String ``` #### field port ```kestrel public var port: UInt16 ``` #### field queryString ```kestrel public var queryString: String ``` #### function requestPath ```kestrel public func requestPath() -> String ``` Returns the full request path including query string (e.g. "/users?page=1"). #### field scheme ```kestrel public var scheme: String ``` ### function parseClientUrl ```kestrel public func parseClientUrl(String) -> Result[ClientUrl, SwoopError] ``` Parses a URL string into a ClientUrl. Supports: http://host/path, https://host/path, with optional :port and ?query ## swoop.tls ### struct TlsStream ```kestrel public struct TlsStream { /* private fields */ } ``` A TLS-encrypted TCP stream that implements `Readable` and `Writable`. Created via `TlsStream.connect(host, port)`. Cleans up the SSL context and closes the socket on `deinit`. # Examples ``` var stream = try TlsStream.connect("example.com", 443); ``` #### function connect ```kestrel public static func connect(String, UInt16) -> Result[TlsStream, IoError] ``` Connects to a remote host over TLS, returning a TlsStream. #### field fd ```kestrel var fd: Int32 ``` #### function flush ```kestrel public mutating func flush() -> Result[(), IoError] ``` #### initializer init ```kestrel init(lang.ptr[lang.i8], lang.ptr[lang.i8], Int32) ``` #### function read ```kestrel public mutating func read(into: ArraySlice[UInt8]) -> Result[Int64, IoError] ``` #### function write ```kestrel public mutating func write(from: ArraySlice[UInt8]) -> Result[Int64, IoError] ``` ## swoop.response ### struct Response ```kestrel public struct Response { /* private fields */ } ``` An HTTP response with status, headers, and body (as both string and bytes). # Examples ``` let res = try Swoop().fetch("http://example.com"); if res.status.isSuccess() { println(res.body); } ``` #### field body ```kestrel public let body: String ``` #### field bodyBytes ```kestrel public let bodyBytes: Array[UInt8] ``` #### function clone ```kestrel public func clone() -> Response ``` #### field headers ```kestrel public let headers: Headers ``` #### initializer init ```kestrel public init(StatusCode, Headers, String, Array[UInt8]) ``` #### function json ```kestrel public func json() -> Result[Value, DeserializeError] ``` Parses the response body as a JSON `Value`. # Examples ``` let res = try Swoop().fetch("http://api.example.com/data"); let json = try res.json(); ``` #### field status ```kestrel public let status: StatusCode ``` #### function validate ```kestrel public func validate() -> Result[Response, SwoopError] ``` Returns the response if the status is 2xx, or a `SwoopError` containing the status code otherwise. # Examples ``` let res = try Swoop().fetch(url); let validated = try res.validate(); ``` ## swoop.error ### struct SwoopError ```kestrel public struct SwoopError { /* private fields */ } ``` An error that occurred during an HTTP request. #### function clone ```kestrel public func clone() -> SwoopError ``` #### function connectionFailed ```kestrel public static func connectionFailed(String) -> SwoopError ``` #### function description ```kestrel public func description() -> String ``` Returns a human-readable description of the error. #### function httpError ```kestrel public static func httpError(Int64) -> SwoopError ``` #### initializer init ```kestrel public init(SwoopErrorKind) ``` #### function invalidResponse ```kestrel public static func invalidResponse(String) -> SwoopError ``` #### function invalidUrl ```kestrel public static func invalidUrl(String) -> SwoopError ``` #### field kind ```kestrel public var kind: SwoopErrorKind ``` #### function timeout ```kestrel public static func timeout() -> SwoopError ``` ### enum SwoopErrorKind ```kestrel public enum SwoopErrorKind ``` The kind of error that occurred during an HTTP request. #### case ConnectionFailed ```kestrel case ConnectionFailed(String) ``` Failed to connect to the remote host. #### case HttpError ```kestrel case HttpError(Int64) ``` The server returned a non-2xx status (from validate()). Contains the status code. #### case InvalidResponse ```kestrel case InvalidResponse(String) ``` Failed to parse the HTTP response from the server. #### case InvalidUrl ```kestrel case InvalidUrl(String) ``` The URL could not be parsed. #### case Timeout ```kestrel case Timeout ``` The request timed out. #### function clone ```kestrel public func clone() -> SwoopErrorKind ``` ## swoop.content ### function byteCount ```kestrel public func byteCount() -> Int64 ``` ### function clone ```kestrel public func clone() -> JsonBody ``` ### function contentType ```kestrel public func contentType() -> String? ``` ### function toBytes ```kestrel public func toBytes() -> Array[UInt8] ``` ## swoop.send ### function sendRequest ```kestrel public func sendRequest[S](S, HttpMethod, ClientUrl, Headers) -> Result[Response, SwoopError] where S: Readable, S: Writable ``` Sends an HTTP request without a body and reads the response. ### function sendRequest ```kestrel public func sendRequest[S, C](S, HttpMethod, ClientUrl, Headers, C) -> Result[Response, SwoopError] where S: Readable, S: Writable, C: Content ``` Sends an HTTP request with a body and reads the response. --- ## kestrel/quill-json 0.2.2 # Quill-JSON JSON support for the quill serialization framework. ## Installation ```toml [dependencies] kestrel/quill = "0.1.0" kestrel/quill-json = "0.1.0" ``` ## Usage ```kestrel // Encode a Value to JSON let value = Value.Obj([ ("name", Value.Str("Alice")), ("age", Value.Int(30)) ]) let json = try Json().encode(value: value) // {"name":"Alice","age":30} // Decode JSON to a Value let parsed = try Json().decode(source: "{\"x\": 1}") // Convenience functions for Serialize types let jsonStr = try toJson(value: mySerializableValue) let pretty = try toJsonPretty(value: mySerializableValue) ``` ## Key Types - **Json** - implements the quill `Format` protocol for JSON - Content type: `application/json` ## Functions - `toJson(value:)` - serialize any `Serialize` type to compact JSON - `toJsonPretty(value:)` - serialize to pretty-printed JSON ## quill.json.error ### struct JsonParseError ```kestrel public struct JsonParseError { /* private fields */ } ``` A syntax error encountered while parsing a JSON string. Carries a human-readable `message` describing what went wrong and the byte `offset` into the source where the parser stopped. Use `description()` to format both into a single diagnostic string. # Representation Two fields: `message` (a short explanation like "unexpected character '}'") and `offset` (the zero-based byte position in the source string). # Examples ``` let err = JsonParseError("unexpected end of input", 42); err.description(); // "JSON parse error at offset 42: unexpected end of input" ``` #### initializer Default ```kestrel public init(String, Int64) ``` Creates an error with the given message and byte offset. #### function clone ```kestrel public func clone() -> JsonParseError ``` Returns a deep copy of this error. #### function description ```kestrel public func description() -> String ``` Formats the error as `"JSON parse error at offset : "`. #### field message ```kestrel public var message: String ``` Short explanation of the syntax violation. #### field offset ```kestrel public var offset: Int64 ``` Zero-based byte offset into the source where parsing failed. ## quill ## quill.json ### struct Json ```kestrel public struct Json { /* private fields */ } ``` JSON serialization format for use with the quill `Format` protocol. `Json` is a stateless type whose static methods convert between `Value` and JSON text. Pass it as a type argument to any generic function that accepts a `Format`, or call its methods directly for one-off encoding and decoding. Encoding always succeeds (every `Value` has a JSON representation). Decoding can fail if the input is malformed; the error carries a byte offset pointing at the problem. # Examples ``` let v = Value.Obj([("name", Value.Str("Alice")), ("age", Value.Int(30))]); let json = try Json.encode(value: v); // json == "{\"name\":\"Alice\",\"age\":30}" let back = try Json.decode(source: json); // back == v ``` #### function contentType ```kestrel public static func contentType() -> String ``` Returns the MIME content type for JSON: `"application/json"`. #### function decode ```kestrel public static func decode(String) -> Result[Value, DeserializeError] ``` Decodes a JSON string into a `Value`. Returns a `DeserializeError` if the input is not syntactically valid JSON. The underlying `JsonParseError` carries the byte offset of the first problem; that detail is folded into the error description. # Errors Returns `.Err` for any JSON syntax violation — unterminated strings, trailing commas, unquoted keys, bare identifiers other than `true`, `false`, or `null`. #### function encode ```kestrel public static func encode(Value) -> Result[String, SerializeError] ``` Encodes a `Value` to a compact JSON string with no extra whitespace. This always succeeds — every well-formed `Value` maps to valid JSON. The output uses no indentation or trailing newlines; use `toJsonPretty` when human readability matters. ### function toJson ```kestrel public func toJson[T](T) -> Result[String, SerializeError] where T: Serialize ``` Serializes any `Serialize` value to a compact JSON string. Combines `value.toValue()` and `emitJson` in a single call. Fails only if the `Serialize` implementation itself returns an error. # Examples ``` let json = try toJson(value: myUser); // json == "{\"name\":\"Alice\",\"age\":30}" ``` ### function toJsonPretty ```kestrel public func toJsonPretty[T](T) -> Result[String, SerializeError] where T: Serialize ``` Serializes any `Serialize` value to a pretty-printed JSON string. Identical to `toJson` except the output uses 2-space indentation and newlines between elements for human readability. # Examples ``` let json = try toJsonPretty(value: myUser); // json == "{\n \"name\": \"Alice\",\n \"age\": 30\n}" ``` ## quill.json.emitter ### function emitJson ```kestrel public func emitJson(Value) -> String ``` Converts a `Value` to a compact JSON string with no extra whitespace. Every `Value` variant maps directly to a JSON production — there is no lossy conversion. The output contains no indentation, no trailing newline, and no spaces around `:` or `,`. # Examples ``` let v = Value.Obj([("x", Value.Int(1)), ("y", Value.Arr([Value.Null]))]); emitJson(v); // "{\"x\":1,\"y\":[null]}" ``` ### function emitJsonPretty ```kestrel public func emitJsonPretty(Value) -> String ``` Converts a `Value` to a pretty-printed JSON string with 2-space indentation. Identical semantics to `emitJson` but inserts newlines between array elements and object entries, indents nested structures by 2 spaces per level, and places a space after `:` in object entries. The output ends with a single trailing newline. # Examples ``` let v = Value.Obj([("name", Value.Str("Alice"))]); emitJsonPretty(v); // "{\n \"name\": \"Alice\"\n}\n" ``` ## quill.json.parser ### function parseJson ```kestrel public func parseJson(String) -> Result[Value, JsonParseError] ``` Parses a complete JSON document into a `Value`. Accepts any single JSON value (object, array, string, number, boolean, or null). Leading and trailing whitespace is skipped; trailing non-whitespace after the value produces an error. # Examples ``` let v = try parseJson("[1, 2, 3]"); // v == Value.Arr([Value.Int(1), Value.Int(2), Value.Int(3)]) ``` # Errors Returns `JsonParseError` for any syntax violation, with a byte offset pointing at the problem character. --- ## kestrel/talon-sqlite 0.1.0 ## talon ## talon.sqlite.value ### protocol Bindable ```kestrel public protocol Bindable ``` Types that can be bound as SQL query parameters. Conforming to `Bindable` allows a type to be interpolated into `SQL` strings. Non-conforming types produce a compile-time error, preventing SQL injection by construction. #### function toSqliteValue ```kestrel func toSqliteValue() -> SqliteValue ``` ### protocol FromSqliteValue ```kestrel public protocol FromSqliteValue ``` Types that can be extracted from a SQLite column value. Use `Int64`, `String`, `Float64` for required columns (throws on NULL). Use `Int64?`, `String?`, `Float64?` for nullable columns (NULL → `.None`). ``` let id = try row.get[Int64](at: 0); // throws if NULL let email = try row.get[String?](at: 2); // NULL → .None ``` #### function fromSqliteValue ```kestrel static func fromSqliteValue(SqliteValue) -> Self throws SqliteError ``` ### enum SqliteValue ```kestrel public enum SqliteValue ``` A dynamically-typed SQLite value. #### case Integer ```kestrel case Integer(Int64) ``` #### case Null ```kestrel case Null ``` #### case Real ```kestrel case Real(Float64) ``` #### case Text ```kestrel case Text(String) ``` #### function clone ```kestrel public func clone() -> SqliteValue ``` ## talon.sqlite.transaction ### struct Transaction ```kestrel public struct Transaction { /* private fields */ } ``` A database transaction that auto-commits or rolls back. Created by `Database.transaction` — not constructed directly. Implements `SqliteExecutor` so it can be used interchangeably with `Database`. #### field db ```kestrel var db: RawPointer ``` #### initializer init ```kestrel init(db: RawPointer) ``` **SqliteExecutor** #### function execute ```kestrel public func execute(SQL) -> () throws SqliteError ``` #### function query ```kestrel public func query[R](SQL) -> Array[R] throws SqliteError where R: FromRow ``` ## talon.sqlite.row ### protocol FromRow ```kestrel public protocol FromRow ``` Types that can be constructed from a database row. ``` struct User: FromRow { var id: Int64 var name: String var email: String? static func fromRow(row: Row) -> User throws SqliteError { User( id: try row.read[Int64](at: 0), name: try row.read[String](at: 1), email: try row.read[String?](at: 2) ) } } ``` #### function fromRow ```kestrel static func fromRow(Row) -> Self throws SqliteError ``` ### function clone ```kestrel public func clone() -> Row ``` ### field columnCount ```kestrel public var columnCount: Int64 { get } ``` Number of columns in this row. ### function read ```kestrel public func read[T](at: Int64) -> T throws SqliteError where T: FromSqliteValue ``` Reads column at `index` as type `T`. Use non-optional types for required columns and optional types for nullable columns: ``` let id = try row.read[Int64](at: 0); // throws if NULL let email = try row.read[String?](at: 2); // NULL becomes .None ``` ### function value ```kestrel public func value(at: Int64) -> SqliteValue ``` Returns the raw SqliteValue at `index`. ## talon.sqlite ## talon.sqlite.connection ## talon.sqlite.sql ### struct SQL ```kestrel public struct SQL { /* private fields */ } ``` A parameterized SQL query with `?` placeholders and bound values. #### typealias Interpolation ```kestrel public type Interpolation = SqlAccumulator ``` #### field bindings ```kestrel public var bindings: Array[SqliteValue] ``` #### function clone ```kestrel public func clone() -> SQL ``` #### initializer init ```kestrel public init(template: String, bindings: Array[SqliteValue]) ``` #### initializer init ```kestrel public init(stringLiteral: lang.ptr[lang.i8], lang.i64) ``` #### initializer init ```kestrel public init(SqlAccumulator) ``` #### field template ```kestrel public var template: String ``` ### struct SqlAccumulator ```kestrel public struct SqlAccumulator { /* private fields */ } ``` Accumulator that builds parameterized SQL. Appends `?` for each interpolation and collects the bound value. #### function appendInterpolation ```kestrel public mutating func appendInterpolation[T](T) where T: Bindable ``` #### function appendLiteral ```kestrel public mutating func appendLiteral(String) ``` #### field bindings ```kestrel var bindings: Array[SqliteValue] ``` #### function build ```kestrel public mutating func build() -> SQL ``` #### function clone ```kestrel public func clone() -> SqlAccumulator ``` #### initializer init ```kestrel public init(literalCapacity: Int64, interpolationCount: Int64) ``` #### field template ```kestrel var template: StringBuilder ``` ## talon.sqlite.database ### function execute ```kestrel public func execute(SQL) -> () throws SqliteError ``` ### function query ```kestrel public func query[R](SQL) -> Array[R] throws SqliteError where R: FromRow ``` ### function transaction ```kestrel public func transaction((Transaction) -> () throws SqliteError) -> () throws SqliteError ``` Runs `body` inside a BEGIN/COMMIT transaction. If `body` throws, the transaction is rolled back and the error is re-thrown. If `body` returns normally, the transaction commits. ``` try db.transaction { tx in try tx.execute("insert into users (name) values ('Alice')"); try tx.execute("insert into users (name) values ('Bob')"); }; ``` ## talon.sqlite.error ### enum SqliteError ```kestrel public enum SqliteError ``` #### case Error ```kestrel case Error(String) ``` #### function clone ```kestrel public func clone() -> SqliteError ``` #### function description ```kestrel public func description() -> String ``` ## talon.sqlite.executor ### protocol SqliteExecutor ```kestrel public protocol SqliteExecutor ``` Common interface for types that can run SQL queries. Both `Database` and `Transaction` conform, so functions can accept `some SqliteExecutor` to work with either: ``` func insertUser(into db: some SqliteExecutor, name: String) throws SqliteError { try db.execute("insert into users (name) values (\(name))"); } ``` #### function execute ```kestrel func execute(SQL) -> () throws SqliteError ``` #### function query ```kestrel func query[R](SQL) -> Array[R] throws SqliteError where R: FromRow ``` ## talon.sqlite.ffi --- ## kestrel/plume 0.2.2 # Plume Lightweight string templating for Kestrel. ## Installation ```toml [dependencies] kestrel/plume = "0.1.0" ``` ## Usage ```kestrel var t = Template() t.put("name", "Alice") t.setInt("count", 42) let html = t.render("

Hello {name}, you have {count} items

") //

Hello Alice, you have 42 items

``` ## Key Types - **Template** - template engine with variable substitution ## API - `put(k, v)` - set a variable (HTML-escaped) - `setRaw(k, v)` - set a variable without escaping - `setInt(k, v)` - set an integer variable - `unset(k)` - remove a variable - `clear()` - remove all variables - `render(pattern)` - render a template string ## Template Syntax - `{key}` - replaced with the variable value - `{{` - literal `{` - `}}` - literal `}` - Missing keys produce an empty string - `put()` automatically escapes `<`, `>`, `&`, `"` for HTML safety ## plume ### struct Template ```kestrel public struct Template { /* private fields */ } ``` A string template engine backed by a `Dictionary[String, String]` of named variables. Variables are stored pre-escaped (or raw) and substituted into pattern strings at render time. The template itself is reusable — set variables once, then render as many patterns as you like. # Examples ``` var t = Template(); t.put("user", "