Skip to content

Commit b400219

Browse files
committed
Merge branch 'jo/append-not-overwrite'
2 parents 49460e8 + 539606c commit b400219

File tree

1 file changed

+14
-4
lines changed

1 file changed

+14
-4
lines changed

Sources/BSON/Codable/Encoding/BSONEncoder.swift

Lines changed: 14 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -88,7 +88,8 @@ fileprivate final class _BSONEncoder: Encoder, AnyBSONEncoder {
8888
}
8989
}
9090
set {
91-
target = .document(newValue ?? [:])
91+
let document = newValue ?? [:]
92+
target = .document(document)
9293
}
9394
}
9495
var primitive: Primitive? {
@@ -107,6 +108,10 @@ fileprivate final class _BSONEncoder: Encoder, AnyBSONEncoder {
107108
}
108109
}
109110

111+
deinit {
112+
writer?(primitive)
113+
}
114+
110115
// MARK: Configuration
111116

112117
let strategies: BSONEncoderStrategies
@@ -163,7 +168,11 @@ fileprivate final class _BSONEncoder: Encoder, AnyBSONEncoder {
163168
return self.document?[converted(key.stringValue)]
164169
}
165170
set {
166-
self.document?[converted(key.stringValue)] = newValue
171+
if let newValue = newValue {
172+
self.document?.appendValue(newValue, forKey: converted(key.stringValue))
173+
} else {
174+
self.document?.removeValue(forKey: converted(key.stringValue))
175+
}
167176
}
168177
}
169178

@@ -206,7 +215,8 @@ fileprivate final class _BSONEncoder: Encoder, AnyBSONEncoder {
206215
)
207216

208217
encoder.writer = { [weak self] primitive in
209-
self?[key] = primitive
218+
guard let self = self else { return }
219+
self[key] = primitive
210220
}
211221

212222
return encoder
@@ -227,7 +237,7 @@ fileprivate struct _BSONKeyedEncodingContainer<Key: CodingKey> : KeyedEncodingCo
227237
mutating func encodeNil(forKey key: Key) throws {
228238
switch encoder.strategies.keyedNilEncodingStrategy {
229239
case .null:
230-
encoder.document?[encoder.converted(key.stringValue)] = BSON.Null()
240+
encoder.document?.appendValue(BSON.Null(), forKey: encoder.converted(key.stringValue))
231241
case .omitted:
232242
return
233243
}

0 commit comments

Comments
 (0)