Add ByteBuffer support to BufferedWriter (#2707)

Motivation:

The `BufferedWriter` in `NIOFileSystem` has API in terms
of `some Sequence<UInt8>`, meaning that you need to pass
`byteBuffer.readableBytesView` which is a bit inconvenient.

Modifications:

- Add overloads which allow you to pass `ByteBuffer` directly
- Remove redundant availability guards; they are already applied to the
  type

Result:

- Better API for users
- Resolves #2662
This commit is contained in:
George Barnett authored and GitHub committed 2024-04-26 09:02:57 +01:00
1 parent d3bdffd5e4
commit f2f4ce8be7
2 files changed
+120 -2

No files matched your search

+37 -2
View File
@@ -13,6 +13,7 @@
//===----------------------------------------------------------------------===//
#if os(macOS) || os(iOS) || os(tvOS) || os(watchOS) || os(Linux) || os(Android)
import NIOCore
/// A writer which buffers bytes in memory before writing them to the file system.
///
@@ -94,6 +95,23 @@ public struct BufferedWriter<Handle: WritableFileHandleProtocol> {
return bytesWritten
}
/// Write the contents of the `ByteBuffer` into the buffer.
///
/// If the number of bytes in the buffer exceeds the size of the buffer then they're
/// automatically written to the file system.
///
/// - Remark: The writer reclaims the buffer's memory when it grows to more than twice the
/// configured size.
///
/// To manually flush bytes use ``flush()``.
///
/// - Parameter bytes: The bytes to write to the buffer.
/// - Returns: The number of bytes written into the buffered writer.
@discardableResult
public mutating func write(contentsOf bytes: ByteBuffer) async throws -> Int64 {
try await self.write(contentsOf: bytes.readableBytesView)
}
/// Write the contents of the `AsyncSequence` of byte chunks to the buffer.
///
/// If appending a chunk to the buffer causes it to exceed the capacity of the buffer then the
@@ -107,7 +125,6 @@ public struct BufferedWriter<Handle: WritableFileHandleProtocol> {
/// - Parameter bytes: The `AsyncSequence` of byte chunks to write to the buffer.
/// - Returns: The number of bytes written into the buffered writer.
@discardableResult
@available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *)
public mutating func write<Chunks: AsyncSequence>(
contentsOf chunks: Chunks
) async throws -> Int64 where Chunks.Element: Sequence<UInt8> {
@@ -131,6 +148,25 @@ public struct BufferedWriter<Handle: WritableFileHandleProtocol> {
return bytesWritten
}
/// Write the contents of the `AsyncSequence` of `ByteBuffer`s into the buffer.
///
/// If appending a chunk to the buffer causes it to exceed the capacity of the buffer then the
/// contents of the buffer are automatically written to the file system.
///
/// - Remark: The writer reclaims the buffer's memory when it grows to more than twice the
/// configured size.
///
/// To manually flush bytes use ``flush()``.
///
/// - Parameter bytes: The `AsyncSequence` of `ByteBuffer`s to write.
/// - Returns: The number of bytes written into the buffered writer.
@discardableResult
public mutating func write<Chunks: AsyncSequence>(
contentsOf chunks: Chunks
) async throws -> Int64 where Chunks.Element == ByteBuffer {
try await self.write(contentsOf: chunks.map { $0.readableBytesView })
}
/// Write the contents of the `AsyncSequence` of bytes the buffer.
///
/// If appending a byte to the buffer causes it to exceed the capacity of the buffer then the
@@ -143,7 +179,6 @@ public struct BufferedWriter<Handle: WritableFileHandleProtocol> {
///
/// - Parameter bytes: The `AsyncSequence` of bytes to write to the buffer.
@discardableResult
@available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *)
public mutating func write<Bytes: AsyncSequence>(
contentsOf bytes: Bytes
) async throws -> Int64 where Bytes.Element == UInt8 {
@@ -59,6 +59,89 @@ final class BufferedWriterTests: XCTestCase {
}
}
func testBufferedWriterByteBuffer() async throws {
let fs = FileSystem.shared
let path = try await fs.temporaryFilePath()
try await fs.withFileHandle(
forReadingAndWritingAt: path,
options: .newFile(replaceExisting: false)
) { file in
let bufferSize = 8192
var writer = file.bufferedWriter(capacity: .bytes(Int64(bufferSize)))
XCTAssertEqual(writer.bufferedBytes, 0)
// Write a full buffers worth of bytes, should be flushed immediately.
try await writer.write(contentsOf: ByteBuffer(repeating: 0, count: bufferSize))
XCTAssertEqual(writer.bufferedBytes, 0)
// Write just under a buffer.
try await writer.write(contentsOf: ByteBuffer(repeating: 1, count: bufferSize - 1))
XCTAssertEqual(writer.bufferedBytes, bufferSize - 1)
// Try to read the as-yet-unwritten bytes.
let emptyChunk = try await file.readChunk(
fromAbsoluteOffset: Int64(bufferSize),
length: .bytes(Int64(bufferSize - 1))
)
XCTAssertEqual(emptyChunk.readableBytes, 0)
// Write one more byte to flush out the buffer.
try await writer.write(contentsOf: ByteBuffer(repeating: 1, count: 1))
XCTAssertEqual(writer.bufferedBytes, 0)
// Try to read now that the bytes have been finished.
let chunk = try await file.readChunk(
fromAbsoluteOffset: Int64(bufferSize),
length: .bytes(Int64(bufferSize))
)
XCTAssertEqual(chunk, ByteBuffer(repeating: 1, count: bufferSize))
}
}
func testBufferedWriterAsyncSequenceOfByteBuffer() async throws {
let fs = FileSystem.shared
let path = try await fs.temporaryFilePath()
let buffers = AsyncStream<ByteBuffer> { continuation in
continuation.yield(ByteBuffer(repeating: 0, count: 1024))
continuation.yield(ByteBuffer(repeating: 1, count: 1024))
continuation.yield(ByteBuffer(repeating: 2, count: 1024))
continuation.finish()
}
try await fs.withFileHandle(
forReadingAndWritingAt: path,
options: .newFile(replaceExisting: false)
) { file in
let bufferSize = 8192
var writer = file.bufferedWriter(capacity: .bytes(Int64(bufferSize)))
XCTAssertEqual(writer.bufferedBytes, 0)
// Write the buffers.
try await writer.write(contentsOf: buffers)
XCTAssertEqual(writer.bufferedBytes, 1024 * 3)
// Try to read the as-yet-unwritten bytes.
let emptyChunk = try await file.readChunk(
fromAbsoluteOffset: 0,
length: .bytes(Int64(1024 * 3))
)
XCTAssertEqual(emptyChunk.readableBytes, 0)
// Flush the buffer.
try await writer.flush()
// Try to read now that the bytes have been finished.
var chunk = try await file.readChunk(fromAbsoluteOffset: 0, length: .bytes(1024 * 3))
XCTAssertEqual(chunk.readableBytes, 1024 * 3)
XCTAssertEqual(chunk.readSlice(length: 1024), ByteBuffer(repeating: 0, count: 1024))
XCTAssertEqual(chunk.readSlice(length: 1024), ByteBuffer(repeating: 1, count: 1024))
XCTAssertEqual(chunk.readSlice(length: 1024), ByteBuffer(repeating: 2, count: 1024))
XCTAssertEqual(chunk.readableBytes, 0)
}
}
func testBufferedWriterAsyncSequenceOfBytes() async throws {
let fs = FileSystem.shared
let path = try await fs.temporaryFilePath()