ronantakizawa/codereview-bench huggingface dataset:
Repository: apple/swift-nio
File: Sources/NIOPosix/SelectableEventLoop.swift (Swift)

Code before:
    static let _nextGroupID = ManagedAtomic<UInt32>(1)  // DO NOT MAKE THIS 0.

    @usableFromInline
    var _loopID: UInt32

    @usableFromInline
    let _groupID: UInt32

    @inlinable
    var groupID: Int {
        Int(self._groupID)
    }

    @inlinable
    var loopID: Int {
        Int(self._loopID)
    }

    @inlinable
    init(_loopID: UInt32, groupID: UInt32) {
        self._loopID = _loopID
        self._groupID = groupID
    }

    static func makeNextGroup() -> Self {
        let groupID = Self._nextGroupID.loadThenWrappingIncrement(ordering: .relaxed)

        return Self(_loopID: 1, groupID: groupID)
    }

    mutating func nextLoop() {
        self._loopID += 1
    }

    @inlinable
    internal var matchesCurrentThread: Bool {
        let threadUniqueID = c_nio_posix_get_el_id()
        return threadUniqueID == self.packedEventLoopID
    }

    @inlinable
    internal var packedEventLoopID: UInt {
        #if arch(arm) || arch(i386) || arch(arm64_32) || arch(wasm32)
        // 32 bit
        let packedID = IntegerBitPacking.packUInt16UInt16(
            UInt16(self._groupID),
            UInt16(self._loopID)
        )
        #else
        // 64 bit
        let packedID = IntegerBitPacking.packUInt32UInt32(self._groupID, self._loopID)

Review comment (suggestion):
Wrapping here is _extremely_ dangerous: we'll start recycling IDs. I appreciate the desire to avoid the checked increment in the atomic, but we should validate that we never see `0` out of this.

Code after:
    static let _nextGroupID = ManagedAtomic<UInt64>(1)  // DO NOT MAKE THIS 0.

    @usableFromInline
    var _loopID: UInt32

    @usableFromInline
    let _groupID: UInt32

    @inlinable
    var groupID: Int {
        Int(self._groupID)
    }

    @inlinable
    var loopID: Int {
        Int(self._loopID)
    }

    @inlinable
    init(_loopID: UInt32, groupID: UInt32) {
        self._loopID = _loopID
        self._groupID = groupID
    }

    static func makeNextGroup() -> Self {
        let groupID = Self._nextGroupID.loadThenWrappingIncrement(ordering: .relaxed)

        // If we're crashing just below, we created more 2^32 ELGs -- unlikely.
        return Self(_loopID: 1, groupID: UInt32(groupID))
    }

    mutating func nextLoop() {
        self._loopID += 1
    }

    @inlinable
    internal var matchesCurrentThread: Bool {
        let threadUniqueID = c_nio_posix_get_el_id()
        return threadUniqueID == self.packedEventLoopID
    }

    @inlinable
    internal var packedEventLoopID: UInt {
        #if arch(arm) || arch(i386) || arch(arm64_32) || arch(wasm32)
        // 32 bit
        // If we're crashing below, we created more than 2^16 (64ki) ELGs which is unsupported.
        precondition(self._groupID < UInt32(UInt16.max), "too many event loops created")
        precondition(self._loopID < UInt32(UInt16.max), "event loop group with too many event loops created")
        let packedID = IntegerBitPacking.packUInt16UInt16(
            UInt16(self._groupID),
            UInt16(self._loopID)
Repository: apple/swift-nio
File: Sources/NIOConcurrencyHelpers/NIOLockedValueBox.swift (Swift)

Code before:

        /// Manually release the lock.
        @inlinable
        public func unlock() {
            self._storage.unlock()
        }

        /// Mutate the value, assuming the lock has been acquired manually.
        ///
        /// - Parameter mutate: A closure with scoped access to the value.
        /// - Returns: The result of the `mutate` closure.
        @inlinable
        public func withValueAssumingLockIsAcquired<Result>(
            _ mutate: (_ value: inout Value) throws -> Result
        ) rethrows -> Result {
            try self._storage.withUnsafeMutablePointerToHeader { value in
                try mutate(&value.pointee)
            }
        }
    }
}

extension NIOLockedValueBox: @unchecked Sendable where Value: Sendable {}

@available(*, unavailable)
extension NIOLockedValueBox.Unsafe: Sendable {}


Review comment (suggestion):
FWIW, the unsafe box _is_ Sendable, so I'm inclined to say that we should probably mark it Sendable to, at least where `Value` is `Sendable`.

Code after:

        /// Manually release the lock.
        @inlinable
        public func unlock() {
            self._storage.unlock()
        }

        /// Mutate the value, assuming the lock has been acquired manually.
        ///
        /// - Parameter mutate: A closure with scoped access to the value.
        /// - Returns: The result of the `mutate` closure.
        @inlinable
        public func withValueAssumingLockIsAcquired<Result>(
            _ mutate: (_ value: inout Value) throws -> Result
        ) rethrows -> Result {
            try self._storage.withUnsafeMutablePointerToHeader { value in
                try mutate(&value.pointee)
            }
        }
    }
}

