diff --git a/Guides/BufferedBytes.md b/Guides/BufferedBytes.md new file mode 100644 index 0000000..166fc51 --- /dev/null +++ b/Guides/BufferedBytes.md @@ -0,0 +1,54 @@ +# AsyncBufferedByteIterator + +[[Source](https://github.com/apple/swift-async-algorithms/blob/main/Sources/AsyncAlgorithms/AsyncBufferedByteIterator.swift) | +[Tests](https://github.com/apple/swift-async-algorithms/blob/main/Tests/AsyncAlgorithmsTests/TestBufferedByteIterator.swift)] + +Provides a highly efficient iterator useful for iterating byte sequences derived from asynchronous read functions. + +This type provides infrastructure for creating `AsyncSequence` types with an `Element` of `UInt8` backed by file descriptors or similar read sources. + +```swift +struct AsyncBytes: AsyncSequence { + public typealias Element = UInt8 + var handle: ReadableThing + + internal init(_ readable: ReadableThing) { + handle = readable + } + + public func makeAsyncIterator() -> AsyncBufferedByteIterator { + return BufferedAsyncByteIterator(capacity: 16384) { buffer in + // This runs once every 16384 invocations of next() + return try await handle.read(into: buffer) + } + } +} +``` + +## Detailed Design + +```swift +public struct AsyncBufferedByteIterator: AsyncIteratorProtocol, Sendable { + public typealias Element = UInt8 + + public init( + capacity: Int, + readFunction: @Sendable @escaping (UnsafeMutableRawBufferPointer) async throws -> Int + ) + + public mutating func next() async throws -> UInt8? +} +``` + +For each invocation of `next` the iterator will check if a buffer has been filled. If the buffer is filled with some amount of bytes a fast path is taken to directly return a byte out of that buffer. If the buffer is not filled then the read function is invoked to acquire the next filled buffer and then it takes a byte out of that buffer. + +If the read function returns 0 indicating it read no more bytes the iterator is claimed to be finished and no additional invocations to the read function are made. + +If the read function throws the error will be thrown by the iteration. Subsequent invocations to the iterator will return nil without invoking the read function. + +During the iteration if the task is cancelled the iteration will check the cancellation only in passes where the read function is invoked and will throw a `CancellationError`. + +### Naming + +This type was named precisely for what it does: it is an asynchronous iterator that buffers bytes. + diff --git a/README.md b/README.md index 5fdd214..8cb8f51 100644 --- a/README.md +++ b/README.md @@ -15,6 +15,10 @@ - [`async`](https://github.com/apple/swift-async-algorithms/blob/main/Guides/Lazy.md): Create an asynchronous sequence composed from a synchronous sequence. +#### Performance optimized asynchronous iterators + +- [`AsyncBufferedByteIterator`](https://github.com/apple/swift-async-algorithms/blob/main/Guides/BufferedBytes.md): A highly efficient iterator useful for iterating byte sequences derived from asynchronous read functions. + #### Other useful asynchronous sequences - [`joined(separator:)`](https://github.com/apple/swift-async-algorithms/blob/main/Guides/): Concatenated elements of an asynchronous sequence of asynchronous sequences, inserting the given separator between each element. - [`compacted()`](https://github.com/apple/swift-async-algorithms/blob/main/Guides/): Remove nil values from an asynchronous sequence. diff --git a/Sources/AsyncAlgorithms/AsyncBufferedByteIterator.swift b/Sources/AsyncAlgorithms/AsyncBufferedByteIterator.swift new file mode 100644 index 0000000..a16d4a7 --- /dev/null +++ b/Sources/AsyncAlgorithms/AsyncBufferedByteIterator.swift @@ -0,0 +1,138 @@ +//===----------------------------------------------------------------------===// +// +// 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 +// +//===----------------------------------------------------------------------===// + +/// AsyncBufferedByteIterator provides a convenient high-performance implementation +/// of a common architecture for AsyncSequences of UInt8s (i.e. byte streams). +/// +/// Bytes are read into an internal buffer of `capacity` bytes via the +/// `readFunction`. Invoking next returns bytes from the internal buffer until it's +/// empty, and then suspends and awaits another invocation of `readFunction` to +/// refill. If `readFunction` returns 0 (indicating nothing was read), next() will +/// return nil from then on. Cancellation is checked before each invocation of +/// `readFunction`, which means that many calls to `next()` will not check for +/// cancellation. +/// +/// A typical use of `AsyncBufferedByteIterator` looks something like this: +/// +/// struct AsyncBytes: AsyncSequence { +/// public typealias Element = UInt8 +/// var handle: ReadableThing +/// +/// internal init(_ readable: ReadableThing) { +/// handle = readable +/// } +/// +/// public func makeAsyncIterator() -> AsyncBufferedByteIterator { +/// return BufferedAsyncByteIterator(capacity: 16384) { buffer in +/// // This runs once every 16384 invocations of next() +/// return try await handle.read(into: buffer) +/// } +/// } +/// } +/// +/// +public struct AsyncBufferedByteIterator: AsyncIteratorProtocol, Sendable { + public typealias Element = UInt8 + @usableFromInline var buffer: _AsyncBytesBuffer + + /// Creates an asynchronous buffered byte iterator with a specified capacity and read function. + /// + /// - Parameters: + /// - capacity: The maximum number of bytes that a single invocation of `readFunction` may produce. + /// This is the allocated capacity of the backing buffer for iteration; the value must be greater than 0. + /// - readFunction: The function for refilling the buffer. + public init( + capacity: Int, + readFunction: @Sendable @escaping (UnsafeMutableRawBufferPointer) async throws -> Int + ) { + buffer = _AsyncBytesBuffer(capacity: capacity, readFunction: readFunction) + } + + /// Reads a byte out of the buffer if available. When no bytes are available this will trigger a + /// the read function to reload the buffer and then return the next byte from that buffer. + @inlinable @inline(__always) + public mutating func next() async throws -> UInt8? { + return try await buffer.next() + } +} + +@frozen @usableFromInline +internal struct _AsyncBytesBuffer: @unchecked Sendable { + @usableFromInline + final class Storage { + fileprivate let readFunction: @Sendable (UnsafeMutableRawBufferPointer) async throws -> Int + fileprivate let buffer: UnsafeMutableRawBufferPointer + fileprivate var finished = false + + init( + capacity: Int, + readFunction: @Sendable @escaping (UnsafeMutableRawBufferPointer) async throws -> Int + ) { + precondition(capacity > 0) + self.readFunction = readFunction + buffer = UnsafeMutableRawBufferPointer.allocate( + byteCount: capacity, + alignment: MemoryLayout.alignment + ) + } + + deinit { + buffer.deallocate() + } + } + + @usableFromInline internal var storage: Storage + @usableFromInline internal var nextPointer: UnsafeRawPointer + @usableFromInline internal var endPointer: UnsafeRawPointer + + @usableFromInline init( + capacity: Int, + readFunction: @Sendable @escaping (UnsafeMutableRawBufferPointer) async throws -> Int + ) { + let s = Storage(capacity: capacity, readFunction: readFunction) + storage = s + nextPointer = UnsafeRawPointer(s.buffer.baseAddress!) + endPointer = nextPointer + } + + @inline(never) @usableFromInline + internal mutating func reloadBufferAndNext() async throws -> UInt8? { + if storage.finished { + return nil + } + try Task.checkCancellation() + do { + let readSize: Int = try await storage.readFunction(storage.buffer) + if readSize == 0 { + storage.finished = true + nextPointer = endPointer + return nil + } + nextPointer = UnsafeRawPointer(storage.buffer.baseAddress!) + endPointer = nextPointer + readSize + } catch { + storage.finished = true + nextPointer = endPointer + throw error + } + return try await next() + } + + @inlinable @inline(__always) + internal mutating func next() async throws -> UInt8? { + if _fastPath(nextPointer != endPointer) { + let byte = nextPointer.load(fromByteOffset: 0, as: UInt8.self) + nextPointer = nextPointer + 1 + return byte + } + return try await reloadBufferAndNext() + } +} diff --git a/Tests/AsyncAlgorithmsTests/TestBufferedByteIterator.swift b/Tests/AsyncAlgorithmsTests/TestBufferedByteIterator.swift new file mode 100644 index 0000000..ee6c5d1 --- /dev/null +++ b/Tests/AsyncAlgorithmsTests/TestBufferedByteIterator.swift @@ -0,0 +1,208 @@ +//===----------------------------------------------------------------------===// +// +// 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 TestBufferedByteIterator: XCTestCase { + actor Isolated { + var value: T + + init(_ value: T) { + self.value = value + } + + func update(_ value: T) async { + self.value = value + } + } + + func test_immediately_empty() async throws { + let reloaded = Isolated(false) + var iterator = AsyncBufferedByteIterator(capacity: 3) { buffer in + XCTAssertEqual(buffer.count, 3) + await reloaded.update(true) + return 0 + } + var wasReloaded = await reloaded.value + XCTAssertFalse(wasReloaded) + let byte = try await iterator.next() + XCTAssertNil(byte) + wasReloaded = await reloaded.value + XCTAssertTrue(wasReloaded) + } + + func test_one_pass() async throws { + let reloaded = Isolated(0) + var iterator = AsyncBufferedByteIterator(capacity: 3) { buffer in + XCTAssertEqual(buffer.count, 3) + let count = await reloaded.value + await reloaded.update(count + 1) + if count >= 1 { + return 0 + } + buffer.copyBytes(from: [1, 2, 3]) + return 3 + } + + var reloadCount = await reloaded.value + XCTAssertEqual(reloadCount, 0) + var byte = try await iterator.next() + XCTAssertEqual(byte, 1) + reloadCount = await reloaded.value + XCTAssertEqual(reloadCount, 1) + byte = try await iterator.next() + XCTAssertEqual(byte, 2) + reloadCount = await reloaded.value + XCTAssertEqual(reloadCount, 1) + byte = try await iterator.next() + XCTAssertEqual(byte, 3) + reloadCount = await reloaded.value + XCTAssertEqual(reloadCount, 1) + byte = try await iterator.next() + XCTAssertNil(byte) + reloadCount = await reloaded.value + XCTAssertEqual(reloadCount, 2) + byte = try await iterator.next() + XCTAssertNil(byte) + reloadCount = await reloaded.value + XCTAssertEqual(reloadCount, 2) + } + + func test_three_pass() async throws { + let reloaded = Isolated(0) + var iterator = AsyncBufferedByteIterator(capacity: 3) { buffer in + XCTAssertEqual(buffer.count, 3) + let count = await reloaded.value + await reloaded.update(count + 1) + if count >= 3 { + return 0 + } + buffer.copyBytes(from: [1, 2, 3]) + return 3 + } + + var reloadCount = await reloaded.value + XCTAssertEqual(reloadCount, 0) + + for n in 1...3 { + var byte = try await iterator.next() + XCTAssertEqual(byte, 1) + reloadCount = await reloaded.value + XCTAssertEqual(reloadCount, n) + byte = try await iterator.next() + XCTAssertEqual(byte, 2) + reloadCount = await reloaded.value + XCTAssertEqual(reloadCount, n) + byte = try await iterator.next() + XCTAssertEqual(byte, 3) + reloadCount = await reloaded.value + XCTAssertEqual(reloadCount, n) + } + + + var byte = try await iterator.next() + XCTAssertNil(byte) + reloadCount = await reloaded.value + XCTAssertEqual(reloadCount, 4) + byte = try await iterator.next() + XCTAssertNil(byte) + reloadCount = await reloaded.value + XCTAssertEqual(reloadCount, 4) + } + + func test_three_pass_throwing() async throws { + let reloaded = Isolated(0) + var iterator = AsyncBufferedByteIterator(capacity: 3) { buffer in + XCTAssertEqual(buffer.count, 3) + let count = await reloaded.value + await reloaded.update(count + 1) + if count >= 3 { + return 0 + } + if count == 2 { + throw Failure() + } + buffer.copyBytes(from: [1, 2, 3]) + return 3 + } + + var reloadCount = await reloaded.value + XCTAssertEqual(reloadCount, 0) + + for n in 1...3 { + do { + var byte = try await iterator.next() + XCTAssertEqual(byte, 1) + reloadCount = await reloaded.value + XCTAssertEqual(reloadCount, n) + byte = try await iterator.next() + XCTAssertEqual(byte, 2) + reloadCount = await reloaded.value + XCTAssertEqual(reloadCount, n) + byte = try await iterator.next() + XCTAssertEqual(byte, 3) + reloadCount = await reloaded.value + XCTAssertEqual(reloadCount, n) + } catch { + XCTAssertEqual(n, 3) + break + } + + } + + + var byte = try await iterator.next() + XCTAssertNil(byte) + reloadCount = await reloaded.value + XCTAssertEqual(reloadCount, 3) + byte = try await iterator.next() + XCTAssertNil(byte) + reloadCount = await reloaded.value + XCTAssertEqual(reloadCount, 3) + } + + func test_cancellation() async { + struct RepeatingBytes: AsyncSequence { + typealias Element = UInt8 + + func makeAsyncIterator() -> AsyncBufferedByteIterator { + AsyncBufferedByteIterator(capacity: 3) { buffer in + buffer.copyBytes(from: [1, 2, 3]) + return 3 + } + } + } + let finished = expectation(description: "finished") + let iterated = expectation(description: "iterated") + let task = Task { + var firstIteration = false + do { + for try await _ in RepeatingBytes() { + if !firstIteration { + iterated.fulfill() + firstIteration = true + } + } + XCTFail("expected to throw a cancellation error") + } catch { + if error is CancellationError { + finished.fulfill() + } + } + } + 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) + } +}