Files
Lyrebird/Sources/Lyrebird/Patterns/Engines/SequencePatternEngine.swift
T

60 lines
1.8 KiB
Swift

// SequencePatternEngine.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
/// Engine backing ``Pattern/sequence(_:repeats:offset:)``.
///
/// Cycles through `values` in order. Each full pass increments the cycle counter.
/// `repeats` full cycles exhaust the source; `-1` is infinite.
///
/// `offset` shifts only the *first* pass: emission starts at `values[offset]`
/// and runs to the end of the array (a short opening pass), after which every
/// later cycle runs the full array from index `0`. `reset()` returns to the
/// offset start.
internal final class SequencePatternEngine<T>: _PatternEngine {
internal typealias Element = T
private let _values: [T]
private let _repeats: Int
private let _offset: Int
private var _index: Int
private var _cycleCount: Int = 0
internal init(
values: [T],
repeats: Int,
offset: Int = 0
) {
_values = values
_repeats = repeats
// Normalise the offset into [0, count) so out-of-range / negative
// offsets wrap rather than trap. Empty arrays pin to 0 (next() guards).
let count: Int = values.count
let normalized: Int = count > 0 ? ((offset % count) + count) % count : 0
_offset = normalized
_index = normalized
}
internal var isExhausted: Bool {
_repeats >= 0 && _cycleCount >= _repeats
}
internal func next() -> T? {
guard !isExhausted, !_values.isEmpty else { return nil }
let value: T = _values[_index]
_index += 1
if _index >= _values.count {
_index = 0
_cycleCount += 1
}
return value
}
internal func reset() {
_index = _offset
_cycleCount = 0
}
}