A trait abstracting over the types that can be passed as a `sockaddr`. # Safety Implementers of this trait must ensure that `with_sockaddr` calls `f` with a pointer that is readable for the passed length, and points to data that is a valid socket address for the system calls that accept `sockaddr` as a const pointer.
| 44 | /// is a valid socket address for the system calls that accept `sockaddr` as a |
| 45 | /// const pointer. |
| 46 | pub unsafe trait SocketAddrArg { |
| 47 | /// Call a closure with the pointer and length to the corresponding C type. |
| 48 | /// |
| 49 | /// The memory pointed to by the pointer of size length is guaranteed to be |
| 50 | /// valid only for the duration of the call. |
| 51 | /// |
| 52 | /// The API uses a closure so that: |
| 53 | /// - The libc types are not exposed in the rustix API. |
| 54 | /// - Types like `SocketAddrUnix` that contain their corresponding C type |
| 55 | /// can pass it directly without a copy. |
| 56 | /// - Other socket types can construct their C-compatible struct on the |
| 57 | /// stack and call the closure with a pointer to it. |
| 58 | /// |
| 59 | /// # Safety |
| 60 | /// |
| 61 | /// For `f` to use its pointer argument, it'll contain an `unsafe` block. |
| 62 | /// The caller of `with_sockaddr` here is responsible for ensuring that the |
| 63 | /// safety condition for that `unsafe` block is satisfied by the guarantee |
| 64 | /// that `with_sockaddr` here provides. |
| 65 | unsafe fn with_sockaddr<R>( |
| 66 | &self, |
| 67 | f: impl FnOnce(*const SocketAddrOpaque, SocketAddrLen) -> R, |
| 68 | ) -> R; |
| 69 | |
| 70 | /// Convert to `SocketAddrAny`. |
| 71 | fn as_any(&self) -> SocketAddrAny { |
| 72 | let mut storage = MaybeUninit::<SocketAddrStorage>::uninit(); |
| 73 | // SAFETY: We've allocated `storage` here, we're writing to it, and |
| 74 | // we're using the number of bytes written. |
| 75 | unsafe { |
| 76 | let len = self.write_sockaddr(storage.as_mut_ptr()); |
| 77 | SocketAddrAny::new(storage, len) |
| 78 | } |
| 79 | } |
| 80 | |
| 81 | /// Encode an address into a `SocketAddrStorage`. |
| 82 | /// |
| 83 | /// Returns the number of bytes that were written. |
| 84 | /// |
| 85 | /// For a safe interface to this functionality, use [`as_any`]. |
| 86 | /// |
| 87 | /// [`as_any`]: Self::as_any |
| 88 | /// |
| 89 | /// # Safety |
| 90 | /// |
| 91 | /// `storage` must be valid to write up to `size_of<SocketAddrStorage>()` |
| 92 | /// bytes to. |
| 93 | unsafe fn write_sockaddr(&self, storage: *mut SocketAddrStorage) -> SocketAddrLen { |
| 94 | // The closure dereferences exactly `len` bytes at `ptr`. |
| 95 | self.with_sockaddr(|ptr, len| { |
| 96 | ptr::copy_nonoverlapping(ptr.cast::<u8>(), storage.cast::<u8>(), len as usize); |
| 97 | len |
| 98 | }) |
| 99 | } |
| 100 | } |
| 101 | |
| 102 | /// Helper for implementing `SocketAddrArg::with_sockaddr`. |
| 103 | /// |