forked from mongodb/swift-bson
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathBSON.swift
496 lines (436 loc) · 14.5 KB
/
BSON.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
import ExtrasJSON
import Foundation
/// Enum representing a BSON value.
/// - SeeAlso: bsonspec.org
public enum BSON {
/// A BSON document.
case document(BSONDocument)
/// A BSON int32.
case int32(Int32)
/// A BSON int64.
case int64(Int64)
/// A BSON Decimal128
case decimal128(BSONDecimal128)
/// A BSON Array
indirect case array([BSON])
/// A BSON Boolean
case bool(Bool)
/// A BSON UTC datetime.
/// - SeeAlso: https://docs.mongodb.com/manual/reference/bson-types/#date
case datetime(Date)
/// A BSON double.
case double(Double)
/// A BSON string.
case string(String)
/// A BSON Symbol
case symbol(BSONSymbol)
/// A BSON Timestamp
case timestamp(BSONTimestamp)
/// A BSON Binary
case binary(BSONBinary)
/// A BSON Regex
case regex(BSONRegularExpression)
/// A BSON ObjectID
case objectID(BSONObjectID = BSONObjectID())
/// A BSON DBPointer
case dbPointer(BSONDBPointer)
/// A BSON Code
case code(BSONCode)
/// A BSON Code with Scope
case codeWithScope(BSONCodeWithScope)
/// A BSON Null
case null
/// A BSON Undefined
case undefined
/// A BSON MinKey
case minKey
/// A BSON MaxKey
case maxKey
/// Initialize a `BSON` from an integer. On 64-bit systems, this will result in an `.int64`. On 32-bit systems,
/// this will result in an `.int32`.
public init(_ int: Int) {
if MemoryLayout<Int>.size == 4 {
self = .int32(Int32(int))
} else {
self = .int64(Int64(int))
}
}
/// Initialize a `BSON` from ExtendedJSON.
/// This is not as performant as decoding via ExtendedJSONDecoder and should only be used scalar values.
///
/// Parameters:
/// - `json`: a `JSON` representing the canonical or relaxed form of ExtendedJSON for any `BSONValue`.
/// - `keyPath`: an array of `Strings`s containing the enclosing JSON keys of the current json being passed in.
/// This is used for error messages.
///
/// Throws:
/// - `DecodingError` if `json` is malformatted extended json
internal init(fromExtJSON json: JSON, keyPath: [String]) throws {
// Spec requires that we try int32, try int64, then try double for decoding numbers
if let int32 = try Int32(fromExtJSON: json, keyPath: keyPath) {
self = int32.bson
return
}
if let int64 = try Int64(fromExtJSON: json, keyPath: keyPath) {
self = int64.bson
return
}
for bsonType in BSON.allBSONTypes.values {
guard bsonType != Int32.self && bsonType != Int64.self && bsonType != BSONDocument.self else {
continue
}
if let value = try bsonType.init(fromExtJSON: json, keyPath: keyPath) {
self = value.bson
return
}
}
// Document accepts any JSON object so it should be tried after all the more specific BSON types are tried
guard let doc = try BSONDocument(fromExtJSON: json, keyPath: keyPath) else {
throw BSONError.InternalError(message: "Could not parse BSON from \(json)")
}
self = doc.bson
}
/// Converts this `BSON` to a corresponding `JSON` in relaxed extendedJSON format.
internal func toRelaxedExtendedJSON() -> JSON {
self.bsonValue.toRelaxedExtendedJSON()
}
/// Converts this `BSON` to a corresponding `JSON` in canonical extendedJSON format.
internal func toCanonicalExtendedJSON() -> JSON {
self.bsonValue.toCanonicalExtendedJSON()
}
/// Get the `BSONType` of this `BSON`.
public var type: BSONType {
self.bsonValue.bsonType
}
}
/// Value getters
extension BSON {
/// If this `BSON` is an `.int32`, return it as an `Int32`. Otherwise, return nil.
public var int32Value: Int32? {
guard case let .int32(i) = self else {
return nil
}
return i
}
/// If this `BSON` is an `.int64`, return it as an `Int64`. Otherwise, return nil.
public var int64Value: Int64? {
guard case let .int64(i) = self else {
return nil
}
return i
}
/// If this `BSON` is an `.decimal128`, return it as an `BSONDecimal128`. Otherwise, return nil.
public var decimal128Value: BSONDecimal128? {
guard case let .decimal128(i) = self else {
return nil
}
return i
}
/// If this `BSON` is a `.document`, return it as a `BSONDocument`. Otherwise, return nil.
public var documentValue: BSONDocument? {
guard case let .document(d) = self else {
return nil
}
return d
}
/// If this `BSON` is a `.array`, return it as a `[BSON]`. Otherwise, return nil.
public var arrayValue: [BSON]? {
guard case let .array(d) = self else {
return nil
}
return d
}
/// If this `BSON` is a `.bool`, return it as a `Bool`. Otherwise, return nil.
public var boolValue: Bool? {
guard case let .bool(d) = self else {
return nil
}
return d
}
/// If this `BSON` is a `.date`, return it as a `Date`. Otherwise, return nil.
public var dateValue: Date? {
guard case let .datetime(d) = self else {
return nil
}
return d
}
/// If this `BSON` is a `.double`, return it as a `Double`. Otherwise, return nil.
public var doubleValue: Double? {
guard case let .double(d) = self else {
return nil
}
return d
}
/// If this `BSON` is a `.string`, return it as a `String`. Otherwise, return nil.
public var stringValue: String? {
guard case let .string(d) = self else {
return nil
}
return d
}
/// If this `BSON` is a `.symbol`, return it as a `BSONSymbol`. Otherwise, return nil.
public var symbolValue: BSONSymbol? {
guard case let .symbol(d) = self else {
return nil
}
return d
}
/// If this `BSON` is a `.timestamp`, return it as a `BSONTimestamp`. Otherwise, return nil.
public var timestampValue: BSONTimestamp? {
guard case let .timestamp(d) = self else {
return nil
}
return d
}
/// If this `BSON` is a `.binary`, return it as a `BSONBinary`. Otherwise, return nil.
public var binaryValue: BSONBinary? {
guard case let .binary(d) = self else {
return nil
}
return d
}
/// If this `BSON` is a `.regex`, return it as a `BSONRegularExpression`. Otherwise, return nil.
public var regexValue: BSONRegularExpression? {
guard case let .regex(d) = self else {
return nil
}
return d
}
/// If this `BSON` is a `.objectID`, return it as a `BSONObjectID`. Otherwise, return nil.
public var objectIDValue: BSONObjectID? {
guard case let .objectID(d) = self else {
return nil
}
return d
}
/// If this `BSON` is a `.dbPointer`, return it as a `BSONDBPointer`. Otherwise, return nil.
public var dbPointerValue: BSONDBPointer? {
guard case let .dbPointer(d) = self else {
return nil
}
return d
}
/// If this `BSON` is a `.code`, return it as a `BSONCode`. Otherwise, return nil.
public var codeValue: BSONCode? {
guard case let .code(d) = self else {
return nil
}
return d
}
/// If this `BSON` is a `.codeWithScope`, return it as a `BSONCodeWithScope`. Otherwise, return nil.
public var codeWithScopeValue: BSONCodeWithScope? {
guard case let .codeWithScope(d) = self else {
return nil
}
return d
}
}
/// Helper functions for converting to numbers.
extension BSON {
/// Return this BSON as an `Int` if possible.
/// This will coerce non-integer numeric cases (e.g. `.double`) into an `Int` if such coercion would be lossless.
public func toInt() -> Int? {
switch self {
case let .int32(value):
return Int(value)
case let .int64(value):
return Int(exactly: value)
case let .double(value):
return Int(exactly: value)
default:
return nil
}
}
/// Return this BSON as an `Int32` if possible.
/// This will coerce numeric cases (e.g. `.double`) into an `Int32` if such coercion would be lossless.
public func toInt32() -> Int32? {
switch self {
case let .int32(value):
return value
case let .int64(value):
return Int32(exactly: value)
case let .double(value):
return Int32(exactly: value)
default:
return nil
}
}
/// Return this BSON as an `Int64` if possible.
/// This will coerce numeric cases (e.g. `.double`) into an `Int64` if such coercion would be lossless.
public func toInt64() -> Int64? {
switch self {
case let .int32(value):
return Int64(value)
case let .int64(value):
return value
case let .double(value):
return Int64(exactly: value)
default:
return nil
}
}
/// Return this BSON as a `Double` if possible.
/// This will coerce numeric cases (e.g. `.int32`) into a `Double` if such coercion would be lossless.
public func toDouble() -> Double? {
switch self {
case let .double(d):
return d
default:
guard let intValue = self.toInt() else {
return nil
}
return Double(intValue)
}
}
/// Return this BSON as a `BSONDecimal128` if possible.
/// This will coerce numeric cases (e.g. `.double`) into a `BSONDecimal128` if such coercion would be lossless.
public func toDecimal128() -> BSONDecimal128? {
switch self {
case let .decimal128(d):
return d
case let .int64(i):
return try? BSONDecimal128(String(i))
case let .int32(i):
return try? BSONDecimal128(String(i))
case let .double(d):
return try? BSONDecimal128(String(d))
default:
return nil
}
}
}
/// Extension providing the internal API of `BSON`
extension BSON {
/// List of all BSONValue types. Can be used to exhaustively check each one at runtime.
internal static var allBSONTypes: [BSONType: BSONValue.Type] = [
.document: BSONDocument.self,
.int32: Int32.self,
.int64: Int64.self,
.decimal128: BSONDecimal128.self,
.bool: Bool.self,
.string: String.self,
.double: Double.self,
.datetime: Date.self,
.array: [BSON].self,
.symbol: BSONSymbol.self,
.timestamp: BSONTimestamp.self,
.binary: BSONBinary.self,
.regex: BSONRegularExpression.self,
.objectID: BSONObjectID.self,
.dbPointer: BSONDBPointer.self,
.code: BSONCode.self,
.codeWithScope: BSONCodeWithScope.self,
.null: BSONNull.self,
.undefined: BSONUndefined.self,
.minKey: BSONMinKey.self,
.maxKey: BSONMaxKey.self
]
/// Get the associated `BSONValue` to this `BSON` case.
internal var bsonValue: BSONValue {
switch self {
case let .document(v):
return v
case let .int32(v):
return v
case let .int64(v):
return v
case let .decimal128(v):
return v
case let .array(v):
return v
case let .bool(v):
return v
case let .datetime(v):
return v
case let .double(v):
return v
case let .string(v):
return v
case let .symbol(v):
return v
case let .timestamp(v):
return v
case let .binary(v):
return v
case let .regex(v):
return v
case let .dbPointer(v):
return v
case let .objectID(v):
return v
case let .code(v):
return v
case let .codeWithScope(v):
return v
case .null:
return BSONNull()
case .undefined:
return BSONUndefined()
case .minKey:
return BSONMinKey()
case .maxKey:
return BSONMaxKey()
}
}
}
extension BSON: ExpressibleByIntegerLiteral {
/// Initialize a `BSON` from an integer. On 64-bit systems, this will result in an `.int64`. On 32-bit systems,
/// this will result in an `.int32`.
public init(integerLiteral value: Int) {
self.init(value)
}
}
extension BSON: ExpressibleByFloatLiteral {
public init(floatLiteral value: Double) {
self = .double(value)
}
}
extension BSON: ExpressibleByBooleanLiteral {
public init(booleanLiteral value: Bool) {
self = .bool(value)
}
}
extension BSON: ExpressibleByDictionaryLiteral {
public init(dictionaryLiteral elements: (String, BSON)...) {
self = .document(BSONDocument(keyValuePairs: elements))
}
}
extension BSON: ExpressibleByStringLiteral {
public init(stringLiteral value: String) {
self = .string(value)
}
}
extension BSON: ExpressibleByArrayLiteral {
public init(arrayLiteral elements: BSON...) {
self = .array(elements)
}
}
extension BSON: Equatable {}
extension BSON: Hashable {}
extension BSON: Codable {
public init(from decoder: Decoder) throws {
if let bsonDecoder = decoder as? _BSONDecoder {
// This path only taken if a BSON is directly decoded at the top-level. Otherwise execution will never reach
// this point.
self = try bsonDecoder.decodeBSON()
} else {
// This path is taken no matter what when a non-BSONDecoder is used.
for bsonType in BSON.allBSONTypes.values {
if let value = try? bsonType.init(from: decoder) {
self = value.bson
}
}
throw DecodingError.typeMismatch(
BSON.self,
DecodingError.Context(
codingPath: decoder.codingPath,
debugDescription: "Encountered a value that could not be decoded to any BSON type"
)
)
}
}
public func encode(to encoder: Encoder) throws {
// This is only reached when a non-BSON encoder is used.
try self.bsonValue.encode(to: encoder)
}
}