From 1c0d6e9f8dd9ee6badfbb25a5edf93d069c40408 Mon Sep 17 00:00:00 2001 From: Joe Heck Date: Tue, 9 Jun 2026 15:06:18 -0700 Subject: [PATCH 1/3] docs clean up and fix up - spelling, grammar, and style guide alignment --- .../SwiftNetwork/Connection/Connection.swift | 324 ++++++++++-------- .../SwiftNetwork/Context/NetworkContext.swift | 32 +- .../Endpoint/EthernetAddress.swift | 2 +- Sources/SwiftNetwork/Endpoint/IPAddress.swift | 10 +- .../SwiftNetwork/Endpoint/IPv4Address.swift | 12 +- .../SwiftNetwork/Endpoint/IPv6Address.swift | 22 +- .../Endpoint/NetlinkAddress.swift | 6 +- .../EndpointFlow/EndpointFlow.swift | 14 +- .../SwiftNetwork/Parameters/Parameters.swift | 23 +- Sources/SwiftNetwork/Path/Interface.swift | 24 +- .../SwiftNetwork/Path/PathProperties.swift | 10 +- .../Protocols/BottomProtocol.swift | 82 +++-- .../SwiftNetwork/Protocols/IPProtocol.swift | 14 +- .../Protocols/ManyToManyProtocol.swift | 34 +- .../Protocols/NetworkEvents.swift | 4 +- .../Protocols/OneToOneProtocol.swift | 147 ++++---- .../Protocols/ProtocolControlHandlers.swift | 4 +- .../Protocols/ProtocolDatagramHandlers.swift | 66 ++-- .../Protocols/ProtocolInstance.swift | 32 +- .../Protocols/ProtocolLinkage.swift | 5 +- .../Protocols/ProtocolListenerHandlers.swift | 2 +- .../Protocols/ProtocolStreamHandlers.swift | 68 ++-- .../SwiftNetwork/Protocols/TopProtocol.swift | 70 ++-- Sources/SwiftNetwork/QUIC/ECN.swift | 32 +- Sources/SwiftNetwork/QUIC/Prague.swift | 55 +-- Sources/SwiftNetwork/QUIC/Protector.swift | 12 +- .../SwiftNetwork/QUIC/QUICConnection.swift | 2 +- Sources/SwiftNetwork/QUIC/QUICStream.swift | 8 +- Sources/SwiftNetwork/QUIC/QUICUtilities.swift | 6 +- .../System/Darwin/DarwinInterface.swift | 20 +- .../System/Darwin/DarwinResources.swift | 2 +- .../System/Darwin/DarwinRoute.swift | 2 +- .../System/Embedded/EmbeddedInterface.swift | 20 +- .../System/Linux/LinuxInterface.swift | 22 +- .../System/Linux/LinuxResources.swift | 2 +- .../System/Linux/LinuxRoute.swift | 16 +- .../SwiftNetwork/System/NetworkError.swift | 21 +- .../SwiftNetwork/System/SystemInterface.swift | 4 +- .../SwiftNetwork/System/SystemResources.swift | 8 +- .../SwiftNetwork/System/SystemSocket.swift | 40 ++- Sources/SwiftNetwork/System/SystemUUID.swift | 4 +- .../SwiftNetwork/Utilities/Deserializer.swift | 33 +- .../SwiftNetwork/Utilities/NetworkClock.swift | 19 +- .../SwiftNetwork/Utilities/SafeAccess.swift | 7 +- .../Utilities/SerializationHelpers.swift | 23 +- .../SwiftNetwork/Utilities/Serializer.swift | 19 +- .../Utilities/StreamDeserializer.swift | 7 +- 47 files changed, 790 insertions(+), 601 deletions(-) diff --git a/Sources/SwiftNetwork/Connection/Connection.swift b/Sources/SwiftNetwork/Connection/Connection.swift index aed1dc1..85d93e6 100644 --- a/Sources/SwiftNetwork/Connection/Connection.swift +++ b/Sources/SwiftNetwork/Connection/Connection.swift @@ -73,8 +73,9 @@ public protocol ConnectionProtocol: Identifiable, Hashable { associatedtype ApplicationProtocolType: NetworkProtocolOptions } -/// Types that conform to NetworkProtocolOptions can be used -/// when configuring protocol stacks. +/// A protocol stack configuration option. +/// +/// Conforming types can be used when configuring protocol stacks. @_spi(Essentials) @available(Network 0.1.0, *) public protocol NetworkMetadataProtocol { @@ -102,8 +103,9 @@ extension NetworkProtocolOptions { } } -/// Types that conform to ConnectionStorage can be used as additional storage within -/// a connection. +/// Additional storage attached to a connection. +/// +/// Conforming types can be used as additional storage within a connection. @_spi(Essentials) @available(Network 0.1.0, *) public protocol ConnectionStorage { @@ -116,26 +118,30 @@ public struct DefaultProtocolStorage: ConnectionStorage, Sendable { public init() {} } -/// Types that conform to OneToOneProtocol are allowed to be the top protocol -/// in a network protocol stack for non-multiplexed connections. +/// A protocol that can sit at the top of a non-multiplexed connection's protocol stack. +/// +/// Conforming types are allowed to be the top protocol in a network protocol stack +/// for non-multiplexed connections. @_spi(Essentials) @available(Network 0.1.0, *) public protocol OneToOneProtocol: NetworkProtocolOptions { } -/// Types that conform to MultiplexProtocol are allowed to be the top protocol -/// in a network protocol stack for multiplexing network connection objects. +/// A protocol that can sit at the top of a multiplexed connection's protocol stack. /// -/// Generally network protocols conforming to this type will not directly expose -/// send or receive methods. Instead, they expose methods to open -/// and listen for multiplexed Subconnections which can send and receive. +/// Conforming types are allowed to be the top protocol in a network protocol stack +/// for multiplexing network connection objects. Generally, network protocols +/// conforming to this type don't directly expose send or receive methods. +/// Instead, they expose methods to open and listen for multiplexed subconnections, +/// which can send and receive. @_spi(Essentials) @available(Network 0.1.0, *) public protocol MultiplexProtocol: NetworkProtocolOptions { } -/// Types that conform to the StreamProtocol protocol expose methods for -/// sending and receiving byte streams. +/// A protocol that exposes byte-stream send and receive methods. +/// +/// Conforming types expose methods for sending and receiving byte streams. @_spi(Essentials) @available(Network 0.1.0, *) public protocol StreamProtocol: OneToOneProtocol { @@ -146,24 +152,26 @@ public protocol StreamProtocol: OneToOneProtocol { extension StreamProtocol { } -/// Types that conform to MessageProtocol send and receive messages. -/// The conforming type is responsible for specifying its message-specific -/// metadata. +/// A protocol that sends and receives messages. +/// +/// Conforming types send and receive messages. The conforming type is responsible for +/// specifying its message-specific metadata. @_spi(Essentials) @available(Network 0.1.0, *) public protocol MessageProtocol: OneToOneProtocol { associatedtype ContentType } -/// Types that conform to DatagramProtocol send and receive messages -/// with minimal or no metadata, usually constrained to a fixed maximum size. +/// A protocol that sends and receives small, bounded messages. +/// +/// Conforming types send and receive messages with minimal or no metadata, +/// usually constrained to a fixed maximum size. @_spi(Essentials) @available(Network 0.1.0, *) public protocol DatagramProtocol: MessageProtocol { } -/// A resultBuilder for specifying and configuring protocol stacks in -/// a declarative way +/// A result builder for specifying and configuring protocol stacks declaratively. @_spi(Essentials) @available(Network 0.1.0, *) @resultBuilder @@ -173,12 +181,13 @@ public struct ProtocolStackBuilder } } -/// Types that conform to the NWParametersProvider protocol can be used to -/// generate an NWParameters. +/// A type that produces parameters for a connection. +/// +/// Conforming types can be used to generate a `Parameters` value. @_spi(Essentials) @available(Network 0.1.0, *) public protocol ParametersProvider { - /// The generated NWParameters. + /// The generated parameters. var parameters: Parameters { get set } /// Require an interface when connecting, listening, and browsing. @@ -207,9 +216,9 @@ public protocol ParametersProvider { /// /// Prohibit connections and listeners from using a network interface /// that is considered expensive by the system, - /// for example some cellular interfaces. + /// for example, some cellular interfaces. /// - /// - Parameter prohibited: True if expensive paths are prohibited, false otherwise. + /// - Parameter prohibited: `true` if expensive paths are prohibited, otherwise `false`. func expensivePathsProhibited(_ prohibited: Bool) -> Self /// Prohibit using constrained paths. @@ -218,13 +227,13 @@ public protocol ParametersProvider { /// that is considered constrained by the system, /// for example an interface in Low Data Mode. /// - /// - Parameter prohibited: True if constrained paths are prohibited, false otherwise. + /// - Parameter prohibited: `true` if constrained paths are prohibited, otherwise `false`. func constrainedPathsProhibited(_ prohibited: Bool) -> Self /// Specify a specific endpoint to use as the local endpoint. /// - /// For connections, this will be used to initiate traffic; - /// for listeners, this will be used for receiving incoming + /// For connections, this is used to initiate traffic; + /// for listeners, this is used for receiving incoming /// connections. /// /// - Parameter endpoint: The local endpoint to require, or `nil` if none. @@ -233,12 +242,11 @@ public protocol ParametersProvider { /// Specify a specific port to use as the local endpoint, /// letting the system select the address. /// - /// For connections, this will be used to initiate traffic; - /// for listeners, this will be used for receiving incoming + /// For connections, this is used to initiate traffic; + /// for listeners, this is used for receiving incoming /// connections. /// /// - Parameter port: The local port to require. - /// Force a specific local port to be used. func localPort(_ port: UInt16) -> Self /// Allow local endpoint reuse. @@ -246,15 +254,15 @@ public protocol ParametersProvider { /// Allow multiple connections to use the same local address and port /// (`SO_REUSEADDR` and `SO_REUSEPORT`). /// - /// - Parameter allowed: True if allowed, false otherwise. + /// - Parameter allowed: `true` if allowed, otherwise `false`. func localEndpointReuseAllowed(_ allowed: Bool) -> Self /// Limit inbound connections to peers attached to the local link. /// - /// Listeners will only advertise services on the local link and - /// will only accept connections from the local link. + /// Listeners only advertise services on the local link and + /// only accept connections from the local link. /// - /// - Parameter local: True if limited to local peers, false otherwise. + /// - Parameter local: `true` if limited to local peers, otherwise `false`. func localOnly(_ local: Bool) -> Self /// Require DNSSEC validation when resolving an endpoint before making @@ -264,17 +272,17 @@ public protocol ParametersProvider { /// requires domain name resolution, such as a host or URL endpoint. /// /// - If this is not set or is set to `false`, DNSSEC validation - /// will not be required. + /// isn't required. /// /// - If this is set to `true` and no additional DNSSEC configuration - /// is set, the default behavior will be followed: - /// Only DNSSEC secure and DNSSEC insecure - /// resolved results will be used to establish a connection. + /// is set, the default behavior is followed: + /// only DNSSEC secure and DNSSEC insecure + /// resolved results are used to establish a connection. /// /// - If this is set to `true` and additional DNSSEC configuration - /// is set on the parameters, the behavior specified by that configuration will be used. + /// is set on the parameters, the behavior specified by that configuration is used. /// - /// - Parameter required: True if DNSSEC validation is required, false otherwise. + /// - Parameter required: `true` if DNSSEC validation is required, otherwise `false`. func dnssecValidationRequired(_ required: Bool) -> Self /// Set the data service class to use for connections. @@ -296,22 +304,22 @@ public protocol ParametersProvider { /// > Warning: This may have security implications for application data. /// In particular, TLS early data is replayable by a network attacker. /// You must account for this when sending data before the handshake - /// is confirmed. See RFC 8446 for more information. You MUST NOT + /// is confirmed. See RFC 8446 for more information. Don't /// enable fast open without a specific application profile that defines its use. /// /// As a side effect, this may implicitly enable fast open or early data for protocols - /// in the stack, even if they did not have fast open explicitly enabled on them + /// in the stack, even if they didn't have fast open explicitly enabled on them /// (such as the option to enable TCP Fast Open). /// - /// - Parameter allowed: True if fast open should be used, false otherwise. + /// - Parameter allowed: `true` if fast open should be used, otherwise `false`. func fastOpenAllowed(_ allowed: Bool) -> Self /// Allow or prohibit the use of expired DNS answers during connection establishment. /// - /// If allowed, a DNS answer that was previously returned may be re-used for new + /// If allowed, a DNS answer that was previously returned may be reused for new /// connections even after the answers are considered expired. A query for fresh answers - /// will be sent in parallel, and the fresh answers will be used as alternate addresses - /// in case the expired answers do not result in successful connections. + /// is sent in parallel, and the fresh answers are used as alternate addresses + /// in case the expired answers don't result in successful connections. /// /// By default, this value is `.systemDefault`, which allows the system to determine /// if it is appropriate to use expired answers. @@ -379,9 +387,9 @@ extension ParametersProvider { /// /// Prohibit connections and listeners from using a network interface /// that is considered expensive by the system, - /// for example some cellular interfaces. + /// for example, some cellular interfaces. /// - /// - Parameter prohibited: True if expensive paths are prohibited, false otherwise. + /// - Parameter prohibited: `true` if expensive paths are prohibited, otherwise `false`. public func expensivePathsProhibited(_ prohibited: Bool) -> Self { var mutableSelf = self mutableSelf.parameters.prohibitExpensivePaths = prohibited @@ -394,7 +402,7 @@ extension ParametersProvider { /// that is considered constrained by the system, /// for example an interface in Low Data Mode. /// - /// - Parameter prohibited: True if constrained paths are prohibited, false otherwise. + /// - Parameter prohibited: `true` if constrained paths are prohibited, otherwise `false`. public func constrainedPathsProhibited(_ prohibited: Bool) -> Self { var mutableSelf = self mutableSelf.parameters.prohibitConstrainedPaths = prohibited @@ -403,8 +411,8 @@ extension ParametersProvider { /// Specify a specific endpoint to use as the local endpoint. /// - /// For connections, this will be used to initiate traffic; - /// for listeners, this will be used for receiving incoming + /// For connections, this is used to initiate traffic; + /// for listeners, this is used for receiving incoming /// connections. /// /// - Parameter endpoint: The local endpoint to require, or `nil` if none. @@ -417,12 +425,11 @@ extension ParametersProvider { /// Specify a specific port to use as the local endpoint, /// letting the system select the address. /// - /// For connections, this will be used to initiate traffic; - /// for listeners, this will be used for receiving incoming + /// For connections, this is used to initiate traffic; + /// for listeners, this is used for receiving incoming /// connections. /// /// - Parameter port: The local port to require. - /// Force a specific local port to be used. public func localPort(_ port: UInt16) -> Self { var mutableSelf = self mutableSelf.parameters.localAddress = Endpoint(hostname: "::", port: port) @@ -434,7 +441,7 @@ extension ParametersProvider { /// Allow multiple connections to use the same local address and port /// (`SO_REUSEADDR` and `SO_REUSEPORT`). /// - /// - Parameter allowed: True if allowed, false otherwise. + /// - Parameter allowed: `true` if allowed, otherwise `false`. public func localEndpointReuseAllowed(_ allowed: Bool) -> Self { var mutableSelf = self mutableSelf.parameters.reuseLocalAddress = allowed @@ -443,10 +450,10 @@ extension ParametersProvider { /// Limit inbound connections to peers attached to the local link. /// - /// Listeners will only advertise services on the local link and - /// will only accept connections from the local link. + /// Listeners only advertise services on the local link and + /// only accept connections from the local link. /// - /// - Parameter local: True if limited to local peers, false otherwise. + /// - Parameter local: `true` if limited to local peers, otherwise `false`. public func localOnly(_ local: Bool) -> Self { var mutableSelf = self mutableSelf.parameters.localOnly = local @@ -460,17 +467,17 @@ extension ParametersProvider { /// requires domain name resolution, such as a host or URL endpoint. /// /// - If this is not set or is set to `false`, DNSSEC validation - /// will not be required. + /// isn't required. /// /// - If this is set to `true` and no additional DNSSEC configuration - /// is set, the default behavior will be followed: - /// Only DNSSEC secure and DNSSEC insecure - /// resolved results will be used to establish a connection. + /// is set, the default behavior is followed: + /// only DNSSEC secure and DNSSEC insecure + /// resolved results are used to establish a connection. /// /// - If this is set to `true` and additional DNSSEC configuration - /// is set on the parameters, the behavior specified by that configuration will be used. + /// is set on the parameters, the behavior specified by that configuration is used. /// - /// - Parameter required: True if DNSSEC validation is required, false otherwise. + /// - Parameter required: `true` if DNSSEC validation is required, otherwise `false`. public func dnssecValidationRequired(_ required: Bool) -> Self { var mutableSelf = self mutableSelf.parameters.requiresDNSSECValidation = required @@ -504,14 +511,14 @@ extension ParametersProvider { /// > Warning: This may have security implications for application data. /// In particular, TLS early data is replayable by a network attacker. /// You must account for this when sending data before the handshake - /// is confirmed. See RFC 8446 for more information. You MUST NOT + /// is confirmed. See RFC 8446 for more information. Don't /// enable fast open without a specific application profile that defines its use. /// /// As a side effect, this may implicitly enable fast open or early data for protocols - /// in the stack, even if they did not have fast open explicitly enabled on them + /// in the stack, even if they didn't have fast open explicitly enabled on them /// (such as the option to enable TCP Fast Open). /// - /// - Parameter allowed: True if fast open should be used, false otherwise. + /// - Parameter allowed: `true` if fast open should be used, otherwise `false`. public func fastOpenAllowed(_ allowed: Bool) -> Self { var mutableSelf = self mutableSelf.parameters.fastOpenEnabled = allowed @@ -520,10 +527,10 @@ extension ParametersProvider { /// Allow or prohibit the use of expired DNS answers during connection establishment. /// - /// If allowed, a DNS answer that was previously returned may be re-used for new + /// If allowed, a DNS answer that was previously returned may be reused for new /// connections even after the answers are considered expired. A query for fresh answers - /// will be sent in parallel, and the fresh answers will be used as alternate addresses - /// in case the expired answers do not result in successful connections. + /// is sent in parallel, and the fresh answers are used as alternate addresses + /// in case the expired answers don't result in successful connections. /// /// By default, this value is `.systemDefault`, which allows the system to determine /// if it is appropriate to use expired answers. @@ -554,7 +561,9 @@ extension ParametersProvider { } } -/// An extension for Parameters that supports chainable configuration. +/// An extension that adds chainable configuration to parameters. +/// +/// Conforms `Parameters` to `ParametersProvider`. @_spi(Essentials) @available(Network 0.1.0, *) extension Parameters: ParametersProvider { @@ -568,7 +577,9 @@ extension Parameters: ParametersProvider { } } -/// Send and receive unreliable datagrams over QUIC via RFC 9221 +/// Sends and receives unreliable datagrams over QUIC. +/// +/// Implements RFC 9221. @_spi(Essentials) @available(Network 0.1.0, *) public struct QUICDatagram: DatagramProtocol { @@ -680,7 +691,7 @@ public struct TLS: StreamProtocol { /// Application layer protocol negotiation (ALPN) tokens /// describe the application protocol in use above TLS. /// - /// - Parameters protocols: An array of application layer protocol + /// - Parameter protocols: An array of application layer protocol /// tokens to use for negotiation during the TLS handshake. public func applicationProtocols(_ protocols: [String]) -> Self { var mutableSelf = self @@ -749,7 +760,7 @@ public struct TCP: StreamProtocol { /// A boolean indicating that TCP should disable /// Nagle's algorithm (`TCP_NODELAY`). /// - /// - Parameter noDelay: True to disable Nagle's algorithm, false otherwise. + /// - Parameter noDelay: `true` to disable Nagle's algorithm, otherwise `false`. public func noDelay(_ noDelay: Bool) -> Self { var mutableSelf = self mutableSelf.noDelay = noDelay @@ -760,7 +771,7 @@ public struct TCP: StreamProtocol { /// /// A boolean indicating that TCP should use no-push mode (`TCP_NOPUSH`). /// - /// - Parameter noPush: True to use no-push mode, false otherwise. + /// - Parameter noPush: `true` to use no-push mode, otherwise `false`. public func noPush(_ noPush: Bool) -> Self { var mutableSelf = self mutableSelf.noPush = noPush @@ -771,7 +782,7 @@ public struct TCP: StreamProtocol { /// /// A boolean indicating that TCP should use no-options mode (`TCP_NOOPT`). /// - /// - Parameter noOptions: True to use no-options mode, false otherwise. + /// - Parameter noOptions: `true` to use no-options mode, otherwise `false`. public func noOptions(_ noOptions: Bool) -> Self { var mutableSelf = self mutableSelf.noOptions = noOptions @@ -834,7 +845,7 @@ public struct TCP: StreamProtocol { return mutableSelf } - /// Set maximum segment size. + /// Set the maximum segment size. /// /// The maximum segment size in bytes (`TCP_MAXSEG`). /// @@ -886,7 +897,7 @@ public struct TCP: StreamProtocol { /// A boolean to cause TCP to drop its connection after /// not receiving an ACK after a FIN (`TCP_RXT_FINDROP`). /// - /// - Parameter drop: True to drop, false otherwise. + /// - Parameter drop: `true` to drop, otherwise `false`. public func retransmitFinDrop(_ drop: Bool) -> Self { var mutableSelf = self mutableSelf.retransmitFinDrop = drop @@ -897,7 +908,7 @@ public struct TCP: StreamProtocol { /// /// A boolean to cause TCP to disable ACK stretching (`TCP_SENDMOREACKS`). /// - /// - Parameter disableAckStretching: True to disable ACK stretching, false otherwise. + /// - Parameter disableAckStretching: `true` to disable ACK stretching, otherwise `false`. public func ackStretchingDisabled(_ disableAckStretching: Bool) -> Self { var mutableSelf = self mutableSelf.disableAckStretching = disableAckStretching @@ -906,7 +917,7 @@ public struct TCP: StreamProtocol { /// Disable ECN negotiation. /// - /// - Parameter disableECN: True to disable ECN, false otherwise. + /// - Parameter disableECN: `true` to disable ECN, otherwise `false`. public func ecnDisabled(_ disableECN: Bool) -> Self { var mutableSelf = self mutableSelf.disableECN = disableECN @@ -925,12 +936,12 @@ public struct TCP: StreamProtocol { /// in the protocol stack. For example, if TLS is running over TCP, /// the Client Hello message may be sent as fast open data. /// - /// If TCP is the top-level protocol in the stack (the one the application - /// directly interacts with), TFO will be disabled unless the application - /// indicated that it will provide its own fast open data by calling - /// NWParameters.allowFastOpen. + /// If TCP is the top-level protocol in the stack (the one the app + /// directly interacts with), TFO is disabled unless the app + /// indicates that it provides its own fast open data by calling + /// `Parameters.allowFastOpen`. /// - /// - Parameter allowed: True to allow TFO, false otherwise. + /// - Parameter allowed: `true` to allow TFO, otherwise `false`. public func fastOpenAllowed(_ allowed: Bool) -> Self { var mutableSelf = self mutableSelf.fastOpen = allowed @@ -943,12 +954,12 @@ public struct TCP: StreamProtocol { /// in the protocol stack. For example, if TLS is running over TCP, /// the Client Hello message may be sent as fast open data. /// - /// If TCP is the top-level protocol in the stack (the one the application - /// directly interacts with), TFO will be disabled unless the application - /// indicated that it will provide its own fast open data by calling - /// NWParameters.allowFastOpen. + /// If TCP is the top-level protocol in the stack (the one the app + /// directly interacts with), TFO is disabled unless the app + /// indicates that it provides its own fast open data by calling + /// `Parameters.allowFastOpen`. /// - /// - Parameter enabled: True to enable TFO, false otherwise. + /// - Parameter enabled: `true` to enable TFO, otherwise `false`. public func fastOpen(_ enabled: Bool) -> Self { var mutableSelf = self mutableSelf.fastOpen = enabled @@ -1040,7 +1051,7 @@ public struct NoTransport: StreamProtocol { /// The system definition of the QUIC protocol. /// -/// Conforms to MultiplexProtocol, +/// Conforms to `MultiplexProtocol`, /// exposing configuration for a multiplexing instance of QUIC, which /// in turn exposes the ability to handle multiple streams of data over QUIC. @_spi(Essentials) @@ -1134,7 +1145,7 @@ public struct QUIC: MultiplexProtocol { /// Set the idle timeout for the QUIC connection, in milliseconds. /// /// If no packets are sent or received within this timeout, - /// the QUIC connection will be closed. + /// the QUIC connection is closed. /// /// - Parameter timeout: The idle timeout, in milliseconds. public func idleTimeout(_ timeout: Int) -> Self { @@ -1263,7 +1274,7 @@ public struct QUIC: MultiplexProtocol { return mutableSelf } - /// Configure TLS when used within QUIC. + /// The TLS configuration to use within QUIC. public var tls: TLS { QUIC.TLS(self) } @@ -1322,9 +1333,9 @@ public struct QUIC: MultiplexProtocol { /// A QUIC stream that runs over a QUIC connection. /// -/// Connections using QUICStream have a similar stream interface to TLS and TCP. +/// Connections using `QUICStream` have a similar stream interface to TLS and TCP. /// -/// > Note: This type is not intended to be inserted into the protocol stack manually; it is vended by connections that use QUIC. +/// > Note: This type isn't intended to be inserted into the protocol stack manually; it's provided by connections that use QUIC. @_spi(Essentials) @available(Network 0.1.0, *) public struct QUICStream: StreamProtocol { @@ -1371,7 +1382,7 @@ public struct UDP: DatagramProtocol { /// Skip computing checksums when sending UDP packets. /// - /// This will only take effect when running over IPv4 (`UDP_NOCKSUM`). + /// This only takes effect when running over IPv4 (`UDP_NOCKSUM`). public func noChecksumPreferred(_ noChecksum: Bool) -> Self { var mutableSelf = self mutableSelf.preferNoChecksum = noChecksum @@ -1389,7 +1400,7 @@ public struct UDP: DatagramProtocol { /// /// Can be used to insert IP into a protocol stack. /// -/// > Note: Specifying IP is optional, and need only be included in a +/// > Note: Specifying IP is optional, and you only need to include it in a /// protocol stack when configuring IP options. @_spi(Essentials) @available(Network 0.1.0, *) @@ -1449,8 +1460,8 @@ public struct IP: NetworkProtocolOptions { /// Specify a single version of the Internet Protocol to allow. /// - /// Setting this value will constrain which address endpoints can - /// be used and will filter DNS results during connection establishment. + /// Setting this value constrains which address endpoints can + /// be used and filters DNS results during connection establishment. /// /// - Parameter version: The IP version, IPv4 or IPv6. public func version(_ version: IPProtocol.Version) -> Self { @@ -1476,7 +1487,7 @@ public struct IP: NetworkProtocolOptions { /// The minimum MTU value is 1280 bytes for IPv6 (`IPV6_USE_MIN_MTU`). /// This value has no effect for IPv4. /// - /// - Parameter useMinimumMTU: True to use the minimum MTU value, false otherwise. + /// - Parameter useMinimumMTU: `true` to use the minimum MTU value, otherwise `false`. public func minimumMTU(_ useMinimumMTU: Bool) -> Self { var mutableSelf = self mutableSelf.useMinimumMTU = useMinimumMTU @@ -1487,7 +1498,7 @@ public struct IP: NetworkProtocolOptions { /// /// Equivalent to `IP_DONTFRAG` for IPv4 and `IPV6_DONTFRAG` for IPv6. /// - /// - Parameter dontFragment: True to disable fragmentation, false otherwise. + /// - Parameter dontFragment: `true` to disable fragmentation, otherwise `false`. public func fragmentationDisabled(_ dontFragment: Bool) -> Self { var mutableSelf = self mutableSelf.disableFragmentation = dontFragment @@ -1496,7 +1507,7 @@ public struct IP: NetworkProtocolOptions { /// Configure IP to calculate receive time for inbound packets. /// - /// - Parameter calculateReceiveTime: True to calculate receive time, false otherwise. + /// - Parameter calculateReceiveTime: `true` to calculate receive time, otherwise `false`. public func receiveTimeCalculated(_ calculateReceiveTime: Bool) -> Self { var mutableSelf = self mutableSelf.calculateReceiveTime = calculateReceiveTime @@ -1516,12 +1527,12 @@ public struct IP: NetworkProtocolOptions { /// Specify if multicast packets should be looped back for local delivery. /// /// By default, a multicast packet sent to a group to which the sending host itself belongs - /// will be looped back for local delivery. `disableMulticastLoopback` disables - /// this behavior and, if set, multicast packets will not be looped back to the sender. + /// is looped back for local delivery. `disableMulticastLoopback` disables + /// this behavior and, if set, multicast packets aren't looped back to the sender. /// /// > Note: Only applies to multicast packets. /// - /// - Parameter disableMulticastLoopback: True to disable multicast loopback, false otherwise. + /// - Parameter disableMulticastLoopback: `true` to disable multicast loopback, otherwise `false`. public func multicastLoopbackDisabled(_ disableMulticastLoopback: Bool) -> Self { var mutableSelf = self mutableSelf.disableMulticastLoopback = disableMulticastLoopback @@ -1547,8 +1558,10 @@ public struct IP: NetworkProtocolOptions { extension DatagramProtocol { } -// An opaque class that is responsible for creating and configuring NWParameters based on -/// the parameterized protocol stack. +/// A builder that creates and configures parameters from a parameterized protocol stack. +/// +/// `ParametersBuilder` is an opaque type that produces a `Parameters` value +/// based on the protocol stack you supply. @_spi(Essentials) @available(Network 0.1.0, *) public struct ParametersBuilder: ParametersProvider { @@ -1587,10 +1600,10 @@ public struct ParametersBuilder: ParametersProvider } } -/// Connect to an endpoint on the network to send and receive data. +/// A connection to an endpoint on the network for sending and receiving data. /// /// A connection handles establishment of any transport, security, and application-level protocols -/// required to transmit and receive user data. Connections may make multiple establishment +/// required to transmit and receive user data. A connection may make multiple establishment /// attempts before the connection is ready. @_spi(Essentials) @available(Network 0.1.0, *) @@ -1606,12 +1619,12 @@ public final class NetworkConnection(LockedState()) - /// Outbound connections + /// Creates an outbound connection. internal override init(kind: Kind, endpoint: Endpoint, parameters: Parameters, uuid: SystemUUID) { super.init(kind: kind, endpoint: endpoint, parameters: parameters, uuid: uuid) } - /// Inbound connections + /// Creates an inbound connection. internal override init(kind: Kind, using flow: EndpointFlow, uuid: SystemUUID) { super.init(kind: kind, using: flow, uuid: uuid) } @@ -1622,14 +1635,16 @@ public final class NetworkConnection Void) ) -> Self { @@ -1659,17 +1674,17 @@ public final class NetworkConnection: NetworkChannelBase, @@ -1753,7 +1768,9 @@ public class NetworkChannel: Networ { let uuid: SystemUUID - /// Compare two instances of NetworkChannel for equality + /// Compares two channels for equality. + /// + /// Compares two instances of `NetworkChannel` for equality. public static func == (lhs: NetworkChannel, rhs: NetworkChannel) -> Bool { lhs.id == rhs.id } @@ -1787,12 +1804,14 @@ public class NetworkChannel: Networ return self } - /// Generate a string representation of NetworkChannel suitable for logging + /// Generates a string representation of the channel suitable for logging. + /// + /// Returns a description of the underlying `NetworkChannel`. public var debugDescription: String { endpointFlow.debugDescription } - /// The set of parameters with which the channel was created + /// The set of parameters with which the channel was created. public var parameters: Parameters { get { endpointFlow.parameters @@ -1805,12 +1824,13 @@ public class NetworkChannel: Networ } } - /// Cancel the connection, and cause all update handlers to be cancelled. + /// Cancels the connection and any registered update handlers. /// - /// Cancel is asynchronous. The last callback will be to the stateUpdateHandler with the cancelled state. After - /// the stateUpdateHandlers are called with the cancelled state, all blocks are released to break retain cycles. + /// Cancellation is asynchronous. The last callback is to the `stateUpdateHandler` + /// with the canceled state. After that final callback, all blocks are released + /// to break retain cycles. /// - /// Calls to cancel after the first one are ignored. + /// Calls to `cancel()` after the first one are ignored. public func cancel() { endpointFlow.cancel() } @@ -1847,7 +1867,7 @@ extension NetworkConnection where ApplicationProtocol: OneToOneProtocol { /// Create a new connection to an endpoint, with protocol stack. /// - /// - Parameter to: The remote endpoint + /// - Parameter to: The remote endpoint. /// - Parameter using: The protocol stack to use for this connection. public convenience init( to endpoint: Endpoint, @@ -1885,11 +1905,12 @@ extension NetworkConnection where ApplicationProtocol: OneToOneProtocol { self.init(kind: .noTransport, endpoint: endpoint, parameters: builder.parameters, uuid: uuid) } - /// Create a new outbound connection to an endpoint, with parameters. + /// Creates a new outbound connection to an endpoint, with parameters. + /// /// The parameters determine the protocols to be used for the connection, and their options. /// /// - Parameter to: The remote endpoint to which to connect. - /// - Parameter using: The parameters define which protocols and path to use. + /// - Parameter using: The parameters that define which protocols and path to use. public convenience init( to endpoint: Endpoint, uuid: SystemUUID = SystemUUID(), @@ -1947,15 +1968,18 @@ extension NetworkConnection where ApplicationProtocol: MultiplexProtocol { self.init(to: endpoint, using: builder.parameters, uuid: uuid) } - /// Initiate some action to open the connection on the network like making a handshake, initiating a multiplexing session, etc. - /// Starts the connection, which will cause the connection to evaluate its path, do resolution, and try to become - /// ready (connected). `NetworkConnection` establishment is asynchronous. `onStateUpdate` will be called - /// when the state changes. If the connection cannot be established, the state will transition to `waiting` with - /// an associated error describing the reason. If an unrecoverable error is encountered, the state will - /// transition to `failed` with an associated error value. If the connection is established, the state will - /// transition to `ready`. + /// Starts the connection. /// - /// Start should only be called once on a connection, and multiple calls to start will be ignored. + /// Initiates the action to open the connection on the network, for example, + /// by making a handshake or initiating a multiplexing session. Causes the + /// connection to evaluate its path, perform resolution, and try to become ready + /// (connected). Establishment is asynchronous; `onStateUpdate` is called when the + /// state changes. If the connection can't be established, the state transitions to + /// `waiting` with an associated error describing the reason. If an unrecoverable + /// error is encountered, the state transitions to `failed` with an associated + /// error value. If the connection is established, the state transitions to `ready`. + /// + /// Call `start()` only once on a connection; subsequent calls are ignored. @discardableResult public func start() -> Self { endpointFlow.start() return self @@ -2011,7 +2035,7 @@ extension QUIC { } /// Set a closure to be called when the connection's state changes, which may be called - /// multiple times until the connection is cancelled. + /// multiple times until the connection is canceled. @discardableResult public func onStateUpdate( _ handler: (@escaping @Sendable (_ connection: Stream, _ state: State) -> Void) ) -> Self { @@ -2039,15 +2063,17 @@ extension NetworkConnection where ApplicationProtocol == QUIC { case newConnection(QUIC.Stream) } - /// Initiate a new data stream over QUIC. When invoked with no parameters, the default stream - /// type will be bidirectional. Unidirectional streams can be initiated by setting the - /// optional `bidirectional` parameter to false. + /// Initiates a new data stream over QUIC. + /// + /// When invoked with no parameters, the default stream type is bidirectional. + /// Unidirectional streams can be initiated by setting the optional `directionality` + /// parameter to `.unidirectional`. /// - /// This call will start the underlying QUIC connection if it has not been started already - /// and will block until the QUIC connection is ready. + /// This call starts the underlying QUIC connection if it has not been started already + /// and blocks until the QUIC connection is ready. /// - /// While streams can be cancelled independently of the underlying connection, - /// if the parent NetworkChannel is cancelled or fails, the streams will as well. + /// While streams can be canceled independently of the underlying connection, + /// if the parent `NetworkChannel` is canceled or fails, the streams are too. public func openStream( directionality: QUICStream.Directionality = .bidirectional, uuid: SystemUUID = SystemUUID(), 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..8b5afc6 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..5ba8dba 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..d234137 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 + /// The data path logging state. 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 + /// Canceled 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/Parameters/Parameters.swift b/Sources/SwiftNetwork/Parameters/Parameters.swift index 51ebcb3..57b3f03 100644 --- a/Sources/SwiftNetwork/Parameters/Parameters.swift +++ b/Sources/SwiftNetwork/Parameters/Parameters.swift @@ -64,14 +64,15 @@ public struct Parameters: Hashable, CustomStringConvertible { } public enum ExpiredDNSBehavior: Hashable, CustomStringConvertible { - /// Let the system determine whether or not to allow expired DNS answers + /// Lets the system determine whether to allow expired DNS answers. case systemDefault - /// Explicitly allow the use of expired DNS answers + /// Explicitly allows the use of expired DNS answers. case allow - /// Explicitly prohibit the use of expired DNS answers + /// Explicitly prohibits the use of expired DNS answers. case prohibit - /// Allow the use of expired DNS answers, and store answers in a persistent per-process cache. - /// This should only be set for hostnames whose resolutions are not expected to change across networks. + /// Allows the use of expired DNS answers and stores them in a persistent per-process cache. + /// + /// Set this only for host names whose resolutions don't change across networks. case persistent public var description: String { @@ -85,17 +86,17 @@ public struct Parameters: Hashable, CustomStringConvertible { } public enum ServiceClass: UInt8, CustomStringConvertible { - /// Default priority traffic + /// Default-priority traffic. case bestEffort = 0 - /// Bulk traffic, or traffic that can be de-prioritized behind foreground traffic + /// Bulk traffic, or traffic that can be deprioritized behind foreground traffic. case background = 1 - /// Interactive video traffic + /// Interactive video traffic. case interactiveVideo = 2 - /// Interactive voice traffic + /// Interactive voice traffic. case interactiveVoice = 3 - /// Responsive data + /// Responsive data. case responsiveData = 4 - /// Signaling + /// Signaling. case signaling = 5 public var description: String { 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..a83c56b 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..77ca05c 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 + /// Reads stream data from this protocol on behalf of 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 + /// Writes stream data on behalf of 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 + /// Reads datagrams from this protocol on behalf of 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 to send on behalf of the upper protocol. + /// + /// 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 on behalf of 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..8d03120 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 + /// Reads stream data from this protocol on behalf of 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 + /// Writes stream data on behalf of 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 + /// Reads stream data from this protocol on behalf of 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 + /// Writes stream data on behalf of 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 + /// Reads datagrams from this protocol on behalf of 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 to send on behalf of the upper protocol. + /// + /// 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 on behalf of 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..7cd65cc 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 an ECN ACK, 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..2408b70 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,10 @@ 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. + /// + /// Call this only if an AQM is present on the path, and only with + /// non-zero values for `new_packets_acked` and `new_packets_marked`. 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..74af2ba 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,11 @@ 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. + // TODO: Change this to use Endpoint when they become available. guard self.sockfd > 0 else { Logger.system.error("File descriptor is bad, cannot bind socket") throw NetworkError.posix(EINVAL) @@ -164,7 +174,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 +193,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 +202,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 +211,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 +220,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 +231,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() } From 4c79bf5a649cc2438243b052224c0d37a41438e5 Mon Sep 17 00:00:00 2001 From: Joe Heck Date: Tue, 9 Jun 2026 15:55:01 -0700 Subject: [PATCH 2/3] Apply PR review feedback - Restore Connection.swift and Parameters.swift to original wording to keep them aligned with the public SDK headerdoc. - Drop incorrect "on behalf of" phrasing in BottomProtocol.swift and OneToOneProtocol.swift; rewrite to describe what each function returns to or sends from the upper protocol. - Apply line suggestions: - IPv4Address/IPv6Address: use 'IPv4 "any" address' / 'IPv6 "any" address' instead of "any-address". - EndpointFlow: clarify log property doc and restore "Cancelled" spelling to match the public API. - PathProperties: drop hyphen from "link-quality measurement". --- .../SwiftNetwork/Connection/Connection.swift | 324 ++++++++---------- .../SwiftNetwork/Endpoint/IPv4Address.swift | 2 +- .../SwiftNetwork/Endpoint/IPv6Address.swift | 2 +- .../EndpointFlow/EndpointFlow.swift | 4 +- .../SwiftNetwork/Parameters/Parameters.swift | 23 +- .../SwiftNetwork/Path/PathProperties.swift | 4 +- .../Protocols/BottomProtocol.swift | 10 +- .../Protocols/OneToOneProtocol.swift | 14 +- 8 files changed, 178 insertions(+), 205 deletions(-) diff --git a/Sources/SwiftNetwork/Connection/Connection.swift b/Sources/SwiftNetwork/Connection/Connection.swift index 85d93e6..aed1dc1 100644 --- a/Sources/SwiftNetwork/Connection/Connection.swift +++ b/Sources/SwiftNetwork/Connection/Connection.swift @@ -73,9 +73,8 @@ public protocol ConnectionProtocol: Identifiable, Hashable { associatedtype ApplicationProtocolType: NetworkProtocolOptions } -/// A protocol stack configuration option. -/// -/// Conforming types can be used when configuring protocol stacks. +/// Types that conform to NetworkProtocolOptions can be used +/// when configuring protocol stacks. @_spi(Essentials) @available(Network 0.1.0, *) public protocol NetworkMetadataProtocol { @@ -103,9 +102,8 @@ extension NetworkProtocolOptions { } } -/// Additional storage attached to a connection. -/// -/// Conforming types can be used as additional storage within a connection. +/// Types that conform to ConnectionStorage can be used as additional storage within +/// a connection. @_spi(Essentials) @available(Network 0.1.0, *) public protocol ConnectionStorage { @@ -118,30 +116,26 @@ public struct DefaultProtocolStorage: ConnectionStorage, Sendable { public init() {} } -/// A protocol that can sit at the top of a non-multiplexed connection's protocol stack. -/// -/// Conforming types are allowed to be the top protocol in a network protocol stack -/// for non-multiplexed connections. +/// Types that conform to OneToOneProtocol are allowed to be the top protocol +/// in a network protocol stack for non-multiplexed connections. @_spi(Essentials) @available(Network 0.1.0, *) public protocol OneToOneProtocol: NetworkProtocolOptions { } -/// A protocol that can sit at the top of a multiplexed connection's protocol stack. +/// Types that conform to MultiplexProtocol are allowed to be the top protocol +/// in a network protocol stack for multiplexing network connection objects. /// -/// Conforming types are allowed to be the top protocol in a network protocol stack -/// for multiplexing network connection objects. Generally, network protocols -/// conforming to this type don't directly expose send or receive methods. -/// Instead, they expose methods to open and listen for multiplexed subconnections, -/// which can send and receive. +/// Generally network protocols conforming to this type will not directly expose +/// send or receive methods. Instead, they expose methods to open +/// and listen for multiplexed Subconnections which can send and receive. @_spi(Essentials) @available(Network 0.1.0, *) public protocol MultiplexProtocol: NetworkProtocolOptions { } -/// A protocol that exposes byte-stream send and receive methods. -/// -/// Conforming types expose methods for sending and receiving byte streams. +/// Types that conform to the StreamProtocol protocol expose methods for +/// sending and receiving byte streams. @_spi(Essentials) @available(Network 0.1.0, *) public protocol StreamProtocol: OneToOneProtocol { @@ -152,26 +146,24 @@ public protocol StreamProtocol: OneToOneProtocol { extension StreamProtocol { } -/// A protocol that sends and receives messages. -/// -/// Conforming types send and receive messages. The conforming type is responsible for -/// specifying its message-specific metadata. +/// Types that conform to MessageProtocol send and receive messages. +/// The conforming type is responsible for specifying its message-specific +/// metadata. @_spi(Essentials) @available(Network 0.1.0, *) public protocol MessageProtocol: OneToOneProtocol { associatedtype ContentType } -/// A protocol that sends and receives small, bounded messages. -/// -/// Conforming types send and receive messages with minimal or no metadata, -/// usually constrained to a fixed maximum size. +/// Types that conform to DatagramProtocol send and receive messages +/// with minimal or no metadata, usually constrained to a fixed maximum size. @_spi(Essentials) @available(Network 0.1.0, *) public protocol DatagramProtocol: MessageProtocol { } -/// A result builder for specifying and configuring protocol stacks declaratively. +/// A resultBuilder for specifying and configuring protocol stacks in +/// a declarative way @_spi(Essentials) @available(Network 0.1.0, *) @resultBuilder @@ -181,13 +173,12 @@ public struct ProtocolStackBuilder } } -/// A type that produces parameters for a connection. -/// -/// Conforming types can be used to generate a `Parameters` value. +/// Types that conform to the NWParametersProvider protocol can be used to +/// generate an NWParameters. @_spi(Essentials) @available(Network 0.1.0, *) public protocol ParametersProvider { - /// The generated parameters. + /// The generated NWParameters. var parameters: Parameters { get set } /// Require an interface when connecting, listening, and browsing. @@ -216,9 +207,9 @@ public protocol ParametersProvider { /// /// Prohibit connections and listeners from using a network interface /// that is considered expensive by the system, - /// for example, some cellular interfaces. + /// for example some cellular interfaces. /// - /// - Parameter prohibited: `true` if expensive paths are prohibited, otherwise `false`. + /// - Parameter prohibited: True if expensive paths are prohibited, false otherwise. func expensivePathsProhibited(_ prohibited: Bool) -> Self /// Prohibit using constrained paths. @@ -227,13 +218,13 @@ public protocol ParametersProvider { /// that is considered constrained by the system, /// for example an interface in Low Data Mode. /// - /// - Parameter prohibited: `true` if constrained paths are prohibited, otherwise `false`. + /// - Parameter prohibited: True if constrained paths are prohibited, false otherwise. func constrainedPathsProhibited(_ prohibited: Bool) -> Self /// Specify a specific endpoint to use as the local endpoint. /// - /// For connections, this is used to initiate traffic; - /// for listeners, this is used for receiving incoming + /// For connections, this will be used to initiate traffic; + /// for listeners, this will be used for receiving incoming /// connections. /// /// - Parameter endpoint: The local endpoint to require, or `nil` if none. @@ -242,11 +233,12 @@ public protocol ParametersProvider { /// Specify a specific port to use as the local endpoint, /// letting the system select the address. /// - /// For connections, this is used to initiate traffic; - /// for listeners, this is used for receiving incoming + /// For connections, this will be used to initiate traffic; + /// for listeners, this will be used for receiving incoming /// connections. /// /// - Parameter port: The local port to require. + /// Force a specific local port to be used. func localPort(_ port: UInt16) -> Self /// Allow local endpoint reuse. @@ -254,15 +246,15 @@ public protocol ParametersProvider { /// Allow multiple connections to use the same local address and port /// (`SO_REUSEADDR` and `SO_REUSEPORT`). /// - /// - Parameter allowed: `true` if allowed, otherwise `false`. + /// - Parameter allowed: True if allowed, false otherwise. func localEndpointReuseAllowed(_ allowed: Bool) -> Self /// Limit inbound connections to peers attached to the local link. /// - /// Listeners only advertise services on the local link and - /// only accept connections from the local link. + /// Listeners will only advertise services on the local link and + /// will only accept connections from the local link. /// - /// - Parameter local: `true` if limited to local peers, otherwise `false`. + /// - Parameter local: True if limited to local peers, false otherwise. func localOnly(_ local: Bool) -> Self /// Require DNSSEC validation when resolving an endpoint before making @@ -272,17 +264,17 @@ public protocol ParametersProvider { /// requires domain name resolution, such as a host or URL endpoint. /// /// - If this is not set or is set to `false`, DNSSEC validation - /// isn't required. + /// will not be required. /// /// - If this is set to `true` and no additional DNSSEC configuration - /// is set, the default behavior is followed: - /// only DNSSEC secure and DNSSEC insecure - /// resolved results are used to establish a connection. + /// is set, the default behavior will be followed: + /// Only DNSSEC secure and DNSSEC insecure + /// resolved results will be used to establish a connection. /// /// - If this is set to `true` and additional DNSSEC configuration - /// is set on the parameters, the behavior specified by that configuration is used. + /// is set on the parameters, the behavior specified by that configuration will be used. /// - /// - Parameter required: `true` if DNSSEC validation is required, otherwise `false`. + /// - Parameter required: True if DNSSEC validation is required, false otherwise. func dnssecValidationRequired(_ required: Bool) -> Self /// Set the data service class to use for connections. @@ -304,22 +296,22 @@ public protocol ParametersProvider { /// > Warning: This may have security implications for application data. /// In particular, TLS early data is replayable by a network attacker. /// You must account for this when sending data before the handshake - /// is confirmed. See RFC 8446 for more information. Don't + /// is confirmed. See RFC 8446 for more information. You MUST NOT /// enable fast open without a specific application profile that defines its use. /// /// As a side effect, this may implicitly enable fast open or early data for protocols - /// in the stack, even if they didn't have fast open explicitly enabled on them + /// in the stack, even if they did not have fast open explicitly enabled on them /// (such as the option to enable TCP Fast Open). /// - /// - Parameter allowed: `true` if fast open should be used, otherwise `false`. + /// - Parameter allowed: True if fast open should be used, false otherwise. func fastOpenAllowed(_ allowed: Bool) -> Self /// Allow or prohibit the use of expired DNS answers during connection establishment. /// - /// If allowed, a DNS answer that was previously returned may be reused for new + /// If allowed, a DNS answer that was previously returned may be re-used for new /// connections even after the answers are considered expired. A query for fresh answers - /// is sent in parallel, and the fresh answers are used as alternate addresses - /// in case the expired answers don't result in successful connections. + /// will be sent in parallel, and the fresh answers will be used as alternate addresses + /// in case the expired answers do not result in successful connections. /// /// By default, this value is `.systemDefault`, which allows the system to determine /// if it is appropriate to use expired answers. @@ -387,9 +379,9 @@ extension ParametersProvider { /// /// Prohibit connections and listeners from using a network interface /// that is considered expensive by the system, - /// for example, some cellular interfaces. + /// for example some cellular interfaces. /// - /// - Parameter prohibited: `true` if expensive paths are prohibited, otherwise `false`. + /// - Parameter prohibited: True if expensive paths are prohibited, false otherwise. public func expensivePathsProhibited(_ prohibited: Bool) -> Self { var mutableSelf = self mutableSelf.parameters.prohibitExpensivePaths = prohibited @@ -402,7 +394,7 @@ extension ParametersProvider { /// that is considered constrained by the system, /// for example an interface in Low Data Mode. /// - /// - Parameter prohibited: `true` if constrained paths are prohibited, otherwise `false`. + /// - Parameter prohibited: True if constrained paths are prohibited, false otherwise. public func constrainedPathsProhibited(_ prohibited: Bool) -> Self { var mutableSelf = self mutableSelf.parameters.prohibitConstrainedPaths = prohibited @@ -411,8 +403,8 @@ extension ParametersProvider { /// Specify a specific endpoint to use as the local endpoint. /// - /// For connections, this is used to initiate traffic; - /// for listeners, this is used for receiving incoming + /// For connections, this will be used to initiate traffic; + /// for listeners, this will be used for receiving incoming /// connections. /// /// - Parameter endpoint: The local endpoint to require, or `nil` if none. @@ -425,11 +417,12 @@ extension ParametersProvider { /// Specify a specific port to use as the local endpoint, /// letting the system select the address. /// - /// For connections, this is used to initiate traffic; - /// for listeners, this is used for receiving incoming + /// For connections, this will be used to initiate traffic; + /// for listeners, this will be used for receiving incoming /// connections. /// /// - Parameter port: The local port to require. + /// Force a specific local port to be used. public func localPort(_ port: UInt16) -> Self { var mutableSelf = self mutableSelf.parameters.localAddress = Endpoint(hostname: "::", port: port) @@ -441,7 +434,7 @@ extension ParametersProvider { /// Allow multiple connections to use the same local address and port /// (`SO_REUSEADDR` and `SO_REUSEPORT`). /// - /// - Parameter allowed: `true` if allowed, otherwise `false`. + /// - Parameter allowed: True if allowed, false otherwise. public func localEndpointReuseAllowed(_ allowed: Bool) -> Self { var mutableSelf = self mutableSelf.parameters.reuseLocalAddress = allowed @@ -450,10 +443,10 @@ extension ParametersProvider { /// Limit inbound connections to peers attached to the local link. /// - /// Listeners only advertise services on the local link and - /// only accept connections from the local link. + /// Listeners will only advertise services on the local link and + /// will only accept connections from the local link. /// - /// - Parameter local: `true` if limited to local peers, otherwise `false`. + /// - Parameter local: True if limited to local peers, false otherwise. public func localOnly(_ local: Bool) -> Self { var mutableSelf = self mutableSelf.parameters.localOnly = local @@ -467,17 +460,17 @@ extension ParametersProvider { /// requires domain name resolution, such as a host or URL endpoint. /// /// - If this is not set or is set to `false`, DNSSEC validation - /// isn't required. + /// will not be required. /// /// - If this is set to `true` and no additional DNSSEC configuration - /// is set, the default behavior is followed: - /// only DNSSEC secure and DNSSEC insecure - /// resolved results are used to establish a connection. + /// is set, the default behavior will be followed: + /// Only DNSSEC secure and DNSSEC insecure + /// resolved results will be used to establish a connection. /// /// - If this is set to `true` and additional DNSSEC configuration - /// is set on the parameters, the behavior specified by that configuration is used. + /// is set on the parameters, the behavior specified by that configuration will be used. /// - /// - Parameter required: `true` if DNSSEC validation is required, otherwise `false`. + /// - Parameter required: True if DNSSEC validation is required, false otherwise. public func dnssecValidationRequired(_ required: Bool) -> Self { var mutableSelf = self mutableSelf.parameters.requiresDNSSECValidation = required @@ -511,14 +504,14 @@ extension ParametersProvider { /// > Warning: This may have security implications for application data. /// In particular, TLS early data is replayable by a network attacker. /// You must account for this when sending data before the handshake - /// is confirmed. See RFC 8446 for more information. Don't + /// is confirmed. See RFC 8446 for more information. You MUST NOT /// enable fast open without a specific application profile that defines its use. /// /// As a side effect, this may implicitly enable fast open or early data for protocols - /// in the stack, even if they didn't have fast open explicitly enabled on them + /// in the stack, even if they did not have fast open explicitly enabled on them /// (such as the option to enable TCP Fast Open). /// - /// - Parameter allowed: `true` if fast open should be used, otherwise `false`. + /// - Parameter allowed: True if fast open should be used, false otherwise. public func fastOpenAllowed(_ allowed: Bool) -> Self { var mutableSelf = self mutableSelf.parameters.fastOpenEnabled = allowed @@ -527,10 +520,10 @@ extension ParametersProvider { /// Allow or prohibit the use of expired DNS answers during connection establishment. /// - /// If allowed, a DNS answer that was previously returned may be reused for new + /// If allowed, a DNS answer that was previously returned may be re-used for new /// connections even after the answers are considered expired. A query for fresh answers - /// is sent in parallel, and the fresh answers are used as alternate addresses - /// in case the expired answers don't result in successful connections. + /// will be sent in parallel, and the fresh answers will be used as alternate addresses + /// in case the expired answers do not result in successful connections. /// /// By default, this value is `.systemDefault`, which allows the system to determine /// if it is appropriate to use expired answers. @@ -561,9 +554,7 @@ extension ParametersProvider { } } -/// An extension that adds chainable configuration to parameters. -/// -/// Conforms `Parameters` to `ParametersProvider`. +/// An extension for Parameters that supports chainable configuration. @_spi(Essentials) @available(Network 0.1.0, *) extension Parameters: ParametersProvider { @@ -577,9 +568,7 @@ extension Parameters: ParametersProvider { } } -/// Sends and receives unreliable datagrams over QUIC. -/// -/// Implements RFC 9221. +/// Send and receive unreliable datagrams over QUIC via RFC 9221 @_spi(Essentials) @available(Network 0.1.0, *) public struct QUICDatagram: DatagramProtocol { @@ -691,7 +680,7 @@ public struct TLS: StreamProtocol { /// Application layer protocol negotiation (ALPN) tokens /// describe the application protocol in use above TLS. /// - /// - Parameter protocols: An array of application layer protocol + /// - Parameters protocols: An array of application layer protocol /// tokens to use for negotiation during the TLS handshake. public func applicationProtocols(_ protocols: [String]) -> Self { var mutableSelf = self @@ -760,7 +749,7 @@ public struct TCP: StreamProtocol { /// A boolean indicating that TCP should disable /// Nagle's algorithm (`TCP_NODELAY`). /// - /// - Parameter noDelay: `true` to disable Nagle's algorithm, otherwise `false`. + /// - Parameter noDelay: True to disable Nagle's algorithm, false otherwise. public func noDelay(_ noDelay: Bool) -> Self { var mutableSelf = self mutableSelf.noDelay = noDelay @@ -771,7 +760,7 @@ public struct TCP: StreamProtocol { /// /// A boolean indicating that TCP should use no-push mode (`TCP_NOPUSH`). /// - /// - Parameter noPush: `true` to use no-push mode, otherwise `false`. + /// - Parameter noPush: True to use no-push mode, false otherwise. public func noPush(_ noPush: Bool) -> Self { var mutableSelf = self mutableSelf.noPush = noPush @@ -782,7 +771,7 @@ public struct TCP: StreamProtocol { /// /// A boolean indicating that TCP should use no-options mode (`TCP_NOOPT`). /// - /// - Parameter noOptions: `true` to use no-options mode, otherwise `false`. + /// - Parameter noOptions: True to use no-options mode, false otherwise. public func noOptions(_ noOptions: Bool) -> Self { var mutableSelf = self mutableSelf.noOptions = noOptions @@ -845,7 +834,7 @@ public struct TCP: StreamProtocol { return mutableSelf } - /// Set the maximum segment size. + /// Set maximum segment size. /// /// The maximum segment size in bytes (`TCP_MAXSEG`). /// @@ -897,7 +886,7 @@ public struct TCP: StreamProtocol { /// A boolean to cause TCP to drop its connection after /// not receiving an ACK after a FIN (`TCP_RXT_FINDROP`). /// - /// - Parameter drop: `true` to drop, otherwise `false`. + /// - Parameter drop: True to drop, false otherwise. public func retransmitFinDrop(_ drop: Bool) -> Self { var mutableSelf = self mutableSelf.retransmitFinDrop = drop @@ -908,7 +897,7 @@ public struct TCP: StreamProtocol { /// /// A boolean to cause TCP to disable ACK stretching (`TCP_SENDMOREACKS`). /// - /// - Parameter disableAckStretching: `true` to disable ACK stretching, otherwise `false`. + /// - Parameter disableAckStretching: True to disable ACK stretching, false otherwise. public func ackStretchingDisabled(_ disableAckStretching: Bool) -> Self { var mutableSelf = self mutableSelf.disableAckStretching = disableAckStretching @@ -917,7 +906,7 @@ public struct TCP: StreamProtocol { /// Disable ECN negotiation. /// - /// - Parameter disableECN: `true` to disable ECN, otherwise `false`. + /// - Parameter disableECN: True to disable ECN, false otherwise. public func ecnDisabled(_ disableECN: Bool) -> Self { var mutableSelf = self mutableSelf.disableECN = disableECN @@ -936,12 +925,12 @@ public struct TCP: StreamProtocol { /// in the protocol stack. For example, if TLS is running over TCP, /// the Client Hello message may be sent as fast open data. /// - /// If TCP is the top-level protocol in the stack (the one the app - /// directly interacts with), TFO is disabled unless the app - /// indicates that it provides its own fast open data by calling - /// `Parameters.allowFastOpen`. + /// If TCP is the top-level protocol in the stack (the one the application + /// directly interacts with), TFO will be disabled unless the application + /// indicated that it will provide its own fast open data by calling + /// NWParameters.allowFastOpen. /// - /// - Parameter allowed: `true` to allow TFO, otherwise `false`. + /// - Parameter allowed: True to allow TFO, false otherwise. public func fastOpenAllowed(_ allowed: Bool) -> Self { var mutableSelf = self mutableSelf.fastOpen = allowed @@ -954,12 +943,12 @@ public struct TCP: StreamProtocol { /// in the protocol stack. For example, if TLS is running over TCP, /// the Client Hello message may be sent as fast open data. /// - /// If TCP is the top-level protocol in the stack (the one the app - /// directly interacts with), TFO is disabled unless the app - /// indicates that it provides its own fast open data by calling - /// `Parameters.allowFastOpen`. + /// If TCP is the top-level protocol in the stack (the one the application + /// directly interacts with), TFO will be disabled unless the application + /// indicated that it will provide its own fast open data by calling + /// NWParameters.allowFastOpen. /// - /// - Parameter enabled: `true` to enable TFO, otherwise `false`. + /// - Parameter enabled: True to enable TFO, false otherwise. public func fastOpen(_ enabled: Bool) -> Self { var mutableSelf = self mutableSelf.fastOpen = enabled @@ -1051,7 +1040,7 @@ public struct NoTransport: StreamProtocol { /// The system definition of the QUIC protocol. /// -/// Conforms to `MultiplexProtocol`, +/// Conforms to MultiplexProtocol, /// exposing configuration for a multiplexing instance of QUIC, which /// in turn exposes the ability to handle multiple streams of data over QUIC. @_spi(Essentials) @@ -1145,7 +1134,7 @@ public struct QUIC: MultiplexProtocol { /// Set the idle timeout for the QUIC connection, in milliseconds. /// /// If no packets are sent or received within this timeout, - /// the QUIC connection is closed. + /// the QUIC connection will be closed. /// /// - Parameter timeout: The idle timeout, in milliseconds. public func idleTimeout(_ timeout: Int) -> Self { @@ -1274,7 +1263,7 @@ public struct QUIC: MultiplexProtocol { return mutableSelf } - /// The TLS configuration to use within QUIC. + /// Configure TLS when used within QUIC. public var tls: TLS { QUIC.TLS(self) } @@ -1333,9 +1322,9 @@ public struct QUIC: MultiplexProtocol { /// A QUIC stream that runs over a QUIC connection. /// -/// Connections using `QUICStream` have a similar stream interface to TLS and TCP. +/// Connections using QUICStream have a similar stream interface to TLS and TCP. /// -/// > Note: This type isn't intended to be inserted into the protocol stack manually; it's provided by connections that use QUIC. +/// > Note: This type is not intended to be inserted into the protocol stack manually; it is vended by connections that use QUIC. @_spi(Essentials) @available(Network 0.1.0, *) public struct QUICStream: StreamProtocol { @@ -1382,7 +1371,7 @@ public struct UDP: DatagramProtocol { /// Skip computing checksums when sending UDP packets. /// - /// This only takes effect when running over IPv4 (`UDP_NOCKSUM`). + /// This will only take effect when running over IPv4 (`UDP_NOCKSUM`). public func noChecksumPreferred(_ noChecksum: Bool) -> Self { var mutableSelf = self mutableSelf.preferNoChecksum = noChecksum @@ -1400,7 +1389,7 @@ public struct UDP: DatagramProtocol { /// /// Can be used to insert IP into a protocol stack. /// -/// > Note: Specifying IP is optional, and you only need to include it in a +/// > Note: Specifying IP is optional, and need only be included in a /// protocol stack when configuring IP options. @_spi(Essentials) @available(Network 0.1.0, *) @@ -1460,8 +1449,8 @@ public struct IP: NetworkProtocolOptions { /// Specify a single version of the Internet Protocol to allow. /// - /// Setting this value constrains which address endpoints can - /// be used and filters DNS results during connection establishment. + /// Setting this value will constrain which address endpoints can + /// be used and will filter DNS results during connection establishment. /// /// - Parameter version: The IP version, IPv4 or IPv6. public func version(_ version: IPProtocol.Version) -> Self { @@ -1487,7 +1476,7 @@ public struct IP: NetworkProtocolOptions { /// The minimum MTU value is 1280 bytes for IPv6 (`IPV6_USE_MIN_MTU`). /// This value has no effect for IPv4. /// - /// - Parameter useMinimumMTU: `true` to use the minimum MTU value, otherwise `false`. + /// - Parameter useMinimumMTU: True to use the minimum MTU value, false otherwise. public func minimumMTU(_ useMinimumMTU: Bool) -> Self { var mutableSelf = self mutableSelf.useMinimumMTU = useMinimumMTU @@ -1498,7 +1487,7 @@ public struct IP: NetworkProtocolOptions { /// /// Equivalent to `IP_DONTFRAG` for IPv4 and `IPV6_DONTFRAG` for IPv6. /// - /// - Parameter dontFragment: `true` to disable fragmentation, otherwise `false`. + /// - Parameter dontFragment: True to disable fragmentation, false otherwise. public func fragmentationDisabled(_ dontFragment: Bool) -> Self { var mutableSelf = self mutableSelf.disableFragmentation = dontFragment @@ -1507,7 +1496,7 @@ public struct IP: NetworkProtocolOptions { /// Configure IP to calculate receive time for inbound packets. /// - /// - Parameter calculateReceiveTime: `true` to calculate receive time, otherwise `false`. + /// - Parameter calculateReceiveTime: True to calculate receive time, false otherwise. public func receiveTimeCalculated(_ calculateReceiveTime: Bool) -> Self { var mutableSelf = self mutableSelf.calculateReceiveTime = calculateReceiveTime @@ -1527,12 +1516,12 @@ public struct IP: NetworkProtocolOptions { /// Specify if multicast packets should be looped back for local delivery. /// /// By default, a multicast packet sent to a group to which the sending host itself belongs - /// is looped back for local delivery. `disableMulticastLoopback` disables - /// this behavior and, if set, multicast packets aren't looped back to the sender. + /// will be looped back for local delivery. `disableMulticastLoopback` disables + /// this behavior and, if set, multicast packets will not be looped back to the sender. /// /// > Note: Only applies to multicast packets. /// - /// - Parameter disableMulticastLoopback: `true` to disable multicast loopback, otherwise `false`. + /// - Parameter disableMulticastLoopback: True to disable multicast loopback, false otherwise. public func multicastLoopbackDisabled(_ disableMulticastLoopback: Bool) -> Self { var mutableSelf = self mutableSelf.disableMulticastLoopback = disableMulticastLoopback @@ -1558,10 +1547,8 @@ public struct IP: NetworkProtocolOptions { extension DatagramProtocol { } -/// A builder that creates and configures parameters from a parameterized protocol stack. -/// -/// `ParametersBuilder` is an opaque type that produces a `Parameters` value -/// based on the protocol stack you supply. +// An opaque class that is responsible for creating and configuring NWParameters based on +/// the parameterized protocol stack. @_spi(Essentials) @available(Network 0.1.0, *) public struct ParametersBuilder: ParametersProvider { @@ -1600,10 +1587,10 @@ public struct ParametersBuilder: ParametersProvider } } -/// A connection to an endpoint on the network for sending and receiving data. +/// Connect to an endpoint on the network to send and receive data. /// /// A connection handles establishment of any transport, security, and application-level protocols -/// required to transmit and receive user data. A connection may make multiple establishment +/// required to transmit and receive user data. Connections may make multiple establishment /// attempts before the connection is ready. @_spi(Essentials) @available(Network 0.1.0, *) @@ -1619,12 +1606,12 @@ public final class NetworkConnection(LockedState()) - /// Creates an outbound connection. + /// Outbound connections internal override init(kind: Kind, endpoint: Endpoint, parameters: Parameters, uuid: SystemUUID) { super.init(kind: kind, endpoint: endpoint, parameters: parameters, uuid: uuid) } - /// Creates an inbound connection. + /// Inbound connections internal override init(kind: Kind, using flow: EndpointFlow, uuid: SystemUUID) { super.init(kind: kind, using: flow, uuid: uuid) } @@ -1635,16 +1622,14 @@ public final class NetworkConnection Void) ) -> Self { @@ -1674,17 +1659,17 @@ public final class NetworkConnection: NetworkChannelBase, @@ -1768,9 +1753,7 @@ public class NetworkChannel: Networ { let uuid: SystemUUID - /// Compares two channels for equality. - /// - /// Compares two instances of `NetworkChannel` for equality. + /// Compare two instances of NetworkChannel for equality public static func == (lhs: NetworkChannel, rhs: NetworkChannel) -> Bool { lhs.id == rhs.id } @@ -1804,14 +1787,12 @@ public class NetworkChannel: Networ return self } - /// Generates a string representation of the channel suitable for logging. - /// - /// Returns a description of the underlying `NetworkChannel`. + /// Generate a string representation of NetworkChannel suitable for logging public var debugDescription: String { endpointFlow.debugDescription } - /// The set of parameters with which the channel was created. + /// The set of parameters with which the channel was created public var parameters: Parameters { get { endpointFlow.parameters @@ -1824,13 +1805,12 @@ public class NetworkChannel: Networ } } - /// Cancels the connection and any registered update handlers. + /// Cancel the connection, and cause all update handlers to be cancelled. /// - /// Cancellation is asynchronous. The last callback is to the `stateUpdateHandler` - /// with the canceled state. After that final callback, all blocks are released - /// to break retain cycles. + /// Cancel is asynchronous. The last callback will be to the stateUpdateHandler with the cancelled state. After + /// the stateUpdateHandlers are called with the cancelled state, all blocks are released to break retain cycles. /// - /// Calls to `cancel()` after the first one are ignored. + /// Calls to cancel after the first one are ignored. public func cancel() { endpointFlow.cancel() } @@ -1867,7 +1847,7 @@ extension NetworkConnection where ApplicationProtocol: OneToOneProtocol { /// Create a new connection to an endpoint, with protocol stack. /// - /// - Parameter to: The remote endpoint. + /// - Parameter to: The remote endpoint /// - Parameter using: The protocol stack to use for this connection. public convenience init( to endpoint: Endpoint, @@ -1905,12 +1885,11 @@ extension NetworkConnection where ApplicationProtocol: OneToOneProtocol { self.init(kind: .noTransport, endpoint: endpoint, parameters: builder.parameters, uuid: uuid) } - /// Creates a new outbound connection to an endpoint, with parameters. - /// + /// Create a new outbound connection to an endpoint, with parameters. /// The parameters determine the protocols to be used for the connection, and their options. /// /// - Parameter to: The remote endpoint to which to connect. - /// - Parameter using: The parameters that define which protocols and path to use. + /// - Parameter using: The parameters define which protocols and path to use. public convenience init( to endpoint: Endpoint, uuid: SystemUUID = SystemUUID(), @@ -1968,18 +1947,15 @@ extension NetworkConnection where ApplicationProtocol: MultiplexProtocol { self.init(to: endpoint, using: builder.parameters, uuid: uuid) } - /// Starts the connection. + /// Initiate some action to open the connection on the network like making a handshake, initiating a multiplexing session, etc. + /// Starts the connection, which will cause the connection to evaluate its path, do resolution, and try to become + /// ready (connected). `NetworkConnection` establishment is asynchronous. `onStateUpdate` will be called + /// when the state changes. If the connection cannot be established, the state will transition to `waiting` with + /// an associated error describing the reason. If an unrecoverable error is encountered, the state will + /// transition to `failed` with an associated error value. If the connection is established, the state will + /// transition to `ready`. /// - /// Initiates the action to open the connection on the network, for example, - /// by making a handshake or initiating a multiplexing session. Causes the - /// connection to evaluate its path, perform resolution, and try to become ready - /// (connected). Establishment is asynchronous; `onStateUpdate` is called when the - /// state changes. If the connection can't be established, the state transitions to - /// `waiting` with an associated error describing the reason. If an unrecoverable - /// error is encountered, the state transitions to `failed` with an associated - /// error value. If the connection is established, the state transitions to `ready`. - /// - /// Call `start()` only once on a connection; subsequent calls are ignored. + /// Start should only be called once on a connection, and multiple calls to start will be ignored. @discardableResult public func start() -> Self { endpointFlow.start() return self @@ -2035,7 +2011,7 @@ extension QUIC { } /// Set a closure to be called when the connection's state changes, which may be called - /// multiple times until the connection is canceled. + /// multiple times until the connection is cancelled. @discardableResult public func onStateUpdate( _ handler: (@escaping @Sendable (_ connection: Stream, _ state: State) -> Void) ) -> Self { @@ -2063,17 +2039,15 @@ extension NetworkConnection where ApplicationProtocol == QUIC { case newConnection(QUIC.Stream) } - /// Initiates a new data stream over QUIC. - /// - /// When invoked with no parameters, the default stream type is bidirectional. - /// Unidirectional streams can be initiated by setting the optional `directionality` - /// parameter to `.unidirectional`. + /// Initiate a new data stream over QUIC. When invoked with no parameters, the default stream + /// type will be bidirectional. Unidirectional streams can be initiated by setting the + /// optional `bidirectional` parameter to false. /// - /// This call starts the underlying QUIC connection if it has not been started already - /// and blocks until the QUIC connection is ready. + /// This call will start the underlying QUIC connection if it has not been started already + /// and will block until the QUIC connection is ready. /// - /// While streams can be canceled independently of the underlying connection, - /// if the parent `NetworkChannel` is canceled or fails, the streams are too. + /// While streams can be cancelled independently of the underlying connection, + /// if the parent NetworkChannel is cancelled or fails, the streams will as well. public func openStream( directionality: QUICStream.Directionality = .bidirectional, uuid: SystemUUID = SystemUUID(), diff --git a/Sources/SwiftNetwork/Endpoint/IPv4Address.swift b/Sources/SwiftNetwork/Endpoint/IPv4Address.swift index 8b5afc6..95dc6b2 100644 --- a/Sources/SwiftNetwork/Endpoint/IPv4Address.swift +++ b/Sources/SwiftNetwork/Endpoint/IPv4Address.swift @@ -14,7 +14,7 @@ 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) } diff --git a/Sources/SwiftNetwork/Endpoint/IPv6Address.swift b/Sources/SwiftNetwork/Endpoint/IPv6Address.swift index 5ba8dba..da93328 100644 --- a/Sources/SwiftNetwork/Endpoint/IPv6Address.swift +++ b/Sources/SwiftNetwork/Endpoint/IPv6Address.swift @@ -14,7 +14,7 @@ public struct IPv6Address: IPAddress, Hashable, CustomDebugStringConvertible { - /// The IPv6 any-address. + /// The IPv6 "any" address. public static var any: IPv6Address { IPv6Address((0, 0, 0, 0)) } diff --git a/Sources/SwiftNetwork/EndpointFlow/EndpointFlow.swift b/Sources/SwiftNetwork/EndpointFlow/EndpointFlow.swift index d234137..6b9045a 100644 --- a/Sources/SwiftNetwork/EndpointFlow/EndpointFlow.swift +++ b/Sources/SwiftNetwork/EndpointFlow/EndpointFlow.swift @@ -30,7 +30,7 @@ internal import Synchronization final class EndpointFlow: CustomDebugStringConvertible { - /// The data path logging state. + /// State used to emit logs on the data path. public var log = NetworkLoggerState() enum State: Equatable, Sendable { @@ -44,7 +44,7 @@ final class EndpointFlow: CustomDebugStringConvertible { case ready /// Failed connections are disconnected and can no longer send or receive data. case failed(NetworkError) - /// Canceled connections have been invalidated by the client and 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/Parameters/Parameters.swift b/Sources/SwiftNetwork/Parameters/Parameters.swift index 57b3f03..51ebcb3 100644 --- a/Sources/SwiftNetwork/Parameters/Parameters.swift +++ b/Sources/SwiftNetwork/Parameters/Parameters.swift @@ -64,15 +64,14 @@ public struct Parameters: Hashable, CustomStringConvertible { } public enum ExpiredDNSBehavior: Hashable, CustomStringConvertible { - /// Lets the system determine whether to allow expired DNS answers. + /// Let the system determine whether or not to allow expired DNS answers case systemDefault - /// Explicitly allows the use of expired DNS answers. + /// Explicitly allow the use of expired DNS answers case allow - /// Explicitly prohibits the use of expired DNS answers. + /// Explicitly prohibit the use of expired DNS answers case prohibit - /// Allows the use of expired DNS answers and stores them in a persistent per-process cache. - /// - /// Set this only for host names whose resolutions don't change across networks. + /// Allow the use of expired DNS answers, and store answers in a persistent per-process cache. + /// This should only be set for hostnames whose resolutions are not expected to change across networks. case persistent public var description: String { @@ -86,17 +85,17 @@ public struct Parameters: Hashable, CustomStringConvertible { } public enum ServiceClass: UInt8, CustomStringConvertible { - /// Default-priority traffic. + /// Default priority traffic case bestEffort = 0 - /// Bulk traffic, or traffic that can be deprioritized behind foreground traffic. + /// Bulk traffic, or traffic that can be de-prioritized behind foreground traffic case background = 1 - /// Interactive video traffic. + /// Interactive video traffic case interactiveVideo = 2 - /// Interactive voice traffic. + /// Interactive voice traffic case interactiveVoice = 3 - /// Responsive data. + /// Responsive data case responsiveData = 4 - /// Signaling. + /// Signaling case signaling = 5 public var description: String { diff --git a/Sources/SwiftNetwork/Path/PathProperties.swift b/Sources/SwiftNetwork/Path/PathProperties.swift index a83c56b..086500b 100644 --- a/Sources/SwiftNetwork/Path/PathProperties.swift +++ b/Sources/SwiftNetwork/Path/PathProperties.swift @@ -244,9 +244,9 @@ public struct PathProperties: CustomStringConvertible { static public let fallbackIsOpportunistic = Flags(rawValue: 1 << 33) } - /// 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 /// The link quality is minimal. case minimal diff --git a/Sources/SwiftNetwork/Protocols/BottomProtocol.swift b/Sources/SwiftNetwork/Protocols/BottomProtocol.swift index 77ca05c..450e745 100644 --- a/Sources/SwiftNetwork/Protocols/BottomProtocol.swift +++ b/Sources/SwiftNetwork/Protocols/BottomProtocol.swift @@ -125,7 +125,7 @@ extension BottomProtocolHandler where Self: ~Copyable, UpperProtocol: InboundDat public protocol BottomStreamProtocol: ~Copyable, BottomProtocolHandler, OutboundStreamHandler where UpperProtocol == InboundStreamLinkage { - /// Reads stream data from this protocol on behalf of the upper protocol. + /// 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? @@ -135,7 +135,7 @@ where UpperProtocol == InboundStreamLinkage { /// Protocols can implement this function to customize behavior. mutating func getOutboundStreamDataRoomAvailable() throws(NetworkError) -> Int - /// Writes stream data on behalf of the upper protocol. + /// Sends stream data created by the upper protocol. /// /// Protocols can implement this function to customize behavior. mutating func sendStreamData(_ streamData: consuming FrameArray) throws(NetworkError) @@ -147,12 +147,12 @@ where UpperProtocol == InboundStreamLinkage { public protocol BottomDatagramProtocol: ~Copyable, BottomProtocolHandler, OutboundDatagramHandler where UpperProtocol == InboundDatagramLinkage { - /// Reads datagrams from this protocol on behalf of the upper protocol. + /// Returns received datagrams to the upper protocol. /// /// Protocols can implement this function to customize behavior. mutating func receiveDatagrams(maximumDatagramCount: Int) throws(NetworkError) -> FrameArray? - /// Returns datagram frames to send on behalf of the upper protocol. + /// Returns datagram frames the upper protocol can use to send. /// /// Protocols can implement this function to customize behavior. mutating func getDatagramsToSend( @@ -160,7 +160,7 @@ where UpperProtocol == InboundDatagramLinkage { minimumDatagramSize: Int ) throws(NetworkError) -> FrameArray? - /// Sends datagrams on behalf of the upper protocol. + /// 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/OneToOneProtocol.swift b/Sources/SwiftNetwork/Protocols/OneToOneProtocol.swift index 8d03120..1b0a784 100644 --- a/Sources/SwiftNetwork/Protocols/OneToOneProtocol.swift +++ b/Sources/SwiftNetwork/Protocols/OneToOneProtocol.swift @@ -148,7 +148,7 @@ where UpperProtocol: InboundDataLinkage, LowerProtocol: OutboundDataLinkage { public protocol OneToOneStreamProtocol: ~Copyable, OneToOneDatapathProtocol where UpperProtocol == InboundStreamLinkage, LowerProtocol == OutboundStreamLinkage { - /// Reads stream data from this protocol on behalf of the upper protocol. + /// 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? @@ -158,7 +158,7 @@ where UpperProtocol == InboundStreamLinkage, LowerProtocol == OutboundStreamLink /// Protocols can implement this function to customize behavior. mutating func getOutboundStreamDataRoomAvailable() throws(NetworkError) -> Int - /// Writes stream data on behalf of the upper protocol. + /// Sends stream data created by the upper protocol. /// /// Protocols can implement this function to customize behavior. mutating func sendStreamData(_ streamData: consuming FrameArray) throws(NetworkError) @@ -180,7 +180,7 @@ where UpperProtocol == InboundStreamLinkage, LowerProtocol == OutboundStreamLink public protocol OneToOneStreamToDatagramProtocol: ~Copyable, OneToOneDatapathProtocol where UpperProtocol == InboundStreamLinkage, LowerProtocol == OutboundDatagramLinkage { - /// Reads stream data from this protocol on behalf of the upper protocol. + /// 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? @@ -190,7 +190,7 @@ where UpperProtocol == InboundStreamLinkage, LowerProtocol == OutboundDatagramLi /// Protocols can implement this function to customize behavior. mutating func getOutboundStreamDataRoomAvailable() throws(NetworkError) -> Int - /// Writes stream data on behalf of the upper protocol. + /// Sends stream data created by the upper protocol. /// /// Protocols can implement this function to customize behavior. mutating func sendStreamData(_ streamData: consuming FrameArray) throws(NetworkError) @@ -202,12 +202,12 @@ where UpperProtocol == InboundStreamLinkage, LowerProtocol == OutboundDatagramLi public protocol OneToOneDatagramProtocol: ~Copyable, OneToOneDatapathProtocol where UpperProtocol == InboundDatagramLinkage, LowerProtocol == OutboundDatagramLinkage { - /// Reads datagrams from this protocol on behalf of the upper protocol. + /// Returns received datagrams to the upper protocol. /// /// Protocols can implement this function to customize behavior. mutating func receiveDatagrams(maximumDatagramCount: Int) throws(NetworkError) -> FrameArray? - /// Returns datagram frames to send on behalf of the upper protocol. + /// Returns datagram frames the upper protocol can use to send. /// /// Protocols can implement this function to customize behavior. mutating func getDatagramsToSend( @@ -215,7 +215,7 @@ where UpperProtocol == InboundDatagramLinkage, LowerProtocol == OutboundDatagram minimumDatagramSize: Int ) throws(NetworkError) -> FrameArray? - /// Sends datagrams on behalf of the upper protocol. + /// Sends datagrams created by the upper protocol. /// /// Protocols can implement this function to customize behavior. mutating func sendDatagrams(_ datagrams: consuming FrameArray) throws(NetworkError) From c2c0ef81dc551e71db485f249af4420cc30f3bff Mon Sep 17 00:00:00 2001 From: Tommy Pauly Date: Tue, 9 Jun 2026 16:45:09 -0700 Subject: [PATCH 3/3] Apply suggestions from code review Co-authored-by: Tommy Pauly --- Sources/SwiftNetwork/QUIC/ECN.swift | 2 +- Sources/SwiftNetwork/QUIC/Prague.swift | 3 --- Sources/SwiftNetwork/System/SystemSocket.swift | 1 - 3 files changed, 1 insertion(+), 5 deletions(-) diff --git a/Sources/SwiftNetwork/QUIC/ECN.swift b/Sources/SwiftNetwork/QUIC/ECN.swift index 7cd65cc..21d116f 100644 --- a/Sources/SwiftNetwork/QUIC/ECN.swift +++ b/Sources/SwiftNetwork/QUIC/ECN.swift @@ -42,7 +42,7 @@ enum ECNState { /// Optimistically sends ECN-capable packets in this state. /// - /// On receiving an ECN ACK, moves to capable if validation succeeds; otherwise, moves to failed. + /// On receiving `ACK_ECN`, moves to capable if validation succeeds; otherwise, moves to failed. case validate /// Validation succeeded. diff --git a/Sources/SwiftNetwork/QUIC/Prague.swift b/Sources/SwiftNetwork/QUIC/Prague.swift index 2408b70..655a6fc 100644 --- a/Sources/SwiftNetwork/QUIC/Prague.swift +++ b/Sources/SwiftNetwork/QUIC/Prague.swift @@ -399,9 +399,6 @@ struct Prague: CongestionControlProtocol, CubicLikeProtocol { } /// Updates alpha after receiving acknowledgments. - /// - /// Call this only if an AQM is present on the path, and only with - /// non-zero values for `new_packets_acked` and `new_packets_marked`. private mutating func pragueUpdateAlpha( largestSentPN: Int64, largestAckedPN: Int64, diff --git a/Sources/SwiftNetwork/System/SystemSocket.swift b/Sources/SwiftNetwork/System/SystemSocket.swift index 74af2ba..942344c 100644 --- a/Sources/SwiftNetwork/System/SystemSocket.swift +++ b/Sources/SwiftNetwork/System/SystemSocket.swift @@ -163,7 +163,6 @@ class SystemSocket { /// /// 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 available. guard self.sockfd > 0 else { Logger.system.error("File descriptor is bad, cannot bind socket") throw NetworkError.posix(EINVAL)