diff --git a/CHANGELOG.md b/CHANGELOG.md index 18d35e7bc..33153fc74 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,7 @@ Release Notes - Upgrade custom SQLite builds to [v3.22.0](http://www.sqlite.org/changes.html) (thanks to [@swiftlyfalling](https://github.com/swiftlyfalling/SQLiteLib)). - The FTS5 full-text search engine has been enhanced with [initial token queries](https://sqlite.org/fts5.html#carrotq), and FTS5Pattern has gained a new initializer: `FTS5Pattern(matchingPrefixPhrase:)` +- The `Cursor` protocol is extended with more methods inspired by the standard Sequence protocol: `drop(while:)`, `dropFirst()`, `dropFirst(_:)`, `dropLast()`, `dropLast(_:)`, `joined(separator:)`, `prefix(_:)`, `max()`, `max(by:)`, `min()`, `min(by:)`, `prefix(while:)`, `reduce(into:_:)`, `suffix(_:)`, ## 2.7.0 diff --git a/GRDB.xcodeproj/project.pbxproj b/GRDB.xcodeproj/project.pbxproj index dfe2cbf5b..4136b0b29 100755 --- a/GRDB.xcodeproj/project.pbxproj +++ b/GRDB.xcodeproj/project.pbxproj @@ -436,6 +436,14 @@ 56BF6D401DEF47DA006039A3 /* Fixits-Swift2.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56BF6D2E1DEF47DA006039A3 /* Fixits-Swift2.swift */; }; 56BF6D431DEF47DA006039A3 /* Fixits-Swift2.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56BF6D2E1DEF47DA006039A3 /* Fixits-Swift2.swift */; }; 56C3F7561CF9F12400F6A361 /* DatabaseSavepointTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56C3F7521CF9F12400F6A361 /* DatabaseSavepointTests.swift */; }; + 56CC922C201DFFB900CB597E /* DropWhileCursorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56CC922B201DFFB900CB597E /* DropWhileCursorTests.swift */; }; + 56CC922D201DFFB900CB597E /* DropWhileCursorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56CC922B201DFFB900CB597E /* DropWhileCursorTests.swift */; }; + 56CC9243201E034D00CB597E /* PrefixWhileCursorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56CC9242201E034D00CB597E /* PrefixWhileCursorTests.swift */; }; + 56CC9244201E034D00CB597E /* PrefixWhileCursorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56CC9242201E034D00CB597E /* PrefixWhileCursorTests.swift */; }; + 56CC9246201E058100CB597E /* DropFirstCursorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56CC9245201E058000CB597E /* DropFirstCursorTests.swift */; }; + 56CC9247201E058100CB597E /* DropFirstCursorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56CC9245201E058000CB597E /* DropFirstCursorTests.swift */; }; + 56CC9251201E093F00CB597E /* PrefixCursorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56CC9250201E093E00CB597E /* PrefixCursorTests.swift */; }; + 56CC9252201E093F00CB597E /* PrefixCursorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56CC9250201E093E00CB597E /* PrefixCursorTests.swift */; }; 56CEB4F11EAA2EFA00BFAF62 /* RowConvertible.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56CEB4F01EAA2EFA00BFAF62 /* RowConvertible.swift */; }; 56CEB4F41EAA2EFA00BFAF62 /* RowConvertible.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56CEB4F01EAA2EFA00BFAF62 /* RowConvertible.swift */; }; 56CEB4F71EAA2EFA00BFAF62 /* RowConvertible.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56CEB4F01EAA2EFA00BFAF62 /* RowConvertible.swift */; }; @@ -950,6 +958,10 @@ 56C494401ED7255500CC72AF /* GRDBDeploymentTarget.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; path = GRDBDeploymentTarget.xcconfig; sourceTree = ""; }; 56CA21FE1BB414FE009A04C5 /* SQLite.xcodeproj */ = {isa = PBXFileReference; lastKnownFileType = "wrapper.pb-project"; name = SQLite.xcodeproj; path = SQLite.swift/SQLite.xcodeproj; sourceTree = ""; }; 56CA22211BB41565009A04C5 /* PerformanceTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = PerformanceTests.swift; sourceTree = ""; }; + 56CC922B201DFFB900CB597E /* DropWhileCursorTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DropWhileCursorTests.swift; sourceTree = ""; }; + 56CC9242201E034D00CB597E /* PrefixWhileCursorTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = PrefixWhileCursorTests.swift; sourceTree = ""; }; + 56CC9245201E058000CB597E /* DropFirstCursorTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DropFirstCursorTests.swift; sourceTree = ""; }; + 56CC9250201E093E00CB597E /* PrefixCursorTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = PrefixCursorTests.swift; sourceTree = ""; }; 56CEB4F01EAA2EFA00BFAF62 /* RowConvertible.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RowConvertible.swift; sourceTree = ""; }; 56CEB4F81EAA2F4D00BFAF62 /* FTS3.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FTS3.swift; sourceTree = ""; }; 56CEB4F91EAA2F4D00BFAF62 /* FTS4.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FTS4.swift; sourceTree = ""; }; @@ -1603,11 +1615,15 @@ 5623932F1DEDFC5700A6B01F /* AnyCursorTests.swift */, 5623935F1DEE06D300A6B01F /* CursorTests.swift */, 56DAA2D11DE99DAB006E10C8 /* DatabaseCursorTests.swift */, + 56CC9245201E058000CB597E /* DropFirstCursorTests.swift */, + 56CC922B201DFFB900CB597E /* DropWhileCursorTests.swift */, 5623934D1DEDFEFB00A6B01F /* EnumeratedCursorTests.swift */, 562393561DEE013C00A6B01F /* FilterCursorTests.swift */, 562393681DEE0CD200A6B01F /* FlattenCursorTests.swift */, 562393441DEDFE4500A6B01F /* IteratorCursorTests.swift */, 562393711DEE104400A6B01F /* MapCursorTests.swift */, + 56CC9250201E093E00CB597E /* PrefixCursorTests.swift */, + 56CC9242201E034D00CB597E /* PrefixWhileCursorTests.swift */, ); name = Cursor; sourceTree = ""; @@ -2359,6 +2375,7 @@ 56176C6E1EACCCC9000F3F2B /* FTS5TableBuilderTests.swift in Sources */, 56A2384C1B9C74A90082EB20 /* UpdateStatementTests.swift in Sources */, 56A2384E1B9C74A90082EB20 /* DatabaseMigratorTests.swift in Sources */, + 56CC9244201E034D00CB597E /* PrefixWhileCursorTests.swift in Sources */, 5657AB4A1D108BA9006283EF /* FoundationNSNullTests.swift in Sources */, 562393491DEDFE4500A6B01F /* IteratorCursorTests.swift in Sources */, 569531351C919DF200CF1A2B /* DatabasePoolCollationTests.swift in Sources */, @@ -2384,8 +2401,10 @@ 5698AC4D1DA2D48A0056AF8C /* FTS3RecordTests.swift in Sources */, 56B15D0B1CD4C35100A24C8B /* FetchedRecordsControllerTests.swift in Sources */, 56A238681B9C74A90082EB20 /* RecordInitializersTests.swift in Sources */, + 56CC9252201E093F00CB597E /* PrefixCursorTests.swift in Sources */, 563363B01C933FF8000BE133 /* MutablePersistableTests.swift in Sources */, 5657AB421D108BA9006283EF /* FoundationNSDataTests.swift in Sources */, + 56CC922D201DFFB900CB597E /* DropWhileCursorTests.swift in Sources */, 56D507621F6BAE8600AE1C5B /* PrimaryKeyInfoTests.swift in Sources */, 56176C6B1EACCCC9000F3F2B /* FTS5CustomTokenizerTests.swift in Sources */, 56300B621C53C42C005A543B /* RowConvertible+QueryInterfaceRequestTests.swift in Sources */, @@ -2427,6 +2446,7 @@ 5698AC9A1DA4B0430056AF8C /* FTS4RecordTests.swift in Sources */, 562393521DEDFEFB00A6B01F /* EnumeratedCursorTests.swift in Sources */, 56A4CDB41D4234B200B1A9B9 /* SQLExpressionLiteralTests.swift in Sources */, + 56CC9247201E058100CB597E /* DropFirstCursorTests.swift in Sources */, 56E8CE0E1BB4FA5600828BEC /* DatabaseValueConvertibleFetchTests.swift in Sources */, 56A238581B9C74A90082EB20 /* RecordPrimaryKeyRowIDTests.swift in Sources */, 56A5EF131EF7F20B00F03071 /* ForeignKeyInfoTests.swift in Sources */, @@ -2499,6 +2519,7 @@ 56176C5C1EACCCC7000F3F2B /* FTS5TableBuilderTests.swift in Sources */, 562206061E420EA4005860AC /* DatabasePoolBackupTests.swift in Sources */, 56D496B51D813413008276D7 /* DatabaseCollationTests.swift in Sources */, + 56CC9243201E034D00CB597E /* PrefixWhileCursorTests.swift in Sources */, 56D496841D813147008276D7 /* SelectStatementTests.swift in Sources */, 56D496B11D8133BC008276D7 /* DatabaseQueueReadOnlyTests.swift in Sources */, 56D4968C1D81316E008276D7 /* RawRepresentable+DatabaseValueConvertibleTests.swift in Sources */, @@ -2524,8 +2545,10 @@ 56D496781D81309E008276D7 /* RecordSubClassTests.swift in Sources */, 56D4965F1D81304E008276D7 /* FoundationNSURLTests.swift in Sources */, 562393301DEDFC5700A6B01F /* AnyCursorTests.swift in Sources */, + 56CC9251201E093F00CB597E /* PrefixCursorTests.swift in Sources */, 56D4965E1D81304E008276D7 /* FoundationNSStringTests.swift in Sources */, 5698AC891DA389380056AF8C /* FTS3TableBuilderTests.swift in Sources */, + 56CC922C201DFFB900CB597E /* DropWhileCursorTests.swift in Sources */, 56D5075E1F6BAE8600AE1C5B /* PrimaryKeyInfoTests.swift in Sources */, 56176C591EACCCC7000F3F2B /* FTS5CustomTokenizerTests.swift in Sources */, 56D4968A1D81316E008276D7 /* DatabaseValueConvertibleSubclassTests.swift in Sources */, @@ -2567,6 +2590,7 @@ 562393601DEE06D300A6B01F /* CursorTests.swift in Sources */, 56D4968F1D81316E008276D7 /* RowFromDictionaryTests.swift in Sources */, 56D4968E1D81316E008276D7 /* RowCopiedFromStatementTests.swift in Sources */, + 56CC9246201E058100CB597E /* DropFirstCursorTests.swift in Sources */, 5698AC401DA2BED90056AF8C /* FTS3PatternTests.swift in Sources */, 562393571DEE013C00A6B01F /* FilterCursorTests.swift in Sources */, 56A5EF0F1EF7F20B00F03071 /* ForeignKeyInfoTests.swift in Sources */, diff --git a/GRDB/Core/Cursor.swift b/GRDB/Core/Cursor.swift index 8d59f977e..26ca0b362 100644 --- a/GRDB/Core/Cursor.swift +++ b/GRDB/Core/Cursor.swift @@ -1,3 +1,16 @@ +//===----------------------------------------------------------------------===// +// +// Parts of this file are derived from the Swift.org open source project: +// +// Copyright (c) 2014 - 2018 Apple Inc. and the Swift project authors +// Licensed under Apache License v2.0 with Runtime Library Exception +// +// See https://swift.org/LICENSE.txt for license information +// +//===----------------------------------------------------------------------===// + +// MARK: - Array, Sequence, Set extensions + extension Array { /// Creates an array containing the elements of a cursor. /// @@ -11,6 +24,15 @@ extension Array { } } +extension Sequence { + + /// Returns a cursor over the concatenated results of mapping transform + /// over self. + public func flatMap(_ transform: @escaping (Iterator.Element) throws -> SegmentOfResult) -> FlattenCursor, SegmentOfResult>> { + return IteratorCursor(self).flatMap(transform) + } +} + extension Set { /// Creates a set containing the elements of a cursor. /// @@ -24,6 +46,8 @@ extension Set { } } +// MARK: - Cursor + /// A type that supplies the values of some external resource, one at a time. /// /// ## Overview @@ -46,19 +70,11 @@ extension Set { /// - A cursor can not be repeated. /// /// The protocol comes with default implementations for many operations similar -/// to those defined by Swift's LazySequenceProtocol: -/// -/// - `func contains(Self.Element)` -/// - `func contains(where: (Self.Element) throws -> Bool)` -/// - `func enumerated()` -/// - `func filter((Self.Element) throws -> Bool)` -/// - `func first(where: (Self.Element) throws -> Bool)` -/// - `func flatMap((Self.Element) throws -> ElementOfResult?)` -/// - `func flatMap((Self.Element) throws -> SegmentOfResult)` -/// - `func forEach((Self.Element) throws -> Void)` -/// - `func joined()` -/// - `func map((Self.Element) throws -> T)` -/// - `func reduce(Result, (Result, Self.Element) throws -> Result)` +/// to those defined by Swift's Sequence protocol: `contains`, `dropFirst`, +/// `dropLast`, `drop(while:)`, `enumerated`, `filter`, `first`, `flatMap`, +/// `forEach`, `joined`, `joined(separator:)`, `max`, `max(by:)`, `min`, +/// `min(by:)`, `map`, `prefix`, `prefix(while:)`, `reduce`, `reduce(into:)`, +/// `suffix`. public protocol Cursor : class { /// The type of element traversed by the cursor. associatedtype Element @@ -68,33 +84,6 @@ public protocol Cursor : class { func next() throws -> Element? } -/// A type-erased cursor of Element. -/// -/// This cursor forwards its next() method to an arbitrary underlying cursor -/// having the same Element type, hiding the specifics of the underlying -/// cursor. -public class AnyCursor : Cursor { - /// Creates a cursor that wraps a base cursor but whose type depends only on - /// the base cursor’s element type - public init(_ base: C) where C.Element == Element { - element = base.next - } - - /// Creates a cursor that wraps the given closure in its next() method - public init(_ body: @escaping () throws -> Element?) { - element = body - } - - /// Advances to the next element and returns it, or nil if no next - /// element exists. - /// :nodoc: - public func next() throws -> Element? { - return try element() - } - - private let element: () throws -> Element? -} - extension Cursor { /// Returns a Boolean value indicating whether the cursor contains an /// element that satisfies the given predicate. @@ -149,6 +138,102 @@ extension Cursor { return map(transform).filter { $0 != nil }.map { $0! } } + /// Returns a cursor that skips any initial elements that satisfy + /// `predicate`. + /// + /// - Parameter predicate: A closure that takes an element of the cursir as + /// its argument and returns `true` if the element should be skipped or + /// `false` otherwise. Once `predicate` returns `false` it will not be + /// called again. + public func drop(while predicate: @escaping (Element) throws -> Bool) -> DropWhileCursor { + return DropWhileCursor(self, predicate: predicate) + } + + /// Returns a cursor containing all but the given number of initial + /// elements. + /// + /// If the number of elements to drop exceeds the number of elements in + /// the cursor, the result is an empty cursor. + /// + /// let numbers = IteratorCursor([1, 2, 3, 4, 5]) + /// try print(numbers.dropFirst(2)) + /// // Prints "[3, 4, 5]" + /// try print(numbers.dropFirst(10)) + /// // Prints "[]" + /// + /// - Parameter n: The number of elements to drop from the beginning of + /// the cursor. `n` must be greater than or equal to zero. + /// - Returns: A cursor starting after the specified number of + /// elements. + public func dropFirst(_ n: Int) -> DropFirstCursor { + return DropFirstCursor(self, limit: n) + } + + /// Returns a cursor containing all but the first element of the cursor. + /// + /// The following example drops the first element from a cursor of integers. + /// + /// let numbers = IteratorCursor([1, 2, 3, 4, 5]) + /// try print(numbers.dropFirst()) + /// // Prints "[2, 3, 4, 5]" + /// + /// If the cursor has no elements, the result is an empty cursor. + /// + /// - Returns: A cursor starting after the first element of the cursor. + public func dropFirst() -> DropFirstCursor { + return dropFirst(1) + } + + /// Returns an array containing all but the given number of final + /// elements. + /// + /// The cursor must be finite. If the number of elements to drop exceeds + /// the number of elements in the cursor, the result is an empty array. + /// + /// let numbers = IteratorCursor([1, 2, 3, 4, 5]) + /// try print(numbers.dropLast(2)) + /// // Prints "[1, 2, 3]" + /// try print(numbers.dropLast(10)) + /// // Prints "[]" + /// + /// - Parameter n: The number of elements to drop off the end of the + /// cursor. `n` must be greater than or equal to zero. + /// - Returns: An array leaving off the specified number of elements. + public func dropLast(_ n: Int) throws -> [Element] { + GRDBPrecondition(n >= 0, "Can't drop a negative number of elements from a cursor") + if n == 0 { return try Array(self) } + + var result: [Element] = [] + var ringBuffer: [Element] = [] + var i = ringBuffer.startIndex + + while let element = try next() { + if ringBuffer.count < n { + ringBuffer.append(element) + } else { + result.append(ringBuffer[i]) + ringBuffer[i] = element + i = ringBuffer.index(after: i) % n + } + } + return result + } + + /// Returns an array containing all but the last element of the cursor. + /// + /// The following example drops the last element from a cursor of integers. + /// + /// let numbers = IteratorCursor([1, 2, 3, 4, 5]) + /// try print(numbers.dropLast()) + /// // Prints "[1, 2, 3, 4]" + /// + /// If the cursor has no elements, the result is an empty cursor. + /// + /// - Returns: An array leaving off the last element of the cursor. + public func dropLast() throws -> [Element] { + return try dropLast(1) + } + /// Returns a cursor over the concatenated results of mapping transform /// over self. public func flatMap(_ transform: @escaping (Element) throws -> SegmentOfResult) -> FlattenCursor>> { @@ -174,17 +259,152 @@ extension Cursor { return MapCursor(self, transform) } - /// Returns the result of calling the given combining closure with each - /// element of this sequence and an accumulating value. - public func reduce(_ initialResult: Result, _ nextPartialResult: (Result, Element) throws -> Result) throws -> Result { - var result = initialResult - while let element = try next() { - result = try nextPartialResult(result, element) + /// Returns the maximum element in the cursor, using the given predicate as + /// the comparison between elements. + /// + /// - Parameter areInIncreasingOrder: A predicate that returns `true` + /// if its first argument should be ordered before its second + /// argument; otherwise, `false`. + /// - Returns: The cursor's maximum element, according to + /// `areInIncreasingOrder`. If the cursor has no elements, returns `nil`. + public func max(by areInIncreasingOrder: (Element, Element) throws -> Bool) throws -> Element? { + guard var result = try next() else { + return nil + } + while let e = try next() { + if try areInIncreasingOrder(result, e) { + result = e + } } return result } + + /// Returns the minimum element in the cursor, using the given predicate as + /// the comparison between elements. + /// + /// - Parameter areInIncreasingOrder: A predicate that returns `true` + /// if its first argument should be ordered before its second + /// argument; otherwise, `false`. + /// - Returns: The cursor's minimum element, according to + /// `areInIncreasingOrder`. If the cursor has no elements, returns `nil`. + public func min(by areInIncreasingOrder: (Element, Element) throws -> Bool) throws -> Element? { + guard var result = try next() else { + return nil + } + while let e = try next() { + if try areInIncreasingOrder(e, result) { + result = e + } + } + return result + } + + /// Returns a cursor, up to the specified maximum length, containing the + /// initial elements of the cursor. + /// + /// If the maximum length exceeds the number of elements in the cursor, + /// the result contains all the elements in the cursor. + /// + /// let numbers = IteratorCursor([1, 2, 3, 4, 5]) + /// try print(numbers.prefix(2)) + /// // Prints "[1, 2]" + /// try print(numbers.prefix(10)) + /// // Prints "[1, 2, 3, 4, 5]" + /// + /// - Parameter maxLength: The maximum number of elements to return. The + /// value of `maxLength` must be greater than or equal to zero. + /// - Returns: A cursor starting at the beginning of this cursor + /// with at most `maxLength` elements. + public func prefix(_ maxLength: Int) -> PrefixCursor { + return PrefixCursor(self, maxLength: maxLength) + } + + /// Returns a cursor of the initial consecutive elements that satisfy + /// `predicate`. + /// + /// - Parameter predicate: A closure that takes an element of the cursor as + /// its argument and returns `true` if the element should be included or + /// `false` otherwise. Once `predicate` returns `false` it will not be + /// called again. + public func prefix(while predicate: @escaping (Element) throws -> Bool) -> PrefixWhileCursor { + return PrefixWhileCursor(self, predicate: predicate) + } + + /// Returns the result of calling the given combining closure with each + /// element of this cursor and an accumulating value. + public func reduce( + _ initialResult: Result, + _ nextPartialResult: (Result, Element) throws -> Result) + throws -> Result + { + var accumulator = initialResult + while let element = try next() { + accumulator = try nextPartialResult(accumulator, element) + } + return accumulator + } + + /// Returns the result of calling the given combining closure with each + /// element of this cursor and an accumulating value. + public func reduce( + into initialResult: Result, + _ updateAccumulatingResult: (inout Result, Element) throws -> Void) + throws -> Result + { + var accumulator = initialResult + while let element = try next() { + try updateAccumulatingResult(&accumulator, element) + } + return accumulator + } + + /// Returns an array, up to the given maximum length, containing the + /// final elements of the cursor. + /// + /// The cursor must be finite. If the maximum length exceeds the number of + /// elements in the cursor, the result contains all the elements in the + /// cursor. + /// + /// let numbers = IteratorCursor([1, 2, 3, 4, 5]) + /// try print(numbers.suffix(2)) + /// // Prints "[4, 5]" + /// try print(numbers.suffix(10)) + /// // Prints "[1, 2, 3, 4, 5]" + /// + /// - Parameter maxLength: The maximum number of elements to return. The + /// value of `maxLength` must be greater than or equal to zero. + public func suffix(_ maxLength: Int) throws -> [Element] { + GRDBPrecondition(maxLength >= 0, "Can't take a suffix of negative length from a cursor") + if maxLength == 0 { + return [] + } + + var ringBuffer: [Element] = [] + ringBuffer.reserveCapacity(maxLength) + + var i = ringBuffer.startIndex + + while let element = try next() { + if ringBuffer.count < maxLength { + ringBuffer.append(element) + } else { + ringBuffer[i] = element + i += 1 + i %= maxLength + } + } + + if i != ringBuffer.startIndex { + let s0 = ringBuffer[i.. Element? { + return try max(by: <) + } + + /// Returns the minimum element in the cursor. + /// + /// - Parameter areInIncreasingOrder: A predicate that returns `true` + /// if its first argument should be ordered before its second + /// argument; otherwise, `false`. + /// - Returns: The cursor's minimum element, according to + /// `areInIncreasingOrder`. If the cursor has no elements, returns + /// `nil`. + public func min() throws -> Element? { + return try min(by: <) + } +} + +// MARK: Cursor elements + extension Cursor where Element: Cursor { /// Returns the elements of this cursor of cursors, concatenated. public func joined() -> FlattenCursor { @@ -205,13 +455,122 @@ extension Cursor where Element: Cursor { } } +// MARK: Sequence elements + extension Cursor where Element: Sequence { /// Returns the elements of this cursor of sequences, concatenated. - public func joined() -> FlattenCursor>> { + public func joined() -> FlattenCursor>> { return flatMap { $0 } } } +// MARK: String elements + +extension Cursor where Element: StringProtocol { + /// Returns the elements of this cursor of sequences, concatenated. + public func joined(separator: String = "") throws -> String { + if separator.isEmpty { + var result = "" + while let x = try next() { + result.append(String(x)) + } + return result + } else { + var result = "" + if let first = try next() { + result.append(String(first)) + while let next = try next() { + result.append(separator) + result.append(String(next)) + } + } + return result + } + } +} + +// MARK: Specialized Cursors + +/// A type-erased cursor of Element. +/// +/// This cursor forwards its next() method to an arbitrary underlying cursor +/// having the same Element type, hiding the specifics of the underlying +/// cursor. +public class AnyCursor : Cursor { + private let element: () throws -> Element? + + /// Creates a cursor that wraps a base cursor but whose type depends only on + /// the base cursor’s element type + public init(_ base: C) where C.Element == Element { + element = base.next + } + + /// Creates a cursor that wraps the given closure in its next() method + public init(_ body: @escaping () throws -> Element?) { + element = body + } + + /// Advances to the next element and returns it, or nil if no next + /// element exists. + /// :nodoc: + public func next() throws -> Element? { + return try element() + } +} + +/// :nodoc: +public final class DropFirstCursor : Cursor { + private let base: Base + private let limit: Int + private var dropped: Int = 0 + + init(_ base: Base, limit: Int) { + GRDBPrecondition(limit >= 0, "Can't drop a negative number of elements from a cursor") + self.base = base + self.limit = limit + } + + public func next() throws -> Base.Element? { + while dropped < limit { + if try base.next() == nil { + dropped = limit + return nil + } + dropped += 1 + } + return try base.next() + } +} + +/// A cursor whose elements consist of the elements that follow the initial +/// consecutive elements of some base cursor that satisfy a given predicate. +/// +/// :nodoc: +public final class DropWhileCursor : Cursor { + private let base: Base + private let predicate: (Base.Element) throws -> Bool + private var predicateHasFailed = false + + init(_ base: Base, predicate: @escaping (Base.Element) throws -> Bool) { + self.base = base + self.predicate = predicate + } + + public func next() throws -> Base.Element? { + if predicateHasFailed { + return try base.next() + } + + while let nextElement = try base.next() { + if try !predicate(nextElement) { + predicateHasFailed = true + return nextElement + } + } + return nil + } +} + /// An enumeration of the elements of a cursor. /// /// To create an instance of `EnumeratedCursor`, call the `enumerated()` method @@ -224,10 +583,15 @@ extension Cursor where Element: Sequence { /// } /// // Prints: "0: foo" /// // Prints: "1: bar" +/// +/// :nodoc: public final class EnumeratedCursor : Cursor { + private let base: Base + private var index: Int + init(_ base: Base) { - self.index = 0 self.base = base + self.index = 0 } /// Advances to the next element and returns it, or nil if no next @@ -238,14 +602,16 @@ public final class EnumeratedCursor : Cursor { defer { index += 1 } return (index, element) } - - private var index: Int - private var base: Base } /// A cursor whose elements consist of the elements of some base cursor that /// also satisfy a given predicate. +/// +/// :nodoc: public final class FilterCursor : Cursor { + private let base: Base + private let isIncluded: (Base.Element) throws -> Bool + init(_ base: Base, _ isIncluded: @escaping (Base.Element) throws -> Bool) { self.base = base self.isIncluded = isIncluded @@ -262,16 +628,18 @@ public final class FilterCursor : Cursor { } return nil } - - private let base: Base - private let isIncluded: (Base.Element) throws -> Bool } /// A cursor consisting of all the elements contained in each segment contained /// in some Base cursor. /// /// See Cursor.joined(), Cursor.flatMap(_:), Sequence.flatMap(_:) +/// +/// :nodoc: public final class FlattenCursor : Cursor where Base.Element: Cursor { + private let base: Base + private var inner: Base.Element? + init(_ base: Base) { self.base = base } @@ -290,16 +658,18 @@ public final class FlattenCursor : Cursor where Base.Element: Curs self.inner = inner } } - - private var inner: Base.Element? - private let base: Base } /// A Cursor whose elements consist of those in a Base Cursor passed through a /// transform function returning Element. /// /// See Cursor.map(_:) +/// +/// :nodoc: public final class MapCursor : Cursor { + private let base: Base + private let transform: (Base.Element) throws -> Element + init(_ base: Base, _ transform: @escaping (Base.Element) throws -> Element) { self.base = base self.transform = transform @@ -312,14 +682,65 @@ public final class MapCursor : Cursor { guard let element = try base.next() else { return nil } return try transform(element) } - +} + +/// A cursor that only consumes up to `n` elements from an underlying +/// `Base` cursor. +/// +/// :nodoc: +public final class PrefixCursor : Cursor { private let base: Base - private let transform: (Base.Element) throws -> Element + private let maxLength: Int + private var taken = 0 + + init(_ base: Base, maxLength: Int) { + self.base = base + self.maxLength = maxLength + } + + public func next() throws -> Base.Element? { + if taken >= maxLength { return nil } + taken += 1 + + if let next = try base.next() { + return next + } + + taken = maxLength + return nil + } +} + +/// A cursor whose elements consist of the initial consecutive elements of +/// some base cursor that satisfy a given predicate. +/// +/// :nodoc: +public final class PrefixWhileCursor : Cursor { + private let base: Base + private let predicate: (Base.Element) throws -> Bool + private var predicateHasFailed = false + + init(_ base: Base, predicate: @escaping (Base.Element) throws -> Bool) { + self.base = base + self.predicate = predicate + } + + public func next() throws -> Base.Element? { + if !predicateHasFailed, let nextElement = try base.next() { + if try predicate(nextElement) { + return nextElement + } else { + predicateHasFailed = true + } + } + return nil + } } /// A Cursor whose elements are those of a sequence iterator. public final class IteratorCursor : Cursor { - + private var base: Base + /// Creates a cursor from a sequence iterator. public init(_ base: Base) { self.base = base @@ -336,15 +757,4 @@ public final class IteratorCursor : Cursor { public func next() -> Base.Element? { return base.next() } - - private var base: Base -} - -extension Sequence { - - /// Returns a cursor over the concatenated results of mapping transform - /// over self. - public func flatMap(_ transform: @escaping (Iterator.Element) throws -> SegmentOfResult) -> FlattenCursor, SegmentOfResult>> { - return IteratorCursor(self).flatMap(transform) - } } diff --git a/GRDBCipher.xcodeproj/project.pbxproj b/GRDBCipher.xcodeproj/project.pbxproj index ed62a0795..9fe2a14b0 100755 --- a/GRDBCipher.xcodeproj/project.pbxproj +++ b/GRDBCipher.xcodeproj/project.pbxproj @@ -676,6 +676,22 @@ 56C3F7551CF9F12400F6A361 /* DatabaseSavepointTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56C3F7521CF9F12400F6A361 /* DatabaseSavepointTests.swift */; }; 56C3F7571CF9F12400F6A361 /* DatabaseSavepointTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56C3F7521CF9F12400F6A361 /* DatabaseSavepointTests.swift */; }; 56C3F7581CF9F12400F6A361 /* DatabaseSavepointTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56C3F7521CF9F12400F6A361 /* DatabaseSavepointTests.swift */; }; + 56CC9236201E009700CB597E /* DropWhileCursorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56CC922E201DFFE200CB597E /* DropWhileCursorTests.swift */; }; + 56CC9237201E009800CB597E /* DropWhileCursorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56CC922E201DFFE200CB597E /* DropWhileCursorTests.swift */; }; + 56CC9238201E009900CB597E /* DropWhileCursorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56CC922E201DFFE200CB597E /* DropWhileCursorTests.swift */; }; + 56CC9239201E009A00CB597E /* DropWhileCursorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56CC922E201DFFE200CB597E /* DropWhileCursorTests.swift */; }; + 56CC923E201E034200CB597E /* PrefixWhileCursorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56CC923D201E034200CB597E /* PrefixWhileCursorTests.swift */; }; + 56CC923F201E034200CB597E /* PrefixWhileCursorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56CC923D201E034200CB597E /* PrefixWhileCursorTests.swift */; }; + 56CC9240201E034200CB597E /* PrefixWhileCursorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56CC923D201E034200CB597E /* PrefixWhileCursorTests.swift */; }; + 56CC9241201E034200CB597E /* PrefixWhileCursorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56CC923D201E034200CB597E /* PrefixWhileCursorTests.swift */; }; + 56CC924C201E059100CB597E /* DropFirstCursorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56CC924B201E059100CB597E /* DropFirstCursorTests.swift */; }; + 56CC924D201E059100CB597E /* DropFirstCursorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56CC924B201E059100CB597E /* DropFirstCursorTests.swift */; }; + 56CC924E201E059100CB597E /* DropFirstCursorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56CC924B201E059100CB597E /* DropFirstCursorTests.swift */; }; + 56CC924F201E059100CB597E /* DropFirstCursorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56CC924B201E059100CB597E /* DropFirstCursorTests.swift */; }; + 56CC9257201E094F00CB597E /* PrefixCursorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56CC9256201E094E00CB597E /* PrefixCursorTests.swift */; }; + 56CC9258201E094F00CB597E /* PrefixCursorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56CC9256201E094E00CB597E /* PrefixCursorTests.swift */; }; + 56CC9259201E094F00CB597E /* PrefixCursorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56CC9256201E094E00CB597E /* PrefixCursorTests.swift */; }; + 56CC925A201E094F00CB597E /* PrefixCursorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56CC9256201E094E00CB597E /* PrefixCursorTests.swift */; }; 56CEB4F21EAA2EFA00BFAF62 /* RowConvertible.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56CEB4F01EAA2EFA00BFAF62 /* RowConvertible.swift */; }; 56CEB4F51EAA2EFA00BFAF62 /* RowConvertible.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56CEB4F01EAA2EFA00BFAF62 /* RowConvertible.swift */; }; 56CEB4FB1EAA2F4D00BFAF62 /* FTS3.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56CEB4F81EAA2F4D00BFAF62 /* FTS3.swift */; }; @@ -1000,6 +1016,10 @@ 56C48E731C9A9923005DF1D9 /* module.modulemap */ = {isa = PBXFileReference; lastKnownFileType = "sourcecode.module-map"; path = module.modulemap; sourceTree = ""; }; 56C494401ED7255500CC72AF /* GRDBDeploymentTarget.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; path = GRDBDeploymentTarget.xcconfig; sourceTree = ""; }; 56C494411ED7269800CC72AF /* GRDBDeploymentTarget.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; name = GRDBDeploymentTarget.xcconfig; path = SQLCipher/GRDBDeploymentTarget.xcconfig; sourceTree = ""; }; + 56CC922E201DFFE200CB597E /* DropWhileCursorTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DropWhileCursorTests.swift; sourceTree = ""; }; + 56CC923D201E034200CB597E /* PrefixWhileCursorTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = PrefixWhileCursorTests.swift; sourceTree = ""; }; + 56CC924B201E059100CB597E /* DropFirstCursorTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DropFirstCursorTests.swift; sourceTree = ""; }; + 56CC9256201E094E00CB597E /* PrefixCursorTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = PrefixCursorTests.swift; sourceTree = ""; }; 56CEB4F01EAA2EFA00BFAF62 /* RowConvertible.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RowConvertible.swift; sourceTree = ""; }; 56CEB4F81EAA2F4D00BFAF62 /* FTS3.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FTS3.swift; sourceTree = ""; }; 56CEB4F91EAA2F4D00BFAF62 /* FTS4.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FTS4.swift; sourceTree = ""; }; @@ -1569,11 +1589,15 @@ 5623932F1DEDFC5700A6B01F /* AnyCursorTests.swift */, 5623935F1DEE06D300A6B01F /* CursorTests.swift */, 56DAA2D11DE99DAB006E10C8 /* DatabaseCursorTests.swift */, + 56CC924B201E059100CB597E /* DropFirstCursorTests.swift */, + 56CC922E201DFFE200CB597E /* DropWhileCursorTests.swift */, 5623934D1DEDFEFB00A6B01F /* EnumeratedCursorTests.swift */, 562393561DEE013C00A6B01F /* FilterCursorTests.swift */, 562393681DEE0CD200A6B01F /* FlattenCursorTests.swift */, 562393441DEDFE4500A6B01F /* IteratorCursorTests.swift */, 562393711DEE104400A6B01F /* MapCursorTests.swift */, + 56CC9256201E094E00CB597E /* PrefixCursorTests.swift */, + 56CC923D201E034200CB597E /* PrefixWhileCursorTests.swift */, ); name = Cursor; sourceTree = ""; @@ -2049,6 +2073,7 @@ 56A8C2421D1918EE0096E9D4 /* FoundationUUIDTests.swift in Sources */, 560FC5681CB00B880014AA8E /* SelectStatementTests.swift in Sources */, 5698AC811DA380A20056AF8C /* VirtualTableModuleTests.swift in Sources */, + 56CC923E201E034200CB597E /* PrefixWhileCursorTests.swift in Sources */, 560FC56A1CB00B880014AA8E /* QueryInterfaceExpressionsTests.swift in Sources */, 562393191DECC02000A6B01F /* RowFetchTests.swift in Sources */, 560FC56B1CB00B880014AA8E /* DatabaseCollationTests.swift in Sources */, @@ -2074,8 +2099,10 @@ 560FC5781CB00B880014AA8E /* RowFromStatementTests.swift in Sources */, 560FC5791CB00B880014AA8E /* RecordPrimaryKeyMultipleTests.swift in Sources */, 562393461DEDFE4500A6B01F /* IteratorCursorTests.swift in Sources */, + 56CC9257201E094F00CB597E /* PrefixCursorTests.swift in Sources */, 5698AC971DA4B0430056AF8C /* FTS4RecordTests.swift in Sources */, 5657AB4F1D108BA9006283EF /* FoundationNSNumberTests.swift in Sources */, + 56CC9236201E009700CB597E /* DropWhileCursorTests.swift in Sources */, 56D5075F1F6BAE8600AE1C5B /* PrimaryKeyInfoTests.swift in Sources */, 56176C631EACCCC7000F3F2B /* FTS5TokenizerTests.swift in Sources */, 5623934F1DEDFEFB00A6B01F /* EnumeratedCursorTests.swift in Sources */, @@ -2117,6 +2144,7 @@ 560FC58F1CB00B880014AA8E /* DatabaseReaderTests.swift in Sources */, 560FC5901CB00B880014AA8E /* RecordEditedTests.swift in Sources */, 560FC5911CB00B880014AA8E /* RecordPrimaryKeySingleWithReplaceConflictResolutionTests.swift in Sources */, + 56CC924C201E059100CB597E /* DropFirstCursorTests.swift in Sources */, 562393311DEDFC5700A6B01F /* AnyCursorTests.swift in Sources */, 560FC5921CB00B880014AA8E /* RowConvertibleTests.swift in Sources */, 56A5EF101EF7F20B00F03071 /* ForeignKeyInfoTests.swift in Sources */, @@ -2189,6 +2217,7 @@ 5671562A1CB16729007DC145 /* UpdateStatementTests.swift in Sources */, 5698AC821DA380A20056AF8C /* VirtualTableModuleTests.swift in Sources */, 5657AB481D108BA9006283EF /* FoundationNSNullTests.swift in Sources */, + 56CC923F201E034200CB597E /* PrefixWhileCursorTests.swift in Sources */, 5671562B1CB16729007DC145 /* DatabaseMigratorTests.swift in Sources */, 5623931A1DECC02000A6B01F /* RowFetchTests.swift in Sources */, 5671562E1CB16729007DC145 /* DatabasePoolCollationTests.swift in Sources */, @@ -2214,8 +2243,10 @@ 567156361CB16729007DC145 /* RowFromStatementTests.swift in Sources */, 567156371CB16729007DC145 /* RecordPrimaryKeyMultipleTests.swift in Sources */, 5657AB401D108BA9006283EF /* FoundationNSDataTests.swift in Sources */, + 56CC9258201E094F00CB597E /* PrefixCursorTests.swift in Sources */, 562393471DEDFE4500A6B01F /* IteratorCursorTests.swift in Sources */, 5698AC981DA4B0430056AF8C /* FTS4RecordTests.swift in Sources */, + 56CC9237201E009800CB597E /* DropWhileCursorTests.swift in Sources */, 56D507601F6BAE8600AE1C5B /* PrimaryKeyInfoTests.swift in Sources */, 56176C691EACCCC8000F3F2B /* FTS5TokenizerTests.swift in Sources */, 562393501DEDFEFB00A6B01F /* EnumeratedCursorTests.swift in Sources */, @@ -2257,6 +2288,7 @@ 567156501CB16729007DC145 /* RecordPrimaryKeySingleWithReplaceConflictResolutionTests.swift in Sources */, 567156511CB16729007DC145 /* RowConvertibleTests.swift in Sources */, 56A8C2441D1918EE0096E9D4 /* FoundationUUIDTests.swift in Sources */, + 56CC924D201E059100CB597E /* DropFirstCursorTests.swift in Sources */, 562393321DEDFC5700A6B01F /* AnyCursorTests.swift in Sources */, 567156531CB16729007DC145 /* DatabaseValueConvertibleSubclassTests.swift in Sources */, 56A5EF111EF7F20B00F03071 /* ForeignKeyInfoTests.swift in Sources */, @@ -2426,6 +2458,7 @@ 56AFCA371CB1AA9900F48B96 /* StatementColumnConvertibleFetchTests.swift in Sources */, 56AFCA381CB1AA9900F48B96 /* QueryInterfaceExpressionsTests.swift in Sources */, 56AFCA391CB1AA9900F48B96 /* SelectStatementTests.swift in Sources */, + 56CC9240201E034200CB597E /* PrefixWhileCursorTests.swift in Sources */, 56AFCA3A1CB1AA9900F48B96 /* UpdateStatementTests.swift in Sources */, 56AFCA3B1CB1AA9900F48B96 /* DatabaseMigratorTests.swift in Sources */, 5657AB4B1D108BA9006283EF /* FoundationNSNullTests.swift in Sources */, @@ -2451,8 +2484,10 @@ 56AFCA4A1CB1AA9900F48B96 /* RecordInitializersTests.swift in Sources */, 566AD8CB1D531BED002EC1A8 /* TableDefinitionTests.swift in Sources */, 56AFCA4B1CB1AA9900F48B96 /* MutablePersistableTests.swift in Sources */, + 56CC9259201E094F00CB597E /* PrefixCursorTests.swift in Sources */, 5657AB431D108BA9006283EF /* FoundationNSDataTests.swift in Sources */, 56AFCA4C1CB1AA9900F48B96 /* RowConvertible+QueryInterfaceRequestTests.swift in Sources */, + 56CC9238201E009900CB597E /* DropWhileCursorTests.swift in Sources */, 56D507631F6BAE8600AE1C5B /* PrimaryKeyInfoTests.swift in Sources */, 56176C751EACCCCA000F3F2B /* FTS5TokenizerTests.swift in Sources */, 56AFCA4D1CB1AA9900F48B96 /* DatabasePoolReadOnlyTests.swift in Sources */, @@ -2494,6 +2529,7 @@ 56AFCA5E1CB1AA9900F48B96 /* RowConvertibleTests.swift in Sources */, 56AFCA5F1CB1AA9900F48B96 /* DatabaseValueConvertibleFetchTests.swift in Sources */, 56AFCA601CB1AA9900F48B96 /* RecordPrimaryKeyRowIDTests.swift in Sources */, + 56CC924E201E059100CB597E /* DropFirstCursorTests.swift in Sources */, 56AFCA611CB1AA9900F48B96 /* RecordEditedTests.swift in Sources */, 56AFCA621CB1AA9900F48B96 /* DatabasePoolSchemaCacheTests.swift in Sources */, 56A5EF141EF7F20B00F03071 /* ForeignKeyInfoTests.swift in Sources */, @@ -2566,6 +2602,7 @@ 56AFCA901CB1ABC800F48B96 /* StatementColumnConvertibleFetchTests.swift in Sources */, 5690C33D1D23E7D200E59934 /* FoundationDateTests.swift in Sources */, 5672DE6C1CDB751D0022BA81 /* DatabasePoolBackupTests.swift in Sources */, + 56CC9241201E034200CB597E /* PrefixWhileCursorTests.swift in Sources */, 565F03C71CE5D3AA00DE108F /* RowAdapterTests.swift in Sources */, 56AFCA911CB1ABC800F48B96 /* QueryInterfaceExpressionsTests.swift in Sources */, 56AFCA921CB1ABC800F48B96 /* SelectStatementTests.swift in Sources */, @@ -2591,8 +2628,10 @@ 569C1EB71CF07DDD0042627B /* SchedulingWatchdogTests.swift in Sources */, 56AFCAA01CB1ABC800F48B96 /* RowFromStatementTests.swift in Sources */, 5690C32C1D23E6D800E59934 /* FoundationDateComponentsTests.swift in Sources */, + 56CC925A201E094F00CB597E /* PrefixCursorTests.swift in Sources */, 56AFCAA21CB1ABC800F48B96 /* StatementArgumentsTests.swift in Sources */, 56AFCAA31CB1ABC800F48B96 /* RecordInitializersTests.swift in Sources */, + 56CC9239201E009A00CB597E /* DropWhileCursorTests.swift in Sources */, 56D507641F6BAE8600AE1C5B /* PrimaryKeyInfoTests.swift in Sources */, 56176C7B1EACCCCB000F3F2B /* FTS5TokenizerTests.swift in Sources */, 566AD8CC1D531BEE002EC1A8 /* TableDefinitionTests.swift in Sources */, @@ -2634,6 +2673,7 @@ 5634B10C1CF9B970005360B9 /* TransactionObserverSavepointsTests.swift in Sources */, 56AFCAB51CB1ABC800F48B96 /* DatabaseQueueReadOnlyTests.swift in Sources */, 56AFCAB61CB1ABC800F48B96 /* DatabaseReaderTests.swift in Sources */, + 56CC924F201E059100CB597E /* DropFirstCursorTests.swift in Sources */, 56AFCAB71CB1ABC800F48B96 /* RowConvertibleTests.swift in Sources */, 56B15D0D1CD4C35100A24C8B /* FetchedRecordsControllerTests.swift in Sources */, 56A5EF151EF7F20B00F03071 /* ForeignKeyInfoTests.swift in Sources */, diff --git a/GRDBCustom.xcodeproj/project.pbxproj b/GRDBCustom.xcodeproj/project.pbxproj index 7883bd7fe..8bf6ef2cf 100755 --- a/GRDBCustom.xcodeproj/project.pbxproj +++ b/GRDBCustom.xcodeproj/project.pbxproj @@ -218,6 +218,14 @@ 56BF6D3F1DEF47DA006039A3 /* Fixits-Swift2.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56BF6D2E1DEF47DA006039A3 /* Fixits-Swift2.swift */; }; 56BF6D421DEF47DA006039A3 /* Fixits-Swift2.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56BF6D2E1DEF47DA006039A3 /* Fixits-Swift2.swift */; }; 56C7A6AE1D2DFF6100EFB0C2 /* FoundationNSDateTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56F0B98E1B6001C600A2F135 /* FoundationNSDateTests.swift */; }; + 56CC9234201E009000CB597E /* DropWhileCursorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56CC9231201DFFF600CB597E /* DropWhileCursorTests.swift */; }; + 56CC9235201E009100CB597E /* DropWhileCursorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56CC9231201DFFF600CB597E /* DropWhileCursorTests.swift */; }; + 56CC923B201E033400CB597E /* PrefixWhileCursorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56CC923A201E033400CB597E /* PrefixWhileCursorTests.swift */; }; + 56CC923C201E033400CB597E /* PrefixWhileCursorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56CC923A201E033400CB597E /* PrefixWhileCursorTests.swift */; }; + 56CC9249201E058900CB597E /* DropFirstCursorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56CC9248201E058900CB597E /* DropFirstCursorTests.swift */; }; + 56CC924A201E058900CB597E /* DropFirstCursorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56CC9248201E058900CB597E /* DropFirstCursorTests.swift */; }; + 56CC9254201E094600CB597E /* PrefixCursorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56CC9253201E094600CB597E /* PrefixCursorTests.swift */; }; + 56CC9255201E094600CB597E /* PrefixCursorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56CC9253201E094600CB597E /* PrefixCursorTests.swift */; }; 56CEB4F31EAA2EFA00BFAF62 /* RowConvertible.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56CEB4F01EAA2EFA00BFAF62 /* RowConvertible.swift */; }; 56CEB4F61EAA2EFA00BFAF62 /* RowConvertible.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56CEB4F01EAA2EFA00BFAF62 /* RowConvertible.swift */; }; 56CEB4FC1EAA2F4D00BFAF62 /* FTS3.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56CEB4F81EAA2F4D00BFAF62 /* FTS3.swift */; }; @@ -706,6 +714,10 @@ 56C48E731C9A9923005DF1D9 /* module.modulemap */ = {isa = PBXFileReference; lastKnownFileType = "sourcecode.module-map"; path = module.modulemap; sourceTree = ""; }; 56C494401ED7255500CC72AF /* GRDBDeploymentTarget.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; path = GRDBDeploymentTarget.xcconfig; sourceTree = ""; }; 56C494421ED726C500CC72AF /* GRDBDeploymentTarget.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; name = GRDBDeploymentTarget.xcconfig; path = SQLiteCustom/GRDBDeploymentTarget.xcconfig; sourceTree = ""; }; + 56CC9231201DFFF600CB597E /* DropWhileCursorTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DropWhileCursorTests.swift; sourceTree = ""; }; + 56CC923A201E033400CB597E /* PrefixWhileCursorTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = PrefixWhileCursorTests.swift; sourceTree = ""; }; + 56CC9248201E058900CB597E /* DropFirstCursorTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DropFirstCursorTests.swift; sourceTree = ""; }; + 56CC9253201E094600CB597E /* PrefixCursorTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = PrefixCursorTests.swift; sourceTree = ""; }; 56CEB4F01EAA2EFA00BFAF62 /* RowConvertible.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RowConvertible.swift; sourceTree = ""; }; 56CEB4F81EAA2F4D00BFAF62 /* FTS3.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FTS3.swift; sourceTree = ""; }; 56CEB4F91EAA2F4D00BFAF62 /* FTS4.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FTS4.swift; sourceTree = ""; }; @@ -1257,11 +1269,15 @@ 5623932F1DEDFC5700A6B01F /* AnyCursorTests.swift */, 5623935F1DEE06D300A6B01F /* CursorTests.swift */, 56DAA2D11DE99DAB006E10C8 /* DatabaseCursorTests.swift */, + 56CC9248201E058900CB597E /* DropFirstCursorTests.swift */, + 56CC9231201DFFF600CB597E /* DropWhileCursorTests.swift */, 5623934D1DEDFEFB00A6B01F /* EnumeratedCursorTests.swift */, 562393561DEE013C00A6B01F /* FilterCursorTests.swift */, 562393681DEE0CD200A6B01F /* FlattenCursorTests.swift */, 562393441DEDFE4500A6B01F /* IteratorCursorTests.swift */, 562393711DEE104400A6B01F /* MapCursorTests.swift */, + 56CC9253201E094600CB597E /* PrefixCursorTests.swift */, + 56CC923A201E033400CB597E /* PrefixWhileCursorTests.swift */, ); name = Cursor; sourceTree = ""; @@ -1766,6 +1782,7 @@ F3BA810A1CFB3056003DC1BA /* FoundationNSDateTests.swift in Sources */, 5657AB4D1D108BA9006283EF /* FoundationNSNullTests.swift in Sources */, 5627564A1E963AAC0035B653 /* DatabaseWriterTests.swift in Sources */, + 56CC923C201E033400CB597E /* PrefixWhileCursorTests.swift in Sources */, F3BA80E51CFB3011003DC1BA /* DatabaseFunctionTests.swift in Sources */, F3BA80531CFB2B59003DC1BA /* DataMemoryTests.swift in Sources */, F3BA80511CFB2B59003DC1BA /* DatabaseQueueReleaseMemoryTests.swift in Sources */, @@ -1791,8 +1808,10 @@ F3BA80FD1CFB3024003DC1BA /* TransactionObserverSavepointsTests.swift in Sources */, F3BA811F1CFB3063003DC1BA /* RecordMinimalPrimaryKeySingleTests.swift in Sources */, 5657AB451D108BA9006283EF /* FoundationNSDataTests.swift in Sources */, + 56CC9255201E094600CB597E /* PrefixCursorTests.swift in Sources */, F3BA80EA1CFB3016003DC1BA /* RowFromStatementTests.swift in Sources */, F3BA80AF1CFB2FB1003DC1BA /* DatabaseCollationTests.swift in Sources */, + 56CC9235201E009100CB597E /* DropWhileCursorTests.swift in Sources */, 56D507651F6BAE8600AE1C5B /* PrimaryKeyInfoTests.swift in Sources */, 5657AB651D108BA9006283EF /* FoundationNSURLTests.swift in Sources */, F3BA80F31CFB301D003DC1BA /* StatementColumnConvertibleTests.swift in Sources */, @@ -1834,6 +1853,7 @@ F3BA80D61CFB2FFD003DC1BA /* DatabaseReaderTests.swift in Sources */, 5698AC9D1DA4B0430056AF8C /* FTS4RecordTests.swift in Sources */, 56A4CDB71D4234B200B1A9B9 /* SQLExpressionLiteralTests.swift in Sources */, + 56CC924A201E058900CB597E /* DropFirstCursorTests.swift in Sources */, 56B964D21DA521450002DA19 /* FTS5RecordTests.swift in Sources */, F3BA80F91CFB3021003DC1BA /* UpdateStatementTests.swift in Sources */, 56A5EF161EF7F20B00F03071 /* ForeignKeyInfoTests.swift in Sources */, @@ -2003,6 +2023,7 @@ 566AD8C91D531BEB002EC1A8 /* TableDefinitionTests.swift in Sources */, 56071A501DB54ED300CA6E47 /* FetchedRecordsControllerTests.swift in Sources */, F3BA80AC1CFB2FA6003DC1BA /* DatabaseQueueSchemaCacheTests.swift in Sources */, + 56CC923B201E033400CB597E /* PrefixWhileCursorTests.swift in Sources */, 562756461E963AAC0035B653 /* DatabaseWriterTests.swift in Sources */, 56A8C2461D1918EF0096E9D4 /* FoundationUUIDTests.swift in Sources */, F3BA80F61CFB301E003DC1BA /* StatementColumnConvertibleFetchTests.swift in Sources */, @@ -2028,8 +2049,10 @@ F3BA80EF1CFB3017003DC1BA /* RowFromStatementTests.swift in Sources */, 562393481DEDFE4500A6B01F /* IteratorCursorTests.swift in Sources */, 5657AB511D108BA9006283EF /* FoundationNSNumberTests.swift in Sources */, + 56CC9254201E094600CB597E /* PrefixCursorTests.swift in Sources */, 562393331DEDFC5700A6B01F /* AnyCursorTests.swift in Sources */, 56B964DB1DA5216B0002DA19 /* FTS5RecordTests.swift in Sources */, + 56CC9234201E009000CB597E /* DropWhileCursorTests.swift in Sources */, 56D507611F6BAE8600AE1C5B /* PrimaryKeyInfoTests.swift in Sources */, F3BA80B01CFB2FB2003DC1BA /* DatabaseCollationTests.swift in Sources */, 56C7A6AE1D2DFF6100EFB0C2 /* FoundationNSDateTests.swift in Sources */, @@ -2071,6 +2094,7 @@ F3BA81321CFB3064003DC1BA /* RecordPrimaryKeySingleWithReplaceConflictResolutionTests.swift in Sources */, 5623935A1DEE013C00A6B01F /* FilterCursorTests.swift in Sources */, F3BA80FC1CFB3021003DC1BA /* UpdateStatementTests.swift in Sources */, + 56CC9249201E058900CB597E /* DropFirstCursorTests.swift in Sources */, 5623936C1DEE0CD200A6B01F /* FlattenCursorTests.swift in Sources */, F3BA80E01CFB300F003DC1BA /* DatabaseTimestampTests.swift in Sources */, 56A5EF121EF7F20B00F03071 /* ForeignKeyInfoTests.swift in Sources */, diff --git a/README.md b/README.md index 1f1dc15c4..87a10788c 100644 --- a/README.md +++ b/README.md @@ -662,7 +662,7 @@ Date.fetchCursor(...) // DatabaseValueCursor Player.fetchCursor(...) // RecordCursor ``` -All cursor types adopt the [Cursor](http://groue.github.io/GRDB.swift/docs/2.7/Protocols/Cursor.html) protocol, which looks a lot like standard [lazy sequences](https://developer.apple.com/reference/swift/lazysequenceprotocol) of Swift. As such, cursors come with many methods: `contains`, `enumerated`, `filter`, `first`, `flatMap`, `forEach`, `joined`, `map`, `reduce`: +All cursor types adopt the [Cursor](http://groue.github.io/GRDB.swift/docs/2.7/Protocols/Cursor.html) protocol, which looks a lot like standard [lazy sequences](https://developer.apple.com/reference/swift/lazysequenceprotocol) of Swift. As such, cursors come with many convenience methods: `contains`, `dropFirst`, `dropLast`, `drop(while:)`, `enumerated`, `filter`, `first`, `flatMap`, `forEach`, `joined`, `joined(separator:)`, `max`, `max(by:)`, `min`, `min(by:)`, `map`, `prefix`, `prefix(while:)`, `reduce`, `reduce(into:)`, `suffix`: ```swift // Iterate all Github links @@ -676,6 +676,12 @@ let cursor = URL .fetchCursor(db, "SELECT url FROM links") .filter { url in url.host == "github.com" } let githubURLs = try Array(cursor) // [URL] + +// Turn a cursor into a set: +let cursor = URL + .fetchCursor(db, "SELECT url FROM links") + .flatMap { url in url.host } +let hosts = try Set(cursor) // Set ``` > :point_up: Don't modify the fetched results during a cursor iteration: diff --git a/Tests/GRDBTests/CursorTests.swift b/Tests/GRDBTests/CursorTests.swift index e25dc7187..19c9370e3 100644 --- a/Tests/GRDBTests/CursorTests.swift +++ b/Tests/GRDBTests/CursorTests.swift @@ -28,6 +28,13 @@ class CursorTests: GRDBTestCase { } } + func testDropLast() { + XCTAssertTrue(try IteratorCursor([1, 2, 3, 4, 5]).dropLast(0) == [1, 2, 3, 4, 5]) + XCTAssertTrue(try IteratorCursor([1, 2, 3, 4, 5]).dropLast(2) == [1, 2, 3]) + XCTAssertTrue(try IteratorCursor([1, 2, 3, 4, 5]).dropLast(10) == []) + XCTAssertTrue(try IteratorCursor([1, 2, 3, 4, 5]).dropLast() == [1, 2, 3, 4]) + } + func testContainsIsLazy() { func makeCursor() -> AnyCursor { var i = 0 @@ -103,9 +110,70 @@ class CursorTests: GRDBTestCase { } } + func testJoinedWithSeparator() throws { + do { + let x = try IteratorCursor([String]()).joined() + XCTAssertEqual(x, "") + } + do { + let x = try IteratorCursor([String]()).joined(separator: "><") + XCTAssertEqual(x, "") + } + do { + let x = try IteratorCursor(["foo"]).joined() + XCTAssertEqual(x, "foo") + } + do { + let x = try IteratorCursor(["foo"]).joined(separator: "><") + XCTAssertEqual(x, "foo") + } + do { + let x = try IteratorCursor(["foo", "bar", "baz"]).joined() + XCTAssertEqual(x, "foobarbaz") + } + do { + let x = try IteratorCursor(["foo", "bar", "baz"]).joined(separator: "><") + XCTAssertEqual(x, "foo>), 1) + } + + func testMin() { + XCTAssertEqual(try IteratorCursor([1, 2, 3]).min(), 1) + XCTAssertEqual(try IteratorCursor([1, 2, 3]).min(by: >), 3) + } + func testReduce() throws { let cursor = IteratorCursor([1, 2]) let squareSum = try cursor.reduce(0) { (acc, int) in acc + int * int } XCTAssertEqual(squareSum, 5) } + + func testReduceInto() throws { + let cursor = IteratorCursor([1, 2]) + let squareSum = try cursor.reduce(into: 0) { (acc, int) in acc += int * int } + XCTAssertEqual(squareSum, 5) + } + + func testSuffix() throws { + do { + let cursor = IteratorCursor([1, 2, 3, 4, 5]) + let suffix = try cursor.suffix(0) + XCTAssertTrue(suffix == []) + } + do { + let cursor = IteratorCursor([1, 2, 3, 4, 5]) + let suffix = try cursor.suffix(2) + XCTAssertTrue(suffix == [4, 5]) + } + do { + let cursor = IteratorCursor([1, 2, 3, 4, 5]) + let suffix = try cursor.suffix(10) + XCTAssertTrue(suffix == [1, 2, 3, 4, 5]) + } + } } diff --git a/Tests/GRDBTests/DropFirstCursorTests.swift b/Tests/GRDBTests/DropFirstCursorTests.swift new file mode 100644 index 000000000..889b21c5f --- /dev/null +++ b/Tests/GRDBTests/DropFirstCursorTests.swift @@ -0,0 +1,82 @@ +import XCTest +#if GRDBCIPHER + import GRDBCipher +#elseif GRDBCUSTOMSQLITE + import GRDBCustomSQLite +#else + import GRDB +#endif + +private struct TestError : Error { } + +class DropFirstCursorTests: GRDBTestCase { + + func testDropFirstCursorFromCursor() throws { + do { + let base = IteratorCursor([1, 2, 3, 4, 5]) + let cursor = base.dropFirst(0) + try XCTAssertEqual(cursor.next()!, 1) + try XCTAssertEqual(cursor.next()!, 2) + try XCTAssertEqual(cursor.next()!, 3) + try XCTAssertEqual(cursor.next()!, 4) + try XCTAssertEqual(cursor.next()!, 5) + XCTAssertTrue(try cursor.next() == nil) // end + XCTAssertTrue(try cursor.next() == nil) // past the end + } + do { + let base = IteratorCursor([1, 2, 3, 4, 5]) + let cursor = base.dropFirst(2) + try XCTAssertEqual(cursor.next()!, 3) + try XCTAssertEqual(cursor.next()!, 4) + try XCTAssertEqual(cursor.next()!, 5) + XCTAssertTrue(try cursor.next() == nil) // end + XCTAssertTrue(try cursor.next() == nil) // past the end + } + do { + let base = IteratorCursor([1, 2, 3, 4, 5]) + let cursor = base.dropFirst(10) + XCTAssertTrue(try cursor.next() == nil) // end + XCTAssertTrue(try cursor.next() == nil) // past the end + } + do { + let base = IteratorCursor([1, 2, 3, 4, 5]) + let cursor = base.dropFirst() + try XCTAssertEqual(cursor.next()!, 2) + try XCTAssertEqual(cursor.next()!, 3) + try XCTAssertEqual(cursor.next()!, 4) + try XCTAssertEqual(cursor.next()!, 5) + XCTAssertTrue(try cursor.next() == nil) // end + XCTAssertTrue(try cursor.next() == nil) // past the end + } + } + + func testDropFirstCursorFromThrowingCursor() throws { + var i = 1 + let base: AnyCursor = AnyCursor { + guard i < 3 else { throw TestError() } + defer { i += 1 } + return i + } + + let cursor = base.dropFirst(1) + try XCTAssertEqual(cursor.next()!, 2) + do { + _ = try cursor.next() + XCTFail() + } catch is TestError { + } catch { + XCTFail() + } + } + + func testDropFirstChain() throws { + let base = IteratorCursor([1, 2, 3, 4, 5]) + let cursor = base.dropFirst(1).dropFirst(1) + try XCTAssertEqual(cursor.next()!, 3) + try XCTAssertEqual(cursor.next()!, 4) + try XCTAssertEqual(cursor.next()!, 5) + XCTAssertTrue(try cursor.next() == nil) // end + XCTAssertTrue(try cursor.next() == nil) // past the end + } + +} diff --git a/Tests/GRDBTests/DropWhileCursorTests.swift b/Tests/GRDBTests/DropWhileCursorTests.swift new file mode 100644 index 000000000..63e9b0832 --- /dev/null +++ b/Tests/GRDBTests/DropWhileCursorTests.swift @@ -0,0 +1,70 @@ +import XCTest +#if GRDBCIPHER + import GRDBCipher +#elseif GRDBCUSTOMSQLITE + import GRDBCustomSQLite +#else + import GRDB +#endif + +private struct TestError : Error { } + +class DropWhileCursorTests: GRDBTestCase { + + func testDropWhileCursorFromCursor() throws { + do { + let base = IteratorCursor([1, 2, 3, 1, 5]) + let cursor = base.drop(while: { $0 < 3 }) + try XCTAssertEqual(cursor.next()!, 3) + try XCTAssertEqual(cursor.next()!, 1) + try XCTAssertEqual(cursor.next()!, 5) + XCTAssertTrue(try cursor.next() == nil) // end + XCTAssertTrue(try cursor.next() == nil) // past the end + } + do { + let base = IteratorCursor([1, 2, 3, 1, 5]) + let cursor = base.drop(while: { _ in true }) + XCTAssertTrue(try cursor.next() == nil) // end + XCTAssertTrue(try cursor.next() == nil) // past the end + } + do { + let base = IteratorCursor([1, 2, 3, 1, 5]) + let cursor = base.drop(while: { _ in false }) + try XCTAssertEqual(cursor.next()!, 1) + try XCTAssertEqual(cursor.next()!, 2) + try XCTAssertEqual(cursor.next()!, 3) + try XCTAssertEqual(cursor.next()!, 1) + try XCTAssertEqual(cursor.next()!, 5) + XCTAssertTrue(try cursor.next() == nil) // end + XCTAssertTrue(try cursor.next() == nil) // past the end + } + do { + let base = IteratorCursor([1, 2, 3, 1, 5]) + let cursor = base.drop(while: { _ in throw TestError() }) + _ = try cursor.next() + XCTFail() + } catch is TestError { + } catch { + XCTFail() + } + } + + func testDropWhileCursorFromThrowingCursor() throws { + var i = 0 + let base: AnyCursor = AnyCursor { + guard i < 4 else { throw TestError() } + defer { i += 1 } + return i + } + + let cursor = base.drop(while: { $0 < 3 }) + try XCTAssertEqual(cursor.next()!, 3) + do { + _ = try cursor.next() + XCTFail() + } catch is TestError { + } catch { + XCTFail() + } + } +} diff --git a/Tests/GRDBTests/PrefixCursorTests.swift b/Tests/GRDBTests/PrefixCursorTests.swift new file mode 100644 index 000000000..fdffab97d --- /dev/null +++ b/Tests/GRDBTests/PrefixCursorTests.swift @@ -0,0 +1,69 @@ +import XCTest +#if GRDBCIPHER + import GRDBCipher +#elseif GRDBCUSTOMSQLITE + import GRDBCustomSQLite +#else + import GRDB +#endif + +private struct TestError : Error { } + +class PrefixCursorTests: GRDBTestCase { + + func testPrefixCursorFromCursor() throws { + do { + let base = IteratorCursor([1, 2, 3, 4, 5]) + let cursor = base.prefix(0) + XCTAssertTrue(try cursor.next() == nil) // end + XCTAssertTrue(try cursor.next() == nil) // past the end + } + do { + let base = IteratorCursor([1, 2, 3, 4, 5]) + let cursor = base.prefix(2) + try XCTAssertEqual(cursor.next()!, 1) + try XCTAssertEqual(cursor.next()!, 2) + XCTAssertTrue(try cursor.next() == nil) // end + XCTAssertTrue(try cursor.next() == nil) // past the end + } + do { + let base = IteratorCursor([1, 2, 3, 4, 5]) + let cursor = base.prefix(10) + try XCTAssertEqual(cursor.next()!, 1) + try XCTAssertEqual(cursor.next()!, 2) + try XCTAssertEqual(cursor.next()!, 3) + try XCTAssertEqual(cursor.next()!, 4) + try XCTAssertEqual(cursor.next()!, 5) + XCTAssertTrue(try cursor.next() == nil) // end + XCTAssertTrue(try cursor.next() == nil) // past the end + } + } + + func testPrefixCursorFromThrowingCursor() throws { + var i = 1 + let base: AnyCursor = AnyCursor { + guard i < 3 else { throw TestError() } + defer { i += 1 } + return i + } + + let cursor = base.prefix(3) + try XCTAssertEqual(cursor.next()!, 1) + try XCTAssertEqual(cursor.next()!, 2) + do { + _ = try cursor.next() + XCTFail() + } catch is TestError { + } catch { + XCTFail() + } + } + + func testPrefixCursorChain() throws { + let base = IteratorCursor([1, 2, 3, 4, 5]) + let cursor = base.prefix(2).prefix(1) + try XCTAssertEqual(cursor.next()!, 1) + XCTAssertTrue(try cursor.next() == nil) // end + XCTAssertTrue(try cursor.next() == nil) // past the end + } +} diff --git a/Tests/GRDBTests/PrefixWhileCursorTests.swift b/Tests/GRDBTests/PrefixWhileCursorTests.swift new file mode 100644 index 000000000..9c0228938 --- /dev/null +++ b/Tests/GRDBTests/PrefixWhileCursorTests.swift @@ -0,0 +1,70 @@ +import XCTest +#if GRDBCIPHER + import GRDBCipher +#elseif GRDBCUSTOMSQLITE + import GRDBCustomSQLite +#else + import GRDB +#endif + +private struct TestError : Error { } + +class PrefixWhileCursorTests: GRDBTestCase { + + func testPrefixWhileCursorFromCursor() throws { + do { + let base = IteratorCursor([1, 2, 3, 1, 5]) + let cursor = base.prefix(while: { $0 < 3 }) + try XCTAssertEqual(cursor.next()!, 1) + try XCTAssertEqual(cursor.next()!, 2) + XCTAssertTrue(try cursor.next() == nil) // end + XCTAssertTrue(try cursor.next() == nil) // past the end + } + do { + let base = IteratorCursor([1, 2, 3, 1, 5]) + let cursor = base.prefix(while: { _ in true }) + try XCTAssertEqual(cursor.next()!, 1) + try XCTAssertEqual(cursor.next()!, 2) + try XCTAssertEqual(cursor.next()!, 3) + try XCTAssertEqual(cursor.next()!, 1) + try XCTAssertEqual(cursor.next()!, 5) + XCTAssertTrue(try cursor.next() == nil) // end + XCTAssertTrue(try cursor.next() == nil) // past the end + } + do { + let base = IteratorCursor([1, 2, 3, 1, 5]) + let cursor = base.prefix(while: { _ in false }) + XCTAssertTrue(try cursor.next() == nil) // end + XCTAssertTrue(try cursor.next() == nil) // past the end + } + do { + let base = IteratorCursor([1, 2, 3, 1, 5]) + let cursor = base.prefix(while: { _ in throw TestError() }) + _ = try cursor.next() + XCTFail() + } catch is TestError { + } catch { + XCTFail() + } + } + + func testPrefixWhileCursorFromThrowingCursor() throws { + var i = 1 + let base: AnyCursor = AnyCursor { + guard i < 3 else { throw TestError() } + defer { i += 1 } + return i + } + + let cursor = base.prefix(while: { $0 < 4 }) + try XCTAssertEqual(cursor.next()!, 1) + try XCTAssertEqual(cursor.next()!, 2) + do { + _ = try cursor.next() + XCTFail() + } catch is TestError { + } catch { + XCTFail() + } + } +}