|
| 1 | +// |
| 2 | +// TLVCoding.swift |
| 3 | +// PureSwift |
| 4 | +// |
| 5 | +// Created by Alsey Coleman Miller on 3/8/18. |
| 6 | +// Copyright © 2018 PureSwift. All rights reserved. |
| 7 | +// |
| 8 | + |
| 9 | +import Foundation |
| 10 | + |
| 11 | +/// Type-Length-Value Codable |
| 12 | +public typealias TLVCodable = TLVEncodable & TLVDecodable |
| 13 | + |
| 14 | +/// TLV Decodable type |
| 15 | +public protocol TLVDecodable { |
| 16 | + |
| 17 | + static var typeCode: TLVTypeCode { get } |
| 18 | + |
| 19 | + init?(valueData: Foundation.Data) |
| 20 | +} |
| 21 | + |
| 22 | +public protocol TLVEncodable { |
| 23 | + |
| 24 | + static var typeCode: TLVTypeCode { get } |
| 25 | + |
| 26 | + var valueData: Foundation.Data { get } |
| 27 | +} |
| 28 | + |
| 29 | +/// TLV Type Code header |
| 30 | +public protocol TLVTypeCode { |
| 31 | + |
| 32 | + init?(rawValue: UInt8) |
| 33 | + |
| 34 | + var rawValue: UInt8 { get } |
| 35 | +} |
| 36 | + |
| 37 | +// MARK: - Codable Implementations |
| 38 | + |
| 39 | +public extension TLVDecodable where Self: RawRepresentable, Self.RawValue: RawRepresentable, Self.RawValue.RawValue: Integer { |
| 40 | + |
| 41 | + public init?(valueData: Foundation.Data) { |
| 42 | + |
| 43 | + typealias IntegerType = Self.RawValue.RawValue |
| 44 | + |
| 45 | + assert(MemoryLayout<IntegerType>.size == 1) |
| 46 | + |
| 47 | + guard valueData.count == 1 |
| 48 | + else { return nil } |
| 49 | + |
| 50 | + let valueByte = valueData[0] |
| 51 | + |
| 52 | + guard let rawValue = RawValue.init(rawValue: numericCast(valueByte) as IntegerType) |
| 53 | + else { return nil } |
| 54 | + |
| 55 | + self.init(rawValue: rawValue) |
| 56 | + } |
| 57 | +} |
| 58 | + |
| 59 | +public extension TLVEncodable where Self: RawRepresentable, Self.RawValue: RawRepresentable, Self.RawValue.RawValue: Integer { |
| 60 | + |
| 61 | + public var valueData: Foundation.Data { |
| 62 | + |
| 63 | + typealias IntegerType = Self.RawValue.RawValue |
| 64 | + |
| 65 | + assert(MemoryLayout<IntegerType>.size == 1) |
| 66 | + |
| 67 | + let byte = numericCast(rawValue.rawValue) as UInt8 |
| 68 | + |
| 69 | + return Data([byte]) |
| 70 | + } |
| 71 | +} |
| 72 | + |
| 73 | +public extension TLVDecodable where Self: RawRepresentable, Self.RawValue: StringProtocol { |
| 74 | + |
| 75 | + public init?(valueData: Foundation.Data) { |
| 76 | + |
| 77 | + guard let string = String(data: valueData, encoding: .utf8) as? Self.RawValue |
| 78 | + else { return nil } |
| 79 | + |
| 80 | + self.init(rawValue: string) |
| 81 | + } |
| 82 | +} |
| 83 | + |
| 84 | +public extension TLVEncodable where Self: RawRepresentable, Self.RawValue: StringProtocol { |
| 85 | + |
| 86 | + public var valueData: Foundation.Data { |
| 87 | + |
| 88 | + guard let data = (self.rawValue as? String)?.data(using: .utf8) |
| 89 | + else { fatalError("Could not encode string") } |
| 90 | + |
| 91 | + return data |
| 92 | + } |
| 93 | +} |
0 commit comments