Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

early return on empty buffer #6

Merged
merged 1 commit into from
Jul 10, 2023
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 15 additions & 4 deletions Sources/Waveform/Renderer.swift
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,7 @@ class Renderer: NSObject, MTKViewDelegate {

func mtkView(_: MTKView, drawableSizeWillChange _: CGSize) {}

func selectBuffers(width: CGFloat) -> (MTLBuffer, MTLBuffer) {
func selectBuffers(width: CGFloat) -> (MTLBuffer?, MTLBuffer?) {
var level = 0
for (minBuffer, maxBuffer) in zip(minBuffers, maxBuffers) {
if CGFloat(minBuffer.length / MemoryLayout<Float>.size) < width {
Expand All @@ -73,9 +73,15 @@ class Renderer: NSObject, MTKViewDelegate {
level += 1
}

return (minBuffers.last!, maxBuffers.last!)
// Use optional binding to safely access last element of each array
if let minBufferLast = minBuffers.last, let maxBufferLast = maxBuffers.last {
return (minBufferLast, maxBufferLast)
} else {
// If either array is empty, return nil
return (nil, nil)
}
}

func encode(to commandBuffer: MTLCommandBuffer,
pass: MTLRenderPassDescriptor,
width: CGFloat)
Expand All @@ -86,7 +92,12 @@ class Renderer: NSObject, MTKViewDelegate {
let startFactor = Float(start) / highestResolutionCount
let lengthFactor = Float(length) / highestResolutionCount

let (minBuffer, maxBuffer) = selectBuffers(width: width / CGFloat(lengthFactor))
let (minBufferOpt, maxBufferOpt) = selectBuffers(width: width / CGFloat(lengthFactor))
guard let minBuffer = minBufferOpt, let maxBuffer = maxBufferOpt else {
//early return to gracefully fail.
return
}

let enc = commandBuffer.makeRenderCommandEncoder(descriptor: pass)!
enc.setRenderPipelineState(pipeline)

Expand Down