extension NIOLockedValueBox: @unchecked Sendable where Value: Sendable {}

extension NIOLockedValueBox.Unsafe: @unchecked Sendable where Value: Sendable {}
Repository: apple/swift-nio
File: Sources/NIOPosix/BSDSocketAPIPosix.swift (Swift)

Code before:
        var enabled: CInt = 0
        var optionLength = socklen_t(MemoryLayout<CInt>.size)
        try withUnsafeMutablePointer(to: &enabled) { enabledBytes in
            try Self.getsockopt(
                socket: socket,
                level: .udp,
                option_name: .udp_gro,
                option_value: enabledBytes,
                option_len: &optionLength
            )
        }
        return enabled != 0
        #else
        throw ChannelError._operationUnsupported
        #endif
    }
}

extension msghdr {
    var control_ptr: UnsafeMutableRawBufferPointer {
        set {
            self.msg_control = newValue.baseAddress
            self.msg_controllen = numericCast(newValue.count)
        }
        get {
            UnsafeMutableRawBufferPointer(start: self.msg_control, count: numericCast(self.msg_controllen))
        }
    }
}
#endif


Review comment (suggestion):
No need for `numericCast` here, this can just be `Int`

Code after:
        var enabled: CInt = 0
        var optionLength = socklen_t(MemoryLayout<CInt>.size)
        try withUnsafeMutablePointer(to: &enabled) { enabledBytes in
            try Self.getsockopt(
                socket: socket,
                level: .udp,
                option_name: .udp_gro,
                option_value: enabledBytes,
                option_len: &optionLength
            )
        }
        return enabled != 0
        #else
        throw ChannelError._operationUnsupported
        #endif
    }
}

extension msghdr {
    var control_ptr: UnsafeMutableRawBufferPointer {
        set {
            self.msg_control = newValue.baseAddress
            self.msg_controllen = numericCast(newValue.count)
        }
        get {
            UnsafeMutableRawBufferPointer(start: self.msg_control, count: Int(self.msg_controllen))
        }
    }
}
#endif
Repository: apple/swift-nio
File: Sources/NIOCore/Utilities.swift (Swift)

Code before:
        #endif
        return nil
    }
}

#if os(Windows)
@usableFromInline
func windows_strerror(_ errnoCode: CInt) -> String? {
    withUnsafeTemporaryAllocation(of: CChar.self, capacity: 256) { ptr in
        if strerror_s(ptr.baseAddress, ptr.count, errnoCode) == 0 {
            return String(cString: UnsafePointer(ptr.baseAddress!))
        }
        return nil
    }
}

func windows_getenv(_ env: String) -> String? {
    var count = 0
    var ptr: UnsafeMutablePointer<CChar>? = nil
    withUnsafeMutablePointer(to: &ptr) { buffer in
        // according to docs only EINVAL and ENOMEM are possible here.
        _ = _dupenv_s(buffer, &count, env)
    }
    defer { ptr?.deallocate() }
    return if count > 0, let ptr {
        String(cString: ptr)
    } else {
        nil
    }
}
#endif


Review comment (performance):
The documentation does not promise that this is a null-terminated string, and even if it did, we were given the count. It's more efficient to use that count.

Code after:
        #endif
        return nil
    }
}

#if os(Windows)
enum Windows {
    @usableFromInline
    static func strerror(_ errnoCode: CInt) -> String? {
        withUnsafeTemporaryAllocation(of: CChar.self, capacity: 256) { ptr in
            if strerror_s(ptr.baseAddress, ptr.count, errnoCode) == 0 {
                return String(cString: UnsafePointer(ptr.baseAddress!))
            }
            return nil
        }
    }

