Skip to content

Commit 4505c86

Browse files
authored
SWIFT-630 Integrate the BSON enum into the public API (#336)
1 parent e3dee07 commit 4505c86

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

54 files changed

+1484
-1899
lines changed

Sources/MongoSwift/BSON/AnyBSONValue.swift

Lines changed: 0 additions & 194 deletions
This file was deleted.

Sources/MongoSwift/BSON/BSON.swift

Lines changed: 31 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -74,14 +74,14 @@ public enum BSON {
7474
/// Initialize a `BSON` from an integer. On 64-bit systems, this will result in an `.int64`. On 32-bit systems,
7575
/// this will result in an `.int32`.
7676
public init(_ int: Int) {
77-
if Int.bsonType == .int32 {
77+
if MemoryLayout<Int>.size == 4 {
7878
self = .int32(Int32(int))
7979
} else {
8080
self = .int64(Int64(int))
8181
}
8282
}
8383

84-
/// Gets the `BSONType` of this `BSON`.
84+
/// Get the `BSONType` of this `BSON`.
8585
public var type: BSONType {
8686
return self.bsonValue.bsonType
8787
}
@@ -403,8 +403,7 @@ extension BSON: ExpressibleByIntegerLiteral {
403403

404404
extension BSON: ExpressibleByDictionaryLiteral {
405405
public init(dictionaryLiteral elements: (String, BSON)...) {
406-
// TODO SWIFT-630: Implement this.
407-
self = .document(Document())
406+
self = .document(Document(keyValuePairs: elements))
408407
}
409408
}
410409

@@ -418,4 +417,31 @@ extension BSON: Equatable {}
418417

419418
extension BSON: Hashable {}
420419

421-
// TODO SWIFT-629: Implement Codable conformance
420+
extension BSON: Codable {
421+
public init(from decoder: Decoder) throws {
422+
if let bsonDecoder = decoder as? _BSONDecoder {
423+
// This path only taken if a BSON is directly decoded at the top-level. Otherwise execution will never reach
424+
// this point.
425+
self = try bsonDecoder.decodeBSON()
426+
} else {
427+
// This path is taken no matter what when a non-BSONDecoder is used.
428+
for bsonType in BSON.allBSONTypes {
429+
if let value = try? bsonType.init(from: decoder) {
430+
self = value.bson
431+
}
432+
}
433+
434+
throw DecodingError.typeMismatch(
435+
BSON.self,
436+
DecodingError.Context(
437+
codingPath: decoder.codingPath,
438+
debugDescription: "Encountered a value that could not be decoded to any BSON type")
439+
)
440+
}
441+
}
442+
443+
public func encode(to encoder: Encoder) throws {
444+
// This is only reached when a non-BSON encoder is used.
445+
try self.bsonValue.encode(to: encoder)
446+
}
447+
}

0 commit comments

Comments
 (0)