TLV.swift 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. // TLV.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 struct TLV<Type, Lenght> where Lenght: BinaryInteger {
  20. public let type: Type
  21. public var value: Bytes
  22. public init(type: Type, value: Bytes) {
  23. self.type = type
  24. self.value = value
  25. }
  26. public func get<T>() throws -> T where T: Readable {
  27. let stream = Input(bytes: value)
  28. return try stream.read()
  29. }
  30. public mutating func set<T>(_ value: T) throws where T: Writable {
  31. self.value = withUnsafeBytes(of: value) { Bytes($0) }
  32. }
  33. }
  34. extension TLV: Readable where Type: Readable, Lenght: Readable {
  35. public init(from input: Input) throws {
  36. type = try input.read()
  37. let lenght = try input.read() as Lenght
  38. value = try input.read(lenght: Int(lenght))
  39. }
  40. }
  41. extension TLV: Writable where Type: Writable, Lenght: Writable {
  42. public func write(to output: Output) throws {
  43. try output.write(type)
  44. try output.write(Lenght(value.lenght))
  45. try output.write(value)
  46. }
  47. }
  48. extension TLV: CustomDebugStringConvertible {
  49. public var debugDescription: String {
  50. "(T:\(type) L:\(value.lenght))"
  51. }
  52. }