Repository: apple/swift-nio
File: Sources/NIOPosix/PendingWritesManager.swift (Swift)

Code before:
                return try triggerVectorBufferWrite({ try vectorBufferWriteOperation($0) })
            case .scalarFileWrite:
                return try triggerScalarFileWrite({ try scalarFileWriteOperation($0, $1, $2) })
            case .nothingToBeWritten:
                assertionFailure("called \(#function) with nothing available to be written")
                return .writtenCompletely
            }
        }

        // If we have no more writes check if we have a pending close
        if self.isEmpty {
            switch result.writeResult {
            case .writtenCompletely:
                switch self.outboundCloseState {
                case .open:
                    ()
                case .pending(let closePromise):
                    self.outboundCloseState = .readyForClose(closePromise)
                case .readyForClose:
                    assertionFailure("Transitioned from readyForClose to readyForClose, shouldn't we have closed?")
                case .closed:
                    ()
                }

            case .couldNotWriteEverything:
                assertionFailure("Write result is .couldNotWriteEverything but we have no more writes to perform.")
            }
            result.writeResult = .writtenCompletely(.init(self.outboundCloseState))
        }
        return result
    }

    /// To be called after a write operation (usually selected and run by `triggerAppropriateWriteOperation`) has
    /// completed.
    ///
    /// - Parameters:
    ///   - itemCount: The number of items we tried to write.
    ///   - result: The result of the write operation.
    private func didWrite(itemCount: Int, result: IOResult<Int>) -> OneWriteOperationResult {
        let (promise, result) = self.state.didWrite(itemCount: itemCount, result: result)

        if self.state.bytes < waterMark.low {
            channelWritabilityFlag.store(true, ordering: .relaxed)
        }

        promise?.succeed(())
        return result
    }

    /// Trigger a write of a single `ByteBuffer` (usually using `write(2)`).
    ///

Review comment (bug):
If this is going to be an assertion failure we should have some fallback logic. Probably that should be throwing an error.

Code after:
            // Returns false to signal the Channel became non-writable and we need to notify the user.
            self.publishedWritability = false
            return false
        }
        return true
    }

    /// Returns the best mechanism to write pending data at the current point in time.
    var currentBestWriteMechanism: WriteMechanism {
        self.state.currentBestWriteMechanism
    }

    /// Triggers the appropriate write operation. This is a fancy way of saying trigger either `write`, `writev` or
    /// `sendfile`.
    ///
    /// - Parameters:
    ///   - scalarBufferWriteOperation: An operation that writes a single, contiguous array of bytes (usually `write`).
    ///   - vectorBufferWriteOperation: An operation that writes multiple contiguous arrays of bytes (usually `writev`).
    ///   - scalarFileWriteOperation: An operation that writes a region of a file descriptor (usually `sendfile`).
    /// - Returns: The `OneWriteOperationResult` and whether the `Channel` is now writable.
    func triggerAppropriateWriteOperations(
        scalarBufferWriteOperation: (UnsafeRawBufferPointer) throws -> IOResult<Int>,
        vectorBufferWriteOperation: (UnsafeBufferPointer<IOVector>) throws -> IOResult<Int>,
        scalarFileWriteOperation: (CInt, Int, Int) throws -> IOResult<Int>
    ) throws -> OverallWriteResult {
        try self.triggerWriteOperations { writeMechanism in
            switch writeMechanism {
            case .scalarBufferWrite:
                return try triggerScalarBufferWrite({ try scalarBufferWriteOperation($0) })
            case .vectorBufferWrite:
                return try triggerVectorBufferWrite({ try vectorBufferWriteOperation($0) })
            case .scalarFileWrite:
                return try triggerScalarFileWrite({ try scalarFileWriteOperation($0, $1, $2) })
            case .nothingToBeWritten:
                assertionFailure("called \(#function) with nothing available to be written")
                return .writtenCompletely
            }
        }
    }

    /// To be called after a write operation (usually selected and run by `triggerAppropriateWriteOperation`) has
    /// completed.
    ///
    /// - Parameters:
    ///   - itemCount: The number of items we tried to write.
    ///   - result: The result of the write operation.
    private func didWrite(itemCount: Int, result: IOResult<Int>) -> OneWriteOperationResult {
        let (promise, result) = self.state.didWrite(itemCount: itemCount, result: result)

        if self.state.bytes < waterMark.low {
            channelWritabilityFlag.store(true, ordering: .relaxed)