diff --git a/Sources/SwiftNetwork/Context/NetworkContext.swift b/Sources/SwiftNetwork/Context/NetworkContext.swift index 4223340..242a4ac 100644 --- a/Sources/SwiftNetwork/Context/NetworkContext.swift +++ b/Sources/SwiftNetwork/Context/NetworkContext.swift @@ -62,21 +62,25 @@ public final class NetworkContext: NetworkContextProtocol, @unchecked Sendable { } public protocol Scheduler: AnyObject { - /// Run an immediate task. No assumptions are made about how the task will be run. + /// Runs an immediate task. No assumptions are made about how the task is run. func runImmediate(_ task: @escaping (() -> Void)) - /// Schedule a task to be run after a delay of the given `milliseconds`, using a reference. + /// Schedules a task to run after a delay, using a reference. + /// + /// The `milliseconds` parameter specifies the delay before the task runs. func schedule(_ task: @escaping (() -> Void), milliseconds: Int64, reference: TimerReference) - /// Unschedule a task with a handle + /// Unschedules a task with a reference. func unschedule(reference: TimerReference) - /// Whether the current code is running in the scheduler + /// A Boolean value that indicates whether the current code is running in the scheduler. var runningInScheduler: Bool { get } } - /// Indicate the privacy level for the context. Public is good for contexts that will be used only with - /// endpoints that do not divulge information about what the user is doing such as a process that always connects - /// to the same server. Private will hide the endpoints involved in connections. This level is appropriate for a - /// browser, where hostnames would indicate a great deal of information about what a user is doing. Sensitive will - /// suppress all logging and is appropriate for something like private browsing. + /// Indicates the privacy level for the context. + /// + /// `publicLogs` is good for contexts used only with endpoints that don't divulge information + /// about what the app is doing, such as a process that always connects to the same server. + /// `privateLogs` hides the endpoints involved in connections; this level is appropriate for a + /// browser, where hostnames would indicate a great deal of information about what the app is doing. + /// `sensitiveLogs` suppresses all logging and is appropriate for something like private browsing. enum PrivacyLevel: Hashable, CustomStringConvertible { case publicLogs case privateLogs @@ -340,20 +344,22 @@ extension NetworkContext { init(globals: Globals) { self.globals = globals } - /// Run an immediate task. No assumptions are made about how the task will be run. + /// Runs an immediate task. No assumptions are made about how the task is run. func runImmediate(_ task: @escaping (() -> Void)) { globals.queue.async(execute: DispatchWorkItem(block: task)) } - /// Schedule a task to be run after a delay of the given `milliseconds`, using a reference. + /// Schedules a task to run after a delay, using a reference. + /// + /// The `milliseconds` parameter specifies the delay before the task runs. func schedule(_ task: @escaping (() -> Void), milliseconds: Int64, reference: TimerReference) { let targetTime = DispatchTime.now() + DispatchTimeInterval.milliseconds(Int(milliseconds)) globals.timerList.insert(targetTime: targetTime, reference: reference, task: task) } - /// Unschedule a task with a reference + /// Unschedules a task with a reference. func unschedule(reference: TimerReference) { globals.timerList.remove(for: reference) } - /// Whether the current code is running in the scheduler + /// A Boolean value that indicates whether the current code is running in the scheduler. var runningInScheduler: Bool { // TODO: Not supported by DispatchQueue fatalError("Unsupported") diff --git a/Sources/SwiftNetwork/Endpoint/EthernetAddress.swift b/Sources/SwiftNetwork/Endpoint/EthernetAddress.swift index 4cddace..f8ee628 100644 --- a/Sources/SwiftNetwork/Endpoint/EthernetAddress.swift +++ b/Sources/SwiftNetwork/Endpoint/EthernetAddress.swift @@ -36,7 +36,7 @@ public struct EthernetAddress: Hashable, CustomDebugStringConvertible { } } - /// An IPv6 address as a byte array + /// An Ethernet address as a byte array. public init?(_ bytes: [UInt8]) { guard bytes.count == MemoryLayout.size else { return nil diff --git a/Sources/SwiftNetwork/Endpoint/IPAddress.swift b/Sources/SwiftNetwork/Endpoint/IPAddress.swift index 2fcf359..28e3550 100644 --- a/Sources/SwiftNetwork/Endpoint/IPAddress.swift +++ b/Sources/SwiftNetwork/Endpoint/IPAddress.swift @@ -12,18 +12,18 @@ // //===----------------------------------------------------------------------===// -/// IPAddress is just a stub for now. +/// A stub protocol that represents an IP address. protocol IPAddress: Sendable { - /// Create IPAddress from raw bytes + /// Creates an IP address from raw bytes. init?(_ bytes: [UInt8]) - /// Indicates the address family used for the IPAddress type + /// The address family used by this IP address. var addressFamily: AddressFamily { get } - /// Indicates if this address is loopback + /// A Boolean value that indicates whether this address is a loopback address. var isLoopback: Bool { get } - /// Indicates if this address is multicast + /// A Boolean value that indicates whether this address is a multicast address. var isMulticast: Bool { get } } diff --git a/Sources/SwiftNetwork/Endpoint/IPv4Address.swift b/Sources/SwiftNetwork/Endpoint/IPv4Address.swift index 46be2a1..95dc6b2 100644 --- a/Sources/SwiftNetwork/Endpoint/IPv4Address.swift +++ b/Sources/SwiftNetwork/Endpoint/IPv4Address.swift @@ -14,27 +14,27 @@ public struct IPv4Address: IPAddress, Hashable, CustomDebugStringConvertible { - /// The IPv4 any address used for listening + /// The IPv4 "any" address used for listening. public static var any: IPv4Address { IPv4Address(UInt32(0x0000_0000).bigEndian) } - /// The IPv4 broadcast address used to broadcast to all hosts + /// The IPv4 broadcast address used to broadcast to all hosts. public static var broadcast: IPv4Address { IPv4Address(UInt32(0xffff_ffff).bigEndian) } - /// The IPv4 loopback address + /// The IPv4 loopback address. public static var loopback: IPv4Address { IPv4Address(UInt32(0x7f00_0001).bigEndian) } - /// Indicates if this IPv4 address is loopback (127.0.0.1) + /// A Boolean value that indicates whether this IPv4 address is the loopback address (127.0.0.1). public var isLoopback: Bool { self == IPv4Address.loopback } - /// Indicates if this IPv4 address is multicast + /// A Boolean value that indicates whether this IPv4 address is a multicast address. public var isMulticast: Bool { let v4WireAddress = self.address let mask = (0xF000_0000 as UInt32).bigEndian @@ -78,7 +78,7 @@ public struct IPv4Address: IPAddress, Hashable, CustomDebugStringConvertible { self.address = rawValue } - /// An IPv4 address as a byte array + /// An IPv4 address as a byte array. public init?(_ bytes: [UInt8]) { guard bytes.count == MemoryLayout.size else { return nil diff --git a/Sources/SwiftNetwork/Endpoint/IPv6Address.swift b/Sources/SwiftNetwork/Endpoint/IPv6Address.swift index 2c8a368..da93328 100644 --- a/Sources/SwiftNetwork/Endpoint/IPv6Address.swift +++ b/Sources/SwiftNetwork/Endpoint/IPv6Address.swift @@ -14,22 +14,24 @@ public struct IPv6Address: IPAddress, Hashable, CustomDebugStringConvertible { - /// IPv6 any address + /// The IPv6 "any" address. public static var any: IPv6Address { IPv6Address((0, 0, 0, 0)) } - /// IPv6 broadcast address + /// The IPv6 broadcast address. public static var broadcast: IPv6Address { IPv6Address((0, 0, 0, 0)) } - /// IPv6 loopback address + /// The IPv6 loopback address. public static var loopback: IPv6Address { IPv6Address((0, 0, 0, UInt32(1).bigEndian)) } - /// Is the loopback address "::1" + /// A Boolean value that indicates whether this is the loopback address. + /// + /// The IPv6 loopback address is `::1`. public var isLoopback: Bool { (self == IPv6Address.loopback) } @@ -78,18 +80,22 @@ public struct IPv6Address: IPAddress, Hashable, CustomDebugStringConvertible { return withUnsafeBytes(of: &addressFirstChunk) { $0[1] & 0xf0 } } - /// Is multicast + /// A Boolean value that indicates whether this is a multicast address. var isMulticast: Bool { var addressFirstChunk = self.address.0 return withUnsafeBytes(of: &addressFirstChunk) { $0[0] == 0xff } } - /// Is an IPv4 mapped address such as "::ffff:1.2.3.4" + /// A Boolean value that indicates whether this is an IPv4-mapped address. + /// + /// For example, `::ffff:1.2.3.4`. var isIPv4Mapped: Bool { Self.isIPv4Mapped(from: address) } - /// For IPv6 addresses that are IPv4 mapped, returns the IPv4 address + /// The IPv4 address for an IPv4-mapped IPv6 address. + /// + /// Returns `nil` if this address isn't IPv4-mapped. var asIPv4: IPv4Address? { guard self.isIPv4Mapped else { return nil @@ -108,7 +114,7 @@ public struct IPv6Address: IPAddress, Hashable, CustomDebugStringConvertible { self.address = tuple } - /// An IPv6 address as a byte array + /// An IPv6 address as a byte array. public init?(_ bytes: [UInt8]) { guard bytes.count == MemoryLayout.size * 4 else { return nil diff --git a/Sources/SwiftNetwork/Endpoint/NetlinkAddress.swift b/Sources/SwiftNetwork/Endpoint/NetlinkAddress.swift index 6771f02..5adfd4f 100644 --- a/Sources/SwiftNetwork/Endpoint/NetlinkAddress.swift +++ b/Sources/SwiftNetwork/Endpoint/NetlinkAddress.swift @@ -23,16 +23,16 @@ internal import os // NetlinkAddress represents sockaddr_nl on Linux struct NetlinkAddress: IPAddress, Hashable, CustomDebugStringConvertible { - /// Indicates if this address is loopback + /// A Boolean value that indicates whether this address is a loopback address. var isLoopback: Bool { false } - /// Indicates if this address is multicast + /// A Boolean value that indicates whether this address is a multicast address. var isMulticast: Bool { // TODO: Extend using nl_groups false } - /// Create IPAddress from raw bytes + /// Creates a Netlink address from raw bytes. init?(_ bytes: [UInt8]) { if bytes.count >= NetlinkAddress.layoutSize { #if os(Linux) diff --git a/Sources/SwiftNetwork/EndpointFlow/EndpointFlow.swift b/Sources/SwiftNetwork/EndpointFlow/EndpointFlow.swift index 64b466c..6b9045a 100644 --- a/Sources/SwiftNetwork/EndpointFlow/EndpointFlow.swift +++ b/Sources/SwiftNetwork/EndpointFlow/EndpointFlow.swift @@ -30,21 +30,21 @@ internal import Synchronization final class EndpointFlow: CustomDebugStringConvertible { - /// Datapath logging + /// State used to emit logs on the data path. public var log = NetworkLoggerState() enum State: Equatable, Sendable { - /// The initial state prior to start + /// The initial state prior to start. case setup - /// Waiting connections have not yet been started, or do not have a viable network + /// Waiting connections haven't yet been started, or don't have a viable network. case waiting(NetworkError) - /// Preparing connections are actively establishing the connection + /// Preparing connections are actively establishing the connection. case preparing - /// Ready connections can send and receive data + /// Ready connections can send and receive data. case ready - /// Failed connections are disconnected and can no longer send or receive data + /// Failed connections are disconnected and can no longer send or receive data. case failed(NetworkError) - /// Cancelled connections have been invalidated by the client and will send no more events + /// Cancelled connections have been invalidated by the client and send no more events. case cancelled public static func == (lhs: State, rhs: State) -> Bool { diff --git a/Sources/SwiftNetwork/Path/Interface.swift b/Sources/SwiftNetwork/Path/Interface.swift index 33ab1d6..2190780 100644 --- a/Sources/SwiftNetwork/Path/Interface.swift +++ b/Sources/SwiftNetwork/Path/Interface.swift @@ -19,35 +19,35 @@ internal import Logging internal import os #endif -/// Interface types represent the underlying media for a network link +/// The type of underlying media for a network link. @_spi(Essentials) @available(Network 0.1.0, *) public enum InterfaceType: Int, Sendable, CaseIterable { - /// A virtual or otherwise unknown interface type + /// A virtual or otherwise unknown interface type. case other = 0 - /// A Wi-Fi link + /// A Wi-Fi link. case wifi = 2 - /// A Cellular link + /// A cellular link. case cellular = 3 - /// A Wired Ethernet link + /// A wired Ethernet link. case wiredEthernet = 4 - /// The Loopback Interface + /// The loopback interface. case loopback = 1 } -/// Interface subtypes represent the underlying media subtype for a network link +/// The subtype of underlying media for a network link. @_spi(Essentials) @available(Network 0.1.0, *) public enum InterfaceSubtype: Int, Sendable, CaseIterable { - /// A virtual or otherwise unknown interface subtype + /// A virtual or otherwise unknown interface subtype. case other = 0 - /// A Wi-Fi Infrastructure subtype + /// A Wi-Fi infrastructure subtype. case wifiInfrastructure = 3 - /// A Wi-Fi AWDL subtype + /// A Wi-Fi AWDL subtype. case wifiAWDL = 4 - /// A Coprocessor subtype + /// A coprocessor subtype. case coprocessor = 6 - /// A Companion subtype + /// A companion subtype. case companion = 7 } diff --git a/Sources/SwiftNetwork/Path/PathProperties.swift b/Sources/SwiftNetwork/Path/PathProperties.swift index 9cc4a8e..086500b 100644 --- a/Sources/SwiftNetwork/Path/PathProperties.swift +++ b/Sources/SwiftNetwork/Path/PathProperties.swift @@ -244,15 +244,15 @@ public struct PathProperties: CustomStringConvertible { static public let fallbackIsOpportunistic = Flags(rawValue: 1 << 33) } - /// Represents the link quality measurement of the link layer network attachment + /// The link quality measurement of the link-layer network attachment. public enum LinkQuality: Sendable { - /// No link quality measurement is available + /// No link quality measurement is available. case unknown - /// Link quality is bad + /// The link quality is minimal. case minimal - /// Link quality is moderate + /// The link quality is moderate. case moderate - /// Link quality is good + /// The link quality is good. case good internal init(_ nw: Int8) { diff --git a/Sources/SwiftNetwork/Protocols/BottomProtocol.swift b/Sources/SwiftNetwork/Protocols/BottomProtocol.swift index 95f43d9..450e745 100644 --- a/Sources/SwiftNetwork/Protocols/BottomProtocol.swift +++ b/Sources/SwiftNetwork/Protocols/BottomProtocol.swift @@ -21,17 +21,19 @@ internal import os // MARK: - Bottom Protocol Adoption -/// Bottom protocols are the bottom of a stack, and only have an upper protocol. +/// Bottom protocols sit at the bottom of a stack and have only an upper protocol. +/// /// Conform to `BottomStreamProtocol` or `BottomDatagramProtocol`. @_spi(ProtocolProvider) @available(Network 0.1.0, *) public protocol BottomProtocolHandler: ~Copyable, OutboundDataHandler { - /// The type of upper protocol (towards the application) that can be attached + /// The type of upper protocol (toward the app) that you can attach. var upper: UpperProtocol { get set } - /// A function called to set up a protocol instance with parameters and endpoints - /// NOTE: Protocols can implement this function to customize behavior + /// Sets up a protocol instance with parameters and endpoints. + /// + /// Protocols can implement this function to customize behavior. func setup( remote: Endpoint?, local: Endpoint?, @@ -39,25 +41,29 @@ public protocol BottomProtocolHandler: ~Copyable, OutboundDataHandler { path: PathProperties? ) throws(NetworkError) - /// A function called when detaching a protocol - /// NOTE: Protocols can implement this function to customize behavior + /// Tears down a protocol when detaching. + /// + /// Protocols can implement this function to customize behavior. func teardown() - /// A function called to request that this protocol initiate its handshake, if any. - /// If not implemented, the protocol will deliver the connected event automatically. - /// NOTE: Protocols can implement this function to customize behavior + /// Requests that this protocol initiate its handshake, if any. + /// + /// If not implemented, the protocol delivers the connected event automatically. + /// Protocols can implement this function to customize behavior. func connect() - /// A function called to request that this protocol gracefully close. - /// NOTE: Protocols can implement this function to customize behavior + /// Requests that this protocol gracefully close. + /// + /// Protocols can implement this function to customize behavior. func disconnect() - /// A function called when the application has sent an event. - /// NOTE: Protocols can implement this function to customize behavior + /// Handles an event the app sent. + /// + /// Protocols can implement this function to customize behavior. func handleApplicationEvent(_ event: ApplicationEvent) #if !NETWORK_EMBEDDED - /// Set the metadata state for this protocol + /// The metadata state for this protocol. var metadata: AbstractProtocolMetadata? { get } #endif } @@ -65,16 +71,16 @@ public protocol BottomProtocolHandler: ~Copyable, OutboundDataHandler { @_spi(ProtocolProvider) @available(Network 0.1.0, *) extension BottomProtocolHandler where Self: ~Copyable { - /// A function to call to indicate to the upper protocol that this protocol is connected. - /// This is only needed if the protocol customizes `connect()` + /// Indicates to the upper protocol that this protocol is connected. + /// + /// Call this only if the protocol customizes `connect()`. public func deliverConnectedEvent() { fromExternal { upper.deliverConnectedEvent(self.reference) } } - /// A function to call to indicate to the upper protocol that this protocol is disconnected, - /// with an error. + /// Indicates to the upper protocol that this protocol is disconnected, with an error. public func deliverDisconnectedEvent(error: NetworkError?) { fromExternal { upper.deliverDisconnectedEvent(self.reference, error: error) @@ -85,7 +91,7 @@ extension BottomProtocolHandler where Self: ~Copyable { @_spi(ProtocolProvider) @available(Network 0.1.0, *) extension BottomProtocolHandler where Self: ~Copyable, UpperProtocol: InboundDataLinkage { - /// A function to call to indicate to the upper protocol that this protocol has data available to read. + /// Indicates to the upper protocol that this protocol has data available to read. public func deliverInboundDataAvailableEvent() { fromExternal { guard isConnected else { return } @@ -93,7 +99,7 @@ extension BottomProtocolHandler where Self: ~Copyable, UpperProtocol: InboundDat } } - /// A function to call to indicate to the upper protocol that this protocol has room available to send. + /// Indicates to the upper protocol that this protocol has room available to send. public func deliverOutboundRoomAvailableEvent() { fromExternal { guard isConnected else { return } @@ -101,7 +107,7 @@ extension BottomProtocolHandler where Self: ~Copyable, UpperProtocol: InboundDat } } - /// A function to call to pass an event to the upper protocol. + /// Passes an event to the upper protocol. public func deliverNetworkProtocolEvent(_ event: NetworkProtocolEvent) { fromExternal { upper.deliverNetworkProtocolEvent( @@ -113,44 +119,50 @@ extension BottomProtocolHandler where Self: ~Copyable, UpperProtocol: InboundDat } } -/// Bottom protocol with an upper stream linkage +/// Bottom protocol with an upper stream linkage. @_spi(ProtocolProvider) @available(Network 0.1.0, *) public protocol BottomStreamProtocol: ~Copyable, BottomProtocolHandler, OutboundStreamHandler where UpperProtocol == InboundStreamLinkage { - /// A function called when the upper protocol is trying to read stream data. - /// NOTE: Protocols can implement this function to customize behavior + /// Returns received stream data to the upper protocol. + /// + /// Protocols can implement this function to customize behavior. mutating func receiveStreamData(minimumBytes: Int, maximumBytes: Int) throws(NetworkError) -> FrameArray? - /// A function called when the upper protocol is trying to check how much stream data can be written - /// NOTE: Protocols can implement this function to customize behavior + /// Returns the number of bytes of stream data that can be written. + /// + /// Protocols can implement this function to customize behavior. mutating func getOutboundStreamDataRoomAvailable() throws(NetworkError) -> Int - /// A function called when the upper protocol is trying to write stream data. - /// NOTE: Protocols can implement this function to customize behavior + /// Sends stream data created by the upper protocol. + /// + /// Protocols can implement this function to customize behavior. mutating func sendStreamData(_ streamData: consuming FrameArray) throws(NetworkError) } -/// Bottom protocol with an upper datagram linkage +/// Bottom protocol with an upper datagram linkage. @_spi(ProtocolProvider) @available(Network 0.1.0, *) public protocol BottomDatagramProtocol: ~Copyable, BottomProtocolHandler, OutboundDatagramHandler where UpperProtocol == InboundDatagramLinkage { - /// A function called when the upper protocol is trying to read datagrams. - /// NOTE: Protocols can implement this function to customize behavior + /// Returns received datagrams to the upper protocol. + /// + /// Protocols can implement this function to customize behavior. mutating func receiveDatagrams(maximumDatagramCount: Int) throws(NetworkError) -> FrameArray? - /// A function called when the upper protocol is trying to get datagram frames to send. - /// NOTE: Protocols can implement this function to customize behavior + /// Returns datagram frames the upper protocol can use to send. + /// + /// Protocols can implement this function to customize behavior. mutating func getDatagramsToSend( maximumDatagramCount: Int, minimumDatagramSize: Int ) throws(NetworkError) -> FrameArray? - /// A function called when the upper protocol is trying to send datagrams. - /// NOTE: Protocols can implement this function to customize behavior + /// Sends datagrams created by the upper protocol. + /// + /// Protocols can implement this function to customize behavior. mutating func sendDatagrams(_ datagrams: consuming FrameArray) throws(NetworkError) } diff --git a/Sources/SwiftNetwork/Protocols/IPProtocol.swift b/Sources/SwiftNetwork/Protocols/IPProtocol.swift index 704707a..4a976fb 100644 --- a/Sources/SwiftNetwork/Protocols/IPProtocol.swift +++ b/Sources/SwiftNetwork/Protocols/IPProtocol.swift @@ -53,11 +53,11 @@ public struct IPProtocol: NetworkProtocol { } public enum Version: UInt8 { - /// Allow any IP version + /// Allows any IP version. case any = 0 - /// Use only IP version 4 (IPv4) + /// Uses only IP version 4 (IPv4). case v4 = 4 - /// Use only IP version 6 (IPv6) + /// Uses only IP version 6 (IPv6). case v6 = 6 } @@ -68,13 +68,13 @@ public struct IPProtocol: NetworkProtocol { } public enum ECN: UInt8 { - /// Non ECN-Capable Transport + /// Non-ECN-capable transport. case nonECT = 0 - /// ECN Capable Transport (0) + /// ECN-capable transport (0). case ect0 = 1 - /// ECN Capable Transport (1) + /// ECN-capable transport (1). case ect1 = 2 - /// Congestion Experienced + /// Congestion experienced. case ce = 3 init(_ rawValue: UInt8) { diff --git a/Sources/SwiftNetwork/Protocols/ManyToManyProtocol.swift b/Sources/SwiftNetwork/Protocols/ManyToManyProtocol.swift index 9783389..735b6e2 100644 --- a/Sources/SwiftNetwork/Protocols/ManyToManyProtocol.swift +++ b/Sources/SwiftNetwork/Protocols/ManyToManyProtocol.swift @@ -21,8 +21,10 @@ internal import os // MARK: - Many-to-Many Protocol Adoption -/// Many-to-many protocols have associated types for flows (that connect to upper protocols) -/// and paths (that connect to lower protocols) +/// A protocol that handles multiple flows over multiple paths. +/// +/// Many-to-many protocols have associated types for flows that connect to upper protocols +/// and paths that connect to lower protocols. @_spi(ProtocolProvider) @available(Network 0.1.0, *) public protocol ManyToManyProtocolHandler: ListenerHandler, LoggableProtocol { @@ -34,7 +36,7 @@ public protocol ManyToManyProtocolHandler: ListenerHandler, LoggableProtocol { var multiplexedFlows: [MultiplexedFlowIdentifier: Flow] { get set } var multiplexingPaths: [MultiplexingPathIdentifier: Path] { get set } - /// Connection-wide calls to implement + // MARK: Connection-wide calls to implement func setup( remote: Endpoint?, local: Endpoint?, @@ -46,7 +48,7 @@ public protocol ManyToManyProtocolHandler: ListenerHandler, LoggableProtocol { func teardown() func handleApplicationEvent(_ event: ApplicationEvent) -> HandleNetworkEventResult - /// Per-flow calls to implement + // MARK: Per-flow calls to implement func setup( flow: MultiplexedFlowIdentifier, remote: Endpoint?, @@ -60,7 +62,7 @@ public protocol ManyToManyProtocolHandler: ListenerHandler, LoggableProtocol { func handleApplicationEvent(flow: MultiplexedFlowIdentifier, event: ApplicationEvent) -> HandleNetworkEventResult func getMetadata

(flow: MultiplexedFlowIdentifier) -> ProtocolMetadata

? where P: NetworkProtocol - /// Per-path events to implement + // MARK: Per-path events to implement func handleConnectedEvent(path: MultiplexingPathIdentifier) func handleDisconnectedEvent(path: MultiplexingPathIdentifier, error: NetworkError?) func handlePathChanged(path pathID: MultiplexingPathIdentifier, event: MultiplexingPathEvent, isPrimary: Bool) @@ -79,7 +81,7 @@ public protocol ManyToManyProtocolHandler: ListenerHandler, LoggableProtocol { ) throws(NetworkError) #endif - /// Helper functions implemented by inheriting either HomogeneousManyToManyProtocolHandler or HeterogenousManyToManyProtocolHandler + // MARK: Helper functions implemented by inheriting either HomogeneousManyToManyProtocolHandler or HeterogeneousManyToManyProtocolHandler mutating func performInitialSetupIfNeeded( remote: Endpoint?, local: Endpoint?, @@ -93,18 +95,16 @@ public protocol ManyToManyProtocolHandler: ListenerHandler, LoggableProtocol { mutating func teardownIfPossible() } -/// `HomogeneousManyToManyProtocolHandler` declares that a many-to-many protocol only supports a single -/// type of flow +/// Declares that a many-to-many protocol supports only a single type of flow. @_spi(ProtocolProvider) @available(Network 0.1.0, *) public protocol HomogeneousManyToManyProtocolHandler: ManyToManyProtocolHandler { } -/// `HeterogenousManyToManyProtocolHandler` allows a many-to-many protocol support a secondary -/// type of flow (such as to handle both stream flows and datagram flows) +/// Allows a many-to-many protocol to support a secondary type of flow, for example, both stream flows and datagram flows. @_spi(ProtocolProvider) @available(Network 0.1.0, *) -public protocol HeterogenousManyToManyProtocolHandler: HeterogenousListenerHandler, ManyToManyProtocolHandler { +public protocol HeterogeneousManyToManyProtocolHandler: HeterogeneousListenerHandler, ManyToManyProtocolHandler { associatedtype SecondaryFlow: MultiplexedFlow var multiplexedSecondaryFlows: [MultiplexedFlowIdentifier: SecondaryFlow] { get set } var secondaryInboundFlowLinkage: SecondaryUpperProtocol { get set } @@ -598,7 +598,7 @@ extension HomogeneousManyToManyProtocolHandler { #endif } -extension HeterogenousManyToManyProtocolHandler { +extension HeterogeneousManyToManyProtocolHandler { fileprivate var hasNoUpperLinkages: Bool { multiplexedFlows.isEmpty && multiplexedSecondaryFlows.isEmpty && inboundFlowLinkage.isDetached } @@ -634,7 +634,7 @@ extension HeterogenousManyToManyProtocolHandler { } } -extension HeterogenousManyToManyProtocolHandler { +extension HeterogeneousManyToManyProtocolHandler { var asSecondaryListener: SecondaryUpperProtocol.PairedLinkage { .init(reference: reference) } public mutating func performInitialSetupIfNeeded( @@ -1063,7 +1063,7 @@ extension ManyToManyDatapathProtocol where Flow.ParentProtocol == Self, Flow: Ou } } -extension HeterogenousManyToManyProtocolHandler +extension HeterogeneousManyToManyProtocolHandler where SecondaryFlow.ParentProtocol == Self, SecondaryFlow: OutboundDatagramHandler { public mutating func attachNewDatagramFlowProtocol( _ from: ProtocolInstanceReference, @@ -1247,7 +1247,7 @@ extension MultiplexedFlow { #endif } -extension MultiplexedFlow where ParentProtocol: HeterogenousManyToManyProtocolHandler { +extension MultiplexedFlow where ParentProtocol: HeterogeneousManyToManyProtocolHandler { public mutating func detach(_ from: ProtocolInstanceReference) throws(NetworkError) { do { try validate(upper: from, #function) } catch { throw NetworkError.posix(EINVAL) } parentProtocol.teardown(flow: identifier) @@ -1527,7 +1527,7 @@ extension ManyToManyApplicationDatagramProtocol where Flow: AutomaticUpperDatagr } } -extension HeterogenousManyToManyProtocolHandler where SecondaryFlow: AutomaticUpperDatagramProcessing { +extension HeterogeneousManyToManyProtocolHandler where SecondaryFlow: AutomaticUpperDatagramProcessing { public func accessDatagramsToSend(flow flowID: MultiplexedFlowIdentifier, _ body: (inout FrameArray) -> Void) { guard var flow = self.secondaryFlow(for: flowID) else { return } body(&flow.upperSendQueue) @@ -1792,7 +1792,7 @@ extension ManyToManyProtocolHandler { } } -extension HeterogenousManyToManyProtocolHandler { +extension HeterogeneousManyToManyProtocolHandler { public func deliverConnectedEvent(flow flowID: MultiplexedFlowIdentifier) { switch flowID { case .allFlows: diff --git a/Sources/SwiftNetwork/Protocols/NetworkEvents.swift b/Sources/SwiftNetwork/Protocols/NetworkEvents.swift index 43a3284..484c032 100644 --- a/Sources/SwiftNetwork/Protocols/NetworkEvents.swift +++ b/Sources/SwiftNetwork/Protocols/NetworkEvents.swift @@ -21,7 +21,7 @@ public struct NetworkEventDomain: Sendable, Hashable, CustomStringConvertible { @_spi(ProtocolProvider) @available(Network 0.1.0, *) -/// An extensible event reported by a lower protocol to upper protocols +/// An extensible event that a lower protocol reports to upper protocols. public struct NetworkProtocolEvent: Sendable, Equatable, CustomStringConvertible { enum InternalEvent: Equatable { case viabilityChanged(viable: Bool) @@ -106,7 +106,7 @@ public struct NetworkProtocolEvent: Sendable, Equatable, CustomStringConvertible @_spi(ProtocolProvider) @available(Network 0.1.0, *) -/// An extensible event from the application, sent from upper protocols to lower protocols +/// An extensible event from the app, sent from upper protocols to lower protocols. public struct ApplicationEvent: Sendable, Equatable, CustomStringConvertible { enum InternalEvent: Equatable { case dataStall diff --git a/Sources/SwiftNetwork/Protocols/OneToOneProtocol.swift b/Sources/SwiftNetwork/Protocols/OneToOneProtocol.swift index 6fab34d..1b0a784 100644 --- a/Sources/SwiftNetwork/Protocols/OneToOneProtocol.swift +++ b/Sources/SwiftNetwork/Protocols/OneToOneProtocol.swift @@ -21,21 +21,22 @@ internal import os // MARK: - One-to-One Protocol Adoption -/// One-to-one protocols are the most basic kinds of protocols that have both -/// an upper and lower protocol. Conform to `OneToOneStreamProtocol`, -/// `OneToOneDatagramProtocol`, or `OneToOneStreamToDatagramProtocol`. +/// The most basic kind of protocol, with both an upper protocol and a lower protocol. +/// +/// Conform to `OneToOneStreamProtocol`, `OneToOneDatagramProtocol`, or `OneToOneStreamToDatagramProtocol`. @_spi(ProtocolProvider) @available(Network 0.1.0, *) public protocol OneToOneProtocolHandler: ~Copyable, OutboundDataHandler, InboundDataHandler, LoggableProtocol { - /// The type of upper protocol (towards the application) that can be attached + /// The type of upper protocol (toward the app) that you can attach. var upper: UpperProtocol { get set } - /// The type of lower protocol (towards the network) that can be attached + /// The type of lower protocol (toward the network) that you can attach. var lower: LowerProtocol { get set } - /// A function called to set up a protocol instance with parameters and endpoints - /// NOTE: Protocols can implement this function to customize behavior + /// Sets up a protocol instance with parameters and endpoints. + /// + /// Protocols can implement this function to customize behavior. mutating func setup( remote: Endpoint?, local: Endpoint?, @@ -43,74 +44,79 @@ public protocol OneToOneProtocolHandler: ~Copyable, OutboundDataHandler, Inbound path: PathProperties? ) throws(NetworkError) - /// A function called when detaching a protocol - /// NOTE: Protocols can implement this function to customize behavior + /// Tears down a protocol when detaching. + /// + /// Protocols can implement this function to customize behavior. mutating func teardown() - /// A function called to request that this protocol initiate its handshake, if any. - /// If not implemented, the protocol will deliver the connected event automatically. - /// NOTE: Protocols can implement this function to customize behavior + /// Requests that this protocol initiate its handshake, if any. + /// + /// If not implemented, the protocol delivers the connected event automatically. + /// Protocols can implement this function to customize behavior. mutating func connect() - /// A function called to request that this protocol gracefully close. - /// NOTE: Protocols can implement this function to customize behavior + /// Requests that this protocol gracefully close. + /// + /// Protocols can implement this function to customize behavior. mutating func disconnect(error: NetworkError?) - /// A function called when the lower protocol has disconnected. - /// NOTE: Protocols can implement this function to customize behavior + /// A function the framework calls when the lower protocol disconnects. + /// + /// Protocols can implement this function to customize behavior. mutating func handleDisconnectedEvent(error: NetworkError?) - /// A function called when some lower protocol has sent an event. - /// Return `.consumed` if the event was handled and should not be passed up to + /// A function the framework calls when a lower protocol sends an event. + /// + /// Returns `.consumed` if the event was handled and shouldn't pass up to /// upper protocols, and `.unconsumed` otherwise. - /// NOTE: Protocols can implement this function to customize behavior + /// Protocols can implement this function to customize behavior. mutating func handleNetworkProtocolEvent(_ event: NetworkProtocolEvent) -> HandleNetworkEventResult - /// A function called when the application has sent an event. - /// Return `.consumed` if the event was handled and should not be passed down to + /// A function the framework calls when the app sends an event. + /// + /// Returns `.consumed` if the event was handled and shouldn't pass down to /// lower protocols, and `.unconsumed` otherwise. - /// NOTE: Protocols can implement this function to customize behavior + /// Protocols can implement this function to customize behavior. mutating func handleApplicationEvent(_ event: ApplicationEvent) -> HandleNetworkEventResult #if !NETWORK_EMBEDDED - /// Set the metadata state for this protocol + /// The metadata state for this protocol. var metadata: AbstractProtocolMetadata? { get } #endif - /// Return true if this protocol does not directly handle any events, but instead only passes through - /// NOTE: Protocols that do not want to handle events should set true initially. - /// The stack may set this to false explicitly, in which case it should not be set back to true. + /// A Boolean value that indicates whether this protocol passes events through without handling them directly. + /// + /// Protocols that don't handle events should initialize this to `true`. + /// The stack may set this to `false` explicitly, after which you shouldn't set it back to `true`. var passthroughEvents: Bool { get set } } @_spi(ProtocolProvider) @available(Network 0.1.0, *) public enum HandleNetworkEventResult { - /// The event was handled and consumed by the protocol, and should not be automatically - /// passed on to the next protocol. + /// The protocol handled and consumed the event, and the system shouldn't automatically pass it on to the next protocol. case consumed - /// The event was not consumed by the protocol, and is allowed to be automatically - /// passed on to the next protocol. + /// The protocol didn't consume the event, and the system can automatically pass it on to the next protocol. case unconsumed } @_spi(ProtocolProvider) @available(Network 0.1.0, *) extension OneToOneProtocolHandler where Self: ~Copyable { - /// A function to call to indicate to the upper protocol that this protocol is connected. - /// This is only needed if the protocol customizes `connect()` + /// Indicates to the upper protocol that this protocol is connected. + /// + /// Call this only if the protocol customizes `connect()`. public func deliverConnectedEvent() { upper.deliverConnectedEvent(self.reference) } - /// A function to call to indicate to the upper protocol that this protocol is disconnected, - /// with an error. + /// Indicates to the upper protocol that this protocol is disconnected, with an error. public func deliverDisconnectedEvent(error: NetworkError?) { upper.deliverDisconnectedEvent(self.reference, error: error) } - /// A function to call to pass an event to the upper protocol. + /// Passes an event to the upper protocol. public func deliverNetworkProtocolEvent(_ event: NetworkProtocolEvent) { upper.deliverNetworkProtocolEvent( originalReference: self.reference, @@ -125,80 +131,93 @@ extension OneToOneProtocolHandler where Self: ~Copyable { public protocol OneToOneDatapathProtocol: ~Copyable, OneToOneProtocolHandler where UpperProtocol: InboundDataLinkage, LowerProtocol: OutboundDataLinkage { - /// A function called when the lower protocol has inbound data available to read. - /// NOTE: Protocols can implement this function to customize behavior + /// A function the framework calls when the lower protocol has inbound data available to read. + /// + /// Protocols can implement this function to customize behavior. mutating func handleInboundDataAvailableEvent() - /// A function called when the lower protocol has outbound room available to sent. - /// NOTE: Protocols can implement this function to customize behavior + /// A function the framework calls when the lower protocol has outbound room available to send. + /// + /// Protocols can implement this function to customize behavior. mutating func handleOutboundRoomAvailableEvent() } -/// One-to-one protocol with an upper stream linkage and a lower stream linkage +/// One-to-one protocol with an upper stream linkage and a lower stream linkage. @_spi(ProtocolProvider) @available(Network 0.1.0, *) public protocol OneToOneStreamProtocol: ~Copyable, OneToOneDatapathProtocol where UpperProtocol == InboundStreamLinkage, LowerProtocol == OutboundStreamLinkage { - /// A function called when the upper protocol is trying to read stream data. - /// NOTE: Protocols can implement this function to customize behavior + /// Returns received stream data to the upper protocol. + /// + /// Protocols can implement this function to customize behavior. mutating func receiveStreamData(minimumBytes: Int, maximumBytes: Int) throws(NetworkError) -> FrameArray? - /// A function called when the upper protocol is trying to check how much stream data can be written - /// NOTE: Protocols can implement this function to customize behavior + /// Returns the number of bytes of stream data that can be written. + /// + /// Protocols can implement this function to customize behavior. mutating func getOutboundStreamDataRoomAvailable() throws(NetworkError) -> Int - /// A function called when the upper protocol is trying to write stream data. - /// NOTE: Protocols can implement this function to customize behavior + /// Sends stream data created by the upper protocol. + /// + /// Protocols can implement this function to customize behavior. mutating func sendStreamData(_ streamData: consuming FrameArray) throws(NetworkError) - /// A function called when the lower protocol has reported that the inbound direction of data has been aborted. - /// NOTE: Protocols can implement this function to customize behavior + /// A function the framework calls when the lower protocol reports that the inbound direction of data is aborted. + /// + /// Protocols can implement this function to customize behavior. mutating func handleInboundAbortedEvent(error: NetworkError?) - /// A function called when the lower protocol has reported that the outbound direction of data has been aborted. - /// NOTE: Protocols can implement this function to customize behavior + /// A function the framework calls when the lower protocol reports that the outbound direction of data is aborted. + /// + /// Protocols can implement this function to customize behavior. mutating func handleOutboundAbortedEvent(error: NetworkError?) } -/// One-to-one protocol with an upper stream linkage and a lower datagram linkage +/// One-to-one protocol with an upper stream linkage and a lower datagram linkage. @_spi(ProtocolProvider) @available(Network 0.1.0, *) public protocol OneToOneStreamToDatagramProtocol: ~Copyable, OneToOneDatapathProtocol where UpperProtocol == InboundStreamLinkage, LowerProtocol == OutboundDatagramLinkage { - /// A function called when the upper protocol is trying to read stream data. - /// NOTE: Protocols can implement this function to customize behavior + /// Returns received stream data to the upper protocol. + /// + /// Protocols can implement this function to customize behavior. mutating func receiveStreamData(minimumBytes: Int, maximumBytes: Int) throws(NetworkError) -> FrameArray? - /// A function called when the upper protocol is trying to check how much stream data can be written - /// NOTE: Protocols can implement this function to customize behavior + /// Returns the number of bytes of stream data that can be written. + /// + /// Protocols can implement this function to customize behavior. mutating func getOutboundStreamDataRoomAvailable() throws(NetworkError) -> Int - /// A function called when the upper protocol is trying to write stream data. - /// NOTE: Protocols can implement this function to customize behavior + /// Sends stream data created by the upper protocol. + /// + /// Protocols can implement this function to customize behavior. mutating func sendStreamData(_ streamData: consuming FrameArray) throws(NetworkError) } -/// One-to-one protocol with an upper datagram linkage and a lower datagram linkage +/// One-to-one protocol with an upper datagram linkage and a lower datagram linkage. @_spi(ProtocolProvider) @available(Network 0.1.0, *) public protocol OneToOneDatagramProtocol: ~Copyable, OneToOneDatapathProtocol where UpperProtocol == InboundDatagramLinkage, LowerProtocol == OutboundDatagramLinkage { - /// A function called when the upper protocol is trying to read datagrams. - /// NOTE: Protocols can implement this function to customize behavior + /// Returns received datagrams to the upper protocol. + /// + /// Protocols can implement this function to customize behavior. mutating func receiveDatagrams(maximumDatagramCount: Int) throws(NetworkError) -> FrameArray? - /// A function called when the upper protocol is trying to get datagram frames to send. - /// NOTE: Protocols can implement this function to customize behavior + /// Returns datagram frames the upper protocol can use to send. + /// + /// Protocols can implement this function to customize behavior. mutating func getDatagramsToSend( maximumDatagramCount: Int, minimumDatagramSize: Int ) throws(NetworkError) -> FrameArray? - /// A function called when the upper protocol is trying to send datagrams. - /// NOTE: Protocols can implement this function to customize behavior + /// Sends datagrams created by the upper protocol. + /// + /// Protocols can implement this function to customize behavior. mutating func sendDatagrams(_ datagrams: consuming FrameArray) throws(NetworkError) } diff --git a/Sources/SwiftNetwork/Protocols/ProtocolControlHandlers.swift b/Sources/SwiftNetwork/Protocols/ProtocolControlHandlers.swift index 8871fb8..f325637 100644 --- a/Sources/SwiftNetwork/Protocols/ProtocolControlHandlers.swift +++ b/Sources/SwiftNetwork/Protocols/ProtocolControlHandlers.swift @@ -12,7 +12,7 @@ // //===----------------------------------------------------------------------===// -/// Upper protocols are protocols that are closer to the application, and have a linkage to a lower protocol (toward the network) +/// A protocol closer to the app, with a linkage to a lower protocol toward the network. @_spi(ProtocolProvider) @available(Network 0.1.0, *) public protocol UpperProtocolHandler: ~Copyable, ProtocolInstance { @@ -119,7 +119,7 @@ extension ProtocolInstanceReference { } -/// Lower protocols are protocols that are closer to the network, and have a linkage to a upper protocol (toward the application) +/// A protocol closer to the network, with a linkage to an upper protocol toward the app. @_spi(ProtocolProvider) @available(Network 0.1.0, *) public protocol LowerProtocolHandler: ~Copyable, ProtocolInstance { diff --git a/Sources/SwiftNetwork/Protocols/ProtocolDatagramHandlers.swift b/Sources/SwiftNetwork/Protocols/ProtocolDatagramHandlers.swift index 10d444d..c30513a 100644 --- a/Sources/SwiftNetwork/Protocols/ProtocolDatagramHandlers.swift +++ b/Sources/SwiftNetwork/Protocols/ProtocolDatagramHandlers.swift @@ -14,55 +14,65 @@ // MARK: Automatic Datagram Processing -/// Add conformance to `AutomaticLowerDatagramProcessing` to automatically send and receive datagrams -/// from lower protocols. +/// A protocol for automatically sending and receiving datagrams with lower protocols. +/// +/// Add conformance to `AutomaticLowerDatagramProcessing` to automatically send and receive +/// datagrams from lower protocols. @_spi(ProtocolProvider) @available(Network 0.1.0, *) public protocol AutomaticLowerDatagramProcessing: ~Copyable, InboundDatagramHandler { var lower: LowerProtocol { get set } - /// A queue of datagrams that will be sent to the lower protocol. - /// NOTE: Protocols generally do not need to access this directly. + /// A queue of datagrams the framework sends to the lower protocol. + /// + /// Protocols generally don't need to access this directly. /// Instead, call `addToLowerSendQueue`. var lowerSendQueue: FrameArray { get set } /// A queue of datagrams that have been received from the lower protocol. - /// NOTE: Protocols should access frames from this queue in response + /// + /// Protocols should access frames from this queue in response /// to the `serviceLowerReceiveQueue` call. var lowerReceiveQueue: FrameArray { get set } - /// A function called when the lower protocol has added datagrams to + /// A function the framework calls when the lower protocol has added datagrams to /// `lowerReceiveQueue`. - /// NOTE: Protocols should implement this function to customize behavior + /// + /// Protocols should implement this function to customize behavior. func serviceLowerReceiveQueue() - /// A function called when there is outbound room available - /// NOTE: Protocols should implement this function to customize behavior + /// A function the framework calls when outbound room becomes available. + /// + /// Protocols should implement this function to customize behavior. func handleOutboundRoomAvailable() } @_spi(ProtocolProvider) @available(Network 0.1.0, *) extension AutomaticLowerDatagramProcessing where Self: ~Copyable { - /// A function to call to add datagrams to `lowerSendQueue` + /// Adds datagrams to the lower send queue. + /// + /// Appends frames to `lowerSendQueue`. public mutating func addToLowerSendQueue(_ datagrams: consuming FrameArray) throws(NetworkError) { lowerSendQueue.add(frames: datagrams) } - /// A function to call to indicate to the lower protocol that datagrams - /// have been added to the `lowerSendQueue`. + /// Indicates to the lower protocol that datagrams have been added to the send queue. + /// + /// Drains `lowerSendQueue` to the lower protocol. public mutating func serviceLowerSendQueue() { guard !lowerSendQueue.isEmpty else { return } try? lower.invokeSendDatagrams(reference, datagrams: lowerSendQueue.drainArray()) } - /// A function to call to indicate that datagrams should be read - /// from the lower protocol. + /// Indicates that datagrams should be read from the lower protocol. public mutating func resumeReadingInboundDatagrams() { _readInboundDatagrams() } } +/// A protocol for automatically processing datagrams from upper protocols. +/// /// Add conformance to `AutomaticUpperDatagramProcessing` to automatically process datagrams /// from upper protocols. @_spi(ProtocolProvider) @@ -71,25 +81,26 @@ public protocol AutomaticUpperDatagramProcessing: ~Copyable, OutboundDatagramHan var upper: UpperProtocol { get set } /// A queue of datagrams that have been sent by the upper protocol. - /// NOTE: Protocols should access frames from this queue in response + /// + /// Protocols should access frames from this queue in response /// to the `serviceUpperSendQueue` call. var upperSendQueue: FrameArray { get set } - /// A function called when the upper protocol has added datagrams to + /// A function the framework calls when the upper protocol has added datagrams to /// `upperSendQueue`. - /// NOTE: Protocols should implement this function to customize behavior + /// + /// Protocols should implement this function to customize behavior. func serviceUpperSendQueue() - /// A value to set to cap the maximum datagram size that the upper protocol - /// will be allowed to send. + /// The maximum datagram size the upper protocol can send. var maximumUpperDatagramSize: Int { get set } - /// A boolean to set if the upper protocol should be blocked from sending - /// datagrams. + /// A Boolean value that indicates whether the upper protocol is blocked from sending datagrams. var blockUpperSendQueue: Bool { get set } - /// A queue of datagrams that will be delivered to the upper protocol. - /// NOTE: Protocols generally do not need to access this directly. + /// A queue of datagrams the framework delivers to the upper protocol. + /// + /// Protocols generally don't need to access this directly. /// Instead, call `addToUpperReceiveQueue`. var upperReceiveQueue: FrameArray { get set } @@ -98,13 +109,16 @@ public protocol AutomaticUpperDatagramProcessing: ~Copyable, OutboundDatagramHan @_spi(ProtocolProvider) @available(Network 0.1.0, *) extension AutomaticUpperDatagramProcessing where Self: ~Copyable { - /// A function to call to add datagrams to `upperReceiveQueue` + /// Adds datagrams to the upper receive queue. + /// + /// Appends frames to `upperReceiveQueue`. public mutating func addToUpperReceiveQueue(_ datagrams: consuming FrameArray) throws(NetworkError) { upperReceiveQueue.add(frames: datagrams) } - /// A function to call to indicate to the upper protocol that datagrams - /// have been added to the `upperReceiveQueue`. + /// Indicates to the upper protocol that datagrams have been added to the receive queue. + /// + /// Notifies the upper protocol that frames are available in `upperReceiveQueue`. public func serviceUpperReceiveQueue() { guard !upperReceiveQueue.isEmpty else { return } upper.deliverInboundDataAvailableEvent(reference) diff --git a/Sources/SwiftNetwork/Protocols/ProtocolInstance.swift b/Sources/SwiftNetwork/Protocols/ProtocolInstance.swift index 179bf74..35d1643 100644 --- a/Sources/SwiftNetwork/Protocols/ProtocolInstance.swift +++ b/Sources/SwiftNetwork/Protocols/ProtocolInstance.swift @@ -26,35 +26,37 @@ internal import os // MARK: Protocol Instance -/// `ProtocolInstance` is the base Swift protocol for any networking protocol instance that -/// can be connected in a stack. Most protocols will conform to either `OneToOneProtocolHandler` -/// or `ManyToManyProtocolHandler`, although protocols that are only the top or bottom of -/// a stack may only conform to `UpperProtocolHandler` or `LowerProtocolHandler`. +/// The base Swift protocol for any networking protocol instance you can connect in a stack. +/// +/// Most protocols conform to either `OneToOneProtocolHandler` +/// or `ManyToManyProtocolHandler`. Protocols that occupy only the top or bottom of +/// a stack conform to `UpperProtocolHandler` or `LowerProtocolHandler`. /// /// For data handling, see `ProtocolDatagramHandlers` and `ProtocolStreamHandlers`. @_spi(ProtocolProvider) @available(Network 0.1.0, *) public protocol ProtocolInstance: ~Copyable { - /// The scheduling context on which the protocol instance must run + /// The scheduling context on which the protocol instance must run. var context: NetworkContext { get } - /// A struct to refer to the protocol instance, and which holds a reference to its containing object + /// A structure that refers to the protocol instance and holds a reference to its containing object. var reference: ProtocolInstanceReference { get } - /// An opaque struct that keeps track of the internal consistency of any protocol. + /// An opaque structure that tracks the internal consistency of any protocol. var eventManager: ProtocolEventManager { get set } } extension ProtocolInstance where Self: ~Copyable { - /// Schedule an asynchronous block from within a protocol implementation + /// Schedules an asynchronous block from within a protocol implementation. public func async(_ block: @escaping () -> Void) { reference.async(block) } - /// Enter a protocol's execution state from an external source. This must be called - /// on the context, and must be called before the protocol invokes any calls to other protocols. + /// Enters a protocol's execution state from an external source. + /// + /// Call this on the context, and call it before the protocol invokes any calls to other protocols. public func fromExternal(_ block: () throws(E) -> R) throws(E) -> R { try reference.fromExternal(block) } @@ -71,11 +73,11 @@ extension ProtocolInstance where Self: ~Copyable { // MARK: Timer Schedulable -/// Indicate that a network protocol can be scheduled using a timer +/// Indicates that a network protocol can be scheduled using a timer. @_spi(ProtocolProvider) @available(Network 0.1.0, *) public protocol TimerSchedulable: ~Copyable, ProtocolInstance { - /// Handle a wakeup from a timer + /// Handles a wakeup from a timer. func wakeup() } @@ -237,8 +239,10 @@ public enum ProtocolInstanceError: Error { // MARK: Protocol Instance Container -/// Conform to `ProtocolInstanceContainer` in order to implement a custom protocol. -/// The index can be used to host multiple protocols within one object. +/// A container that hosts one or more custom protocol implementations. +/// +/// Conform to `ProtocolInstanceContainer` to implement a custom protocol. +/// Use the index to host multiple protocols within one object. @_spi(ProtocolProvider) @available(Network 0.1.0, *) public protocol ProtocolInstanceContainer: AnyObject { diff --git a/Sources/SwiftNetwork/Protocols/ProtocolLinkage.swift b/Sources/SwiftNetwork/Protocols/ProtocolLinkage.swift index 2dac45c..e26f2de 100644 --- a/Sources/SwiftNetwork/Protocols/ProtocolLinkage.swift +++ b/Sources/SwiftNetwork/Protocols/ProtocolLinkage.swift @@ -12,8 +12,9 @@ // //===----------------------------------------------------------------------===// -/// A protocol linkage is a strongly-typed struct that holds a reference to another protocol, -/// and can dispatch functions to it. Each linkage is paired with a linkage that matches it. +/// A strongly typed structure that holds a reference to another protocol and dispatches functions to it. +/// +/// Each linkage is paired with a matching linkage. @_spi(ProtocolProvider) @available(Network 0.1.0, *) public protocol ProtocolLinkage { diff --git a/Sources/SwiftNetwork/Protocols/ProtocolListenerHandlers.swift b/Sources/SwiftNetwork/Protocols/ProtocolListenerHandlers.swift index 5292ced..c9920ba 100644 --- a/Sources/SwiftNetwork/Protocols/ProtocolListenerHandlers.swift +++ b/Sources/SwiftNetwork/Protocols/ProtocolListenerHandlers.swift @@ -126,7 +126,7 @@ where UpperProtocol.DataLinkage == OutboundStreamLinkage { @_spi(ProtocolProvider) @available(Network 0.1.0, *) -public protocol HeterogenousListenerHandler: ~Copyable, ListenerHandler { +public protocol HeterogeneousListenerHandler: ~Copyable, ListenerHandler { associatedtype SecondaryUpperProtocol: InboundFlowLinkage } diff --git a/Sources/SwiftNetwork/Protocols/ProtocolStreamHandlers.swift b/Sources/SwiftNetwork/Protocols/ProtocolStreamHandlers.swift index b6da579..8d4b7e8 100644 --- a/Sources/SwiftNetwork/Protocols/ProtocolStreamHandlers.swift +++ b/Sources/SwiftNetwork/Protocols/ProtocolStreamHandlers.swift @@ -21,51 +21,60 @@ internal import os // MARK: Automatic Stream Processing -/// Add conformance to `AutomaticLowerStreamProcessing` to automatically send and receive stream data -/// from lower protocols. +/// A protocol for automatically sending and receiving stream data with lower protocols. +/// +/// Add conformance to `AutomaticLowerStreamProcessing` to automatically send and receive +/// stream data from lower protocols. @_spi(ProtocolProvider) @available(Network 0.1.0, *) public protocol AutomaticLowerStreamProcessing: ~Copyable, InboundStreamHandler { var lower: LowerProtocol { get set } - /// A queue of stream data that will be sent to the lower protocol. - /// NOTE: Protocols generally do not need to access this directly. + /// A queue of stream data the framework sends to the lower protocol. + /// + /// Protocols generally don't need to access this directly. /// Instead, call `addToLowerSendQueue`. var lowerSendQueue: FrameArray { get set } /// A queue of datagrams that have been received from the lower protocol. - /// NOTE: Protocols should access frames from this queue in response + /// + /// Protocols should access frames from this queue in response /// to the `serviceLowerReceiveQueue` call. var lowerReceiveQueue: FrameArray { get set } - /// A function called when the lower protocol has added stream data to + /// A function the framework calls when the lower protocol has added stream data to /// `lowerReceiveQueue`. - /// NOTE: Protocols should implement this function to customize behavior + /// + /// Protocols should implement this function to customize behavior. func serviceLowerReceiveQueue() } @_spi(ProtocolProvider) @available(Network 0.1.0, *) extension AutomaticLowerStreamProcessing where Self: ~Copyable { - /// A function to call to add stream data to `lowerSendQueue` + /// Adds stream data to the lower send queue. + /// + /// Appends frames to `lowerSendQueue`. public mutating func addToLowerSendQueue(_ streamData: consuming FrameArray) throws(NetworkError) { lowerSendQueue.add(frames: streamData) } - /// A function to call to indicate to the lower protocol that stream data - /// has been added to the `lowerSendQueue`. + /// Indicates to the lower protocol that stream data has been added to the send queue. + /// + /// Drains `lowerSendQueue` to the lower protocol. public mutating func serviceLowerSendQueue() { guard !lowerSendQueue.isEmpty else { return } try? lower.invokeSendStreamData(reference, streamData: lowerSendQueue.drainArray()) } - /// A function to call to indicate that stream data should be read - /// from the lower protocol. + /// Indicates that stream data should be read from the lower protocol. public mutating func resumeReadingInboundStreamData() { _readInboundStreamData() } } +/// A protocol for automatically processing stream data from upper protocols. +/// /// Add conformance to `AutomaticUpperStreamProcessing` to automatically process stream data /// from upper protocols. @_spi(ProtocolProvider) @@ -74,44 +83,51 @@ public protocol AutomaticUpperStreamProcessing: ~Copyable, OutboundStreamHandler var upper: UpperProtocol { get set } /// A queue of stream data that has been sent by the upper protocol. - /// NOTE: Protocols should access frames from this queue in response + /// + /// Protocols should access frames from this queue in response /// to the `serviceUpperSendQueue` call. var upperSendQueue: FrameArray { get set } - /// A function called when the upper protocol has added stream data to + /// A function the framework calls when the upper protocol has added stream data to /// `upperSendQueue`. - /// NOTE: Protocols should implement this function to customize behavior + /// + /// Protocols should implement this function to customize behavior. func serviceUpperSendQueue() - /// A value to set to cap the maximum amount of stream data that is allowed - /// to be pending in the `upperSendQueue`. + /// The maximum amount of stream data allowed to be pending in the upper send queue. + /// + /// Caps the total bytes pending in `upperSendQueue`. var maximumStreamDataSize: Int { get set } - /// A boolean to set if the upper protocol should be blocked from sending - /// stream data. + /// A Boolean value that indicates whether the upper protocol is blocked from sending stream data. var blockUpperSendQueue: Bool { get set } - /// A queue of stream data that will be delivered to the upper protocol. - /// NOTE: Protocols generally do not need to access this directly. + /// A queue of stream data the framework delivers to the upper protocol. + /// + /// Protocols generally don't need to access this directly. /// Instead, call `addToUpperReceiveQueue`. var upperReceiveQueue: FrameArray { get set } - /// A function called when the upper protocol has read stream data out of + /// A function the framework calls when the upper protocol has read stream data out of /// `upperReceiveQueue`. - /// NOTE: Protocols can implement this function to customize behavior + /// + /// Protocols can implement this function to customize behavior. mutating func upperReceiveQueueDrainedBytes(_ bytes: Int) } @_spi(ProtocolProvider) @available(Network 0.1.0, *) extension AutomaticUpperStreamProcessing where Self: ~Copyable { - /// A function to call to add stream data to `upperReceiveQueue` + /// Adds stream data to the upper receive queue. + /// + /// Appends frames to `upperReceiveQueue`. public mutating func addToUpperReceiveQueue(_ streamData: consuming FrameArray) throws(NetworkError) { upperReceiveQueue.add(frames: streamData) } - /// A function to call to indicate to the upper protocol that stream data - /// has been added to the `upperReceiveQueue`. + /// Indicates to the upper protocol that stream data has been added to the receive queue. + /// + /// Notifies the upper protocol that frames are available in `upperReceiveQueue`. public func serviceUpperReceiveQueue() { guard !upperReceiveQueue.isEmpty else { return } upper.deliverInboundDataAvailableEvent(reference) diff --git a/Sources/SwiftNetwork/Protocols/TopProtocol.swift b/Sources/SwiftNetwork/Protocols/TopProtocol.swift index 19c8f6e..4a3f98a 100644 --- a/Sources/SwiftNetwork/Protocols/TopProtocol.swift +++ b/Sources/SwiftNetwork/Protocols/TopProtocol.swift @@ -21,25 +21,29 @@ internal import os // MARK: - Top Protocol Adoption -/// Top protocols are the Top of a stack, and only have an lower protocol. +/// Top protocols sit at the top of a stack and have only a lower protocol. +/// /// Conform to `TopStreamProtocol` or `TopDatagramProtocol`. @_spi(ProtocolProvider) @available(Network 0.1.0, *) public protocol TopProtocolHandler: ~Copyable, InboundDataHandler { - /// The type of lower protocol (towards the network) that can be attached + /// The type of lower protocol (toward the network) that you can attach. var lower: LowerProtocol { get set } - /// A function called when the lower protocol has connected. - /// NOTE: Protocols can implement this function to customize behavior + /// A function the framework calls when the lower protocol connects. + /// + /// Protocols can implement this function to customize behavior. func handleConnectedEvent() - /// A function called when the lower protocol has disconnected. - /// NOTE: Protocols can implement this function to customize behavior + /// A function the framework calls when the lower protocol disconnects. + /// + /// Protocols can implement this function to customize behavior. func handleDisconnectedEvent(error: NetworkError?) - /// A function called when some lower protocol has sent an event. - /// NOTE: Protocols can implement this function to customize behavior + /// A function the framework calls when a lower protocol sends an event. + /// + /// Protocols can implement this function to customize behavior. func handleNetworkProtocolEvent(_ event: NetworkProtocolEvent) } @@ -47,33 +51,35 @@ public protocol TopProtocolHandler: ~Copyable, InboundDataHandler { @available(Network 0.1.0, *) public protocol TopDatapathProtocol: ~Copyable, TopProtocolHandler where LowerProtocol: OutboundDataLinkage { - /// A function called when the lower protocol has inbound data available to read. - /// NOTE: Protocols can implement this function to customize behavior + /// A function the framework calls when the lower protocol has inbound data available to read. + /// + /// Protocols can implement this function to customize behavior. func handleInboundDataAvailableEvent() - /// A function called when the lower protocol has outbound room available to sent. - /// NOTE: Protocols can implement this function to customize behavior + /// A function the framework calls when the lower protocol has outbound room available to send. + /// + /// Protocols can implement this function to customize behavior. func handleOutboundRoomAvailableEvent() } @_spi(ProtocolProvider) @available(Network 0.1.0, *) extension TopProtocolHandler where Self: ~Copyable { - /// A function to call to indicate to request the lower protocol to start connecting. + /// Requests that the lower protocol start connecting. public func invokeConnect() { fromExternal { lower.invokeConnect(self.reference) } } - /// A function to call to indicate to request the lower protocol to disconnect. + /// Requests that the lower protocol disconnect. public func invokeDisconnect(error: NetworkError?) { fromExternal { lower.invokeDisconnect(self.reference, error: error) } } - /// A function to call to indicate to detach the lower protocol. + /// Detaches the lower protocol. public mutating func invokeDetach() throws(NetworkError) { try fromExternal { () throws(NetworkError) in try lower.invokeDetach(self.reference) @@ -81,14 +87,14 @@ extension TopProtocolHandler where Self: ~Copyable { lower = .init(reference: .init()) } - /// A function to call to signal an application-level event to lower protocols. + /// Signals an application-level event to lower protocols. public func invokeApplicationEvent(_ event: ApplicationEvent) { fromExternal { lower.invokeApplicationEvent(self.reference, event: event) } } - /// A function to call to access protocol metadata from a lower protocol. + /// Accesses protocol metadata from a lower protocol. public func invokeGetMetadata() -> ProtocolMetadata

? { fromExternal { lower.invokeGetMetadata(self.reference) @@ -97,45 +103,47 @@ extension TopProtocolHandler where Self: ~Copyable { } } -/// Top protocol with an upper stream linkage +/// Top protocol with a lower stream linkage. @_spi(ProtocolProvider) @available(Network 0.1.0, *) public protocol TopStreamProtocol: ~Copyable, TopDatapathProtocol, InboundStreamHandler where LowerProtocol == OutboundStreamLinkage { - /// A function called when the lower protocol sent an event that inbound stream data is aborted. - /// NOTE: Protocols can implement this function to customize behavior + /// A function the framework calls when the lower protocol reports that inbound stream data is aborted. + /// + /// Protocols can implement this function to customize behavior. func handleInboundAbortedEvent(error: NetworkError?) - /// A function called when the lower protocol sent an event that outbound stream data is aborted. - /// NOTE: Protocols can implement this function to customize behavior + /// A function the framework calls when the lower protocol reports that outbound stream data is aborted. + /// + /// Protocols can implement this function to customize behavior. func handleOutboundAbortedEvent(error: NetworkError?) } @_spi(ProtocolProvider) @available(Network 0.1.0, *) extension TopStreamProtocol where Self: ~Copyable { - /// A function to receive stream data from the lower protocol. + /// Receives stream data from the lower protocol. public func invokeReceiveStreamData(minimumBytes: Int, maximumBytes: Int) throws(NetworkError) -> FrameArray? { try fromExternal { () throws(NetworkError) in try lower.invokeReceiveStreamData(self.reference, minimumBytes: minimumBytes, maximumBytes: maximumBytes) } } - /// A function to check how much stream data may be sent to the lower protocol. + /// Returns the number of bytes of stream data you can send to the lower protocol. public func invokeGetOutboundStreamDataRoomAvailable() throws(NetworkError) -> Int { try fromExternal { () throws(NetworkError) in try lower.invokeGetOutboundStreamDataRoomAvailable(self.reference) } } - /// A function to send stream data to the lower protocol. + /// Sends stream data to the lower protocol. public func invokeSendStreamData(_ streamData: consuming FrameArray) throws(NetworkError) { try fromExternal(streamData) { streamData throws(NetworkError) in try lower.invokeSendStreamData(self.reference, streamData: streamData) } } - /// A function to send early stream data to the lower protocol. + /// Sends early stream data to the lower protocol. public func invokeSendEarlyStreamData(_ streamData: consuming FrameArray) throws(NetworkError) { try fromExternal(streamData) { streamData throws(NetworkError) in try lower.invokeSendEarlyStreamData(self.reference, streamData: streamData) @@ -143,7 +151,7 @@ extension TopStreamProtocol where Self: ~Copyable { } } -/// Top protocol with an upper datagram linkage +/// Top protocol with a lower datagram linkage. @_spi(ProtocolProvider) @available(Network 0.1.0, *) public protocol TopDatagramProtocol: ~Copyable, TopDatapathProtocol, InboundDatagramHandler @@ -154,14 +162,14 @@ where LowerProtocol == OutboundDatagramLinkage { @_spi(ProtocolProvider) @available(Network 0.1.0, *) extension TopDatagramProtocol where Self: ~Copyable, Self: ~Copyable { - /// A function to receive datagrams from the lower protocol. + /// Receives datagrams from the lower protocol. public func invokeReceiveDatagrams(maximumDatagramCount: Int) throws(NetworkError) -> FrameArray? { try fromExternal { () throws(NetworkError) in try lower.invokeReceiveDatagrams(self.reference, maximumDatagramCount: maximumDatagramCount) } } - /// A function to get datagram memory to write into from the lower protocol. + /// Returns datagram memory you can write into, from the lower protocol. public func invokeGetDatagramsToSend( maximumDatagramCount: Int, minimumDatagramSize: Int @@ -175,7 +183,9 @@ extension TopDatagramProtocol where Self: ~Copyable, Self: ~Copyable { } } - /// A function to send datagrams previously retrieved with `invokeGetDatagramsToSend`. + /// Sends previously retrieved datagrams to the lower protocol. + /// + /// Sends datagrams previously retrieved with `invokeGetDatagramsToSend`. public func invokeSendDatagrams(_ datagrams: consuming FrameArray) throws(NetworkError) { try fromExternal(datagrams) { datagrams throws(NetworkError) in try lower.invokeSendDatagrams(self.reference, datagrams: datagrams) diff --git a/Sources/SwiftNetwork/QUIC/ECN.swift b/Sources/SwiftNetwork/QUIC/ECN.swift index 8c87897..21d116f 100644 --- a/Sources/SwiftNetwork/QUIC/ECN.swift +++ b/Sources/SwiftNetwork/QUIC/ECN.swift @@ -27,31 +27,41 @@ internal import os #endif enum ECNState { - /// App explicitly asked to disable ECN + /// The app explicitly asked to disable ECN. case disabled - /// Send 10 packets marked with ECT(0) or ECT(1) and move to validate + /// Sends a probe burst, then moves to the validate state. + /// + /// Sends 10 packets marked with `ECT(0)` or `ECT(1)`, then moves to the validate state. case probing - /// During probing, we reach this state if 1 or more packets have been successfully validated. - /// Used in establishment report to provide ECN state (before we have a chance to send 10 packets). + /// Indicates that one or more packets have been successfully validated during probing. + /// + /// The establishment report uses this state to report ECN status before 10 packets have been sent. case handshakeValidationSuccess - /// Optimistically send ECN capable packets in this state. - /// On receiving ACK_ECN, if validation succeeds: move to capable, else: move to failed. + /// Optimistically sends ECN-capable packets in this state. + /// + /// On receiving `ACK_ECN`, moves to capable if validation succeeds; otherwise, moves to failed. case validate - /// Validation succeeded, always send ECT(0) or ECT(1) packets in this state. - /// Continue validating on each received ACK_ECN. If validation fails, go to failed state. + /// Validation succeeded. + /// + /// Always sends `ECT(0)` or `ECT(1)` packets in this state. + /// Continues validating on each received `ACK_ECN`. If validation fails, transitions to the failed state. case capable - /// Either we disabled ECN or validation failed + /// Either ECN is disabled or validation failed. case unsupported - /// Packets sent with ECN were dropped. This state is propagated to establishment report. + /// Indicates that packets sent with ECN were dropped. + /// + /// The establishment report receives this state. case blackholed - /// Once we are in validate, mangling is detected if all sent packets were marked with CE + /// Indicates that mangling was detected. + /// + /// Once in the validate state, the system detects mangling if all sent packets are marked with CE. case manglingDetected var shouldNotUseECN: Bool { diff --git a/Sources/SwiftNetwork/QUIC/Prague.swift b/Sources/SwiftNetwork/QUIC/Prague.swift index 4202b61..655a6fc 100644 --- a/Sources/SwiftNetwork/QUIC/Prague.swift +++ b/Sources/SwiftNetwork/QUIC/Prague.swift @@ -27,13 +27,11 @@ internal import Logging internal import os #endif -/// RTT independence control type +/// Indicates the RTT independence control type. enum RTTControlType: UInt8 { - /// Trade off some throughput balance at very low RTTs for scalability, - /// i.e. to get non-zero marks per RTT + /// Trades off some throughput balance at very low RTTs for scalability — that is, to get non-zero marks per RTT. case balanceRateScalable - /// Get near perfect throughput equivalence at the cost of losing - /// scalability for very low RTTs + /// Gets near-perfect throughput equivalence at the cost of losing scalability for very low RTTs. case rateEquivalence } @@ -88,12 +86,17 @@ struct Prague: CongestionControlProtocol, CubicLikeProtocol { private var reducedDueToCE = false private var rttControl: RTTControlType = .rateEquivalence - /// Largest sent PN set at the start of the round for alpha; - /// different from the common state that tracks round for CWR + /// The largest sent packet number set at the start of the round for alpha. + /// + /// Differs from the common state, which tracks the round for CWR. private var largestSentPNForAlpha: Int64 = 0 - /// Scaled value of DCTCP.alpha + /// The scaled value of the DCTCP alpha. + /// + /// Stores the scaled `DCTCP.alpha`. private var scaledAlpha: UInt64 = 0 - /// AI.alpha used after CE for additive increase + /// The additive-increase alpha used after CE. + /// + /// Stores the `AI.alpha` value used after CE for additive increase. private var alphaAI: UInt64 = 0 // Local link congestion info @@ -133,10 +136,12 @@ struct Prague: CongestionControlProtocol, CubicLikeProtocol { logState(qlog: qlog, state: .slowStart, trigger: nil) } - /// K is the time period(s) that W_cubic(t) function takes to increase - /// the current window size to W_max if there are no further - /// congestion events. Compute the cubic K using, - /// K = cubic_root(W_max(1-ß)/C) + /// Computes the cubic K factor for the current congestion window. + /// + /// `K` is the time period(s) that the `W_cubic(t)` function takes to increase + /// the current window size to `W_max` if there are no further + /// congestion events. Computes the cubic `K` using + /// `K = cubic_root(W_max(1-ß)/C)`. private mutating func setCubicK(mss: Int) { guard cubicMaxCongestionWindow != 0 else { cubicK = 0 @@ -198,7 +203,7 @@ struct Prague: CongestionControlProtocol, CubicLikeProtocol { ) } - /// Handle an ACK in congestion avoidance phase after packet loss + /// Handles an ACK in the congestion-avoidance phase after packet loss. private mutating func cubicProcessAckCA( bytesAcked: UInt64, smoothedRTT: NetworkDuration, @@ -238,9 +243,10 @@ struct Prague: CongestionControlProtocol, CubicLikeProtocol { } } - /// RTT independence using square of RTT ratio to achieve rate fairness. - /// Note that this loses scalable marking (1 or 2 marks per RTT) for low RTT. - /// For additive increase, alpha = (RTT / REF_RTT) ^ 2 + /// Computes RTT independence using the square of the RTT ratio to achieve rate fairness. + /// + /// Note that this loses scalable marking (one or two marks per RTT) for low RTT. + /// For additive increase, `alpha = (RTT / REF_RTT) ^ 2`. private mutating func pragueAIAlphaRate(sRTT: NetworkDuration) { if sRTT > Prague.referenceRTTRate { alphaAI = 1 << Prague.congestionWindowShift @@ -255,8 +261,9 @@ struct Prague: CongestionControlProtocol, CubicLikeProtocol { alphaAI = (numer + (divisor >> 1)) / divisor } - /// Achieve a balance between throughput equivalence and scalable marking every RTT. - /// For additive increase, alpha = C * lg(R/R0+2) / lg(R0/R+2) + /// Achieves a balance between throughput equivalence and scalable marking every RTT. + /// + /// For additive increase, `alpha = C * lg(R/R0+2) / lg(R0/R+2)`. private mutating func pragueAIAlphaScalable(sRTT: NetworkDuration) { // If we don't have a SRTT, set to 1 if sRTT == .zero { @@ -278,7 +285,7 @@ struct Prague: CongestionControlProtocol, CubicLikeProtocol { #endif } - /// Handle an ACK in congestion avoidance phase after the decrease happened due to CE + /// Handles an ACK in the congestion-avoidance phase after the decrease caused by CE. private mutating func pragueCAAfterCE(bytesAcked: UInt64, mss: Int) { var increase = bytesAcked * UInt64(mss) * alphaAI increase = (increase + (congestionWindow >> 1)) / congestionWindow @@ -356,7 +363,7 @@ struct Prague: CongestionControlProtocol, CubicLikeProtocol { logState(qlog: qlog, state: .recovery, trigger: nil) } - /// An ACK was received with new CE counts, enter CWR and stay for 1 RTT. + /// Enters CWR for one RTT after receiving an ACK with new CE counts. private mutating func pragueCWR( largestAckedSentTime: NetworkClock.Instant, mss: Int, @@ -391,8 +398,7 @@ struct Prague: CongestionControlProtocol, CubicLikeProtocol { logState(qlog: qlog, state: .cwr, trigger: nil) } - /// Call only if some AQM is present on the path and with - /// non-zero values for new_packets_acked and new_packets_marked + /// Updates alpha after receiving acknowledgments. private mutating func pragueUpdateAlpha( largestSentPN: Int64, largestAckedPN: Int64, diff --git a/Sources/SwiftNetwork/QUIC/Protector.swift b/Sources/SwiftNetwork/QUIC/Protector.swift index 1f36dd2..b47d0b1 100644 --- a/Sources/SwiftNetwork/QUIC/Protector.swift +++ b/Sources/SwiftNetwork/QUIC/Protector.swift @@ -771,10 +771,11 @@ struct Protector: ~Copyable, PrefixedLoggable { swap(&readFramer[keyState.rawValue], &writeFramer[keyState.rawValue]) } - /// Prepare a nonce from the given iv bytes + /// Prepares a nonce from the given IV bytes. /// - /// Parameters: - /// - nonce: must have nonce.byteCount == iv.byteCount + /// - Parameters: + /// - iv: The IV used to derive the nonce. + /// - packetNumber: The packet number XOR'd into the right side of the IV. @inline(__always) private static func prepareNonce( iv: ProtectorIV, @@ -1422,8 +1423,9 @@ extension MutableRawSpan { } extension Array where Element == UInt8 { - /// Copy of the bytes of the given raw span into this array. The span - /// must have exactly count bytes in it. + /// Copies the bytes of the given raw span into this array. + /// + /// The span must contain exactly `count` bytes. init(copying bytes: RawSpan) { self.init(unsafeUninitializedCapacity: bytes.byteCount) { buffer, initializedCount in for i in 0.., parentProtocol.handleStreamClose(stream: self, error: errorCode) } - /// Application error code for the inbound (receive) direction, used for STOP_SENDING. + /// The application error code for the inbound (receive) direction. + /// + /// Used for the `STOP_SENDING` frame. var inboundApplicationError: UInt64? - /// Application error code for the outbound (send) direction, used for RESET_STREAM. + /// The application error code for the outbound (send) direction. + /// + /// Used for the `RESET_STREAM` frame. var outboundApplicationError: UInt64? public func abortOutbound(error: NetworkError?) { diff --git a/Sources/SwiftNetwork/QUIC/QUICUtilities.swift b/Sources/SwiftNetwork/QUIC/QUICUtilities.swift index 55c4689..e4503bc 100644 --- a/Sources/SwiftNetwork/QUIC/QUICUtilities.swift +++ b/Sources/SwiftNetwork/QUIC/QUICUtilities.swift @@ -176,11 +176,11 @@ public struct QUICConnectionUtilities { ) } - /// Given a token and a length, create a Stateless Reset packet + /// Creates a stateless reset packet from the given token and length. /// /// - Parameters: - /// - token: The stateless reset token to send - /// - triggeringPacketLength: The size of the packet that cause this stateless reset token to be sent + /// - token: The stateless reset token to send. + /// - triggeringPacketLength: The size of the packet that caused this stateless reset token to be sent. public static func createStatelessResetPacket( token: QUICStatelessResetToken, triggeringPacketLength: Int diff --git a/Sources/SwiftNetwork/System/Darwin/DarwinInterface.swift b/Sources/SwiftNetwork/System/Darwin/DarwinInterface.swift index 9bda8eb..4033600 100644 --- a/Sources/SwiftNetwork/System/Darwin/DarwinInterface.swift +++ b/Sources/SwiftNetwork/System/Darwin/DarwinInterface.swift @@ -19,7 +19,7 @@ internal import os import Darwin #endif -/// Set of Darwin system APIs for interacting with the system interface +/// A set of Darwin system APIs for interacting with the system interface. internal enum SystemInterface { enum Constants { @@ -40,7 +40,9 @@ internal enum SystemInterface { static let IFF_RUNNING: UInt32 = 0x0000_0040 } - /// Get MTU from the interface using ioctl + /// Gets the MTU from the interface. + /// + /// Uses `ioctl` to fetch the value. static func interfaceGetMTU(socket: Int32, name: String) throws -> Int { if name.isEmpty { return 65535 @@ -61,7 +63,9 @@ internal enum SystemInterface { } } - /// Check to see if an interface has a specific flag. For example, UP,RUNNING,BROADFAST,MULTICAST + /// Returns a Boolean value that indicates whether an interface has a specific flag. + /// + /// For example, `UP`, `RUNNING`, `BROADCAST`, or `MULTICAST`. static func interfaceHasFlag(socket: Int32, name: String, flag: Interface.Details.Flags) throws -> Bool { if name.isEmpty { return false @@ -94,7 +98,7 @@ internal enum SystemInterface { } } - /// Get functional type flags for the interface + /// Returns the functional type flags for the interface. static func getFunctionalType(socket: Int32, name: String) throws -> UInt32 { if name.isEmpty { return 0 @@ -115,7 +119,7 @@ internal enum SystemInterface { } } - /// Get all of the interface flags for a specified interface + /// Returns all of the interface flags for the specified interface. static func interfaceGetInterfaceFlags(socket: Int32, name: String) throws -> UInt32 { if name.isEmpty { return 0 @@ -136,7 +140,7 @@ internal enum SystemInterface { return UInt32(interfaceFlags) } } - /// Get all of the interface type for a specified interface + /// Returns the interface type for the specified interface. static func interfaceGetInterfaceType(socket: Int32, name: String) throws -> InterfaceType { var interfaceType = InterfaceType.other // Check for interface type using SIOCGIFFUNCTIONALTYPE @@ -153,7 +157,7 @@ internal enum SystemInterface { return interfaceType } - /// Get interface sub type + /// Returns the interface subtype. static func interfaceGetInterfaceSubType(socket: Int32, name: String) throws -> InterfaceSubtype { var interfaceSubtype = InterfaceSubtype.other if socket == 0 { @@ -172,7 +176,7 @@ internal enum SystemInterface { return interfaceSubtype } - /// Get interface name from index + /// Returns the interface name from the index. static func interfaceGetNameFromIndex(index: UInt32) throws -> String? { guard index > 0 else { Logger.interface.error("Invalid index for interface: 0") diff --git a/Sources/SwiftNetwork/System/Darwin/DarwinResources.swift b/Sources/SwiftNetwork/System/Darwin/DarwinResources.swift index 299d535..3a73828 100644 --- a/Sources/SwiftNetwork/System/Darwin/DarwinResources.swift +++ b/Sources/SwiftNetwork/System/Darwin/DarwinResources.swift @@ -15,7 +15,7 @@ #if (!os(Linux) || (!NETWORK_PRIVATE && canImport(Darwin))) && !NETWORK_EMBEDDED import Darwin -/// Set of Darwin system APIs for interacting with the system resources +/// A set of Darwin system APIs for interacting with the system resources. internal enum SystemResources { static func getFDLimit() -> UInt64 { diff --git a/Sources/SwiftNetwork/System/Darwin/DarwinRoute.swift b/Sources/SwiftNetwork/System/Darwin/DarwinRoute.swift index 7fc9754..94b00cb 100644 --- a/Sources/SwiftNetwork/System/Darwin/DarwinRoute.swift +++ b/Sources/SwiftNetwork/System/Darwin/DarwinRoute.swift @@ -57,7 +57,7 @@ public let RTA_IFP: Int32 = 0x10 public let RTA_DST: Int32 = 0x1 public let RTF_IFSCOPE: Int32 = 0x1000000 -/// Set of Darwin system APIs for interacting with the system interface +/// A set of Darwin system APIs for interacting with the system interface. internal enum SystemRoute { static func routeGetInterfaceIndex(dst: any IPAddress, scopedIndex: UInt32 = 0) throws -> UInt32 { diff --git a/Sources/SwiftNetwork/System/Embedded/EmbeddedInterface.swift b/Sources/SwiftNetwork/System/Embedded/EmbeddedInterface.swift index 476b702..165e9fd 100644 --- a/Sources/SwiftNetwork/System/Embedded/EmbeddedInterface.swift +++ b/Sources/SwiftNetwork/System/Embedded/EmbeddedInterface.swift @@ -14,40 +14,44 @@ #if (NETWORK_EMBEDDED || NETWORK_STANDALONE) && !NETWORK_DRIVERKIT -/// Set of Embedded system APIs for interacting with the system interface +/// A set of embedded system APIs for interacting with the system interface. internal enum SystemInterface { - /// Get MTU from the intereface using ioctl + /// Gets the MTU from the interface. + /// + /// Uses `ioctl` to fetch the value. static func interfaceGetMTU(socket: Int32, name: String) throws -> Int { 1500 } - /// Check to see if an interface has a specific flag. For exampe, UP,RUNNING,BROADFAST,MULTICAST + /// Returns a Boolean value that indicates whether an interface has a specific flag. + /// + /// For example, `UP`, `RUNNING`, `BROADCAST`, or `MULTICAST`. static func interfaceHasFlag(socket: Int32, name: String, flag: Interface.Details.Flags) throws -> Bool { false } - /// Get functional type flags for the interface + /// Returns the functional type flags for the interface. static func getFunctionalType(socket: Int32, name: String) throws -> UInt32 { 0 } - /// Get all of the interface flags for a specified interface + /// Returns all of the interface flags for the specified interface. static func interfaceGetInterfaceFlags(socket: Int32, name: String) throws -> UInt32 { 0 } - /// Get all of the interface type for a specified interface + /// Returns the interface type for the specified interface. static func interfaceGetInterfaceType(socket: Int32, name: String) throws -> InterfaceType { .loopback } - /// Get interface sub type + /// Returns the interface subtype. static func interfaceGetInterfaceSubType(socket: Int32, name: String) throws -> InterfaceSubtype { .wifiInfrastructure } - /// Get interface name from index + /// Returns the interface name from the index. static func interfaceGetNameFromIndex(index: UInt32) throws -> String? { String("BogusInterface") } diff --git a/Sources/SwiftNetwork/System/Linux/LinuxInterface.swift b/Sources/SwiftNetwork/System/Linux/LinuxInterface.swift index 7b5d5c0..bb66768 100644 --- a/Sources/SwiftNetwork/System/Linux/LinuxInterface.swift +++ b/Sources/SwiftNetwork/System/Linux/LinuxInterface.swift @@ -17,7 +17,7 @@ import Glibc internal import Logging internal import SwiftNetworkLinuxShim -/// Set of Linux system APIs for interacting with the system interface +/// A set of Linux system APIs for interacting with the system interface. internal enum SystemInterface { enum Constants { @@ -58,7 +58,9 @@ internal enum SystemInterface { }.result } - /// Get MTU from the interface using ioctl + /// Gets the MTU from the interface. + /// + /// Uses `ioctl` to fetch the value. static func interfaceGetMTU(socket: Int32, name: String) throws -> Int { if name.isEmpty { return 65535 @@ -74,7 +76,9 @@ internal enum SystemInterface { } } - /// Check to see if an interface has a specific flag. For example, UP,RUNNING,BROADFAST,MULTICAST + /// Returns a Boolean value that indicates whether an interface has a specific flag. + /// + /// For example, `UP`, `RUNNING`, `BROADCAST`, or `MULTICAST`. static func interfaceHasFlag(socket: Int32, name: String, flag: Interface.Details.Flags) throws -> Bool { if name.isEmpty { return false @@ -101,7 +105,7 @@ internal enum SystemInterface { } } - /// Check to see if an interface is loopback + /// Returns a Boolean value that indicates whether an interface is loopback. static func interfaceIsLoopback(socket: Int32, name: String) throws -> Bool { if name.isEmpty { return false @@ -120,7 +124,7 @@ internal enum SystemInterface { } } - /// Check if this is a wireless interface + /// Returns a Boolean value that indicates whether this is a wireless interface. static func interfaceHasWireless(socket: Int32, name: String) throws -> Bool { if name.isEmpty { return false @@ -140,7 +144,7 @@ internal enum SystemInterface { } } - /// Check if this is a ethernet interface + /// Returns a Boolean value that indicates whether this is an Ethernet interface. static func interfaceHasEthernet(socket: Int32, name: String) throws -> Bool { if name.isEmpty { return false @@ -159,7 +163,7 @@ internal enum SystemInterface { } } - /// Get all of the interface flags for a specified interface + /// Returns all of the interface flags for the specified interface. static func interfaceGetInterfaceFlags(socket: Int32, name: String) throws -> UInt32 { if name.isEmpty { return 0 @@ -175,7 +179,7 @@ internal enum SystemInterface { } } - /// Get all of the interface type for a specified interface + /// Returns the interface type for the specified interface. static func interfaceGetInterfaceType(socket: Int32, name: String) throws -> InterfaceType { var interfaceType = InterfaceType.other // Check for loopback, wireless, and wired. @@ -196,7 +200,7 @@ internal enum SystemInterface { } } - /// Get name of the interface by index + /// Returns the name of the interface by index. static func interfaceGetNameFromIndex(index: UInt32) throws -> String? { // NOTE: on Linux calling if_indextoname with an index of 0 will return NULL, which is fine // but will set the errno to 6 - abort, which we do not want, so we guard for this here. diff --git a/Sources/SwiftNetwork/System/Linux/LinuxResources.swift b/Sources/SwiftNetwork/System/Linux/LinuxResources.swift index bc6441b..3fc9f76 100644 --- a/Sources/SwiftNetwork/System/Linux/LinuxResources.swift +++ b/Sources/SwiftNetwork/System/Linux/LinuxResources.swift @@ -16,7 +16,7 @@ import Glibc internal import SwiftNetworkLinuxShim -/// Set of Linux system APIs for interacting with the system resources +/// A set of Linux system APIs for interacting with the system resources. internal enum SystemResources { static func getFDLimit() -> UInt64 { diff --git a/Sources/SwiftNetwork/System/Linux/LinuxRoute.swift b/Sources/SwiftNetwork/System/Linux/LinuxRoute.swift index f3dca5e..b3cd090 100644 --- a/Sources/SwiftNetwork/System/Linux/LinuxRoute.swift +++ b/Sources/SwiftNetwork/System/Linux/LinuxRoute.swift @@ -17,7 +17,7 @@ import Glibc internal import Logging internal import SwiftNetworkLinuxShim -/// Set of Linux system APIs for interacting with the system interface +/// A set of Linux system APIs for interacting with the system interface. internal enum SystemRoute { enum Constants { @@ -222,9 +222,11 @@ internal enum SystemRoute { } } - /// From a routing table buffer parse out multiple `rtattr` and append them to an array. - /// Note that the buffer passed in here should only represent the buffer of the rtattr data and not the rest of the buffer. - /// https://man7.org/linux/man-pages/man7/rtnetlink.7.html + /// Parses routing-table attributes and appends them to an array. + /// + /// Parses multiple `rtattr` values from a routing-table buffer. + /// The buffer passed in must represent only the `rtattr` data, not the rest of the buffer. + /// See https://man7.org/linux/man-pages/man7/rtnetlink.7.html internal static func parseRouteAttributes( buffer: UnsafeBufferPointer, totalAttributeBytesSize: Int, @@ -288,8 +290,10 @@ internal enum SystemRoute { return attributes } - /// Perform a routing table lookup using NLM_F_REQUEST and RTM_GETADDR. - /// The result of the query will hand back the entire routing table along with ifaddrmsg + /// Performs a routing-table lookup. + /// + /// Performs the lookup using `NLM_F_REQUEST` and `RTM_GETADDR`. + /// The query returns the entire routing table along with the `ifaddrmsg`. static func routeGetInterfaceIndex(dst: any IPAddress, scopedIndex: UInt32 = 0) throws -> UInt32 { var ifIndex: UInt32 = 0 diff --git a/Sources/SwiftNetwork/System/NetworkError.swift b/Sources/SwiftNetwork/System/NetworkError.swift index 61ce191..f6bd918 100644 --- a/Sources/SwiftNetwork/System/NetworkError.swift +++ b/Sources/SwiftNetwork/System/NetworkError.swift @@ -19,16 +19,16 @@ internal import Logging internal import os #endif -/// `NetworkDomainSpecificError` allows a protocol implementation to define its own set of errors. +/// A protocol that lets a protocol implementation define its own set of errors. /// /// It consists of a domain, a code, an optional category, and a description. /// /// - Domain should be unique. /// - Category is usually a computed property based on the code, it enables protocol-agnostic -/// error handling. For example, EBUSY, HTTP/2 `ENHANCE_YOUR_CALM`, and `H3_EXCESSIVE_LOAD` are +/// error handling. For example, `EBUSY`, HTTP/2 `ENHANCE_YOUR_CALM`, and `H3_EXCESSIVE_LOAD` are /// all considered `excessiveLoad`. /// -/// See `NetworkPOSIXError` and `HTTP2Error` as 2 examples of `NetworkDomainSpecificError`. +/// See `NetworkPOSIXError` and `HTTP2Error` as two examples of `NetworkDomainSpecificError`. @_spi(ProtocolProvider) @available(Network 0.1.0, *) public protocol NetworkDomainSpecificError: Error, Sendable, CustomStringConvertible { @@ -37,8 +37,7 @@ public protocol NetworkDomainSpecificError: Error, Sendable, CustomStringConvert static func category(of error: Self) -> NetworkError.CommonCategory? } -/// `NetworkError` is a type erased container for all errors generated by network protocol -/// implementations. +/// A type-erased container for all errors generated by network protocol implementations. /// /// It consists of a description, and at least one of a domain specific error, or a common /// category. @@ -46,9 +45,9 @@ public protocol NetworkDomainSpecificError: Error, Sendable, CustomStringConvert /// A concrete error is initialized from a domain specific error. It contains a specific error /// domain and code, as well as an optional category. /// -/// An abstract error is initialized from a category. It is useful when an application wants to -/// emit an error that can be translated into different error codes by different protocols (e.g. -/// HTTP/2 `ENHANCE_YOUR_CALM` vs `H3_EXCESSIVE_LOAD`). +/// An abstract error is initialized from a category. It is useful when an app wants to +/// emit an error that protocols can translate into different error codes — for example, +/// HTTP/2 `ENHANCE_YOUR_CALM` versus `H3_EXCESSIVE_LOAD`. @_spi(ProtocolProvider) @available(Network 0.1.0, *) public struct NetworkError: Error, Sendable, Hashable, CustomStringConvertible { @@ -72,8 +71,10 @@ public struct NetworkError: Error, Sendable, Hashable, CustomStringConvertible { } } - /// Identifier of a common category must be unique. If the category is specific to an area, - /// add a nested enum and use the format of "area.name" for the identifier to avoid conflicts. + /// The identifier of a common category must be unique. + /// + /// If the category is specific to an area, add a nested enum and use the format `area.name` + /// for the identifier to avoid conflicts. /// See `HTTP.http1FallbackRequested`. public struct CommonCategory: Sendable, Hashable { public let identifier: String diff --git a/Sources/SwiftNetwork/System/SystemInterface.swift b/Sources/SwiftNetwork/System/SystemInterface.swift index bee48b1..e456191 100644 --- a/Sources/SwiftNetwork/System/SystemInterface.swift +++ b/Sources/SwiftNetwork/System/SystemInterface.swift @@ -24,7 +24,9 @@ internal import errno_h #endif #endif -/// Extension of System specifically for system interfaces +/// An extension that adds system-interface APIs. +/// +/// Extends `System` with system-interface functions. extension System { static func interfaceGetMTU(socket: Int32, name: String) throws -> Int { diff --git a/Sources/SwiftNetwork/System/SystemResources.swift b/Sources/SwiftNetwork/System/SystemResources.swift index 3ba8233..f71a5b8 100644 --- a/Sources/SwiftNetwork/System/SystemResources.swift +++ b/Sources/SwiftNetwork/System/SystemResources.swift @@ -12,10 +12,14 @@ // //===----------------------------------------------------------------------===// -/// Extension of System specifically for system resources +/// An extension that adds system-resource APIs. +/// +/// Extends `System` with system-resource functions. extension System { - /// Returns a valid FD limit or `nil` if none was obtained. + /// Returns the file-descriptor limit, if available. + /// + /// Returns `nil` if no limit was obtained. static func getFDLimit() -> UInt64? { let fdLimit = SystemResources.getFDLimit() return fdLimit > 0 ? fdLimit : nil diff --git a/Sources/SwiftNetwork/System/SystemSocket.swift b/Sources/SwiftNetwork/System/SystemSocket.swift index bed8fa3..942344c 100644 --- a/Sources/SwiftNetwork/System/SystemSocket.swift +++ b/Sources/SwiftNetwork/System/SystemSocket.swift @@ -51,7 +51,7 @@ enum SocketType: CUnsignedInt, Sendable { } -/// System type for creating a cross platform socket +/// A type that creates a cross-platform socket. class SystemSocket { /// Socket file descriptor @@ -82,7 +82,7 @@ class SystemSocket { #endif } - /// Create the actual cross platform descriptor + /// Creates the actual cross-platform descriptor. private static func createSocket( protocolFamily: AddressFamily, sockType: SocketType, @@ -104,7 +104,7 @@ class SystemSocket { try body(self.sockfd) } - /// Optionally set the socket as non-blocking + /// Optionally sets the socket as non-blocking. private func setSocketAsNonBlocking() throws(NetworkError) { guard self.sockfd > 0 else { Logger.system.error("File descriptor is bad, cannot set non-blocking") @@ -114,7 +114,11 @@ class SystemSocket { } #if !NETWORK_PRIVATE - /// Connect the socket to an IPAddress and port + /// Connects the socket to a remote address and port. + /// + /// - Parameters: + /// - address: The remote `IPAddress` to connect to. + /// - port: The remote port to connect to. public func connectSocket(to address: any IPAddress, port: UInt16) throws(NetworkError) -> Bool { guard self.sockfd > 0 else { Logger.system.error("File descriptor is bad, cannot connect socket") @@ -129,7 +133,9 @@ class SystemSocket { } } - /// Call bind on a socket with a port + /// Binds the socket to an address and port. + /// + /// Wraps a call to the system `bind` function. public func bindSocket(address: any IPAddress, port: UInt16) throws { guard self.sockfd > 0 else { Logger.system.error("File descriptor is bad, cannot bind socket") @@ -140,7 +146,9 @@ class SystemSocket { } } - /// Connect the socket to an IPAddress + /// Connects the socket to a remote address. + /// + /// - Parameter address: The remote `IPAddress` to connect to. public func connectSocket(to address: any IPAddress) throws(NetworkError) -> Bool { guard self.sockfd > 0 else { Logger.system.error("File descriptor is bad, cannot connect socket") @@ -151,9 +159,10 @@ class SystemSocket { } } - /// Call bind on a socket + /// Binds the socket. + /// + /// Wraps a call to the system `bind` function. public func bindSocket(address: any IPAddress, bytes: Int) throws { - // TODO: Change this to use Endpoint when they become vailable. guard self.sockfd > 0 else { Logger.system.error("File descriptor is bad, cannot bind socket") throw NetworkError.posix(EINVAL) @@ -164,7 +173,7 @@ class SystemSocket { } #endif - /// Read from socket, at optional length on buffer + /// Reads from the socket up to the specified length into the buffer. public func read(buffer: UnsafeMutableRawPointer, size: Int) throws -> Int { guard self.sockfd > 0 else { Logger.system.error("File descriptor is bad, cannot read from socket") @@ -183,7 +192,7 @@ class SystemSocket { } } - /// For doing basic reads on a socket. Note this should only be used for things like control or routing sockets, NOT data read from the actual network. + /// Performs a basic read on a socket. Use this only for control or routing sockets, not for data read from the actual network. public func platformRead(buffer: UnsafeMutableRawPointer, size: Int) throws -> Int { guard self.sockfd > 0 else { Logger.system.error("File descriptor is bad, cannot read from socket") @@ -192,7 +201,7 @@ class SystemSocket { return sysRead(self.sockfd, buffer, size) } - /// Write a buffer to a socket, at optional length on buffer + /// Writes a buffer to the socket up to the specified length. public func write(buffer: UnsafeRawPointer, size: Int) throws -> Int { guard self.sockfd > 0 else { Logger.system.error("File descriptor is bad, cannot write to socket") @@ -201,7 +210,7 @@ class SystemSocket { return try System.write(descriptor: self.sockfd, pointer: buffer, size: size) } - /// For doing basic write on a socket. Note this should only be used for things like control or routing sockets, NOT data sent to the actual network. + /// Performs a basic write on a socket. Use this only for control or routing sockets, not for data sent to the actual network. public func platformWrite(buffer: UnsafeRawPointer, size: Int) throws -> Int { guard self.sockfd > 0 else { Logger.system.error("File descriptor is bad, cannot write to socket") @@ -210,7 +219,9 @@ class SystemSocket { return sysWrite(self.sockfd, buffer, size) } - /// For sending msghdr's on a control socket + /// Sends a message header on a control socket. + /// + /// Use this to send a `msghdr` structure on the socket. public func sendmsg(msgHdr: UnsafePointer, flags: CInt) throws -> Int { guard self.sockfd > 0 else { Logger.system.error("File descriptor is bad, cannot send a message on a socket") @@ -219,7 +230,7 @@ class SystemSocket { return try System.sendmsg(descriptor: self.sockfd, msgHdr: msgHdr, flags: flags).result } - /// For receiving a message buffer on a control socket + /// Receives a message buffer on a control socket. public func recvmsg(msgHdr: UnsafeMutablePointer, flags: CInt) throws -> Int { guard self.sockfd > 0 else { Logger.system.error("File descriptor is bad, cannot receive a message on a socket") diff --git a/Sources/SwiftNetwork/System/SystemUUID.swift b/Sources/SwiftNetwork/System/SystemUUID.swift index 2fefa3d..24af256 100644 --- a/Sources/SwiftNetwork/System/SystemUUID.swift +++ b/Sources/SwiftNetwork/System/SystemUUID.swift @@ -68,7 +68,9 @@ public struct SystemUUID: Hashable, Equatable, CustomStringConvertible, Sendable self.storage = storage } - /// Returns a string created from the UUID, such as "E621E1F8-C36C-495A-93FC-0C247A3E6E5F" + /// Returns a string representation of the UUID. + /// + /// For example, `E621E1F8-C36C-495A-93FC-0C247A3E6E5F`. public var description: String { var result = "" for i in 0.. Factory { factory @@ -98,9 +98,9 @@ public struct Deserializer Bool { guard let span = factory.nextSpan() else { @@ -157,9 +157,9 @@ public struct Deserializer(_ value: inout T) throws(DeserializationError) { let length = MemoryLayout.size precondition(length <= 16) @@ -180,8 +180,7 @@ public struct Deserializer( _ value: inout T, networkByteOrder: Bool @@ -192,8 +191,10 @@ public struct Deserializer(_ value: inout T) throws(DeserializationError) { let length = MemoryLayout.size guard hasRoom(length) else { @@ -204,7 +205,9 @@ public struct Deserializer( _ value: inout T? ) throws(DeserializationError) { @@ -213,8 +216,7 @@ public struct Deserializer( _ value: inout T, networkByteOrder: Bool @@ -225,8 +227,7 @@ public struct Deserializer( _ value: inout T?, networkByteOrder: Bool diff --git a/Sources/SwiftNetwork/Utilities/NetworkClock.swift b/Sources/SwiftNetwork/Utilities/NetworkClock.swift index 295afee..1e70b2c 100644 --- a/Sources/SwiftNetwork/Utilities/NetworkClock.swift +++ b/Sources/SwiftNetwork/Utilities/NetworkClock.swift @@ -12,11 +12,12 @@ // //===----------------------------------------------------------------------===// -/// NetworkDuration is a shorter representation of Swift.Duration using only 8 bytes. -/// The purpose of NetworkDuration is to represent times relative to the system boot up time -/// or relative to the UNIX epoch. -/// Although it can represent durations that span several years, its purpose is limited -/// to representing durations relevant to networking protocols which are usually under one hour. +/// A compact 8-byte duration representation. +/// +/// A shorter representation of `Swift.Duration`. Use `NetworkDuration` to represent times +/// relative to the system boot-up time or to the UNIX epoch. Although `NetworkDuration` +/// can represent durations that span several years, its purpose is limited to durations +/// relevant to networking protocols, which are usually under one hour. #if !NETWORK_EMBEDDED @_spi(Essentials) @available(Network 0.1.0, *) @@ -209,9 +210,11 @@ public struct NetworkDuration: DurationProtocol, Hashable, Equatable, CustomStri } } -/// NetworkClock is a continuous clock that mimics Swift.ContinuousClock but it has two changes -/// 1. It uses NetworkDuration internally to make its size 8 bytes. -/// 2. It allows clocks to be created with any random value for unit tests. +/// A continuous clock with a compact representation and configurable initial value. +/// +/// Mimics `Swift.ContinuousClock`, with two differences: +/// 1. It uses `NetworkDuration` internally so its size is 8 bytes. +/// 2. You can create a clock with any value, which is useful for unit tests. #if !NETWORK_EMBEDDED @_spi(Essentials) @available(Network 0.1.0, *) diff --git a/Sources/SwiftNetwork/Utilities/SafeAccess.swift b/Sources/SwiftNetwork/Utilities/SafeAccess.swift index 3500fb0..aa16a3f 100644 --- a/Sources/SwiftNetwork/Utilities/SafeAccess.swift +++ b/Sources/SwiftNetwork/Utilities/SafeAccess.swift @@ -16,14 +16,17 @@ enum SafeAccess { - /// Access a c structure from a raw buffer pointer. - /// NOTE: The structure will be loaded aligned and will return nil if misaligned. + /// Accesses a C structure from a raw buffer pointer. + /// + /// The structure loads aligned, and the method returns `nil` if the buffer is misaligned. /// /// Example usage: + /// ```swift /// let headerBuffer = UnsafeRawBufferPointer(pointer) /// guard let cstruct = self.loadCStructure(buffer: headerBuffer, type: cstruct.self) else { /// continue /// } + /// ``` static func loadCStructure(buffer: UnsafeRawBufferPointer, type: T.Type) -> T? { let size = MemoryLayout.size diff --git a/Sources/SwiftNetwork/Utilities/SerializationHelpers.swift b/Sources/SwiftNetwork/Utilities/SerializationHelpers.swift index cdb99f1..eced5ac 100644 --- a/Sources/SwiftNetwork/Utilities/SerializationHelpers.swift +++ b/Sources/SwiftNetwork/Utilities/SerializationHelpers.swift @@ -17,16 +17,17 @@ @_spi(ProtocolProvider) @available(Network 0.1.0, *) public protocol DeserializerSpanFactory: ~Copyable, ~Escapable { - /// Access the next span from the factory. + /// Returns the next span from the factory. @_lifetime(&self) mutating func nextSpan() -> RawSpan? - /// Access the total available byte count across all spans that this factory can emit. + /// The total available byte count across all spans this factory can emit. var availableByteCount: Int { get } } /// A factory that stores a single span. -/// Used when the Deserializer is initialized directly from a RawSpan. +/// +/// Use this factory when initializing a `Deserializer` directly from a `RawSpan`. @_spi(ProtocolProvider) @available(Network 0.1.0, *) public struct SingleSpanFactory: ~Escapable, DeserializerSpanFactory { @@ -55,16 +56,17 @@ public struct SingleSpanFactory: ~Escapable, DeserializerSpanFactory { @_spi(ProtocolProvider) @available(Network 0.1.0, *) public protocol SerializerSpanFactory: ~Copyable, ~Escapable { - /// Access the next span from the factory. + /// Returns the next mutable span from the factory. @_lifetime(&self) mutating func nextMutableSpan() -> MutableRawSpan? - /// Access the total available byte count across all spans that this factory can emit. + /// The total available byte count across all spans this factory can emit. var availableByteCount: Int { get } } /// A factory that stores a single mutable span. -/// Used when the Serializer is initialized directly from a MutableRawSpan. +/// +/// Use this factory when initializing a `Serializer` directly from a `MutableRawSpan`. @_spi(ProtocolProvider) @available(Network 0.1.0, *) public struct SingleMutableSpanFactory: ~Copyable, ~Escapable, SerializerSpanFactory { @@ -92,9 +94,10 @@ public struct SingleMutableSpanFactory: ~Copyable, ~Escapable, SerializerSpanFac // MARK: - FrameArraySpanFactory -/// A span factory that walks across the frames in a FrameArray, -/// providing each frame's bytes as a span and optionally claiming -/// consumed bytes from each frame. +/// A span factory that walks the frames in a frame array. +/// +/// Provides each frame's bytes as a span and optionally claims consumed bytes from each frame. +/// Walks the frames in a `FrameArray`. @_spi(ProtocolProvider) @available(Network 0.1.0, *) public struct FrameArraySpanFactory: ~Copyable, ~Escapable, DeserializerSpanFactory { @@ -103,7 +106,7 @@ public struct FrameArraySpanFactory: ~Copyable, ~Escapable, DeserializerSpanFact private var spanCount: Int public private(set) var availableByteCount: Int - /// Extract the frame array from the factory, consuming it in the process. + /// Extracts the frame array from the factory, consuming the factory in the process. consuming func takeFrameArray() -> FrameArray { frameArray } diff --git a/Sources/SwiftNetwork/Utilities/Serializer.swift b/Sources/SwiftNetwork/Utilities/Serializer.swift index 3642b57..32399e0 100644 --- a/Sources/SwiftNetwork/Utilities/Serializer.swift +++ b/Sources/SwiftNetwork/Utilities/Serializer.swift @@ -365,7 +365,7 @@ public struct InPlaceSerializer Factory { factory @@ -379,9 +379,9 @@ public struct InPlaceSerializer Bool { guard let span = factory.nextMutableSpan() else { @@ -431,8 +431,9 @@ public struct InPlaceSerializer(_ value: T) throws(SerializationError) { let length = MemoryLayout.size guard hasRoom(length) else { @@ -444,7 +445,7 @@ public struct InPlaceSerializer(_ value: T) throws(SerializationError) { let length = MemoryLayout.size precondition(length <= 16) @@ -634,7 +635,7 @@ public struct FrameSerializer: ~Copyable { } } - /// Extract the frame array from the serializer, consuming it in the process. + /// Extracts the frame array from the serializer, consuming the serializer in the process. fileprivate consuming func extractFrames() -> FrameArray { convertBufferToFrame() return frameArray @@ -675,7 +676,7 @@ public struct FrameSerializer: ~Copyable { self.capacity = capacity } - /// Write a fixed-size value into an output span + /// Writes a fixed-size value into an output span. private mutating func writeFixedSize(_ value: T) { withOutputSpan(length: MemoryLayout.size) { outputSpan in outputSpan.append(value, as: T.self) diff --git a/Sources/SwiftNetwork/Utilities/StreamDeserializer.swift b/Sources/SwiftNetwork/Utilities/StreamDeserializer.swift index bbaacdd..88d8807 100644 --- a/Sources/SwiftNetwork/Utilities/StreamDeserializer.swift +++ b/Sources/SwiftNetwork/Utilities/StreamDeserializer.swift @@ -69,11 +69,12 @@ public struct StreamDeserializationBuilder< @available(Network 0.1.0, *) public protocol StreamDeserializerState: ~Copyable { - /// An associated type that defines comparable identifiers for state machine steps. - /// These identifiers are used for looping and jumping states when deserializing. + /// An associated type that defines hashable identifiers for state-machine steps. + /// + /// Use these identifiers to loop and jump between states during deserialization. associatedtype StateMachineStepIdentifier: Hashable - /// Creates a new default state. + /// Creates a default state. init() }