Files
Lyrebird/Sources/Lyrebird/Buffers/RTScratchBuffer.swift
T
josh 844dc4d9cd v2.1.0 release: Swift 6.4 modernization
Typed throws across the closed-error-set APIs (OSC, MIDI, engine add/schedule,
bus/config/parameter, and the WAV/RF64/Spectral file codecs — source-compatible
narrowing, new .ioFailure cases), plus internal hardening: NSLock-guarded
scheduling/MIDI state moved to Mutex<State>, and the Spectral/FFT scratch owners
moved to a ~Copyable RTScratchBuffer RAII buffer. No API or behavioral change.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-09-24 19:54:59 -07:00

112 lines
4.4 KiB
Swift

// RTScratchBuffer.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
/// A single-owner, heap-allocated scratch buffer with compiler-enforced lifetime.
///
/// `RTScratchBuffer` replaces the hand-paired `UnsafeMutablePointer.allocate` /
/// `deinitialize` / `deallocate` dance that scratch-owning generators (the
/// Spectral / FFT family) repeat across many buffers. Because the type is
/// `~Copyable`, the compiler guarantees:
///
/// - it is freed **exactly once**, at `deinit`, with the correct element count —
/// no forgotten free, no double free, no count mismatch;
/// - it cannot be copied, so two owners can never alias the same allocation.
///
/// It carries no ARC: the handle is a raw pointer, so reading or writing an
/// element is a plain load/store with no retain/release traffic. Every accessor
/// is `@inline(__always)`, so a generator's hot loop compiles to the same code
/// as the raw-pointer form it replaces.
///
/// **RT usage.** Allocation happens in `init` (off the render thread, at
/// generator setup); `deinit` runs when the owning generator is freed, which the
/// engine does off the RT thread via its free queue. Element access
/// (`subscript`, ``baseAddress``) is RT-safe — no allocation, no locking, no ARC.
/// Pass ``baseAddress`` to Accelerate / vDSP calls exactly as with a raw pointer.
///
/// ```swift
/// // In a generator:
/// private let _scratch: RTScratchBuffer<Float>
/// init(size: Int) {
/// _scratch = RTScratchBuffer(count: size) // allocated + zero-filled
/// }
/// // deinit is automatic — no teardown code needed.
///
/// func process(count: Int) {
/// vDSP_vsq(input, 1, _scratch.baseAddress, 1, vDSP_Length(count))
/// let peak: Float = _scratch[0]
/// }
/// ```
@_spi(LyrebirdExtensions)
public struct RTScratchBuffer<Element>: ~Copyable {
@usableFromInline let _base: UnsafeMutablePointer<Element>
@usableFromInline let _count: Int
/// Allocates `count` elements, each initialised to `value`.
///
/// Use this when the buffer needs a non-zero initial fill (e.g. a unity gain
/// table initialised to `1`), where the zero-filling ``init(count:)`` would
/// silently seed the wrong value.
///
/// - Parameters:
/// - count: Element capacity. Must be `> 0`.
/// - value: Value written to every element.
@inlinable
public init(count: Int, repeating value: Element) {
precondition(count > 0, "RTScratchBuffer requires count > 0")
_count = count
_base = UnsafeMutablePointer<Element>.allocate(capacity: count)
_base.initialize(repeating: value, count: count)
}
/// Allocates `count` elements, zero-filled. Convenience for numeric buffers.
///
/// - Parameter count: Element capacity. Must be `> 0`.
@inlinable
public init(count: Int) where Element: Numeric {
self.init(count: count, repeating: .zero)
}
/// Base pointer, for Accelerate / vDSP interop and raw indexing. Valid only
/// for the duration of the call — never persist it beyond the lifetime of the
/// buffer (i.e. of the generator that owns it), exactly as with the raw
/// `UnsafeMutablePointer` this replaces.
@inlinable @inline(__always)
public var baseAddress: UnsafeMutablePointer<Element> { _base }
/// Element capacity.
@inlinable @inline(__always)
public var count: Int { _count }
/// Element access. No bounds check — callers stay within `count`, exactly as
/// they must with the raw pointer this replaces.
///
/// The setter is `nonmutating`: writing an element stores through the base
/// pointer and leaves the struct's own fields untouched, so a buffer held as a
/// `let` (the usual case in a generator) is still writable — matching the raw
/// `UnsafeMutablePointer` this replaces.
@inlinable @inline(__always)
public subscript(_ index: Int) -> Element {
get {
#if DEBUG
precondition(index >= 0 && index < _count, "RTScratchBuffer index out of range")
#endif
return _base[index]
}
nonmutating set {
#if DEBUG
precondition(index >= 0 && index < _count, "RTScratchBuffer index out of range")
#endif
_base[index] = newValue
}
}
deinit {
_base.deinitialize(count: _count)
_base.deallocate()
}
}