mirror of
https://github.com/apple/swift-nio
synced 2026-11-25 04:47:49 +00:00
Quality of Life: Add NIOLoopBoundBox.withValue (#3385)
When having a state machine inside the `NIOLoopBoundBox` we currently check the EL when reading and writing. This is unnecessary. Because of this, this PR introduces a new `withValue` method, that allows users to read and write the value inside the NIOLoopBoundBox while only paying the cost for the EL check once.
This commit is contained in:
1 parent
83d438650a
commit
45b463c5eb
2 files changed
+48
No files matched your search
@@ -173,4 +173,24 @@ public final class NIOLoopBoundBox<Value>: @unchecked Sendable {
|
||||
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)
|
||||
}
|
||||
}
|
||||
@@ -114,6 +114,34 @@ final class NIOLoopBoundTests: XCTestCase {
|
||||
XCTAssertTrue(loopBoundBox.value.mutateInPlace())
|
||||
}
|
||||
|
||||
func testWithValue() {
|
||||
var expectedValue = 0
|
||||
let loopBound = NIOLoopBoundBox(expectedValue, eventLoop: loop)
|
||||
for value in 1...100 {
|
||||
loopBound.withValue { boundValue in
|
||||
XCTAssertEqual(boundValue, expectedValue)
|
||||
boundValue = value
|
||||
expectedValue = value
|
||||
}
|
||||
}
|
||||
XCTAssertEqual(100, loopBound.value)
|
||||
}
|
||||
|
||||
func testWithValueRethrows() {
|
||||
struct TestError: Error {}
|
||||
|
||||
let loopBound = NIOLoopBoundBox(0, eventLoop: loop)
|
||||
XCTAssertThrowsError(
|
||||
try loopBound.withValue { boundValue in
|
||||
XCTAssertEqual(0, boundValue)
|
||||
boundValue = 10
|
||||
throw TestError()
|
||||
}
|
||||
)
|
||||
|
||||
XCTAssertEqual(10, loopBound.value, "Ensure value is set even if we throw")
|
||||
}
|
||||
|
||||
// MARK: - Helpers
|
||||
func sendableBlackhole<S: Sendable>(_ sendableThing: S) {}
|
||||
|
||||
|
||||
Reference in new issue
Block a user