| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768 |
- // TLV.swift
- // This file is part of MiKee.
- //
- // Copyright © 2019 Maxime Epain. All rights reserved.
- //
- // MiKee is free software: you can redistribute it and/or modify
- // it under the terms of the GNU General Public License as published by
- // the Free Software Foundation, either version 3 of the License, or
- // (at your option) any later version.
- //
- // MiKee is distributed in the hope that it will be useful,
- // but WITHOUT ANY WARRANTY; without even the implied warranty of
- // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- // GNU General Public License for more details.
- //
- // You should have received a copy of the GNU General Public License
- // along with MiKee. If not, see <https://www.gnu.org/licenses/>.
- import Foundation
- public struct TLV<Type, Lenght> where Lenght: BinaryInteger {
- public let type: Type
- public var value: Bytes
- public init(type: Type, value: Bytes) {
- self.type = type
- self.value = value
- }
- public func get<T>() throws -> T where T: Readable {
- let stream = Input(bytes: value)
- return try stream.read()
- }
- public mutating func set<T>(_ value: T) throws where T: Writable {
- self.value = withUnsafeBytes(of: value) { Bytes($0) }
- }
- }
- extension TLV: Readable where Type: Readable, Lenght: Readable {
- public init(from input: Input) throws {
- type = try input.read()
- let lenght = try input.read() as Lenght
- value = try input.read(lenght: Int(lenght))
- }
- }
- extension TLV: Writable where Type: Writable, Lenght: Writable {
- public func write(to output: Output) throws {
- try output.write(type)
- try output.write(Lenght(value.lenght))
- try output.write(value)
- }
- }
- extension TLV: CustomDebugStringConvertible {
- public var debugDescription: String {
- "(T:\(type) L:\(value.lenght))"
- }
- }
|