@@ -158,29 +158,14 @@ public final class Writer: SmithyWriter {
158158 ) throws {
159159 guard let value else { return }
160160 var map : [ String : CBORType ] = [ : ]
161-
162161 for (key, val) in value {
163162 let writer = self [ key]
164163 try valueWritingClosure ( val, writer)
165164
166- // If the writer itself doesn't have a cborValue, build it from its children
167- if writer. cborValue == nil , !writer. children. isEmpty {
168- var childMap : [ String : CBORType ] = [ : ]
169- for child in writer. children {
170- if let childCborValue = child. cborValue {
171- childMap [ child. nodeInfo] = childCborValue
172- }
173- }
174- writer. cborValue = . map( childMap) // Construct the map for the writer
175- }
176-
177- // Add to the parent map
178- if let cborValue = writer. cborValue {
165+ if let cborValue = extractCBORValue ( from: writer) {
179166 map [ key] = cborValue
180167 }
181168 }
182-
183- // Assign the constructed map to the current writer
184169 self . cborValue = . map( map)
185170 }
186171
@@ -191,34 +176,41 @@ public final class Writer: SmithyWriter {
191176 isFlattened: Bool
192177 ) throws {
193178 guard let value else { return }
194-
195179 var array : [ CBORType ] = [ ]
196-
197180 for val in value {
198181 // Create a child writer for each list element
199182 let childWriter = Writer ( nodeInfo: memberNodeInfo, parent: self )
200183 try memberWritingClosure ( val, childWriter)
201-
202- // If the child writer has a cborValue, add it to the array
203- if let cborValue = childWriter. cborValue {
184+ if let cborValue = extractCBORValue ( from: childWriter) {
204185 array. append ( cborValue)
205- } else if !childWriter. children. isEmpty {
206- // If no cborValue but has children, create a map from its children
207- var childMap : [ String : CBORType ] = [ : ]
208- for child in childWriter. children {
209- if let childCborValue = child. cborValue {
210- childMap [ child. nodeInfo] = childCborValue
211- }
212- }
213- array. append ( . map( childMap) ) // Append the constructed map
214186 }
215187 }
216-
217- // Assign the array to the current writer's cborValue
218188 self . cborValue = . array( array)
219189 }
220190
221191 public func writeNull( ) throws {
222192 self . cborValue = . null
223193 }
194+
195+ private func extractCBORValue( from writer: Writer ) -> CBORType ? {
196+ // If the writer has a value, return it immediately
197+ if let value = writer. cborValue {
198+ return value
199+ }
200+ // Otherwise, if it has children, recursively check each child
201+ if !writer. children. isEmpty {
202+ var childMap : [ String : CBORType ] = [ : ]
203+ for child in writer. children {
204+ if let childValue = extractCBORValue ( from: child) {
205+ childMap [ child. nodeInfo] = childValue
206+ }
207+ }
208+ // Return a map if any children provided a value
209+ if !childMap. isEmpty {
210+ return . map( childMap)
211+ }
212+ }
213+ // No value found at any level
214+ return nil
215+ }
224216}
0 commit comments