    static func getenv(_ env: String) -> String? {
        var count = 0
        var ptr: UnsafeMutablePointer<CChar>? = nil
        withUnsafeMutablePointer(to: &ptr) { buffer in
            // according to docs only EINVAL and ENOMEM are possible here.
            _ = _dupenv_s(buffer, &count, env)
        }
        defer { if let ptr { free(ptr) } }
        if count > 0, let ptr {
            let buffer = UnsafeBufferPointer(start: ptr, count: count)
            return buffer.withMemoryRebound(to: UInt8.self) {
                String(decoding: $0, as: Unicode.UTF8.self)
            }
        } else {
            return nil
        }
    }
}
#endif
Repository: apple/swift-nio
File: Sources/NIOPosix/SelectorWSAPoll.swift (Swift)

Code before:
    }

    func deregister0(
        selectableFD: NIOBSDSocket.Handle,
        fileDescriptor: NIOBSDSocket.Handle,
        oldInterested: SelectorEventSet,
        registrationID: SelectorRegistrationID
    ) throws {
        fatalError("TODO: Unimplemented")
    }

    func wakeup0() throws {
        // will be called from a different thread
        let result = try self.myThread.withHandleUnderLock { handle in
            QueueUserAPC(wakeupTarget, handle, 0)
        }
        if result == 0 {
            let errorCode = GetLastError()
            if let errorMsg = Windows.makeErrorMessageFromCode(errorCode) {
                throw IOError(errnoCode: Int32(errorCode), reason: errorMsg)
            }
        }
    }

    func close0() throws {
        // Throw away all pollFDs?
    }
}

func wakeupTarget(_ ptr: UInt64) {
    // This is the target of our wakeup call.
    // We don't really need to do anything here. We just need any target
}
#endif


Review comment (suggestion):
Yeah, this is nice and straightforward to implement for `WSAPoll`, as there's no stateful kernel handle.

Code after:
        fileDescriptor: NIOBSDSocket.Handle,
        oldInterested: SelectorEventSet,
        newInterested: SelectorEventSet,
        registrationID: SelectorRegistrationID
    ) throws {
        fatalError("TODO: Unimplemented")
    }

    func deregister0(
        selectableFD: NIOBSDSocket.Handle,
        fileDescriptor: NIOBSDSocket.Handle,
        oldInterested: SelectorEventSet,
        registrationID: SelectorRegistrationID
    ) throws {
        fatalError("TODO: Unimplemented")
    }

    func wakeup0() throws {
        // will be called from a different thread
        let result = try self.myThread.withHandleUnderLock { handle in
            QueueUserAPC(wakeupTarget, handle, 0)
        }
        if result == 0 {
            let errorCode = GetLastError()
            if let errorMsg = Windows.makeErrorMessageFromCode(errorCode) {
                throw IOError(errnoCode: Int32(errorCode), reason: errorMsg)
            }
        }
    }

    func close0() throws {
        self.pollFDs.removeAll()
    }
}

private func wakeupTarget(_ ptr: UInt64) {
    // This is the target of our wakeup call.
    // We don't really need to do anything here. We just need any target
}
#endif
Repository: apple/swift-nio
File: Tests/NIOCoreTests/ByteBufferSpanTests.swift (Swift)

Code before:
//===----------------------------------------------------------------------===//
//
// This source file is part of the SwiftNIO open source project
//
// Copyright (c) 2025 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

import NIOCore

#if compiler(>=6.2)
@available(macOS 10.14.4, iOS 12.2, watchOS 5.2, tvOS 12.2, visionOS 1.0, *)
final class ByteBufferSpanTests: XCTestCase {
    func testReadableBytesSpanOfEmptyByteBuffer() {
        let bb = ByteBuffer()
        XCTAssertEqual(bb.readableBytesSpan.byteCount, 0)
    }

    func testReadableBytesSpanOfSimpleBuffer() {
        let bb = ByteBuffer(string: "Hello, world!")
        XCTAssertEqual(bb.readableBytesSpan.byteCount, 13)
        XCTAssertTrue(bb.readableBytesSpan.elementsEqual("Hello, world!".utf8))
    }

