Re: qsort_b in Swift


Quincey Morris
 

On Sep 15, 2017, at 21:18 , Gerriet M. Denkmann <g@...> wrote:

I would like to compare the efficiency of “sort” with “qsort_b”, but cannot figure out how to call it in Swift.

Yikes, this is masochistic!

This is the prototype:

public func qsort_b(_ __base: UnsafeMutableRawPointer!, _ __nel: Int, _ __width: Int, _ __compar: @escaping (UnsafeRawPointer?, UnsafeRawPointer?) -> Int32)

So I think the code looks like this (syntax-checked in Xcode 9 but not tested):

var sortedArray = [UInt32]()
qsort_b (&sortedArray, sortedArray.count, MemoryLayout<UInt32>.stride) {
(aPtr, bPtr) -> Int32 in
guard let a = aPtr?.load (fromByteOffset: 0, as: UInt32.self) else { return 0 } // or otherwise handle a nil pointer
guard let b = bPtr?.load (fromByteOffset: 0, as: UInt32.self) else { return 0 } // or otherwise handle a nil pointer
return a > b ? 1 : a < b ? -1 : 0
}

The “&sortedArray” relies on the compiler auto-bridging to the UnsafeMutableRawPointer. I don’t know if there’s an easier way to get the UInt32 values from the closure parameters, but perhaps “load” is the right way. Also, I may have the comparison test in the return backwards.

Join cocoa@apple-dev.groups.io to automatically receive all group messages.