Skip to content

Commit

Permalink
Hotfix alloc crash, when no read data avail. (#24)
Browse files Browse the repository at this point in the history
* 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.
  • Loading branch information
furby-tm authored May 5, 2024
1 parent b0e00f8 commit 96ad58b
Showing 1 changed file with 8 additions and 5 deletions.
13 changes: 8 additions & 5 deletions Sources/SwiftTreeSitter/Input.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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)

Expand Down

0 comments on commit 96ad58b

Please sign in to comment.