Last active
January 5, 2021 12:24
-
-
Save ctreffs/95c6126c809f71782230024fe3337bfa to your computer and use it in GitHub Desktop.
[Swift] Access uniform tuples (i.e. C arrays) like a collection in Swift
This file contains hidden or 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
public enum CArray<T> { | |
@discardableResult | |
@_transparent | |
public static func write<C, O>(_ cArray: inout C, _ body: (UnsafeMutableBufferPointer<T>) throws -> O) rethrows -> O { | |
try withUnsafeMutablePointer(to: &cArray) { | |
try body(UnsafeMutableBufferPointer<T>(start: UnsafeMutableRawPointer($0).assumingMemoryBound(to: T.self), | |
count: (MemoryLayout<C>.stride / MemoryLayout<T>.stride))) | |
} | |
} | |
@discardableResult | |
@_transparent | |
public static func read<C, O>(_ cArray: C, _ body: (UnsafeBufferPointer<T>) throws -> O) rethrows -> O { | |
try withUnsafePointer(to: cArray) { | |
try body(UnsafeBufferPointer<T>(start: UnsafeRawPointer($0).assumingMemoryBound(to: T.self), | |
count: (MemoryLayout<C>.stride / MemoryLayout<T>.stride))) | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Usage: