Skip to content

Instantly share code, notes, and snippets.

@ctreffs
Last active January 5, 2021 12:24
Show Gist options
  • Save ctreffs/95c6126c809f71782230024fe3337bfa to your computer and use it in GitHub Desktop.
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
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)))
}
}
}
@ctreffs
Copy link
Author

ctreffs commented Sep 1, 2019

Usage:

// var MouseDown: (Bool, Bool, Bool, Bool, Bool)
let button = event.buttonNumber
 CArray<Bool>.write(&io.pointee.MouseDown) { mouseButtons in
     if button >= 0 && button < mouseButtons.count {
        mouseButtons[Int(button)] = true
     }
 }

@ctreffs
Copy link
Author

ctreffs commented Sep 1, 2019

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment