From 143e336ce129b202fc8a2b5f87fe22e354f8b5da Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?furby=E2=84=A2?= Date: Sat, 4 May 2024 18:18:23 -0600 Subject: [PATCH] Hotfix alloc crash, when no read data avail. * This fixes a Swift allocation crash, when attempting to allocate an internally managed buffer with a capacity of 0 (zero), if there's no read data available for the data copy - we early out and return nil. --- Sources/SwiftTreeSitter/Input.swift | 13 ++++++++----- 1 file changed, 8 insertions(+), 5 deletions(-) diff --git a/Sources/SwiftTreeSitter/Input.swift b/Sources/SwiftTreeSitter/Input.swift index d203bbe..0fbdc33 100644 --- a/Sources/SwiftTreeSitter/Input.swift +++ b/Sources/SwiftTreeSitter/Input.swift @@ -50,14 +50,17 @@ private func readFunction(payload: UnsafeMutableRawPointer?, byteIndex: UInt32, // get our self reference let wrapper: Input = Unmanaged.fromOpaque(payload!).takeUnretainedValue() - // call our Swift-friendly reader block - guard let data = wrapper.readBlock(Int(byteIndex), Point(internalPoint: position)) else { - bytesRead?.pointee = 0 - return nil + // call our Swift-friendly reader block, or early out if there's no data to copy. + guard let data = wrapper.readBlock(Int(byteIndex), Point(internalPoint: position)), + data.count > 0 + else + { + bytesRead?.pointee = 0 + return nil } // copy the data into an internally-managed buffer with a lifetime of wrapper - let buffer = Input.Buffer.allocate(capacity: data.count) + let buffer = Input.Buffer.allocate(capacity: data.count) let copiedLength = data.copyBytes(to: buffer) precondition(copiedLength == data.count)