@@ -85,6 +85,70 @@ public extension TLVEncodable where Self: RawRepresentable, Self.RawValue == Str
8585 return data
8686 }
8787}
88+
89+ #elseif swift(>=3.0)
90+
91+ public extension TLVDecodable where Self: RawRepresentable , Self. RawValue: RawRepresentable , Self. RawValue. RawValue: UnsignedInteger {
92+
93+ public init ? ( valueData: Foundation . Data ) {
94+
95+ typealias IntegerType = Self . RawValue . RawValue
96+
97+ assert ( MemoryLayout< IntegerType> . size == 1 , " Default implementation only for UInt8 enums " )
98+
99+ guard valueData. count == 1
100+ else { return nil }
101+
102+ let valueByte = valueData [ 0 ]
103+
104+ guard let rawValue = RawValue . init ( rawValue: valueByte as! IntegerType )
105+ else { return nil }
106+
107+ self . init ( rawValue: rawValue)
108+ }
109+ }
110+
111+ public extension TLVEncodable where Self: RawRepresentable , Self. RawValue: RawRepresentable , Self. RawValue. RawValue: UnsignedInteger {
112+
113+ public var valueData : Foundation . Data {
114+
115+ typealias IntegerType = Self . RawValue . RawValue
116+
117+ assert ( MemoryLayout< IntegerType> . size == 1 , " Default implementation only for UInt8 enums " )
118+
119+ let byte = numericCast ( rawValue. rawValue) as UInt8
120+
121+ return Data ( [ byte] )
122+ }
123+ }
124+
125+ public extension TLVDecodable where Self: RawRepresentable , Self. RawValue: ExpressibleByStringLiteral {
126+
127+ public init ? ( valueData: Foundation . Data ) {
128+
129+ typealias StringType = Self . RawValue
130+
131+ assert ( Self . RawValue. self == String . self, " Default implementation only for String " )
132+
133+ guard let string = String ( data: valueData, encoding: . utf8)
134+ else { return nil }
135+
136+ self . init ( rawValue: string as! StringType )
137+ }
138+ }
139+
140+ public extension TLVEncodable where Self: RawRepresentable , Self. RawValue: ExpressibleByStringLiteral {
141+
142+ public var valueData : Foundation . Data {
143+
144+ assert ( Self . RawValue. self == String . self, " Default implementation only for String " )
145+
146+ guard let data = ( self . rawValue as! String ) . data ( using: . utf8)
147+ else { fatalError ( " Could not encode string " ) }
148+
149+ return data
150+ }
151+ }
88152
89153#endif
90154
0 commit comments