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

60 lines
1.8 KiB
Swift

// ShufflePatternEngine.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
/// Engine backing ``Pattern/shuffle(_:repeats:seed:)``.
///
/// Permutes `values` once at init via Fisher-Yates with a seeded xorshift64
/// PRNG, then cycles through the permuted order like ``SequencePatternEngine``.
/// `repeats` full cycles exhaust the source; `-1` is infinite. `reset()`
/// rewinds the cycle counter but intentionally does **not** re-shuffle —
/// the same permutation replays on retrigger, mirroring SC `Pshuf` semantics.
internal final class ShufflePatternEngine<T>: _PatternEngine {
internal typealias Element = T
private let _shuffled: [T]
private let _repeats: Int
private var _index: Int = 0
private var _cycleCount: Int = 0
internal init(
values: [T],
repeats: Int,
seed: UInt64?
) {
var rng: UInt64 = lyrebirdSeedXorshift64(from: seed)
var buffer: [T] = values
// Fisher-Yates: walk from end to start, swap with random earlier index.
if buffer.count > 1 {
for i: Int in (1..<buffer.count).reversed() {
let j: Int = Int(xorshift64NextRaw(&rng) % UInt64(i + 1))
buffer.swapAt(i, j)
}
}
_shuffled = buffer
_repeats = repeats
}
internal var isExhausted: Bool {
isCounterExhausted(count: _cycleCount, limit: _repeats)
}
internal func next() -> T? {
guard !isExhausted, !_shuffled.isEmpty else { return nil }
let value: T = _shuffled[_index]
_index += 1
if _index >= _shuffled.count {
_index = 0
_cycleCount += 1
}
return value
}
internal func reset() {
_index = 0
_cycleCount = 0
}
}