@@ -2,22 +2,28 @@ import Foundation
22
33final class ValueDecoder : AbstractDecodingNode , SingleValueDecodingContainer {
44
5- let data : BinaryStreamProvider
5+ private var storage : Storage
66
77 private let isOptional : Bool
88
99 private let isInUnkeyedContainer : Bool
1010
11- init ( data : BinaryStreamProvider , isOptional: Bool , isInUnkeyedContainer: Bool , path: [ CodingKey ] , info: UserInfo ) {
12- self . data = data
11+ init ( storage : Storage , isOptional: Bool , isInUnkeyedContainer: Bool , path: [ CodingKey ] , info: UserInfo ) {
12+ self . storage = storage
1313 self . isOptional = isOptional
1414 self . isInUnkeyedContainer = isInUnkeyedContainer
1515 super. init ( path: path, info: info)
1616 }
1717
18+ private func asDecoder( ) -> BinaryStreamProvider {
19+ let decoder = self . storage. useAsDecoder ( )
20+ self . storage = . decoder( decoder)
21+ return decoder
22+ }
23+
1824 func decodeNil( ) -> Bool {
1925 do {
20- let byte = try data . getByte ( path: codingPath)
26+ let byte = try asDecoder ( ) . getByte ( path: codingPath)
2127 return byte == 0
2228 } catch {
2329 return false
@@ -26,18 +32,28 @@ final class ValueDecoder: AbstractDecodingNode, SingleValueDecodingContainer {
2632
2733 func decode< T> ( _ type: T . Type ) throws -> T where T : Decodable {
2834 if type is AnyOptional . Type {
29- let node = DecodingNode ( decoder : data , isOptional: true , path: codingPath, info: userInfo)
35+ let node = DecodingNode ( storage : storage , isOptional: true , path: codingPath, info: userInfo)
3036 return try T . init ( from: node)
3137 } else if let Primitive = type as? DecodablePrimitive . Type {
3238 let data : Data
33- if !isInUnkeyedContainer, Primitive . dataType == . variableLength, !isOptional, let d = self . data as? DataDecoder {
34- data = d. getAllData ( )
39+ if !isInUnkeyedContainer, Primitive . dataType == . variableLength, !isOptional {
40+ switch storage {
41+ case . data( let d) :
42+ data = d
43+ case . decoder( let decoder) :
44+ if let d = decoder as? DataDecoder {
45+ data = d. getAllData ( )
46+ } else {
47+ data = try decoder. getData ( for: Primitive . dataType, path: codingPath)
48+ }
49+ }
3550 } else {
36- data = try self . data. getData ( for: Primitive . dataType, path: codingPath)
51+ let decoder = asDecoder ( )
52+ data = try decoder. getData ( for: Primitive . dataType, path: codingPath)
3753 }
3854 return try Primitive . init ( decodeFrom: data, path: codingPath) as! T
3955 } else {
40- let node = DecodingNode ( decoder : data , path: codingPath, info: userInfo)
56+ let node = DecodingNode ( storage : storage , path: codingPath, info: userInfo)
4157 return try T . init ( from: node)
4258 }
4359 }
0 commit comments