    func testReadableBytesSpanNotAtTheStart() {
        var bb = ByteBuffer(string: "Hello, world!")
        bb.moveReaderIndex(forwardBy: 5)
        XCTAssertEqual(bb.readableBytesSpan.byteCount, 8)
        XCTAssertTrue(bb.readableBytesSpan.elementsEqual(", world!".utf8))
    }

    func testReadableBytesSpanOfSlice() {

Review comment (suggestion):
Just a suggestion but since this is already 6.2+ we may wanna consider using `Testing` here to avoid having to migrate the tests in the future.

Code after:
//===----------------------------------------------------------------------===//
//
// This source file is part of the SwiftNIO open source project
//
// Copyright (c) 2025 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 NIOCore
import Testing

#if compiler(>=6.2)
@Suite
struct ByteBufferSpanTests {
    @Test
    @available(macOS 10.14.4, iOS 12.2, watchOS 5.2, tvOS 12.2, visionOS 1.0, *)
    func testReadableBytesSpanOfEmptyByteBuffer() {
        let bb = ByteBuffer()
        #expect(bb.readableBytesSpan.byteCount == 0)
    }

    @Test
    @available(macOS 10.14.4, iOS 12.2, watchOS 5.2, tvOS 12.2, visionOS 1.0, *)
    func testReadableBytesSpanOfSimpleBuffer() {
        let bb = ByteBuffer(string: "Hello, world!")
        #expect(bb.readableBytesSpan.byteCount == 13)
        let bytesEqual = bb.readableBytesSpan.elementsEqual("Hello, world!".utf8)
        #expect(bytesEqual)
    }

    @Test
    @available(macOS 10.14.4, iOS 12.2, watchOS 5.2, tvOS 12.2, visionOS 1.0, *)
    func testReadableBytesSpanNotAtTheStart() {
        var bb = ByteBuffer(string: "Hello, world!")
Repository: apple/swift-nio
File: Sources/NIOCore/NIOLoopBound.swift (Swift)

Code before:
    @inlinable
    public var value: Value {
        get {
            self.eventLoop.preconditionInEventLoop()
            return self._value
        }
        _modify {
            self.eventLoop.preconditionInEventLoop()
            yield &self._value
        }
    }

    #if compiler(>=6.0)
    /// Safely access and potentially modify the contained value with a closure.
    ///
    /// This method provides a way to perform operations on the contained value while ensuring
    /// thread safety through EventLoop verification. The closure receives an `inout` parameter
    /// allowing both read and write access to the value.
    ///
    /// - Parameter handler: A closure that receives an `inout` reference to the contained value.
    ///   The closure can read from and write to this value. Any modifications made within the
    ///   closure will be reflected in the box after the closure completes, even if the closure throws.
    /// - Returns: The value returned by the `handler` closure.
    /// - Note: This method is particularly useful when you need to perform read and write operations
    ///         on the value because it reduces the on EventLoop checks.
    public func withValue<T, E: Error>(_ handler: (inout Value) throws(E) -> T) throws(E) -> T {
        self.eventLoop.preconditionInEventLoop()
        var value = self._value
        defer { self._value = value }
        return try handler(&value)
    }
    #endif
}


Review comment (bug):
Can we use `Result` and `Failure` instead of `T` and `E`?

Code after:
        get {
            self.eventLoop.preconditionInEventLoop()
            return self._value
        }
        _modify {
            self.eventLoop.preconditionInEventLoop()
            yield &self._value
        }
    }

    /// Safely access and potentially modify the contained value with a closure.
    ///
    /// This method provides a way to perform operations on the contained value while ensuring
    /// thread safety through EventLoop verification. The closure receives an `inout` parameter
    /// allowing both read and write access to the value.
    ///
    /// - Parameter handler: A closure that receives an `inout` reference to the contained value.
    ///   The closure can read from and write to this value. Any modifications made within the
    ///   closure will be reflected in the box after the closure completes, even if the closure throws.
    /// - Returns: The value returned by the `handler` closure.
    /// - Note: This method is particularly useful when you need to perform read and write operations
    ///         on the value because it reduces the on EventLoop checks.
    @inlinable
    public func withValue<Success, Failure: Error>(
        _ handler: (inout Value) throws(Failure) -> Success
    ) throws(Failure) -> Success {
        self.eventLoop.preconditionInEventLoop()
        return try handler(&self._value)
    }
}
Repository: apple/swift-nio
File: Benchmarks/Benchmarks/NIOPosixBenchmarks/UDPEcho.swift (Swift)

Code before:
//===----------------------------------------------------------------------===//
//
// This source file is part of the SwiftNIO open source project
//
// Copyright (c) 2024 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 NIOCore
import NIOPosix

private final class UDPEchoHandler: ChannelInboundHandler {
    typealias InboundIn = AddressedEnvelope<ByteBuffer>
    typealias OutboundOut = AddressedEnvelope<ByteBuffer>

