-
Notifications
You must be signed in to change notification settings - Fork 23
/
Copy pathBool+BSONValue.swift
54 lines (46 loc) · 1.75 KB
/
Bool+BSONValue.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
import NIOCore
extension Bool: BSONValue {
internal static let extJSONTypeWrapperKeys: [String] = []
/*
* Initializes a `Bool` from ExtendedJSON.
*
* Parameters:
* - `json`: a `JSON` representing the canonical or relaxed form of ExtendedJSON for a `Bool`.
* - `keyPath`: an array of `String`s containing the enclosing JSON keys of the current json being passed in.
* This is used for error messages.
*
* Returns:
* - `nil` if the provided value is not a `Bool`.
*/
internal init?(fromExtJSON json: JSON, keyPath _: [String]) {
switch json.value {
case let .bool(b):
// canonical or relaxed extended JSON
self = b
default:
return nil
}
}
/// Converts this `Bool` to a corresponding `JSON` in relaxed extendedJSON format.
internal func toRelaxedExtendedJSON() -> JSON {
self.toCanonicalExtendedJSON()
}
/// Converts this `Bool` to a corresponding `JSON` in canonical extendedJSON format.
internal func toCanonicalExtendedJSON() -> JSON {
JSON(.bool(self))
}
internal static var bsonType: BSONType { .bool }
internal var bson: BSON { .bool(self) }
internal static func read(from buffer: inout ByteBuffer) throws -> BSON {
guard let value = buffer.readInteger(as: UInt8.self) else {
throw BSONError.InternalError(message: "Could not read Bool")
}
guard value == 0 || value == 1 else {
throw BSONError.InternalError(message: "Bool must be 0 or 1, found:\(value)")
}
return .bool(value == 0 ? false : true)
}
internal func write(to buffer: inout ByteBuffer) {
buffer.writeBytes([self ? 1 : 0])
}
}