Skip to content

Instantly share code, notes, and snippets.

@jwhitley
Created December 24, 2016 02:16
Show Gist options
  • Save jwhitley/c219d4d8bda43be1e48d295d820eea16 to your computer and use it in GitHub Desktop.
Save jwhitley/c219d4d8bda43be1e48d295d820eea16 to your computer and use it in GitHub Desktop.
Swift 3 ArraySlice setBytes extension
import Foundation
extension ArraySlice {
// Overwrites the ArraySlice region with the passed-in array of bytes
mutating func setBytes(_ from: [UInt8]) {
var fromIter = from.makeIterator()
self.withUnsafeMutableBytes { bytes in
for i in stride(from: bytes.startIndex, to: bytes.endIndex - 1, by: 1) {
if let fromByte = fromIter.next() {
bytes[i] = fromByte
}
}
}
}
// Converts its parameter to a byte memory image (e.g. UInt32 as
// a length 4 array of UInt8) and overwrites the slice.
//
mutating func setBytes<T>(_ from: T) {
var buffer = from
let count = MemoryLayout<T>.size
let bytePtr = withUnsafePointer(to: &buffer) {
$0.withMemoryRebound(to: UInt8.self, capacity: count) {
UnsafeBufferPointer(start: $0, count: count)
}
}
let byteArray = Array(bytePtr)
self.setBytes(byteArray)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment