From 361c7926d1369df159b636f7063e89bf655fc6ea Mon Sep 17 00:00:00 2001 From: Philippe Hausler Date: Tue, 11 Jan 2022 10:26:32 -0800 Subject: [PATCH] Add a package layout and initial implementation and tests for AsyncLazySequence (#2) * Add a package layout and initial implementation and tests for AsyncLazySequence; a type for converting non asynchronous sequences into asynchronous ones * Add a first iteration pass expectation to ensure that tasks spawn for testing cancellation of AsyncLazySequence * Simplify the iterator for AsyncLazySequence --- .gitignore | 9 ++ Package.swift | 27 ++++ .../AsyncAlgorithms/AsyncLazySequence.swift | 67 ++++++++++ Tests/AsyncAlgorithmsTests/Indefinite.swift | 22 ++++ .../ReportingSequence.swift | 78 +++++++++++ Tests/AsyncAlgorithmsTests/TestLazy.swift | 124 ++++++++++++++++++ 6 files changed, 327 insertions(+) create mode 100644 .gitignore create mode 100644 Package.swift create mode 100644 Sources/AsyncAlgorithms/AsyncLazySequence.swift create mode 100644 Tests/AsyncAlgorithmsTests/Indefinite.swift create mode 100644 Tests/AsyncAlgorithmsTests/ReportingSequence.swift create mode 100644 Tests/AsyncAlgorithmsTests/TestLazy.swift diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..3fd927b --- /dev/null +++ b/.gitignore @@ -0,0 +1,9 @@ +.DS_Store +/.build +/Packages +/*.xcodeproj +xcuserdata/ +DerivedData/ +.swiftpm/config/registries.json +.swiftpm/xcode/package.xcworkspace/contents.xcworkspacedata +.netrc \ No newline at end of file diff --git a/Package.swift b/Package.swift new file mode 100644 index 0000000..194ab8f --- /dev/null +++ b/Package.swift @@ -0,0 +1,27 @@ +// swift-tools-version: 5.6 + +import PackageDescription + +let package = Package( + name: "AsyncAlgorithms", + platforms: [ + .macOS("10.15"), + .iOS("13.0"), + .tvOS("13.0"), + .watchOS("6.0") + ], + products: [ + .library( + name: "AsyncAlgorithms", + targets: ["AsyncAlgorithms"]), + ], + dependencies: [], + targets: [ + .target( + name: "AsyncAlgorithms", + dependencies: []), + .testTarget( + name: "AsyncAlgorithmsTests", + dependencies: ["AsyncAlgorithms"]), + ] +) \ No newline at end of file diff --git a/Sources/AsyncAlgorithms/AsyncLazySequence.swift b/Sources/AsyncAlgorithms/AsyncLazySequence.swift new file mode 100644 index 0000000..2e9ba8f --- /dev/null +++ b/Sources/AsyncAlgorithms/AsyncLazySequence.swift @@ -0,0 +1,67 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the Swift Async Algorithms open source project +// +// Copyright (c) 2022 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 +// +//===----------------------------------------------------------------------===// + +extension Sequence { + @inlinable + public var async: AsyncLazySequence { + AsyncLazySequence(self) + } +} + +@frozen +public struct AsyncLazySequence: AsyncSequence { + public typealias Element = Base.Element + + @frozen + public struct Iterator: AsyncIteratorProtocol { + @usableFromInline + var iterator: Base.Iterator? + + @usableFromInline + init(_ iterator: Base.Iterator) { + self.iterator = iterator + } + + @inlinable + public mutating func next() async -> Base.Element? { + if !Task.isCancelled, let value = iterator?.next() { + return value + } else { + iterator = nil + return nil + } + } + } + + @usableFromInline + let base: Base + + @usableFromInline + init(_ base: Base) { + self.base = base + } + + @inlinable + public func makeAsyncIterator() -> Iterator { + Iterator(base.makeIterator()) + } +} + +extension AsyncLazySequence: Sendable where Base: Sendable { } +extension AsyncLazySequence.Iterator: Sendable where Base.Iterator: Sendable { } + +extension AsyncLazySequence: Codable where Base: Codable { } + +extension AsyncLazySequence: Equatable where Base: Equatable { } + +extension AsyncLazySequence: Hashable where Base: Hashable { } + + diff --git a/Tests/AsyncAlgorithmsTests/Indefinite.swift b/Tests/AsyncAlgorithmsTests/Indefinite.swift new file mode 100644 index 0000000..62beec7 --- /dev/null +++ b/Tests/AsyncAlgorithmsTests/Indefinite.swift @@ -0,0 +1,22 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the Swift Async Algorithms open source project +// +// Copyright (c) 2022 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 +// +//===----------------------------------------------------------------------===// + +struct Indefinite: Sequence, IteratorProtocol, Sendable { + let value: Element + + func next() -> Element? { + return value + } + + func makeIterator() -> Indefinite { + self + } +} diff --git a/Tests/AsyncAlgorithmsTests/ReportingSequence.swift b/Tests/AsyncAlgorithmsTests/ReportingSequence.swift new file mode 100644 index 0000000..a03e6f8 --- /dev/null +++ b/Tests/AsyncAlgorithmsTests/ReportingSequence.swift @@ -0,0 +1,78 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the Swift Async Algorithms open source project +// +// Copyright (c) 2022 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 +// +//===----------------------------------------------------------------------===// + +final class ReportingSequence: Sequence, IteratorProtocol { + enum Event: Equatable, CustomStringConvertible { + case next + case makeIterator + + var description: String { + switch self { + case .next: return "next()" + case .makeIterator: return "makeIterator()" + } + } + } + + var events = [Event]() + var elements: [Element] + + init(_ elements: [Element]) { + self.elements = elements + } + + func next() -> Element? { + events.append(.next) + guard elements.count > 0 else { + return nil + } + return elements.removeFirst() + } + + func makeIterator() -> ReportingSequence { + events.append(.makeIterator) + return self + } +} + +final class ReportingAsyncSequence: AsyncSequence, AsyncIteratorProtocol { + enum Event: Equatable, CustomStringConvertible { + case next + case makeAsyncIterator + + var description: String { + switch self { + case .next: return "next()" + case .makeAsyncIterator: return "makeAsyncIterator()" + } + } + } + + var events = [Event]() + var elements: [Element] + + init(_ elements: [Element]) { + self.elements = elements + } + + func next() async -> Element? { + events.append(.next) + guard elements.count > 0 else { + return nil + } + return elements.removeFirst() + } + + func makeAsyncIterator() -> ReportingAsyncSequence { + events.append(.makeAsyncIterator) + return self + } +} diff --git a/Tests/AsyncAlgorithmsTests/TestLazy.swift b/Tests/AsyncAlgorithmsTests/TestLazy.swift new file mode 100644 index 0000000..d3181c1 --- /dev/null +++ b/Tests/AsyncAlgorithmsTests/TestLazy.swift @@ -0,0 +1,124 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the Swift Async Algorithms open source project +// +// Copyright (c) 2022 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 +// +//===----------------------------------------------------------------------===// + +import XCTest +import AsyncAlgorithms + +final class TestLazy: XCTestCase { + func test_array() async { + let source = [1, 2, 3, 4] + let expected = source + let sequence = source.async + + var actual = [Int]() + for await item in sequence { + actual.append(item) + } + + XCTAssertEqual(expected, actual) + } + + func test_set() async { + let source: Set = [1, 2, 3, 4] + let expected = source + let sequence = source.async + + var actual = Set() + for await item in sequence { + actual.insert(item) + } + + XCTAssertEqual(expected, actual) + } + + func test_empty() async { + let source = EmptyCollection() + let expected = [Int]() + let sequence = source.async + + var actual = [Int]() + for await item in sequence { + actual.append(item) + } + + XCTAssertEqual(expected, actual) + } + + func test_iteration() async { + let source = ReportingSequence([1, 2, 3]) + let sequence = source.async + XCTAssertEqual(source.events, []) + var collected = [Int]() + for await item in sequence { + collected.append(item) + } + XCTAssertEqual(collected, [1, 2, 3]) + XCTAssertEqual(source.events, [ + .makeIterator, + .next, + .next, + .next, + .next + ]) + } + + func test_manual_iteration() async { + let source = ReportingSequence([1, 2, 3]) + let sequence = source.async + XCTAssertEqual(source.events, []) + var collected = [Int]() + var iterator = sequence.makeAsyncIterator() + while let item = await iterator.next() { + collected.append(item) + } + XCTAssertEqual(collected, [1, 2, 3]) + XCTAssertEqual(source.events, [ + .makeIterator, + .next, + .next, + .next, + .next + ]) + let pastEnd = await iterator.next() + XCTAssertEqual(pastEnd, nil) + // ensure that iterating past the end does not invoke next again + XCTAssertEqual(source.events, [ + .makeIterator, + .next, + .next, + .next, + .next + ]) + } + + func test_cancellation() async { + let source = Indefinite(value: "test") + let sequence = source.async + let finished = expectation(description: "finished") + let iterated = expectation(description: "iterated") + let task = Task { + var firstIteration = false + for await _ in sequence { + if !firstIteration { + firstIteration = true + iterated.fulfill() + } + } + finished.fulfill() + } + // ensure the other task actually starts + wait(for: [iterated], timeout: 1.0) + // cancellation should ensure the loop finishes + // without regards to the remaining underlying sequence + task.cancel() + wait(for: [finished], timeout: 1.0) + } +}