Skip to content

Commit

Permalink
Add withSockAddr() helper function
Browse files Browse the repository at this point in the history
  • Loading branch information
lhoward committed Nov 14, 2024
1 parent ca8c077 commit 09b09bf
Showing 1 changed file with 11 additions and 7 deletions.
18 changes: 11 additions & 7 deletions FlyingSocks/Sources/SocketAddress.swift
Original file line number Diff line number Diff line change
Expand Up @@ -46,12 +46,7 @@ public protocol SocketAddress: Sendable {

extension SocketAddress {
public var family: sa_family_t {
var this = self
return withUnsafePointer(to: &this) {
$0.withMemoryRebound(to: sockaddr.self, capacity: 1) {
$0.pointee.sa_family
}
}
withSockAddr { $0.pointee.sa_family }
}

var size: socklen_t {
Expand Down Expand Up @@ -154,7 +149,7 @@ extension sockaddr_un: SocketAddress, @unchecked Sendable {

public extension SocketAddress {
static func make(from storage: sockaddr_storage) throws -> Self {
guard self is sockaddr_storage || storage.ss_family == family else {
guard self is sockaddr_storage.Type || storage.ss_family == family else {
throw SocketError.unsupportedAddress
}
var storage = storage
Expand Down Expand Up @@ -244,3 +239,12 @@ public struct AnySocketAddress: Sendable, SocketAddress {
}
}

public extension SocketAddress {
func withSockAddr<T>(_ body: (_ sa: UnsafePointer<sockaddr>) throws -> T) rethrows -> T {
return try withUnsafePointer(to: self) {
try $0.withMemoryRebound(to: sockaddr.self, capacity: 1) { sa in
try body(sa)
}
}
}
}

0 comments on commit 09b09bf

Please sign in to comment.