Skip to content

Commit 8192ef9

Browse files
authored
SWIFT-835 Standardize on conversion method names (#484)
1 parent 26b1729 commit 8192ef9

26 files changed

+119
-126
lines changed

Sources/MongoSwift/BSON/BSON.swift

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -224,7 +224,7 @@ public enum BSON {
224224

225225
/// Return this BSON as an `Int` if possible.
226226
/// This will coerce non-integer numeric cases (e.g. `.double`) into an `Int` if such coercion would be lossless.
227-
public func asInt() -> Int? {
227+
public func toInt() -> Int? {
228228
switch self {
229229
case let .int32(value):
230230
return Int(value)
@@ -239,7 +239,7 @@ public enum BSON {
239239

240240
/// Return this BSON as an `Int32` if possible.
241241
/// This will coerce numeric cases (e.g. `.double`) into an `Int32` if such coercion would be lossless.
242-
public func asInt32() -> Int32? {
242+
public func toInt32() -> Int32? {
243243
switch self {
244244
case let .int32(value):
245245
return value
@@ -254,7 +254,7 @@ public enum BSON {
254254

255255
/// Return this BSON as an `Int64` if possible.
256256
/// This will coerce numeric cases (e.g. `.double`) into an `Int64` if such coercion would be lossless.
257-
public func asInt64() -> Int64? {
257+
public func toInt64() -> Int64? {
258258
switch self {
259259
case let .int32(value):
260260
return Int64(value)
@@ -269,12 +269,12 @@ public enum BSON {
269269

270270
/// Return this BSON as a `Double` if possible.
271271
/// This will coerce numeric cases (e.g. `.decimal128`) into a `Double` if such coercion would be lossless.
272-
public func asDouble() -> Double? {
272+
public func toDouble() -> Double? {
273273
switch self {
274274
case let .double(d):
275275
return d
276276
default:
277-
guard let intValue = self.asInt() else {
277+
guard let intValue = self.toInt() else {
278278
return nil
279279
}
280280
return Double(intValue)
@@ -283,7 +283,7 @@ public enum BSON {
283283

284284
/// Return this BSON as a `Decimal128` if possible.
285285
/// This will coerce numeric cases (e.g. `.double`) into a `Decimal128` if such coercion would be lossless.
286-
public func asDecimal128() -> Decimal128? {
286+
public func toDecimal128() -> Decimal128? {
287287
switch self {
288288
case let .decimal128(d):
289289
return d

Sources/MongoSwift/BSON/BSONDecoder.swift

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -439,7 +439,7 @@ extension _BSONDecoder {
439439
case .binary:
440440
let binary = try self.unboxCustom(value) { $0.binaryValue }
441441
do {
442-
return try UUID(from: binary)
442+
return try binary.toUUID()
443443
} catch {
444444
throw DecodingError.dataCorrupted(
445445
DecodingError.Context(

Sources/MongoSwift/BSON/BSONEncoder.swift

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -169,7 +169,7 @@ public class BSONEncoder {
169169
)
170170
}
171171

172-
return dict.asDocument()
172+
return dict.toDocument()
173173
}
174174

175175
/**
@@ -778,7 +778,7 @@ private class MutableDictionary: BSONValue {
778778
fileprivate static var bsonType: BSONType { .document }
779779

780780
// This is unused
781-
fileprivate var bson: BSON { .document(self.asDocument()) }
781+
fileprivate var bson: BSON { .document(self.toDocument()) }
782782

783783
// rather than using a dictionary, do this so we preserve key orders
784784
fileprivate var keys = [String]()
@@ -806,7 +806,7 @@ private class MutableDictionary: BSONValue {
806806
}
807807

808808
/// Converts self to a `Document` with equivalent key-value pairs.
809-
fileprivate func asDocument() -> Document {
809+
fileprivate func toDocument() -> Document {
810810
var doc = Document()
811811
for i in 0..<self.keys.count {
812812
doc[self.keys[i]] = self.values[i].bson

Sources/MongoSwift/BSON/BSONValue.swift

Lines changed: 31 additions & 38 deletions
Original file line numberDiff line numberDiff line change
@@ -137,7 +137,7 @@ extension Array: BSONValue where Element == BSON {
137137
}
138138

139139
/// Attempts to map this `[BSON]` to a `[T]`, where `T` is a `BSONValue`.
140-
internal func asArrayOf<T: BSONValue>(_: T.Type) -> [T]? {
140+
internal func toArrayOf<T: BSONValue>(_: T.Type) -> [T]? {
141141
var result: [T] = []
142142
for element in self {
143143
guard let bsonValue = element.bsonValue as? T else {
@@ -321,6 +321,27 @@ public struct BSONBinary: BSONValue, Equatable, Codable, Hashable {
321321
return try self.init(data: dataObj, subtype: UInt8(subtype.rawValue))
322322
})
323323
}
324+
325+
/// Converts this `BSONBinary` instance to a `UUID`.
326+
/// - Throws:
327+
/// - `InvalidArgumentError` if a non-UUID subtype is set on this `BSONBinary`.
328+
public func toUUID() throws -> UUID {
329+
guard [Subtype.uuid.rawValue, Subtype.uuidDeprecated.rawValue].contains(self.subtype) else {
330+
throw InvalidArgumentError(
331+
message: "Expected a UUID binary subtype, got subtype \(self.subtype) instead."
332+
)
333+
}
334+
335+
let data = self.data
336+
let uuid: uuid_t = (
337+
data[0], data[1], data[2], data[3],
338+
data[4], data[5], data[6], data[7],
339+
data[8], data[9], data[10], data[11],
340+
data[12], data[13], data[14], data[15]
341+
)
342+
343+
return UUID(uuid: uuid)
344+
}
324345
}
325346

326347
/// An extension of `Bool` to represent the BSON Boolean type.
@@ -886,34 +907,6 @@ extension BSONObjectID: Hashable {
886907
}
887908
}
888909

889-
/// Extension to allow a `UUID` to be initialized from a `BSONBinary`.
890-
extension UUID {
891-
/// Initializes a `UUID` instance from a `BSONBinary`.
892-
/// - Throws:
893-
/// - `InvalidArgumentError` if a non-UUID subtype is set on the `BSONBinary`.
894-
public init(from binary: BSONBinary) throws {
895-
guard [
896-
BSONBinary.Subtype.uuid.rawValue,
897-
BSONBinary.Subtype.uuidDeprecated.rawValue
898-
].contains(binary.subtype) else {
899-
throw InvalidArgumentError(
900-
message: "Expected a UUID binary type " +
901-
"(\(BSONBinary.Subtype.uuid)), got \(binary.subtype) instead."
902-
)
903-
}
904-
905-
let data = binary.data
906-
let uuid: uuid_t = (
907-
data[0], data[1], data[2], data[3],
908-
data[4], data[5], data[6], data[7],
909-
data[8], data[9], data[10], data[11],
910-
data[12], data[13], data[14], data[15]
911-
)
912-
913-
self.init(uuid: uuid)
914-
}
915-
}
916-
917910
// A mapping of regex option characters to their equivalent `NSRegularExpression` option.
918911
// note that there is a BSON regexp option 'l' that `NSRegularExpression`
919912
// doesn't support. The flag will be dropped if BSON containing it is parsed,
@@ -926,7 +919,7 @@ private let regexOptsMap: [Character: NSRegularExpression.Options] = [
926919
"x": .allowCommentsAndWhitespace
927920
]
928921

929-
/// An extension of `NSRegularExpression` to allow it to be initialized from a `BSONRegularExpression`.
922+
/// An extension of `NSRegularExpression` to support conversion to and from `BSONRegularExpression`.
930923
extension NSRegularExpression {
931924
/// Convert a string of options flags into an equivalent `NSRegularExpression.Options`
932925
internal static func optionsFromString(_ stringOptions: String) -> NSRegularExpression.Options {
@@ -945,14 +938,6 @@ extension NSRegularExpression {
945938
for (char, o) in regexOptsMap { if options.contains(o) { optsString += String(char) } }
946939
return String(optsString.sorted())
947940
}
948-
949-
/// Initializes a new `NSRegularExpression` with the pattern and options of the provided `BSONRegularExpression`.
950-
/// Note: `NSRegularExpression` does not support the `l` locale dependence option, so it will
951-
/// be omitted if set on the provided `BSONRegularExpression`.
952-
public convenience init(from regex: BSONRegularExpression) throws {
953-
let opts = NSRegularExpression.optionsFromString(regex.options)
954-
try self.init(pattern: regex.pattern, options: opts)
955-
}
956941
}
957942

958943
/// A struct to represent a BSON regular expression.
@@ -1016,6 +1001,14 @@ public struct BSONRegularExpression: BSONValue, Equatable, Codable, Hashable {
10161001
return self.init(pattern: patternString, options: optionsString)
10171002
})
10181003
}
1004+
1005+
/// Converts this `BSONRegularExpression` to an `NSRegularExpression`.
1006+
/// Note: `NSRegularExpression` does not support the `l` locale dependence option, so it will be omitted if it was
1007+
/// set on this instance.
1008+
public func toNSRegularExpression() throws -> NSRegularExpression {
1009+
let opts = NSRegularExpression.optionsFromString(self.options)
1010+
return try NSRegularExpression(pattern: self.pattern, options: opts)
1011+
}
10191012
}
10201013

10211014
/// An extension of String to represent the BSON string type.

Sources/MongoSwift/MongoCollection+BulkWrite.swift

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -408,22 +408,22 @@ public struct BulkWriteResult: Decodable {
408408
return nil
409409
}
410410

411-
self.deletedCount = try reply.getValue(for: MongocKeys.deletedCount.rawValue)?.asInt() ?? 0
412-
self.insertedCount = try reply.getValue(for: MongocKeys.insertedCount.rawValue)?.asInt() ?? 0
411+
self.deletedCount = try reply.getValue(for: MongocKeys.deletedCount.rawValue)?.toInt() ?? 0
412+
self.insertedCount = try reply.getValue(for: MongocKeys.insertedCount.rawValue)?.toInt() ?? 0
413413
self.insertedIDs = insertedIDs
414-
self.matchedCount = try reply.getValue(for: MongocKeys.matchedCount.rawValue)?.asInt() ?? 0
415-
self.modifiedCount = try reply.getValue(for: MongocKeys.modifiedCount.rawValue)?.asInt() ?? 0
416-
self.upsertedCount = try reply.getValue(for: MongocKeys.upsertedCount.rawValue)?.asInt() ?? 0
414+
self.matchedCount = try reply.getValue(for: MongocKeys.matchedCount.rawValue)?.toInt() ?? 0
415+
self.modifiedCount = try reply.getValue(for: MongocKeys.modifiedCount.rawValue)?.toInt() ?? 0
416+
self.upsertedCount = try reply.getValue(for: MongocKeys.upsertedCount.rawValue)?.toInt() ?? 0
417417

418418
var upsertedIDs = [Int: BSON]()
419419

420420
if let upserted = try reply.getValue(for: MongocKeys.upserted.rawValue)?.arrayValue {
421-
guard let upserted = upserted.asArrayOf(Document.self) else {
421+
guard let upserted = upserted.toArrayOf(Document.self) else {
422422
throw InternalError(message: "\"upserted\" array did not contain only documents")
423423
}
424424

425425
for upsert in upserted {
426-
guard let index = try upsert.getValue(for: "index")?.asInt() else {
426+
guard let index = try upsert.getValue(for: "index")?.toInt() else {
427427
throw InternalError(message: "Could not cast upserted index to `Int`")
428428
}
429429
upsertedIDs[index] = upsert["_id"]

Sources/MongoSwift/MongoCollection+FindAndModify.swift

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -138,7 +138,7 @@ internal protocol FindAndModifyOptionsConvertible {
138138
/// Converts `self` to a `FindAndModifyOptions`
139139
///
140140
/// - Throws: `InvalidArgumentError` if any of the options are invalid.
141-
func asFindAndModifyOptions() throws -> FindAndModifyOptions
141+
func toFindAndModifyOptions() throws -> FindAndModifyOptions
142142
}
143143

144144
/// Options to use when executing a `findOneAndDelete` command on a `MongoCollection`.
@@ -158,7 +158,7 @@ public struct FindOneAndDeleteOptions: FindAndModifyOptionsConvertible, Decodabl
158158
/// An optional `WriteConcern` to use for the command.
159159
public var writeConcern: WriteConcern?
160160

161-
internal func asFindAndModifyOptions() throws -> FindAndModifyOptions {
161+
internal func toFindAndModifyOptions() throws -> FindAndModifyOptions {
162162
try FindAndModifyOptions(
163163
collation: self.collation,
164164
maxTimeMS: self.maxTimeMS,
@@ -211,7 +211,7 @@ public struct FindOneAndReplaceOptions: FindAndModifyOptionsConvertible, Decodab
211211
/// An optional `WriteConcern` to use for the command.
212212
public var writeConcern: WriteConcern?
213213

214-
internal func asFindAndModifyOptions() throws -> FindAndModifyOptions {
214+
internal func toFindAndModifyOptions() throws -> FindAndModifyOptions {
215215
try FindAndModifyOptions(
216216
bypassDocumentValidation: self.bypassDocumentValidation,
217217
collation: self.collation,
@@ -275,7 +275,7 @@ public struct FindOneAndUpdateOptions: FindAndModifyOptionsConvertible, Decodabl
275275
/// An optional `WriteConcern` to use for the command.
276276
public var writeConcern: WriteConcern?
277277

278-
internal func asFindAndModifyOptions() throws -> FindAndModifyOptions {
278+
internal func toFindAndModifyOptions() throws -> FindAndModifyOptions {
279279
try FindAndModifyOptions(
280280
arrayFilters: self.arrayFilters,
281281
bypassDocumentValidation: self.bypassDocumentValidation,

Sources/MongoSwift/MongoCollection+Write.swift

Lines changed: 8 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -29,7 +29,7 @@ extension MongoCollection {
2929
options: InsertOneOptions? = nil,
3030
session: ClientSession? = nil
3131
) -> EventLoopFuture<InsertOneResult?> {
32-
self.bulkWrite([.insertOne(value)], options: options?.asBulkWriteOptions(), session: session)
32+
self.bulkWrite([.insertOne(value)], options: options?.toBulkWriteOptions(), session: session)
3333
.flatMapThrowing { try InsertOneResult(from: $0) }
3434
.flatMapErrorThrowing { throw convertBulkWriteError($0) }
3535
}
@@ -93,7 +93,7 @@ extension MongoCollection {
9393
) -> EventLoopFuture<UpdateResult?> {
9494
let modelOptions = ReplaceOneModelOptions(collation: options?.collation, upsert: options?.upsert)
9595
let model = WriteModel.replaceOne(filter: filter, replacement: replacement, options: modelOptions)
96-
return self.bulkWrite([model], options: options?.asBulkWriteOptions(), session: session)
96+
return self.bulkWrite([model], options: options?.toBulkWriteOptions(), session: session)
9797
.flatMapThrowing { try UpdateResult(from: $0) }
9898
.flatMapErrorThrowing { throw convertBulkWriteError($0) }
9999
}
@@ -131,7 +131,7 @@ extension MongoCollection {
131131
upsert: options?.upsert
132132
)
133133
let model: WriteModel<CollectionType> = .updateOne(filter: filter, update: update, options: modelOptions)
134-
return self.bulkWrite([model], options: options?.asBulkWriteOptions(), session: session)
134+
return self.bulkWrite([model], options: options?.toBulkWriteOptions(), session: session)
135135
.flatMapThrowing { try UpdateResult(from: $0) }
136136
.flatMapErrorThrowing { throw convertBulkWriteError($0) }
137137
}
@@ -169,7 +169,7 @@ extension MongoCollection {
169169
upsert: options?.upsert
170170
)
171171
let model: WriteModel<CollectionType> = .updateMany(filter: filter, update: update, options: modelOptions)
172-
return self.bulkWrite([model], options: options?.asBulkWriteOptions(), session: session)
172+
return self.bulkWrite([model], options: options?.toBulkWriteOptions(), session: session)
173173
.flatMapThrowing { try UpdateResult(from: $0) }
174174
.flatMapErrorThrowing { throw convertBulkWriteError($0) }
175175
}
@@ -201,7 +201,7 @@ extension MongoCollection {
201201
) -> EventLoopFuture<DeleteResult?> {
202202
let modelOptions = DeleteModelOptions(collation: options?.collation)
203203
let model: WriteModel<CollectionType> = .deleteOne(filter, options: modelOptions)
204-
return self.bulkWrite([model], options: options?.asBulkWriteOptions(), session: session)
204+
return self.bulkWrite([model], options: options?.toBulkWriteOptions(), session: session)
205205
.flatMapThrowing { try DeleteResult(from: $0) }
206206
.flatMapErrorThrowing { throw convertBulkWriteError($0) }
207207
}
@@ -233,7 +233,7 @@ extension MongoCollection {
233233
) -> EventLoopFuture<DeleteResult?> {
234234
let modelOptions = DeleteModelOptions(collation: options?.collation)
235235
let model: WriteModel<CollectionType> = .deleteMany(filter, options: modelOptions)
236-
return self.bulkWrite([model], options: options?.asBulkWriteOptions(), session: session)
236+
return self.bulkWrite([model], options: options?.toBulkWriteOptions(), session: session)
237237
.flatMapThrowing { try DeleteResult(from: $0) }
238238
.flatMapErrorThrowing { throw convertBulkWriteError($0) }
239239
}
@@ -243,12 +243,12 @@ extension MongoCollection {
243243
private protocol BulkWriteOptionsConvertible {
244244
var bypassDocumentValidation: Bool? { get }
245245
var writeConcern: WriteConcern? { get }
246-
func asBulkWriteOptions() -> BulkWriteOptions
246+
func toBulkWriteOptions() -> BulkWriteOptions
247247
}
248248

249249
/// Default implementation of the protocol.
250250
private extension BulkWriteOptionsConvertible {
251-
func asBulkWriteOptions() -> BulkWriteOptions {
251+
func toBulkWriteOptions() -> BulkWriteOptions {
252252
BulkWriteOptions(
253253
bypassDocumentValidation: self.bypassDocumentValidation,
254254
writeConcern: self.writeConcern

Sources/MongoSwift/MongoError.swift

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -277,7 +277,7 @@ private func parseMongocError(_ error: bson_error_t, reply: Document?) -> MongoE
277277
let code = mongoc_error_code_t(rawValue: error.code)
278278
let message = toErrorString(error)
279279

280-
let errorLabels = reply?["errorLabels"]?.arrayValue?.asArrayOf(String.self)
280+
let errorLabels = reply?["errorLabels"]?.arrayValue?.toArrayOf(String.self)
281281
let codeName = reply?["codeName"]?.stringValue ?? ""
282282

283283
switch (domain, code) {
@@ -352,7 +352,7 @@ internal func extractMongoError(error bsonError: bson_error_t, reply: Document?
352352
return WriteError(
353353
writeFailure: writeError,
354354
writeConcernFailure: wcError,
355-
errorLabels: serverReply["errorLabels"]?.arrayValue?.asArrayOf(String.self)
355+
errorLabels: serverReply["errorLabels"]?.arrayValue?.toArrayOf(String.self)
356356
)
357357
} catch {
358358
return fallback
@@ -439,7 +439,7 @@ internal func extractBulkWriteError<T: Codable>(
439439
writeConcernFailure: try extractWriteConcernError(from: reply),
440440
otherError: other,
441441
result: errResult,
442-
errorLabels: reply["errorLabels"]?.arrayValue?.asArrayOf(String.self)
442+
errorLabels: reply["errorLabels"]?.arrayValue?.toArrayOf(String.self)
443443
)
444444
} catch {
445445
return fallback

Sources/MongoSwift/Operations/FindAndModifyOperation.swift

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -157,7 +157,7 @@ internal struct FindAndModifyOperation<T: Codable>: Operation {
157157
internal func execute(using connection: Connection, session: ClientSession?) throws -> T? {
158158
// we always need to send *something*, as findAndModify requires one of "remove"
159159
// or "update" to be set.
160-
let opts = try self.options?.asFindAndModifyOptions() ?? FindAndModifyOptions()
160+
let opts = try self.options?.toFindAndModifyOptions() ?? FindAndModifyOptions()
161161
if let session = session { try opts.setSession(session) }
162162
if let update = self.update { try opts.setUpdate(update) }
163163

Sources/MongoSwift/Operations/ListDatabasesOperation.swift

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -79,7 +79,7 @@ internal struct ListDatabasesOperation: Operation {
7979
}
8080
}
8181

82-
guard let databases = reply["databases"]?.arrayValue?.asArrayOf(Document.self) else {
82+
guard let databases = reply["databases"]?.arrayValue?.toArrayOf(Document.self) else {
8383
throw InternalError(message: "Invalid server response: \(reply)")
8484
}
8585

0 commit comments

Comments
 (0)