Skip to content

Commit

Permalink
Adopt UseEarlyExits
Browse files Browse the repository at this point in the history
  • Loading branch information
FranzBusch committed Jul 18, 2024
1 parent ad7c3b6 commit d1ac5bb
Show file tree
Hide file tree
Showing 90 changed files with 1,399 additions and 1,654 deletions.
2 changes: 1 addition & 1 deletion .swift-format
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@
"OrderedImports" : true,
"ReplaceForEachWithForLoop" : true,
"ReturnVoidInsteadOfEmptyTuple" : true,
"UseEarlyExits" : false,
"UseEarlyExits" : true,
"UseExplicitNilCheckInConditions" : false,
"UseLetInEveryBoundCaseVariable" : false,
"UseShorthandTypeNames" : true,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -27,12 +27,11 @@ private final class PongDecoder: ByteToMessageDecoder {
typealias InboundOut = UInt8

public func decode(context: ChannelHandlerContext, buffer: inout ByteBuffer) -> DecodingState {
if let ping = buffer.readInteger(as: UInt8.self) {
context.fireChannelRead(Self.wrapInboundOut(ping))
return .continue
} else {
guard let ping = buffer.readInteger(as: UInt8.self) else {
return .needMoreData
}
context.fireChannelRead(Self.wrapInboundOut(ping))
return .continue
}

public func decodeLast(
Expand Down
7 changes: 3 additions & 4 deletions Sources/NIOConcurrencyHelpers/atomics.swift
Original file line number Diff line number Diff line change
Expand Up @@ -501,12 +501,11 @@ public final class AtomicBox<T: AnyObject> {
return true
} else {
let currentPtrBits = self.storage.load()
if currentPtrBits == 0 || currentPtrBits == expectedPtrBits {
sys_sched_yield()
continue
} else {
guard currentPtrBits == 0 || currentPtrBits == expectedPtrBits else {
return false
}
sys_sched_yield()
continue
}
}
}
Expand Down
237 changes: 114 additions & 123 deletions Sources/NIOCore/AsyncSequences/NIOAsyncWriter.swift

Large diffs are not rendered by default.

Original file line number Diff line number Diff line change
Expand Up @@ -1197,27 +1197,7 @@ extension NIOThrowingAsyncSequenceProducer {
):
self._state = .modifying

if let element = buffer.popFirst() {
// We have an element to fulfil the demand right away.

let shouldProduceMore = backPressureStrategy.didConsume(bufferDepth: buffer.count)

self._state = .streaming(
backPressureStrategy: backPressureStrategy,
buffer: buffer,
continuation: nil,
hasOutstandingDemand: shouldProduceMore,
iteratorInitialized: iteratorInitialized
)

if shouldProduceMore && !hasOutstandingDemand {
// We didn't have any demand but now we do, so we need to inform the delegate.
return .returnElementAndCallProduceMore(element)
} else {
// We don't have any new demand, so we can just return the element.
return .returnElement(element)
}
} else {
guard let element = buffer.popFirst() else {
// There is nothing in the buffer to fulfil the demand so we need to suspend.
// We are not interacting with the back-pressure strategy here because
// we are doing this inside `next(:)`
Expand All @@ -1231,25 +1211,42 @@ extension NIOThrowingAsyncSequenceProducer {

return .suspendTask
}
// We have an element to fulfil the demand right away.

let shouldProduceMore = backPressureStrategy.didConsume(bufferDepth: buffer.count)

self._state = .streaming(
backPressureStrategy: backPressureStrategy,
buffer: buffer,
continuation: nil,
hasOutstandingDemand: shouldProduceMore,
iteratorInitialized: iteratorInitialized
)

guard shouldProduceMore && !hasOutstandingDemand else {
// We don't have any new demand, so we can just return the element.
return .returnElement(element)
}
// We didn't have any demand but now we do, so we need to inform the delegate.
return .returnElementAndCallProduceMore(element)

case .sourceFinished(var buffer, let iteratorInitialized, let failure):
self._state = .modifying

// Check if we have an element left in the buffer and return it
if let element = buffer.popFirst() {
self._state = .sourceFinished(
buffer: buffer,
iteratorInitialized: iteratorInitialized,
failure: failure
)

return .returnElement(element)
} else {
guard let element = buffer.popFirst() else {
// We are returning the queued failure now and can transition to finished
self._state = .finished(iteratorInitialized: iteratorInitialized)

return .returnFailureAndCallDidTerminate(failure)
}
self._state = .sourceFinished(
buffer: buffer,
iteratorInitialized: iteratorInitialized,
failure: failure
)

return .returnElement(element)

case .cancelled(let iteratorInitialized):
self._state = .finished(iteratorInitialized: iteratorInitialized)
Expand Down Expand Up @@ -1299,11 +1296,10 @@ extension NIOThrowingAsyncSequenceProducer {
iteratorInitialized: iteratorInitialized
)

if shouldProduceMore && !hasOutstandingDemand {
return .callProduceMore
} else {
guard shouldProduceMore && !hasOutstandingDemand else {
return .none
}
return .callProduceMore

case .streaming(_, _, .some(_), _, _), .sourceFinished, .finished, .cancelled:
preconditionFailure("This should have already been handled by `next()`")
Expand Down
48 changes: 25 additions & 23 deletions Sources/NIOCore/ByteBuffer-aux.swift
Original file line number Diff line number Diff line change
Expand Up @@ -119,13 +119,14 @@ extension ByteBuffer {
@inlinable
mutating func _setStringSlowpath(_ string: String, at index: Int) -> Int {
// slow path, let's try to force the string to be native
if let written = (string + "").utf8.withContiguousStorageIfAvailable({ utf8Bytes in
self.setBytes(utf8Bytes, at: index)
}) {
return written
} else {
guard
let written = (string + "").utf8.withContiguousStorageIfAvailable({ utf8Bytes in
self.setBytes(utf8Bytes, at: index)
})
else {
return self.setBytes(string.utf8, at: index)
}
return written
}

/// Write `string` into this `ByteBuffer` at `index` using UTF-8 encoding. Does not move the writer index.
Expand All @@ -140,14 +141,15 @@ extension ByteBuffer {
// Do not implement setString via setSubstring. Before Swift version 5.3,
// Substring.UTF8View did not implement withContiguousStorageIfAvailable
// and therefore had no fast access to the backing storage.
if let written = string.utf8.withContiguousStorageIfAvailable({ utf8Bytes in
self.setBytes(utf8Bytes, at: index)
}) {
// fast path, directly available
return written
} else {
guard
let written = string.utf8.withContiguousStorageIfAvailable({ utf8Bytes in
self.setBytes(utf8Bytes, at: index)
})
else {
return self._setStringSlowpath(string, at: index)
}
// fast path, directly available
return written
}

/// Write `string` null terminated into this `ByteBuffer` at `index` using UTF-8 encoding. Does not move the writer index.
Expand Down Expand Up @@ -262,15 +264,16 @@ extension ByteBuffer {
public mutating func setSubstring(_ substring: Substring, at index: Int) -> Int {
// Substring.UTF8View implements withContiguousStorageIfAvailable starting with
// Swift version 5.3.
if let written = substring.utf8.withContiguousStorageIfAvailable({ utf8Bytes in
self.setBytes(utf8Bytes, at: index)
}) {
// fast path, directly available
return written
} else {
guard
let written = substring.utf8.withContiguousStorageIfAvailable({ utf8Bytes in
self.setBytes(utf8Bytes, at: index)
})
else {
// slow path, convert to string
return self.setString(String(substring), at: index)
}
// fast path, directly available
return written
}

// MARK: DispatchData APIs
Expand Down Expand Up @@ -844,13 +847,12 @@ extension Optional where Wrapped == ByteBuffer {
@discardableResult
@inlinable
public mutating func setOrWriteBuffer(_ buffer: inout ByteBuffer) -> Int {
if self == nil {
let readableBytes = buffer.readableBytes
self = buffer
buffer.moveReaderIndex(to: buffer.writerIndex)
return readableBytes
} else {
guard self == nil else {
return self!.writeBuffer(&buffer)
}
let readableBytes = buffer.readableBytes
self = buffer
buffer.moveReaderIndex(to: buffer.writerIndex)
return readableBytes
}
}
18 changes: 9 additions & 9 deletions Sources/NIOCore/ByteBuffer-core.swift
Original file line number Diff line number Diff line change
Expand Up @@ -537,14 +537,15 @@ public struct ByteBuffer {
@inlinable
mutating func _setBytes<Bytes: Sequence>(_ bytes: Bytes, at index: _Index) -> _Capacity
where Bytes.Element == UInt8 {
if let written = bytes.withContiguousStorageIfAvailable({ bytes in
self._setBytes(UnsafeRawBufferPointer(bytes), at: index)
}) {
// fast path, we've got access to the contiguous bytes
return written
} else {
guard
let written = bytes.withContiguousStorageIfAvailable({ bytes in
self._setBytes(UnsafeRawBufferPointer(bytes), at: index)
})
else {
return self._setSlowPath(bytes: bytes, at: index)
}
// fast path, we've got access to the contiguous bytes
return written
}

// MARK: Public Core API
Expand Down Expand Up @@ -1190,11 +1191,10 @@ extension ByteBuffer {
/// - returns: The return value of `body`.
@inlinable
public mutating func modifyIfUniquelyOwned<T>(_ body: (inout ByteBuffer) throws -> T) rethrows -> T? {
if isKnownUniquelyReferenced(&self._storage) {
return try body(&self)
} else {
guard isKnownUniquelyReferenced(&self._storage) else {
return nil
}
return try body(&self)
}
}

Expand Down
10 changes: 4 additions & 6 deletions Sources/NIOCore/ByteBuffer-hexdump.swift
Original file line number Diff line number Diff line change
Expand Up @@ -248,18 +248,16 @@ extension ByteBuffer {
public func hexDump(format: HexDumpFormat) -> String {
switch format.value {
case .plain(let maxBytes):
if let maxBytes = maxBytes {
return self.hexDumpPlain(maxBytes: maxBytes)
} else {
guard let maxBytes = maxBytes else {
return self.hexDumpPlain()
}
return self.hexDumpPlain(maxBytes: maxBytes)

case .detailed(let maxBytes):
if let maxBytes = maxBytes {
return self.hexDumpDetailed(maxBytes: maxBytes)
} else {
guard let maxBytes = maxBytes else {
return self.hexdumpDetailed()
}
return self.hexDumpDetailed(maxBytes: maxBytes)
}
}
}
7 changes: 3 additions & 4 deletions Sources/NIOCore/ChannelOption.swift
Original file line number Diff line number Diff line change
Expand Up @@ -392,12 +392,11 @@ extension ChannelOptions {
var hasSet = false
self._storage = self._storage.map { currentKeyAndValue in
let (currentKey, _) = currentKeyAndValue
if let currentKey = currentKey as? Option, currentKey == newKey {
hasSet = true
return (currentKey, (newValue, applier))
} else {
guard let currentKey = currentKey as? Option, currentKey == newKey else {
return currentKeyAndValue
}
hasSet = true
return (currentKey, (newValue, applier))
}
if !hasSet {
self._storage.append((newKey, (newValue, applier)))
Expand Down
5 changes: 2 additions & 3 deletions Sources/NIOCore/ChannelPipeline.swift
Original file line number Diff line number Diff line change
Expand Up @@ -570,11 +570,10 @@ public final class ChannelPipeline: ChannelInvoker {
internal func _contextSync(_ body: (ChannelHandlerContext) -> Bool) -> Result<ChannelHandlerContext, Error> {
self.eventLoop.assertInEventLoop()

if let context = self.contextForPredicate0(body) {
return .success(context)
} else {
guard let context = self.contextForPredicate0(body) else {
return .failure(ChannelPipelineError.notFound)
}
return .success(context)
}

/// Returns a `ChannelHandlerContext` which matches.
Expand Down
15 changes: 6 additions & 9 deletions Sources/NIOCore/CircularBuffer.swift
Original file line number Diff line number Diff line change
Expand Up @@ -456,11 +456,10 @@ extension CircularBuffer {
/// Returns the number of element in the ring.
@inlinable
public var count: Int {
if self.tailBackingIndex >= self.headBackingIndex {
return self.tailBackingIndex &- self.headBackingIndex
} else {
guard self.tailBackingIndex >= self.headBackingIndex else {
return self._buffer.count &- (self.headBackingIndex &- self.tailBackingIndex)
}
return self.tailBackingIndex &- self.headBackingIndex
}

/// The total number of elements that the ring can contain without allocating new storage.
Expand Down Expand Up @@ -538,11 +537,10 @@ extension CircularBuffer: RangeReplaceableCollection {
/// - Complexity: O(1)
@inlinable
public mutating func popFirst() -> Element? {
if count > 0 {
return self.removeFirst()
} else {
guard count > 0 else {
return nil
}
return self.removeFirst()
}

/// Removes and returns the last element of the `CircularBuffer`.
Expand All @@ -557,11 +555,10 @@ extension CircularBuffer: RangeReplaceableCollection {
/// - Complexity: O(1)
@inlinable
public mutating func popLast() -> Element? {
if count > 0 {
return self.removeLast()
} else {
guard count > 0 else {
return nil
}
return self.removeLast()
}

/// Removes the specified number of elements from the end of the
Expand Down
14 changes: 6 additions & 8 deletions Sources/NIOCore/Codec.swift
Original file line number Diff line number Diff line change
Expand Up @@ -304,12 +304,11 @@ extension B2MDBuffer {
var buffer = self.buffers.removeFirst()
buffer.writeBuffers(self.buffers)
self.buffers.removeAll(keepingCapacity: self.buffers.capacity < 16) // don't grow too much
if buffer.readableBytes > 0 || allowEmptyBuffer {
self.state = .processingInProgress
return .available(buffer)
} else {
guard buffer.readableBytes > 0 || allowEmptyBuffer else {
return .nothingAvailable
}
self.state = .processingInProgress
return .available(buffer)
case .ready:
assert(self.buffers.isEmpty)
if allowEmptyBuffer {
Expand Down Expand Up @@ -618,12 +617,11 @@ extension ByteToMessageHandler {
self.tryDecodeWrites()
continue
case .didProcess(.needMoreData):
if self.queuedWrites.count > 0 {
self.tryDecodeWrites()
continue // we might have received more, so let's spin once more
} else {
guard self.queuedWrites.count > 0 else {
return .didProcess(.needMoreData)
}
self.tryDecodeWrites()
continue // we might have received more, so let's spin once more
case .cannotProcessReentrantly:
return .cannotProcessReentrantly
}
Expand Down
Loading

0 comments on commit d1ac5bb

Please sign in to comment.