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

try to fix packet list iterator #7

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
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
31 changes: 17 additions & 14 deletions Sources/MIDIKit/MIDIKit.swift
Original file line number Diff line number Diff line change
Expand Up @@ -447,22 +447,25 @@ extension MIDIInputConnection: Hashable {

extension MIDIPacketList {
public func parse(using parser: inout MIDIParser) -> [Result<[MIDIMessage], Error>] {
withUnsafePointer(to: self) { (packetList) in
let packetCount = numPackets
var packet = UnsafeRawPointer(packetList)
.advanced(by: MemoryLayout<MIDIPacketList>.offset(of: \MIDIPacketList.packet)!)
.assumingMemoryBound(to: MIDIPacket.self)
return (0..<packetCount).map { _ -> Result<[MIDIMessage], Error> in

let data = UnsafeRawPointer(packet)
.advanced(by: MemoryLayout<MIDIPacket>.offset(of: \MIDIPacket.data)!)
.assumingMemoryBound(to: UInt8.self)

let bytes = UnsafeBufferPointer<UInt8>(start: data, count: Int(packet.pointee.length))

let packetCount = numPackets
var packet = self.packet
return (0..<packetCount).map { index -> Result<[MIDIMessage], Error> in
withUnsafeBytes(of: packet.data) { (datPointer) -> Result<[MIDIMessage], Error> in
let data = datPointer.baseAddress!.assumingMemoryBound(to: UInt8.self)
let bytes = UnsafeBufferPointer<UInt8>(start: data, count: Int(packet.length))

let result = Result { try parser.parse(data: bytes) }

packet = UnsafePointer(MIDIPacketNext(packet))
let nextPacket = MIDIPacketNext(&packet)

let isNotLastPacket = index < packetCount
if isNotLastPacket {
assert(
nextPacket != UnsafeMutablePointer(nil),
"Packet pointer should not be nil. MIDIPacketList should contain \(packetCount) packets, but we could only read \(index)"
)
packet = nextPacket.pointee
}

return result
}
Expand Down
16 changes: 16 additions & 0 deletions Tests/MIDIKitTests/MIDIMessageListParseTests.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
//
// File.swift
//
//
// Created by David Nadoba on 01.12.20.
//

import XCTest
@testable import MIDIKit
import CoreMIDI

class MIDIMessageListParseTests: XCTestCase {
func test() {

}
}