Skip to content

Instantly share code, notes, and snippets.

@normanzb
Last active August 22, 2022 11:45
Show Gist options
  • Save normanzb/2d9a059891e4cb3eaaa631dc9b4f9710 to your computer and use it in GitHub Desktop.
Save normanzb/2d9a059891e4cb3eaaa631dc9b4f9710 to your computer and use it in GitHub Desktop.
Argument aggregator for avoid nesting withUnsafeBytes
private func argAgregate<ResultType> (
dataObjects: [Data],
callback: (([UnsafeRawBufferPointer]) -> ResultType)
) -> ResultType {
var callbacks = [(([UnsafeRawBufferPointer]) -> Void)]()
let withOutFirstDataObjects = dataObjects.dropFirst()
withOutFirstDataObjects.enumerated().forEach { (index, value) in
callbacks.append { pointers in
dataObjects[index + 1].withUnsafeBytes { pointer in
var newPointers: [UnsafeRawBufferPointer] = []
newPointers.append(contentsOf: pointers)
newPointers.append(pointer)
callbacks[index + 1](newPointers)
} }
}
dataObjects[0].withUnsafeBytes { firstPointer in
callbacks[0]([firstPointer])
}
}
// to use it
argAgregate(dataObjects: [key, vi, dataIn]) { pointers in
// no array destructuring in swift, lame
let keyPointer = pointers[0]
let viPointer = pointers[1]
let dataInPointer = pointers[2]
CCCrypt(
CCOperation(op),
CCAlgorithm(alg),
CCOptions(kCCOptionPKCS7Padding),
keyPointer.bindMemory(to: UInt8.self).baseAddress,
key.count,
viPointer.bindMemory(to: UInt8.self).baseAddress,
dataInPointer.bindMemory(to: UInt8.self).baseAddress,
dataIn.count,
dataOutPointer.bindMemory(to: UInt8.self).baseAddress,
dataOut.count,
&dataOutMoved
)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment