OutputStream.swift 1.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041
  1. //
  2. // OutputStream.swift
  3. // LoopKit
  4. //
  5. // Created by Darin Krauss on 8/28/20.
  6. // Copyright © 2020 LoopKit Authors. All rights reserved.
  7. //
  8. import Foundation
  9. extension OutputStream {
  10. func write(_ string: String) throws {
  11. if let streamError = streamError {
  12. throw streamError
  13. }
  14. let bytes = [UInt8](string.utf8)
  15. write(bytes, maxLength: bytes.count)
  16. if let streamError = streamError {
  17. throw streamError
  18. }
  19. }
  20. func write(_ data: Data) throws {
  21. if let streamError = streamError {
  22. throw streamError
  23. }
  24. if data.isEmpty {
  25. return
  26. }
  27. _ = data.withUnsafeBytes { (unsafeRawBuffer: UnsafeRawBufferPointer) -> UInt8 in
  28. if let unsafe = unsafeRawBuffer.baseAddress?.assumingMemoryBound(to: UInt8.self) {
  29. write(unsafe, maxLength: unsafeRawBuffer.count)
  30. }
  31. return 0
  32. }
  33. if let streamError = streamError {
  34. throw streamError
  35. }
  36. }
  37. }