Skip to content

Instantly share code, notes, and snippets.

@dimitris-c
Created November 19, 2020 13:13
Show Gist options
  • Save dimitris-c/c592df01ab46272e118e68e2dd1f3768 to your computer and use it in GitHub Desktop.
Save dimitris-c/c592df01ab46272e118e68e2dd1f3768 to your computer and use it in GitHub Desktop.
Chucks of size from Data
@inline(__always)
private func chunks(of size: Int, in data: Data) -> [Data] {
let chunkSize = size
return data.withUnsafeBytes { (buffer: UnsafeRawBufferPointer) -> [Data] in
guard !buffer.isEmpty else { return [] }
let mutableRawPointer = UnsafeMutableRawBufferPointer(mutating: buffer)
let totalSize = buffer.count
var offset = 0
var chunks = [Data]()
while offset < totalSize {
let chunkSize = offset + chunkSize > totalSize ? totalSize - offset : chunkSize
let data = Data(bytesNoCopy: mutableRawPointer.baseAddress! + offset, count: chunkSize, deallocator: .none)
chunks.append(data)
offset += chunkSize
}
return chunks
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment