Input.swift 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. // Input.swift
  2. // This file is part of MiKee.
  3. //
  4. // Copyright © 2019 Maxime Epain. All rights reserved.
  5. //
  6. // MiKee 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. // MiKee 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 MiKee. 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 {
  23. bytes.suffix(from: offset)
  24. }
  25. public var hasBytesAvailable: Bool { stream.hasBytesAvailable }
  26. private let stream: InputStream
  27. public init(bytes: Bytes) {
  28. self.bytes = bytes
  29. let data = Data(bytes.rawValue)
  30. stream = InputStream(data: data)
  31. stream.open()
  32. }
  33. deinit {
  34. stream.close()
  35. }
  36. public func read(lenght: Int) throws -> Bytes {
  37. var out = Bytes(lenght: lenght)
  38. let count = stream.read(&out.rawValue, maxLength: lenght)
  39. if let error = stream.streamError { throw error }
  40. offset += count
  41. return out.prefix(count)
  42. }
  43. public func read<T>(lenght: Int) throws -> T where T: BytesRepresentable {
  44. let bytes = try read(lenght: lenght)
  45. return try T(bytes)
  46. }
  47. public func read<T>() throws -> T where T: Readable {
  48. return try T(from: self)
  49. }
  50. public func read<T>(maxLenght: Int) throws -> [T] where T: Readable {
  51. var array = [T]()
  52. var count = 0
  53. while count < maxLenght {
  54. array.append(try read() as T)
  55. count += 1
  56. }
  57. return array
  58. }
  59. }