DataOutputStream.swift 999 B

1234567891011121314151617181920212223242526272829303132333435363738
  1. //
  2. // DataOutputStream.swift
  3. // LoopKit
  4. //
  5. // Created by Pete Schwamb on 5/7/2023
  6. // Copyright © 2020 LoopKit Authors. All rights reserved.
  7. //
  8. import Foundation
  9. enum DataOutputStreamError: Error {
  10. case couldNotEncodeString
  11. }
  12. public protocol DataOutputStream: AnyObject {
  13. // Writes data to the stream. Errors detected while
  14. // processing should be thrown.
  15. func write(_ data: Data) throws
  16. // Lets the receiver know the stream is finished.
  17. // If sync is true, block until data is finished processing.
  18. // If no errors thrown, then data was processed successfully.
  19. func finish(sync: Bool) throws
  20. var streamError: Error? { get }
  21. }
  22. extension DataOutputStream {
  23. // Convenience function to convert String into utf8 Data and write it.
  24. public func write(_ string: String) throws {
  25. if let data = string.data(using: .utf8) {
  26. try write(data)
  27. } else {
  28. throw DataOutputStreamError.couldNotEncodeString
  29. }
  30. }
  31. }