    func channelRead(context: ChannelHandlerContext, data: NIOAny) {
        context.write(data, promise: nil)
    }

    func channelReadComplete(context: ChannelHandlerContext) {
        context.flush()
    }
}


Review comment (security):
```suggestion
// Copyright (c) 2025 Apple Inc. and the SwiftNIO project authors
```

Code after:
//===----------------------------------------------------------------------===//
//
// This source file is part of the SwiftNIO open source project
//
// Copyright (c) 2025 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 NIOCore
import NIOPosix

private final class UDPEchoHandler: ChannelInboundHandler {
    typealias InboundIn = AddressedEnvelope<ByteBuffer>
    typealias OutboundOut = AddressedEnvelope<ByteBuffer>

    func channelRead(context: ChannelHandlerContext, data: NIOAny) {
        context.write(data, promise: nil)
    }

    func channelReadComplete(context: ChannelHandlerContext) {
        context.flush()
    }
}
Repository: apple/swift-nio
File: Sources/NIOPosix/BaseSocketChannel.swift (Swift)

Code before:
    public struct SynchronousOptions: NIOSynchronousChannelOptions {
        @usableFromInline  // should be private
        internal let _channel: BaseSocketChannel<SocketType>

        @inlinable  // should be fileprivate
        internal init(_channel channel: BaseSocketChannel<SocketType>) {
            self._channel = channel
        }

        @inlinable
        public func setOption<Option: ChannelOption>(_ option: Option, value: Option.Value) throws {
            try self._channel.setOption0(option, value: value)
        }

        @inlinable
        public func getOption<Option: ChannelOption>(_ option: Option) throws -> Option.Value {
            try self._channel.getOption0(option)
        }
    }

    public final var syncOptions: NIOSynchronousChannelOptions? {
        SynchronousOptions(_channel: self)
    }
}

extension BaseSocketChannel: NIOTransportAccessibleChannelCore where SocketType: BaseSocket {
    /// The underlying transport which is a BSD socket file handle.
    typealias Transport = NIOBSDSocket.Handle

    /// Provides scoped access to the BSD socket file handle.
    func withUnsafeTransport<Result>(_ body: (_ transport: NIOBSDSocket.Handle) throws -> Result) throws -> Result {
        try self.socket.withUnsafeHandle(body)
    }
}

/// Execute the given function and synchronously complete the given `EventLoopPromise` (if not `nil`).
func executeAndComplete<Value: Sendable>(_ promise: EventLoopPromise<Value>?, _ body: () throws -> Value) {
    do {
        let result = try body()
        promise?.succeed(result)
    } catch let e {
        promise?.fail(e)
    }
}
#endif  // !os(WASI)


Review comment (suggestion):
We should probably do this with `PipeChannel while we're here.

Code after:
    public struct SynchronousOptions: NIOSynchronousChannelOptions {
        @usableFromInline  // should be private
        internal let _channel: BaseSocketChannel<SocketType>

        @inlinable  // should be fileprivate
        internal init(_channel channel: BaseSocketChannel<SocketType>) {
            self._channel = channel
        }

        @inlinable
        public func setOption<Option: ChannelOption>(_ option: Option, value: Option.Value) throws {
            try self._channel.setOption0(option, value: value)
        }

        @inlinable
        public func getOption<Option: ChannelOption>(_ option: Option) throws -> Option.Value {
            try self._channel.getOption0(option)
        }
    }

    public final var syncOptions: NIOSynchronousChannelOptions? {
        SynchronousOptions(_channel: self)
    }
}

/// Execute the given function and synchronously complete the given `EventLoopPromise` (if not `nil`).
func executeAndComplete<Value: Sendable>(_ promise: EventLoopPromise<Value>?, _ body: () throws -> Value) {
    do {
        let result = try body()
        promise?.succeed(result)
    } catch let e {
        promise?.fail(e)
    }
}
#endif  // !os(WASI)