//===----------------------------------------------------------------------===// // // This source file is part of the SwiftNIO open source project // // Copyright (c) 2017-2018 Apple Inc. and the SwiftNIO project authors // Licensed under Apache License v2.0 // // See LICENSE.txt for license information // See CONTRIBUTORS.txt for the list of SwiftNIO project authors // // SPDX-License-Identifier: Apache-2.0 // //===----------------------------------------------------------------------===// import XCTest @testable import NIO class FileRegionTest : XCTestCase { private func temporaryFilePath() -> String { let fileManager = FileManager.default let filePath: String #if os(Linux) filePath = "/tmp/\(UUID().uuidString)" #else if #available(OSX 10.12, *) { filePath = "\(fileManager.temporaryDirectory.path)/\(UUID().uuidString)" } else { filePath = "/tmp/\(UUID().uuidString)" } #endif return filePath } func testWriteFileRegion() throws { let group = MultiThreadedEventLoopGroup(numThreads: 1) defer { try! group.syncShutdownGracefully() } let numBytes = 16 * 1024 var content = "" for i in 0..] = [] for _ in 0..<10 { futures.append(try clientChannel.write(data: NIOAny(FileRegion(file: filePath, readerIndex: 0, endIndex: 0)))) } try clientChannel.writeAndFlush(data: NIOAny(FileRegion(file: filePath, readerIndex: 0, endIndex: 0))).wait() try futures.forEach { try $0.wait() } } private final class ByteCountingHandler : ChannelInboundHandler { typealias InboundIn = ByteBuffer private let numBytes: Int private let promise: EventLoopPromise private var buffer: ByteBuffer! init(numBytes: Int, promise: EventLoopPromise) { self.numBytes = numBytes self.promise = promise } func handlerAdded(ctx: ChannelHandlerContext) { buffer = ctx.channel!.allocator.buffer(capacity: numBytes) if self.numBytes == 0 { self.promise.succeed(result: buffer) } } func channelRead(ctx: ChannelHandlerContext, data: NIOAny) { var currentBuffer = self.unwrapInboundIn(data) buffer.write(buffer: ¤tBuffer) if buffer.readableBytes == numBytes { promise.succeed(result: buffer) } } func assertReceived(buffer: ByteBuffer) throws { let received = try promise.futureResult.wait() XCTAssertEqual(buffer, received) } } func testOutstandingFileRegionsWork() throws { let group = MultiThreadedEventLoopGroup(numThreads: 1) defer { try! group.syncShutdownGracefully() } let numBytes = 16 * 1024 var content = "" for i in 0..