Created
March 11, 2020 19:49
-
-
Save natecook1000/c323ad31ab4eb8f8c5f03444a4266c57 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/// Calls the given closure with a buffer over the given tuple's elements. | |
/// | |
/// - Parameters: | |
/// - tuple: The tuple. | |
/// - elementType: The type of all of the elements in the tuple. | |
/// - body: The closure to execute. | |
/// | |
/// - Returns: The result of `body`, if any. | |
func withUnsafeElementBufferPointer<Tuple, Element, Result>( | |
of tuple: Tuple, | |
elementType: Element.Type, | |
body: (UnsafeBufferPointer<Element>) throws -> Result | |
) rethrows -> Result { | |
assert( | |
MemoryLayout<Tuple>.stride.isMultiple(of: MemoryLayout<Element>.stride), | |
"Incompatible tuple and element types.") | |
let count = MemoryLayout<Tuple>.stride / MemoryLayout<Element>.stride | |
return try withUnsafeBytes(of: tuple) { bytes -> Result in | |
let start = bytes.baseAddress!.assumingMemoryBound(to: Element.self) | |
return try body(.init(start: start, count: count)) | |
} | |
} | |
let x = (1, 2, 3, 4) | |
let sum = withUnsafeElementBufferPointer(of: x, elementType: Int.self) { | |
$0.reduce(0, +) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment