Output.swift 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. // Output.swift
  2. // This file is part of KeePass.swift
  3. //
  4. // Copyright © 2021 Maxime Epain. All rights reserved.
  5. //
  6. // KeePass.swift is free software: you can redistribute it and/or modify
  7. // it under the terms of the GNU General Public License as published by
  8. // the Free Software Foundation, either version 3 of the License, or
  9. // (at your option) any later version.
  10. //
  11. // KeePass.swift is distributed in the hope that it will be useful,
  12. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  14. // GNU General Public License for more details.
  15. //
  16. // You should have received a copy of the GNU General Public License
  17. // along with KeePass.swift. If not, see <https://www.gnu.org/licenses/>.
  18. import Foundation
  19. public class Output {
  20. public var bytes: Bytes? {
  21. guard let data = stream.property(forKey: .dataWrittenToMemoryStreamKey) as? Data else { return nil }
  22. return Bytes(data: data)
  23. }
  24. public private(set) var lenght = 0
  25. private let stream: OutputStream
  26. public init() {
  27. stream = OutputStream.toMemory()
  28. stream.open()
  29. }
  30. public init?(url: URL, append: Bool = false) {
  31. guard let stream = OutputStream(url: url, append: append) else { return nil }
  32. self.stream = stream
  33. self.stream.open()
  34. }
  35. deinit {
  36. stream.close()
  37. }
  38. public func write(_ bytes: Bytes) throws {
  39. let count = stream.write(bytes.rawValue, maxLength: bytes.lenght)
  40. if let error = stream.streamError { throw error }
  41. lenght += count
  42. }
  43. public func write<T>(_ value: T) throws where T: Writable {
  44. try value.write(to: self)
  45. }
  46. }