Skip to content

Instantly share code, notes, and snippets.

@natecook1000
Created March 11, 2020 19:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save natecook1000/c323ad31ab4eb8f8c5f03444a4266c57 to your computer and use it in GitHub Desktop.
Save natecook1000/c323ad31ab4eb8f8c5f03444a4266c57 to your computer and use it in GitHub Desktop.
/// 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