Input.swift 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. // Input.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 Input {
  20. public let bytes: Bytes
  21. public private(set) var offset = 0
  22. public var remaining: Bytes { bytes.suffix(from: offset) }
  23. public var hasBytesAvailable: Bool { stream.hasBytesAvailable }
  24. private let stream: InputStream
  25. public init(bytes: Bytes) {
  26. self.bytes = bytes
  27. let data = Data(bytes.rawValue)
  28. stream = InputStream(data: data)
  29. stream.open()
  30. }
  31. deinit {
  32. stream.close()
  33. }
  34. public func read(lenght: Int) throws -> Bytes {
  35. var out = Bytes(lenght: lenght)
  36. let count = stream.read(&out.rawValue, maxLength: lenght)
  37. if let error = stream.streamError { throw error }
  38. offset += count
  39. return out.prefix(count)
  40. }
  41. public func read<T>(lenght: Int) throws -> T where T: LosslessBytesConvertible {
  42. let bytes = try read(lenght: lenght)
  43. return try T(bytes)
  44. }
  45. public func read<T>() throws -> T where T: Readable {
  46. return try T(from: self)
  47. }
  48. public func read<T>(maxLenght: Int) throws -> [T] where T: Readable {
  49. var array = [T]()
  50. var count = 0
  51. while count < maxLenght {
  52. array.append(try read() as T)
  53. count += 1
  54. }
  55. return array
  56. }
  57. }