Input.swift 1.9 KB

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