Skip to content

Instantly share code, notes, and snippets.

@laevandus
Last active December 11, 2022 11:16
Embed
What would you like to do?
extension Data {
init(inputStream: InputStream) throws {
inputStream.open()
defer { inputStream.close() }
self.init()
let bufferSize = 512
var readBuffer = [UInt8](repeating: 0, count: bufferSize)
while inputStream.hasBytesAvailable {
let readBytes = inputStream.read(&readBuffer, maxLength: bufferSize)
switch readBytes {
case 0:
break
case ..<0:
throw inputStream.streamError!
default:
append(readBuffer, count: readBytes)
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment