diff --git a/Sources/MongoSwift/BSON/BSON.swift b/Sources/MongoSwift/BSON/BSON.swift index 0d8fd3a89..dedf5a6dd 100644 --- a/Sources/MongoSwift/BSON/BSON.swift +++ b/Sources/MongoSwift/BSON/BSON.swift @@ -224,7 +224,7 @@ public enum 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 asInt() -> Int? { + public func toInt() -> Int? { switch self { case let .int32(value): return Int(value) @@ -239,7 +239,7 @@ public enum BSON { /// 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 asInt32() -> Int32? { + public func toInt32() -> Int32? { switch self { case let .int32(value): return value @@ -254,7 +254,7 @@ public enum BSON { /// 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 asInt64() -> Int64? { + public func toInt64() -> Int64? { switch self { case let .int32(value): return Int64(value) @@ -269,12 +269,12 @@ public enum BSON { /// Return this BSON as a `Double` if possible. /// This will coerce numeric cases (e.g. `.decimal128`) into a `Double` if such coercion would be lossless. - public func asDouble() -> Double? { + public func toDouble() -> Double? { switch self { case let .double(d): return d default: - guard let intValue = self.asInt() else { + guard let intValue = self.toInt() else { return nil } return Double(intValue) @@ -283,7 +283,7 @@ public enum BSON { /// Return this BSON as a `Decimal128` if possible. /// This will coerce numeric cases (e.g. `.double`) into a `Decimal128` if such coercion would be lossless. - public func asDecimal128() -> Decimal128? { + public func toDecimal128() -> Decimal128? { switch self { case let .decimal128(d): return d diff --git a/Sources/MongoSwift/BSON/BSONDecoder.swift b/Sources/MongoSwift/BSON/BSONDecoder.swift index 2a1f30ef3..e7b299036 100644 --- a/Sources/MongoSwift/BSON/BSONDecoder.swift +++ b/Sources/MongoSwift/BSON/BSONDecoder.swift @@ -439,7 +439,7 @@ extension _BSONDecoder { case .binary: let binary = try self.unboxCustom(value) { $0.binaryValue } do { - return try UUID(from: binary) + return try binary.toUUID() } catch { throw DecodingError.dataCorrupted( DecodingError.Context( diff --git a/Sources/MongoSwift/BSON/BSONEncoder.swift b/Sources/MongoSwift/BSON/BSONEncoder.swift index ad3f6d11c..618abe72b 100644 --- a/Sources/MongoSwift/BSON/BSONEncoder.swift +++ b/Sources/MongoSwift/BSON/BSONEncoder.swift @@ -169,7 +169,7 @@ public class BSONEncoder { ) } - return dict.asDocument() + return dict.toDocument() } /** @@ -778,7 +778,7 @@ private class MutableDictionary: BSONValue { fileprivate static var bsonType: BSONType { .document } // This is unused - fileprivate var bson: BSON { .document(self.asDocument()) } + fileprivate var bson: BSON { .document(self.toDocument()) } // rather than using a dictionary, do this so we preserve key orders fileprivate var keys = [String]() @@ -806,7 +806,7 @@ private class MutableDictionary: BSONValue { } /// Converts self to a `Document` with equivalent key-value pairs. - fileprivate func asDocument() -> Document { + fileprivate func toDocument() -> Document { var doc = Document() for i in 0..(_: T.Type) -> [T]? { + internal func toArrayOf(_: T.Type) -> [T]? { var result: [T] = [] for element in self { guard let bsonValue = element.bsonValue as? T else { @@ -321,6 +321,27 @@ public struct BSONBinary: BSONValue, Equatable, Codable, Hashable { return try self.init(data: dataObj, subtype: UInt8(subtype.rawValue)) }) } + + /// Converts this `BSONBinary` instance to a `UUID`. + /// - Throws: + /// - `InvalidArgumentError` if a non-UUID subtype is set on this `BSONBinary`. + public func toUUID() throws -> UUID { + guard [Subtype.uuid.rawValue, Subtype.uuidDeprecated.rawValue].contains(self.subtype) else { + throw InvalidArgumentError( + message: "Expected a UUID binary subtype, got subtype \(self.subtype) instead." + ) + } + + let data = self.data + let uuid: uuid_t = ( + data[0], data[1], data[2], data[3], + data[4], data[5], data[6], data[7], + data[8], data[9], data[10], data[11], + data[12], data[13], data[14], data[15] + ) + + return UUID(uuid: uuid) + } } /// An extension of `Bool` to represent the BSON Boolean type. @@ -886,34 +907,6 @@ extension BSONObjectID: Hashable { } } -/// Extension to allow a `UUID` to be initialized from a `BSONBinary`. -extension UUID { - /// Initializes a `UUID` instance from a `BSONBinary`. - /// - Throws: - /// - `InvalidArgumentError` if a non-UUID subtype is set on the `BSONBinary`. - public init(from binary: BSONBinary) throws { - guard [ - BSONBinary.Subtype.uuid.rawValue, - BSONBinary.Subtype.uuidDeprecated.rawValue - ].contains(binary.subtype) else { - throw InvalidArgumentError( - message: "Expected a UUID binary type " + - "(\(BSONBinary.Subtype.uuid)), got \(binary.subtype) instead." - ) - } - - let data = binary.data - let uuid: uuid_t = ( - data[0], data[1], data[2], data[3], - data[4], data[5], data[6], data[7], - data[8], data[9], data[10], data[11], - data[12], data[13], data[14], data[15] - ) - - self.init(uuid: uuid) - } -} - // A mapping of regex option characters to their equivalent `NSRegularExpression` option. // note that there is a BSON regexp option 'l' that `NSRegularExpression` // doesn't support. The flag will be dropped if BSON containing it is parsed, @@ -926,7 +919,7 @@ private let regexOptsMap: [Character: NSRegularExpression.Options] = [ "x": .allowCommentsAndWhitespace ] -/// An extension of `NSRegularExpression` to allow it to be initialized from a `BSONRegularExpression`. +/// An extension of `NSRegularExpression` to support conversion to and from `BSONRegularExpression`. extension NSRegularExpression { /// Convert a string of options flags into an equivalent `NSRegularExpression.Options` internal static func optionsFromString(_ stringOptions: String) -> NSRegularExpression.Options { @@ -945,14 +938,6 @@ extension NSRegularExpression { for (char, o) in regexOptsMap { if options.contains(o) { optsString += String(char) } } return String(optsString.sorted()) } - - /// Initializes a new `NSRegularExpression` with the pattern and options of the provided `BSONRegularExpression`. - /// Note: `NSRegularExpression` does not support the `l` locale dependence option, so it will - /// be omitted if set on the provided `BSONRegularExpression`. - public convenience init(from regex: BSONRegularExpression) throws { - let opts = NSRegularExpression.optionsFromString(regex.options) - try self.init(pattern: regex.pattern, options: opts) - } } /// A struct to represent a BSON regular expression. @@ -1016,6 +1001,14 @@ public struct BSONRegularExpression: BSONValue, Equatable, Codable, Hashable { return self.init(pattern: patternString, options: optionsString) }) } + + /// Converts this `BSONRegularExpression` to an `NSRegularExpression`. + /// Note: `NSRegularExpression` does not support the `l` locale dependence option, so it will be omitted if it was + /// set on this instance. + public func toNSRegularExpression() throws -> NSRegularExpression { + let opts = NSRegularExpression.optionsFromString(self.options) + return try NSRegularExpression(pattern: self.pattern, options: opts) + } } /// An extension of String to represent the BSON string type. diff --git a/Sources/MongoSwift/MongoCollection+BulkWrite.swift b/Sources/MongoSwift/MongoCollection+BulkWrite.swift index 6277caaea..824841e1d 100644 --- a/Sources/MongoSwift/MongoCollection+BulkWrite.swift +++ b/Sources/MongoSwift/MongoCollection+BulkWrite.swift @@ -408,22 +408,22 @@ public struct BulkWriteResult: Decodable { return nil } - self.deletedCount = try reply.getValue(for: MongocKeys.deletedCount.rawValue)?.asInt() ?? 0 - self.insertedCount = try reply.getValue(for: MongocKeys.insertedCount.rawValue)?.asInt() ?? 0 + self.deletedCount = try reply.getValue(for: MongocKeys.deletedCount.rawValue)?.toInt() ?? 0 + self.insertedCount = try reply.getValue(for: MongocKeys.insertedCount.rawValue)?.toInt() ?? 0 self.insertedIDs = insertedIDs - self.matchedCount = try reply.getValue(for: MongocKeys.matchedCount.rawValue)?.asInt() ?? 0 - self.modifiedCount = try reply.getValue(for: MongocKeys.modifiedCount.rawValue)?.asInt() ?? 0 - self.upsertedCount = try reply.getValue(for: MongocKeys.upsertedCount.rawValue)?.asInt() ?? 0 + self.matchedCount = try reply.getValue(for: MongocKeys.matchedCount.rawValue)?.toInt() ?? 0 + self.modifiedCount = try reply.getValue(for: MongocKeys.modifiedCount.rawValue)?.toInt() ?? 0 + self.upsertedCount = try reply.getValue(for: MongocKeys.upsertedCount.rawValue)?.toInt() ?? 0 var upsertedIDs = [Int: BSON]() if let upserted = try reply.getValue(for: MongocKeys.upserted.rawValue)?.arrayValue { - guard let upserted = upserted.asArrayOf(Document.self) else { + guard let upserted = upserted.toArrayOf(Document.self) else { throw InternalError(message: "\"upserted\" array did not contain only documents") } for upsert in upserted { - guard let index = try upsert.getValue(for: "index")?.asInt() else { + guard let index = try upsert.getValue(for: "index")?.toInt() else { throw InternalError(message: "Could not cast upserted index to `Int`") } upsertedIDs[index] = upsert["_id"] diff --git a/Sources/MongoSwift/MongoCollection+FindAndModify.swift b/Sources/MongoSwift/MongoCollection+FindAndModify.swift index c4d8d1614..e88cbc08a 100644 --- a/Sources/MongoSwift/MongoCollection+FindAndModify.swift +++ b/Sources/MongoSwift/MongoCollection+FindAndModify.swift @@ -138,7 +138,7 @@ internal protocol FindAndModifyOptionsConvertible { /// Converts `self` to a `FindAndModifyOptions` /// /// - Throws: `InvalidArgumentError` if any of the options are invalid. - func asFindAndModifyOptions() throws -> FindAndModifyOptions + func toFindAndModifyOptions() throws -> FindAndModifyOptions } /// Options to use when executing a `findOneAndDelete` command on a `MongoCollection`. @@ -158,7 +158,7 @@ public struct FindOneAndDeleteOptions: FindAndModifyOptionsConvertible, Decodabl /// An optional `WriteConcern` to use for the command. public var writeConcern: WriteConcern? - internal func asFindAndModifyOptions() throws -> FindAndModifyOptions { + internal func toFindAndModifyOptions() throws -> FindAndModifyOptions { try FindAndModifyOptions( collation: self.collation, maxTimeMS: self.maxTimeMS, @@ -211,7 +211,7 @@ public struct FindOneAndReplaceOptions: FindAndModifyOptionsConvertible, Decodab /// An optional `WriteConcern` to use for the command. public var writeConcern: WriteConcern? - internal func asFindAndModifyOptions() throws -> FindAndModifyOptions { + internal func toFindAndModifyOptions() throws -> FindAndModifyOptions { try FindAndModifyOptions( bypassDocumentValidation: self.bypassDocumentValidation, collation: self.collation, @@ -275,7 +275,7 @@ public struct FindOneAndUpdateOptions: FindAndModifyOptionsConvertible, Decodabl /// An optional `WriteConcern` to use for the command. public var writeConcern: WriteConcern? - internal func asFindAndModifyOptions() throws -> FindAndModifyOptions { + internal func toFindAndModifyOptions() throws -> FindAndModifyOptions { try FindAndModifyOptions( arrayFilters: self.arrayFilters, bypassDocumentValidation: self.bypassDocumentValidation, diff --git a/Sources/MongoSwift/MongoCollection+Write.swift b/Sources/MongoSwift/MongoCollection+Write.swift index 0b49b59f0..2bad8192f 100644 --- a/Sources/MongoSwift/MongoCollection+Write.swift +++ b/Sources/MongoSwift/MongoCollection+Write.swift @@ -29,7 +29,7 @@ extension MongoCollection { options: InsertOneOptions? = nil, session: ClientSession? = nil ) -> EventLoopFuture { - self.bulkWrite([.insertOne(value)], options: options?.asBulkWriteOptions(), session: session) + self.bulkWrite([.insertOne(value)], options: options?.toBulkWriteOptions(), session: session) .flatMapThrowing { try InsertOneResult(from: $0) } .flatMapErrorThrowing { throw convertBulkWriteError($0) } } @@ -93,7 +93,7 @@ extension MongoCollection { ) -> EventLoopFuture { let modelOptions = ReplaceOneModelOptions(collation: options?.collation, upsert: options?.upsert) let model = WriteModel.replaceOne(filter: filter, replacement: replacement, options: modelOptions) - return self.bulkWrite([model], options: options?.asBulkWriteOptions(), session: session) + return self.bulkWrite([model], options: options?.toBulkWriteOptions(), session: session) .flatMapThrowing { try UpdateResult(from: $0) } .flatMapErrorThrowing { throw convertBulkWriteError($0) } } @@ -131,7 +131,7 @@ extension MongoCollection { upsert: options?.upsert ) let model: WriteModel = .updateOne(filter: filter, update: update, options: modelOptions) - return self.bulkWrite([model], options: options?.asBulkWriteOptions(), session: session) + return self.bulkWrite([model], options: options?.toBulkWriteOptions(), session: session) .flatMapThrowing { try UpdateResult(from: $0) } .flatMapErrorThrowing { throw convertBulkWriteError($0) } } @@ -169,7 +169,7 @@ extension MongoCollection { upsert: options?.upsert ) let model: WriteModel = .updateMany(filter: filter, update: update, options: modelOptions) - return self.bulkWrite([model], options: options?.asBulkWriteOptions(), session: session) + return self.bulkWrite([model], options: options?.toBulkWriteOptions(), session: session) .flatMapThrowing { try UpdateResult(from: $0) } .flatMapErrorThrowing { throw convertBulkWriteError($0) } } @@ -201,7 +201,7 @@ extension MongoCollection { ) -> EventLoopFuture { let modelOptions = DeleteModelOptions(collation: options?.collation) let model: WriteModel = .deleteOne(filter, options: modelOptions) - return self.bulkWrite([model], options: options?.asBulkWriteOptions(), session: session) + return self.bulkWrite([model], options: options?.toBulkWriteOptions(), session: session) .flatMapThrowing { try DeleteResult(from: $0) } .flatMapErrorThrowing { throw convertBulkWriteError($0) } } @@ -233,7 +233,7 @@ extension MongoCollection { ) -> EventLoopFuture { let modelOptions = DeleteModelOptions(collation: options?.collation) let model: WriteModel = .deleteMany(filter, options: modelOptions) - return self.bulkWrite([model], options: options?.asBulkWriteOptions(), session: session) + return self.bulkWrite([model], options: options?.toBulkWriteOptions(), session: session) .flatMapThrowing { try DeleteResult(from: $0) } .flatMapErrorThrowing { throw convertBulkWriteError($0) } } @@ -243,12 +243,12 @@ extension MongoCollection { private protocol BulkWriteOptionsConvertible { var bypassDocumentValidation: Bool? { get } var writeConcern: WriteConcern? { get } - func asBulkWriteOptions() -> BulkWriteOptions + func toBulkWriteOptions() -> BulkWriteOptions } /// Default implementation of the protocol. private extension BulkWriteOptionsConvertible { - func asBulkWriteOptions() -> BulkWriteOptions { + func toBulkWriteOptions() -> BulkWriteOptions { BulkWriteOptions( bypassDocumentValidation: self.bypassDocumentValidation, writeConcern: self.writeConcern diff --git a/Sources/MongoSwift/MongoError.swift b/Sources/MongoSwift/MongoError.swift index c0700f0d8..cb85eb255 100644 --- a/Sources/MongoSwift/MongoError.swift +++ b/Sources/MongoSwift/MongoError.swift @@ -277,7 +277,7 @@ private func parseMongocError(_ error: bson_error_t, reply: Document?) -> MongoE let code = mongoc_error_code_t(rawValue: error.code) let message = toErrorString(error) - let errorLabels = reply?["errorLabels"]?.arrayValue?.asArrayOf(String.self) + let errorLabels = reply?["errorLabels"]?.arrayValue?.toArrayOf(String.self) let codeName = reply?["codeName"]?.stringValue ?? "" switch (domain, code) { @@ -352,7 +352,7 @@ internal func extractMongoError(error bsonError: bson_error_t, reply: Document? return WriteError( writeFailure: writeError, writeConcernFailure: wcError, - errorLabels: serverReply["errorLabels"]?.arrayValue?.asArrayOf(String.self) + errorLabels: serverReply["errorLabels"]?.arrayValue?.toArrayOf(String.self) ) } catch { return fallback @@ -439,7 +439,7 @@ internal func extractBulkWriteError( writeConcernFailure: try extractWriteConcernError(from: reply), otherError: other, result: errResult, - errorLabels: reply["errorLabels"]?.arrayValue?.asArrayOf(String.self) + errorLabels: reply["errorLabels"]?.arrayValue?.toArrayOf(String.self) ) } catch { return fallback diff --git a/Sources/MongoSwift/Operations/FindAndModifyOperation.swift b/Sources/MongoSwift/Operations/FindAndModifyOperation.swift index eff588df2..4c1969f71 100644 --- a/Sources/MongoSwift/Operations/FindAndModifyOperation.swift +++ b/Sources/MongoSwift/Operations/FindAndModifyOperation.swift @@ -157,7 +157,7 @@ internal struct FindAndModifyOperation: Operation { internal func execute(using connection: Connection, session: ClientSession?) throws -> T? { // we always need to send *something*, as findAndModify requires one of "remove" // or "update" to be set. - let opts = try self.options?.asFindAndModifyOptions() ?? FindAndModifyOptions() + let opts = try self.options?.toFindAndModifyOptions() ?? FindAndModifyOptions() if let session = session { try opts.setSession(session) } if let update = self.update { try opts.setUpdate(update) } diff --git a/Sources/MongoSwift/Operations/ListDatabasesOperation.swift b/Sources/MongoSwift/Operations/ListDatabasesOperation.swift index 59784c7a0..ca363d96c 100644 --- a/Sources/MongoSwift/Operations/ListDatabasesOperation.swift +++ b/Sources/MongoSwift/Operations/ListDatabasesOperation.swift @@ -79,7 +79,7 @@ internal struct ListDatabasesOperation: Operation { } } - guard let databases = reply["databases"]?.arrayValue?.asArrayOf(Document.self) else { + guard let databases = reply["databases"]?.arrayValue?.toArrayOf(Document.self) else { throw InternalError(message: "Invalid server response: \(reply)") } diff --git a/Tests/BSONTests/BSONValueTests.swift b/Tests/BSONTests/BSONValueTests.swift index a7bfcfc67..e262f655b 100644 --- a/Tests/BSONTests/BSONValueTests.swift +++ b/Tests/BSONTests/BSONValueTests.swift @@ -195,14 +195,14 @@ final class BSONValueTests: MongoSwiftTestCase { return } - BSONNumberTestCase.compare(computed: l.asInt(), expected: self.int) - BSONNumberTestCase.compare(computed: l.asInt32(), expected: self.int32) - BSONNumberTestCase.compare(computed: l.asInt64(), expected: self.int64) - BSONNumberTestCase.compare(computed: l.asDouble(), expected: self.double) + BSONNumberTestCase.compare(computed: l.toInt(), expected: self.int) + BSONNumberTestCase.compare(computed: l.toInt32(), expected: self.int32) + BSONNumberTestCase.compare(computed: l.toInt64(), expected: self.int64) + BSONNumberTestCase.compare(computed: l.toDouble(), expected: self.double) // Skip double for this conversion since it generates a Decimal128(5.0) =/= Decimal128(5) if l.doubleValue == nil { - BSONNumberTestCase.compare(computed: l.asDecimal128(), expected: self.decimal) + BSONNumberTestCase.compare(computed: l.toDecimal128(), expected: self.decimal) } } } @@ -212,8 +212,8 @@ final class BSONValueTests: MongoSwiftTestCase { let decimal128 = Decimal128("5.5")! let double: BSON = 5.5 - expect(double.asDouble()).to(equal(5.5)) - expect(double.asDecimal128()).to(equal(decimal128)) + expect(double.toDouble()).to(equal(5.5)) + expect(double.toDecimal128()).to(equal(decimal128)) let cases = [ BSONNumberTestCase(int: 5, double: 5.0, int32: Int32(5), int64: Int64(5), decimal: Decimal128("5")!), diff --git a/Tests/BSONTests/Document+SequenceTests.swift b/Tests/BSONTests/Document+SequenceTests.swift index 4eb6d268a..4e2bfe7d0 100644 --- a/Tests/BSONTests/Document+SequenceTests.swift +++ b/Tests/BSONTests/Document+SequenceTests.swift @@ -94,7 +94,7 @@ final class Document_SequenceTests: MongoSwiftTestCase { let doc1: Document = ["a": 1, "b": .null, "c": 3, "d": 4, "e": .null] expect(doc1.mapValues { $0 == .null ? 1 : $0 }).to(equal(["a": 1, "b": 1, "c": 3, "d": 4, "e": 1])) let output1 = doc1.mapValues { val in - if let int = val.asInt() { + if let int = val.toInt() { return BSON(integerLiteral: int + 1) } return val @@ -111,7 +111,7 @@ final class Document_SequenceTests: MongoSwiftTestCase { case let .string(val): return .string(val + " there") case .array: - return BSON(integerLiteral: val.arrayValue!.compactMap { $0.asInt() }.reduce(0, +)) + return BSON(integerLiteral: val.arrayValue!.compactMap { $0.toInt() }.reduce(0, +)) default: return val } @@ -128,10 +128,10 @@ final class Document_SequenceTests: MongoSwiftTestCase { let doc: Document = ["a": 1, "b": "hi", "c": [1, 2], "d": false, "e": .null, "f": .minKey, "g": 10] // shared predicates for subsequence tests - func isInt(_ pair: Document.KeyValuePair) -> Bool { pair.value.asInt() != nil } + func isInt(_ pair: Document.KeyValuePair) -> Bool { pair.value.toInt() != nil } func isNotNil(_ pair: Document.KeyValuePair) -> Bool { pair.value != .null } func is10(_ pair: Document.KeyValuePair) -> Bool { - if let int = pair.value.asInt() { + if let int = pair.value.toInt() { return int == 10 } return false diff --git a/Tests/BSONTests/DocumentTests.swift b/Tests/BSONTests/DocumentTests.swift index cdce6243f..4fb440c56 100644 --- a/Tests/BSONTests/DocumentTests.swift +++ b/Tests/BSONTests/DocumentTests.swift @@ -157,7 +157,7 @@ final class DocumentTests: MongoSwiftTestCase { let regex = doc["regex"]?.regexValue expect(regex).to(equal(BSONRegularExpression(pattern: "^abc", options: "imx"))) - expect(try NSRegularExpression(from: regex!)).to(equal(try NSRegularExpression( + expect(try regex?.toNSRegularExpression()).to(equal(try NSRegularExpression( pattern: "^abc", options: NSRegularExpression.optionsFromString("imx") ))) @@ -182,7 +182,7 @@ final class DocumentTests: MongoSwiftTestCase { expect(doc["binary6"]).to(equal(.binary(try BSONBinary(data: testData, subtype: .userDefined)))) expect(doc["binary7"]).to(equal(.binary(try BSONBinary(data: testData, subtype: 200)))) - let nestedArray = doc["nestedarray"]?.arrayValue?.compactMap { $0.arrayValue?.compactMap { $0.asInt() } } + let nestedArray = doc["nestedarray"]?.arrayValue?.compactMap { $0.arrayValue?.compactMap { $0.toInt() } } expect(nestedArray?[0]).to(equal([1, 2])) expect(nestedArray?[1]).to(equal([3, 4])) @@ -218,13 +218,13 @@ final class DocumentTests: MongoSwiftTestCase { let regex = DocumentTests.testDoc.regex?.regexValue expect(regex).to(equal(BSONRegularExpression(pattern: "^abc", options: "imx"))) - expect(try NSRegularExpression(from: regex!)).to(equal(try NSRegularExpression( + expect(try regex?.toNSRegularExpression()).to(equal(try NSRegularExpression( pattern: "^abc", options: NSRegularExpression.optionsFromString("imx") ))) let nestedArray = DocumentTests.testDoc.nestedarray?.arrayValue?.compactMap { - $0.arrayValue?.compactMap { $0.asInt() } + $0.arrayValue?.compactMap { $0.toInt() } } expect(nestedArray?[0]).to(equal([1, 2])) expect(nestedArray?[1]).to(equal([3, 4])) diff --git a/Tests/MongoSwiftSyncTests/CommandMonitoringTests.swift b/Tests/MongoSwiftSyncTests/CommandMonitoringTests.swift index dfeac2f52..5584b9f84 100644 --- a/Tests/MongoSwiftSyncTests/CommandMonitoringTests.swift +++ b/Tests/MongoSwiftSyncTests/CommandMonitoringTests.swift @@ -134,17 +134,17 @@ private struct CMTest: Decodable { hint = .indexSpec(hintDoc) } let options = FindOptions( - batchSize: self.op.args["batchSize"]?.asInt(), + batchSize: self.op.args["batchSize"]?.toInt(), comment: modifiers?["$comment"]?.stringValue, hint: hint, - limit: self.op.args["limit"]?.asInt(), + limit: self.op.args["limit"]?.toInt(), max: modifiers?["$max"]?.documentValue, - maxTimeMS: modifiers?["$maxTimeMS"]?.asInt(), + maxTimeMS: modifiers?["$maxTimeMS"]?.toInt(), min: modifiers?["$min"]?.documentValue, readPreference: self.op.readPreference, returnKey: modifiers?["$returnKey"]?.boolValue, showRecordID: modifiers?["$showDiskLoc"]?.boolValue, - skip: self.op.args["skip"]?.asInt(), + skip: self.op.args["skip"]?.toInt(), sort: self.op.args["sort"]?.documentValue ) @@ -258,7 +258,7 @@ private func normalizeCommand(_ input: Document) -> Document { // parses it as an Int32 which we convert to Int. convert to Int64 here because we // (as per the crud spec) use an Int64 for maxTimeMS and send that to // the server in our actual commands. - } else if k == "maxTimeMS", let iV = v.asInt64() { + } else if k == "maxTimeMS", let iV = v.toInt64() { output[k] = .int64(iV) // recursively normalize if it's a document @@ -336,7 +336,7 @@ private struct CommandSucceededExpectation: ExpectationType, Decodable { let receivedCursor = event.reply["cursor"]?.documentValue if let expectedCursor = self.cursor { // if the received cursor has an ID, and the expected ID is not 0, compare cursor IDs - if let id = receivedCursor!["id"], expectedCursor["id"]?.asInt() != 0 { + if let id = receivedCursor!["id"], expectedCursor["id"]?.toInt() != 0 { let storedId = testContext["cursorId"] as? BSON // if we aren't already storing a cursor ID for this test, add one if storedId == nil { @@ -359,7 +359,7 @@ private struct CommandSucceededExpectation: ExpectationType, Decodable { expect(expected.count).to(equal(actual.count)) for err in actual { // check each error code exists and is > 0 - expect(err["code"]?.asInt()).to(beGreaterThan(0)) + expect(err["code"]?.toInt()).to(beGreaterThan(0)) // check each error msg exists and has length > 0 expect(err["errmsg"]?.stringValue).toNot(beEmpty()) } @@ -390,7 +390,7 @@ private func normalizeExpectedReply(_ input: Document) -> Document { continue // The server sends back doubles, but the JSON test files // contain integer statuses (see SPEC-1050.) - } else if k == "ok", let dV = v.asDouble() { + } else if k == "ok", let dV = v.toDouble() { output[k] = .double(dV) // just copy the value over as is } else { diff --git a/Tests/MongoSwiftSyncTests/CrudTests.swift b/Tests/MongoSwiftSyncTests/CrudTests.swift index 032779065..c41cd72df 100644 --- a/Tests/MongoSwiftSyncTests/CrudTests.swift +++ b/Tests/MongoSwiftSyncTests/CrudTests.swift @@ -126,11 +126,11 @@ private class CrudTest { let collection: Document? var arrayFilters: [Document]? { self.args["arrayFilters"]?.arrayValue?.compactMap { $0.documentValue } } - var batchSize: Int? { self.args["batchSize"]?.asInt() } + var batchSize: Int? { self.args["batchSize"]?.toInt() } var collation: Document? { self.args["collation"]?.documentValue } var sort: Document? { self.args["sort"]?.documentValue } - var skip: Int? { self.args["skip"]?.asInt() } - var limit: Int? { self.args["limit"]?.asInt() } + var skip: Int? { self.args["skip"]?.toInt() } + var limit: Int? { self.args["limit"]?.toInt() } var projection: Document? { self.args["projection"]?.documentValue } var returnDoc: ReturnDocument? { if let ret = self.args["returnDocument"]?.stringValue { @@ -256,22 +256,22 @@ private class BulkWriteTest: CrudTest { return } - if let expectedDeletedCount = expected["deletedCount"]?.asInt() { + if let expectedDeletedCount = expected["deletedCount"]?.toInt() { expect(result.deletedCount).to(equal(expectedDeletedCount)) } - if let expectedInsertedCount = expected["insertedCount"]?.asInt() { + if let expectedInsertedCount = expected["insertedCount"]?.toInt() { expect(result.insertedCount).to(equal(expectedInsertedCount)) } if let expectedInsertedIds = expected["insertedIDs"]?.documentValue { expect(BulkWriteTest.prepareIds(result.insertedIDs)).to(equal(expectedInsertedIds)) } - if let expectedMatchedCount = expected["matchedCount"]?.asInt() { + if let expectedMatchedCount = expected["matchedCount"]?.toInt() { expect(result.matchedCount).to(equal(expectedMatchedCount)) } - if let expectedModifiedCount = expected["modifiedCount"]?.asInt() { + if let expectedModifiedCount = expected["modifiedCount"]?.toInt() { expect(result.modifiedCount).to(equal(expectedModifiedCount)) } - if let expectedUpsertedCount = expected["upsertedCount"]?.asInt() { + if let expectedUpsertedCount = expected["upsertedCount"]?.toInt() { expect(result.upsertedCount).to(equal(expectedUpsertedCount)) } if let expectedUpsertedIds = expected["upsertedIDs"]?.documentValue { @@ -291,7 +291,7 @@ private class CountDocumentsTest: CrudTest { let filter: Document = try self.args.get("filter") let options = CountDocumentsOptions(collation: self.collation, limit: self.limit, skip: self.skip) let result = try coll.countDocuments(filter, options: options) - expect(result).to(equal(self.result?.asInt())) + expect(result).to(equal(self.result?.toInt())) } } @@ -300,7 +300,7 @@ private class EstimatedDocumentCountTest: CrudTest { override func execute(usingCollection coll: MongoCollection) throws { let options = EstimatedDocumentCountOptions() let result = try coll.estimatedDocumentCount(options: options) - expect(result).to(equal(self.result?.asInt())) + expect(result).to(equal(self.result?.toInt())) } } @@ -317,7 +317,7 @@ private class DeleteTest: CrudTest { } let expected = self.result?.documentValue // the only value in a DeleteResult is `deletedCount` - expect(result?.deletedCount).to(equal(expected?["deletedCount"]?.asInt())) + expect(result?.deletedCount).to(equal(expected?["deletedCount"]?.toInt())) } } @@ -450,7 +450,7 @@ private class InsertManyTest: CrudTest { return } - if let expectedInsertedCount = expected["insertedCount"]?.asInt() { + if let expectedInsertedCount = expected["insertedCount"]?.toInt() { expect(result.insertedCount).to(equal(expectedInsertedCount)) } if let expectedInsertedIds = expected["insertedIDs"]?.documentValue { diff --git a/Tests/MongoSwiftSyncTests/MongoCollection+IndexTests.swift b/Tests/MongoSwiftSyncTests/MongoCollection+IndexTests.swift index 1b4a2af16..c8f10122e 100644 --- a/Tests/MongoSwiftSyncTests/MongoCollection+IndexTests.swift +++ b/Tests/MongoSwiftSyncTests/MongoCollection+IndexTests.swift @@ -238,10 +238,10 @@ final class MongoCollection_IndexTests: MongoSwiftTestCase { expect(receivedEvents.count).to(equal(2)) expect(receivedEvents[0].command["createIndexes"]).toNot(beNil()) expect(receivedEvents[0].command["maxTimeMS"]).toNot(beNil()) - expect(receivedEvents[0].command["maxTimeMS"]?.asInt()).to(equal(maxTimeMS)) + expect(receivedEvents[0].command["maxTimeMS"]?.toInt()).to(equal(maxTimeMS)) expect(receivedEvents[1].command["dropIndexes"]).toNot(beNil()) expect(receivedEvents[1].command["maxTimeMS"]).toNot(beNil()) - expect(receivedEvents[1].command["maxTimeMS"]?.asInt()).to(equal(maxTimeMS)) + expect(receivedEvents[1].command["maxTimeMS"]?.toInt()).to(equal(maxTimeMS)) } } diff --git a/Tests/MongoSwiftSyncTests/MongoCollectionTests.swift b/Tests/MongoSwiftSyncTests/MongoCollectionTests.swift index e4759a32f..83bf38c94 100644 --- a/Tests/MongoSwiftSyncTests/MongoCollectionTests.swift +++ b/Tests/MongoSwiftSyncTests/MongoCollectionTests.swift @@ -142,7 +142,7 @@ final class MongoCollectionTests: MongoSwiftTestCase { // the inserted IDs should either be the ones we set, // or newly created BSONObjectIDs for (_, v) in res!.insertedIDs { - if let val = v.asInt() { + if let val = v.toInt() { expect([10, 11]).to(contain(val)) } else { expect(v.type).to(equal(.objectID)) diff --git a/Tests/MongoSwiftSyncTests/MongoCursorTests.swift b/Tests/MongoSwiftSyncTests/MongoCursorTests.swift index 90ea72afa..e9c645114 100644 --- a/Tests/MongoSwiftSyncTests/MongoCursorTests.swift +++ b/Tests/MongoSwiftSyncTests/MongoCursorTests.swift @@ -206,7 +206,7 @@ final class MongoCursorTests: MongoSwiftTestCase { $0.isSuccess }.map { result -> Int? in let document = try! result.get() // always succeeds due to filter stage - return document["_id"]?.asInt() + return document["_id"]?.toInt() } expect(Array(filteredMapped)).to(equal([1, 2, 3])) } @@ -224,7 +224,7 @@ final class MongoCursorTests: MongoSwiftTestCase { // never execute, since the tailable cursor would be blocked in a `next` call indefinitely. // Because they're lazy, the for loop will execute its body 3 times for each available result then // return manually when count == 3. - for id in cursor.filter({ $0.isSuccess }).compactMap({ try! $0.get()["_id"]?.asInt() }) { + for id in cursor.filter({ $0.isSuccess }).compactMap({ try! $0.get()["_id"]?.toInt() }) { results.append(id) if results.count == 3 { return results diff --git a/Tests/MongoSwiftSyncTests/MongoDatabaseTests.swift b/Tests/MongoSwiftSyncTests/MongoDatabaseTests.swift index 51f436bd3..50521f5dc 100644 --- a/Tests/MongoSwiftSyncTests/MongoDatabaseTests.swift +++ b/Tests/MongoSwiftSyncTests/MongoDatabaseTests.swift @@ -21,7 +21,7 @@ final class MongoDatabaseTests: MongoSwiftTestCase { let command: Document = ["create": .string(self.getCollectionName(suffix: "1"))] let res = try db.runCommand(command) - expect(res["ok"]?.asDouble()).to(equal(1.0)) + expect(res["ok"]?.toDouble()).to(equal(1.0)) expect(try (Array(db.listCollections())).count).to(equal(1)) // create collection using createCollection diff --git a/Tests/MongoSwiftSyncTests/ReadPreferenceOperationTests.swift b/Tests/MongoSwiftSyncTests/ReadPreferenceOperationTests.swift index c004a4afd..4bfa34a27 100644 --- a/Tests/MongoSwiftSyncTests/ReadPreferenceOperationTests.swift +++ b/Tests/MongoSwiftSyncTests/ReadPreferenceOperationTests.swift @@ -20,7 +20,7 @@ final class ReadPreferenceOperationTests: MongoSwiftTestCase { // expect runCommand to return a success response when passing in a valid read preference let opts = RunCommandOptions(readPreference: .secondaryPreferred) let res = try db.runCommand(command, options: opts) - expect(res["ok"]?.asDouble()).to(equal(1.0)) + expect(res["ok"]?.toDouble()).to(equal(1.0)) // expect running other commands to not throw errors when passing in a valid read preference expect(try coll.find(options: FindOptions(readPreference: .primary))).toNot(throwError()) diff --git a/Tests/MongoSwiftSyncTests/ReadWriteConcernOperationTests.swift b/Tests/MongoSwiftSyncTests/ReadWriteConcernOperationTests.swift index 7f73f723f..e7e9071d5 100644 --- a/Tests/MongoSwiftSyncTests/ReadWriteConcernOperationTests.swift +++ b/Tests/MongoSwiftSyncTests/ReadWriteConcernOperationTests.swift @@ -20,12 +20,12 @@ final class ReadWriteConcernOperationTests: MongoSwiftTestCase { // run command with a valid readConcern let options1 = RunCommandOptions(readConcern: .local) let res1 = try db.runCommand(command, options: options1) - expect(res1["ok"]?.asDouble()).to(equal(1.0)) + expect(res1["ok"]?.toDouble()).to(equal(1.0)) // run command with an empty readConcern let options2 = RunCommandOptions(readConcern: .serverDefault) let res2 = try db.runCommand(command, options: options2) - expect(res2["ok"]?.asDouble()).to(equal(1.0)) + expect(res2["ok"]?.toDouble()).to(equal(1.0)) // running command with an invalid RC level should throw let options3 = RunCommandOptions(readConcern: .other("blah")) @@ -117,12 +117,12 @@ final class ReadWriteConcernOperationTests: MongoSwiftTestCase { // run command with a valid writeConcern let options1 = RunCommandOptions(writeConcern: wc1) let res1 = try db.runCommand(command, options: options1) - expect(res1["ok"]?.asDouble()).to(equal(1.0)) + expect(res1["ok"]?.toDouble()).to(equal(1.0)) // run command with an empty writeConcern let options2 = RunCommandOptions(writeConcern: wc2) let res2 = try db.runCommand(command, options: options2) - expect(res2["ok"]?.asDouble()).to(equal(1.0)) + expect(res2["ok"]?.toDouble()).to(equal(1.0)) expect(try coll.insertOne(nextDoc(), options: InsertOneOptions(writeConcern: wc1))).toNot(throwError()) expect(try coll.insertOne(nextDoc(), options: InsertOneOptions(writeConcern: wc3))).toNot(throwError()) diff --git a/Tests/MongoSwiftSyncTests/SpecTestRunner/FailPoint.swift b/Tests/MongoSwiftSyncTests/SpecTestRunner/FailPoint.swift index db23e00f8..296321133 100644 --- a/Tests/MongoSwiftSyncTests/SpecTestRunner/FailPoint.swift +++ b/Tests/MongoSwiftSyncTests/SpecTestRunner/FailPoint.swift @@ -56,7 +56,7 @@ internal struct FailPoint: Decodable { var data = v.documentValue, var wcErr = data["writeConcernError"]?.documentValue, let code = wcErr["code"] { - wcErr["code"] = .int32(code.asInt32()!) + wcErr["code"] = .int32(code.toInt32()!) data["writeConcernError"] = .document(wcErr) commandDoc["data"] = .document(data) } else { diff --git a/Tests/MongoSwiftSyncTests/SpecTestRunner/Match.swift b/Tests/MongoSwiftSyncTests/SpecTestRunner/Match.swift index 6432535a4..6960fb2e9 100644 --- a/Tests/MongoSwiftSyncTests/SpecTestRunner/Match.swift +++ b/Tests/MongoSwiftSyncTests/SpecTestRunner/Match.swift @@ -85,7 +85,7 @@ extension Document: Matchable { /// Extension that adds MATCHES functionality to `BSON`. extension BSON: Matchable { internal func isPlaceholder() -> Bool { - self.asInt()?.isPlaceholder() == true || self.stringValue?.isPlaceholder() == true + self.toInt()?.isPlaceholder() == true || self.stringValue?.isPlaceholder() == true } internal func contentMatches(expected: BSON) -> Bool { @@ -95,7 +95,7 @@ extension BSON: Matchable { case let (.array(actual), .array(expected)): return actual.matches(expected: expected) default: - if let selfInt = self.asInt(), let expectedInt = expected.asInt() { + if let selfInt = self.toInt(), let expectedInt = expected.toInt() { return selfInt == expectedInt } return self == expected diff --git a/Tests/MongoSwiftSyncTests/SyncChangeStreamTests.swift b/Tests/MongoSwiftSyncTests/SyncChangeStreamTests.swift index 853cdad41..c98b9bad4 100644 --- a/Tests/MongoSwiftSyncTests/SyncChangeStreamTests.swift +++ b/Tests/MongoSwiftSyncTests/SyncChangeStreamTests.swift @@ -1050,7 +1050,7 @@ final class SyncChangeStreamTests: MongoSwiftTestCase { // never execute, since the tailable cursor would be blocked in a `next` call indefinitely. // Because they're lazy, the for loop will execute its body 3 times for each available result then // return manually when count == 3. - for id in stream.filter({ $0.isSuccess }).compactMap({ try! $0.get().fullDocument?["_id"]?.asInt() }) { + for id in stream.filter({ $0.isSuccess }).compactMap({ try! $0.get().fullDocument?["_id"]?.toInt() }) { results.append(id) if results.count == 3 { return results diff --git a/Tests/MongoSwiftSyncTests/SyncTestUtils.swift b/Tests/MongoSwiftSyncTests/SyncTestUtils.swift index c9e6c4e0e..9b98c4d1a 100644 --- a/Tests/MongoSwiftSyncTests/SyncTestUtils.swift +++ b/Tests/MongoSwiftSyncTests/SyncTestUtils.swift @@ -67,7 +67,7 @@ extension MongoClient { internal func maxWireVersion() throws -> Int { let options = RunCommandOptions(readPreference: .primary) let isMaster = try self.db("admin").runCommand(["isMaster": 1], options: options) - guard let max = isMaster["maxWireVersion"]?.asInt() else { + guard let max = isMaster["maxWireVersion"]?.toInt() else { throw TestError(message: "isMaster reply missing maxwireversion \(isMaster)") } return max diff --git a/Tests/MongoSwiftTests/ReadWriteConcernSpecTests.swift b/Tests/MongoSwiftTests/ReadWriteConcernSpecTests.swift index 13fcbfb32..6b7bcb52a 100644 --- a/Tests/MongoSwiftTests/ReadWriteConcernSpecTests.swift +++ b/Tests/MongoSwiftTests/ReadWriteConcernSpecTests.swift @@ -13,11 +13,11 @@ extension WriteConcern { var w: W? if let wtag = doc["w"]?.stringValue { w = wtag == "majority" ? .majority : .tag(wtag) - } else if let wInt = doc["w"]?.asInt() { + } else if let wInt = doc["w"]?.toInt() { w = .number(wInt) } - let wt = doc["wtimeoutMS"]?.asInt() + let wt = doc["wtimeoutMS"]?.toInt() try self.init(journal: j, w: w, wtimeoutMS: wt) } @@ -107,7 +107,7 @@ class ReadWriteConcernSpecTests: MongoSwiftTestCase { expect(try encoder.encode(wc)).to(beNil()) } else { if let wtimeoutMS = expected["wtimeout"] { - expected["wtimeout"] = .int64(wtimeoutMS.asInt64()!) + expected["wtimeout"] = .int64(wtimeoutMS.toInt64()!) } expect(try encoder.encode(wc)).to(sortedEqual(expected)) }