Skip to main content

gio/
socket.rs

1// Take a look at the license at the top of the repository in the LICENSE file.
2
3#[cfg(unix)]
4use std::os::unix::io::{AsFd, AsRawFd, BorrowedFd, FromRawFd, IntoRawFd, OwnedFd, RawFd};
5#[cfg(windows)]
6use std::os::windows::io::{
7    AsRawSocket, AsSocket, BorrowedSocket, FromRawSocket, IntoRawSocket, OwnedSocket, RawSocket,
8};
9#[cfg(feature = "v2_60")]
10use std::time::Duration;
11use std::{cell::RefCell, marker::PhantomData, mem::transmute, pin::Pin, ptr};
12
13use futures_core::stream::Stream;
14use glib::{Slice, prelude::*, translate::*};
15
16#[cfg(feature = "v2_60")]
17use crate::PollableReturn;
18use crate::{Cancellable, Socket, SocketAddress, SocketControlMessage, ffi};
19
20impl Socket {
21    /// Creates a new #GSocket from a native file descriptor
22    /// or winsock SOCKET handle.
23    ///
24    /// This reads all the settings from the file descriptor so that
25    /// all properties should work. Note that the file descriptor
26    /// will be set to non-blocking mode, independent on the blocking
27    /// mode of the #GSocket.
28    ///
29    /// On success, the returned #GSocket takes ownership of @fd. On failure, the
30    /// caller must close @fd themselves.
31    ///
32    /// Since GLib 2.46, it is no longer a fatal error to call this on a non-socket
33    /// descriptor.  Instead, a GError will be set with code [`IOErrorEnum::Failed`][crate::IOErrorEnum::Failed]
34    /// ## `fd`
35    /// a native socket file descriptor.
36    ///
37    /// # Returns
38    ///
39    /// a #GSocket or [`None`] on error.
40    ///     Free the returned object with g_object_unref().
41    #[cfg(unix)]
42    #[cfg_attr(docsrs, doc(cfg(unix)))]
43    #[doc(alias = "g_socket_new_from_fd")]
44    pub fn from_fd(fd: OwnedFd) -> Result<Socket, glib::Error> {
45        unsafe { Self::from_raw_fd(fd) }
46    }
47
48    #[cfg(unix)]
49    #[cfg_attr(docsrs, doc(cfg(unix)))]
50    #[doc(alias = "g_socket_new_from_fd")]
51    pub unsafe fn from_raw_fd(fd: impl IntoRawFd) -> Result<Socket, glib::Error> {
52        let fd = fd.into_raw_fd();
53        let mut error = ptr::null_mut();
54        unsafe {
55            let ret = ffi::g_socket_new_from_fd(fd, &mut error);
56            if error.is_null() {
57                Ok(from_glib_full(ret))
58            } else {
59                let _ = OwnedFd::from_raw_fd(fd);
60                Err(from_glib_full(error))
61            }
62        }
63    }
64
65    #[cfg(windows)]
66    #[cfg_attr(docsrs, doc(cfg(windows)))]
67    pub fn from_socket(socket: OwnedSocket) -> Result<Socket, glib::Error> {
68        unsafe { Self::from_raw_socket(socket) }
69    }
70
71    #[cfg(windows)]
72    #[cfg_attr(docsrs, doc(cfg(windows)))]
73    pub fn from_raw_socket(socket: impl IntoRawSocket) -> Result<Socket, glib::Error> {
74        let socket = socket.into_raw_socket();
75        let mut error = ptr::null_mut();
76        unsafe {
77            let ret = ffi::g_socket_new_from_fd(socket as i32, &mut error);
78            if error.is_null() {
79                Ok(from_glib_full(ret))
80            } else {
81                let _ = OwnedSocket::from_raw_socket(socket);
82                Err(from_glib_full(error))
83            }
84        }
85    }
86}
87
88#[cfg(unix)]
89#[cfg_attr(docsrs, doc(cfg(unix)))]
90impl AsRawFd for Socket {
91    fn as_raw_fd(&self) -> RawFd {
92        unsafe { ffi::g_socket_get_fd(self.to_glib_none().0) as _ }
93    }
94}
95
96#[cfg(unix)]
97#[cfg_attr(docsrs, doc(cfg(unix)))]
98impl AsFd for Socket {
99    fn as_fd(&self) -> BorrowedFd<'_> {
100        unsafe {
101            let raw_fd = self.as_raw_fd();
102            BorrowedFd::borrow_raw(raw_fd)
103        }
104    }
105}
106
107#[cfg(windows)]
108#[cfg_attr(docsrs, doc(cfg(windows)))]
109impl AsRawSocket for Socket {
110    fn as_raw_socket(&self) -> RawSocket {
111        unsafe { ffi::g_socket_get_fd(self.to_glib_none().0) as _ }
112    }
113}
114
115#[cfg(windows)]
116#[cfg_attr(docsrs, doc(cfg(windows)))]
117impl AsSocket for Socket {
118    fn as_socket(&self) -> BorrowedSocket<'_> {
119        unsafe {
120            let raw_socket = self.as_raw_socket();
121            BorrowedSocket::borrow_raw(raw_socket)
122        }
123    }
124}
125
126#[doc(alias = "GInputVector")]
127#[repr(transparent)]
128#[derive(Debug)]
129pub struct InputVector<'v> {
130    vector: ffi::GInputVector,
131    buffer: PhantomData<&'v mut [u8]>,
132}
133
134impl<'v> InputVector<'v> {
135    #[inline]
136    pub fn new(buffer: &'v mut [u8]) -> Self {
137        Self {
138            vector: ffi::GInputVector {
139                buffer: buffer.as_mut_ptr() as *mut _,
140                size: buffer.len(),
141            },
142            buffer: PhantomData,
143        }
144    }
145}
146
147unsafe impl Send for InputVector<'_> {}
148unsafe impl Sync for InputVector<'_> {}
149
150impl std::ops::Deref for InputVector<'_> {
151    type Target = [u8];
152
153    #[inline]
154    fn deref(&self) -> &Self::Target {
155        unsafe { std::slice::from_raw_parts(self.vector.buffer as *const _, self.vector.size) }
156    }
157}
158
159impl std::ops::DerefMut for InputVector<'_> {
160    #[inline]
161    fn deref_mut(&mut self) -> &mut Self::Target {
162        unsafe { std::slice::from_raw_parts_mut(self.vector.buffer as *mut _, self.vector.size) }
163    }
164}
165
166#[derive(Debug)]
167pub struct SocketControlMessages {
168    ptr: *mut *mut ffi::GSocketControlMessage,
169    len: u32,
170}
171
172impl SocketControlMessages {
173    #[inline]
174    pub const fn new() -> Self {
175        Self {
176            ptr: ptr::null_mut(),
177            len: 0,
178        }
179    }
180}
181
182impl AsRef<[SocketControlMessage]> for SocketControlMessages {
183    #[inline]
184    fn as_ref(&self) -> &[SocketControlMessage] {
185        unsafe { std::slice::from_raw_parts(self.ptr as *const _, self.len as usize) }
186    }
187}
188
189impl std::ops::Deref for SocketControlMessages {
190    type Target = [SocketControlMessage];
191
192    #[inline]
193    fn deref(&self) -> &Self::Target {
194        self.as_ref()
195    }
196}
197
198impl Default for SocketControlMessages {
199    #[inline]
200    fn default() -> Self {
201        Self::new()
202    }
203}
204
205impl Drop for SocketControlMessages {
206    #[inline]
207    fn drop(&mut self) {
208        unsafe {
209            let _: Slice<SocketControlMessage> =
210                Slice::from_glib_full_num(self.ptr as *mut _, self.len as usize);
211        }
212    }
213}
214
215/// Structure used for scatter/gather data input when receiving multiple
216/// messages or packets in one go. You generally pass in an array of empty
217/// #GInputVectors and the operation will use all the buffers as if they
218/// were one buffer, and will set @bytes_received to the total number of bytes
219/// received across all #GInputVectors.
220///
221/// This structure closely mirrors `struct mmsghdr` and `struct msghdr` from
222/// the POSIX sockets API (see `man 2 recvmmsg`).
223///
224/// If @address is non-[`None`] then it is set to the source address the message
225/// was received from, and the caller must free it afterwards.
226///
227/// If @control_messages is non-[`None`] then it is set to an array of control
228/// messages received with the message (if any), and the caller must free it
229/// afterwards. @num_control_messages is set to the number of elements in
230/// this array, which may be zero.
231///
232/// Flags relevant to this message will be returned in @flags. For example,
233/// `MSG_EOR` or `MSG_TRUNC`.
234#[doc(alias = "GInputMessage")]
235#[repr(transparent)]
236#[derive(Debug)]
237pub struct InputMessage<'m> {
238    message: ffi::GInputMessage,
239    address: PhantomData<Option<&'m mut Option<SocketAddress>>>,
240    vectors: PhantomData<&'m mut [InputVector<'m>]>,
241    control_messages: PhantomData<Option<&'m mut SocketControlMessages>>,
242}
243
244impl<'m> InputMessage<'m> {
245    pub fn new(
246        mut address: Option<&'m mut Option<SocketAddress>>,
247        vectors: &'m mut [InputVector<'m>],
248        control_messages: Option<&'m mut SocketControlMessages>,
249    ) -> Self {
250        let address = address
251            .as_mut()
252            .map(|a| {
253                assert!(a.is_none());
254                *a as *mut _ as *mut _
255            })
256            .unwrap_or_else(ptr::null_mut);
257        let (control_messages, num_control_messages) = control_messages
258            .map(|c| (&mut c.ptr as *mut _, &mut c.len as *mut _))
259            .unwrap_or_else(|| (ptr::null_mut(), ptr::null_mut()));
260        Self {
261            message: ffi::GInputMessage {
262                address,
263                vectors: vectors.as_mut_ptr() as *mut ffi::GInputVector,
264                num_vectors: vectors.len().try_into().unwrap(),
265                bytes_received: 0,
266                flags: 0,
267                control_messages,
268                num_control_messages,
269            },
270            address: PhantomData,
271            vectors: PhantomData,
272            control_messages: PhantomData,
273        }
274    }
275    #[inline]
276    pub fn vectors(&mut self) -> &'m mut [InputVector<'m>] {
277        unsafe {
278            std::slice::from_raw_parts_mut(
279                self.message.vectors as *mut _,
280                self.message.num_vectors as usize,
281            )
282        }
283    }
284    #[inline]
285    pub const fn flags(&self) -> i32 {
286        self.message.flags
287    }
288    #[inline]
289    pub const fn bytes_received(&self) -> usize {
290        self.message.bytes_received
291    }
292}
293
294#[doc(alias = "GOutputVector")]
295#[repr(transparent)]
296#[derive(Debug)]
297pub struct OutputVector<'v> {
298    vector: ffi::GOutputVector,
299    buffer: PhantomData<&'v [u8]>,
300}
301
302impl<'v> OutputVector<'v> {
303    #[inline]
304    pub const fn new(buffer: &'v [u8]) -> Self {
305        Self {
306            vector: ffi::GOutputVector {
307                buffer: buffer.as_ptr() as *const _,
308                size: buffer.len(),
309            },
310            buffer: PhantomData,
311        }
312    }
313}
314
315unsafe impl Send for OutputVector<'_> {}
316unsafe impl Sync for OutputVector<'_> {}
317
318impl std::ops::Deref for OutputVector<'_> {
319    type Target = [u8];
320
321    #[inline]
322    fn deref(&self) -> &Self::Target {
323        unsafe { std::slice::from_raw_parts(self.vector.buffer as *const _, self.vector.size) }
324    }
325}
326
327/// Structure used for scatter/gather data output when sending multiple
328/// messages or packets in one go. You generally pass in an array of
329/// #GOutputVectors and the operation will use all the buffers as if they
330/// were one buffer.
331///
332/// If @address is [`None`] then the message is sent to the default receiver
333/// (as previously set by g_socket_connect()).
334#[doc(alias = "GOutputMessage")]
335#[repr(transparent)]
336#[derive(Debug)]
337pub struct OutputMessage<'m> {
338    message: ffi::GOutputMessage,
339    address: PhantomData<Option<&'m SocketAddress>>,
340    vectors: PhantomData<&'m [OutputVector<'m>]>,
341    control_messages: PhantomData<&'m [SocketControlMessage]>,
342}
343
344impl<'m> OutputMessage<'m> {
345    pub fn new<A: IsA<SocketAddress>>(
346        address: Option<&'m A>,
347        vectors: &'m [OutputVector<'m>],
348        control_messages: &'m [SocketControlMessage],
349    ) -> Self {
350        Self {
351            message: ffi::GOutputMessage {
352                address: address
353                    .map(|a| a.upcast_ref::<SocketAddress>().as_ptr())
354                    .unwrap_or_else(ptr::null_mut),
355                vectors: mut_override(vectors.as_ptr() as *const ffi::GOutputVector),
356                num_vectors: vectors.len().try_into().unwrap(),
357                bytes_sent: 0,
358                control_messages: control_messages.as_ptr() as *mut _,
359                num_control_messages: control_messages.len().try_into().unwrap(),
360            },
361            address: PhantomData,
362            vectors: PhantomData,
363            control_messages: PhantomData,
364        }
365    }
366    #[inline]
367    pub fn vectors(&self) -> &'m [OutputVector<'m>] {
368        unsafe {
369            std::slice::from_raw_parts(
370                self.message.vectors as *const _,
371                self.message.num_vectors as usize,
372            )
373        }
374    }
375    #[inline]
376    pub fn bytes_sent(&self) -> u32 {
377        self.message.bytes_sent
378    }
379}
380
381pub trait SocketExtManual: IsA<Socket> + Sized {
382    /// Receive data (up to @size bytes) from a socket. This is mainly used by
383    /// connection-oriented sockets; it is identical to g_socket_receive_from()
384    /// with @address set to [`None`].
385    ///
386    /// For [`SocketType::Datagram`][crate::SocketType::Datagram] and [`SocketType::Seqpacket`][crate::SocketType::Seqpacket] sockets,
387    /// g_socket_receive() will always read either 0 or 1 complete messages from
388    /// the socket. If the received message is too large to fit in @buffer, then
389    /// the data beyond @size bytes will be discarded, without any explicit
390    /// indication that this has occurred.
391    ///
392    /// For [`SocketType::Stream`][crate::SocketType::Stream] sockets, g_socket_receive() can return any
393    /// number of bytes, up to @size. If more than @size bytes have been
394    /// received, the additional data will be returned in future calls to
395    /// g_socket_receive().
396    ///
397    /// If the socket is in blocking mode the call will block until there
398    /// is some data to receive, the connection is closed, or there is an
399    /// error. If there is no data available and the socket is in
400    /// non-blocking mode, a [`IOErrorEnum::WouldBlock`][crate::IOErrorEnum::WouldBlock] error will be
401    /// returned. To be notified when data is available, wait for the
402    /// [`glib::IOCondition::IN`][crate::glib::IOCondition::IN] condition.
403    ///
404    /// On error -1 is returned and @error is set accordingly.
405    /// ## `cancellable`
406    /// a `GCancellable` or [`None`]
407    ///
408    /// # Returns
409    ///
410    /// Number of bytes read, or 0 if the connection was closed by
411    /// the peer, or -1 on error
412    ///
413    /// ## `buffer`
414    ///
415    ///     a buffer to read data into (which should be at least @size bytes long).
416    #[doc(alias = "g_socket_receive")]
417    fn receive<B: AsMut<[u8]>, C: IsA<Cancellable>>(
418        &self,
419        mut buffer: B,
420        cancellable: Option<&C>,
421    ) -> Result<usize, glib::Error> {
422        let cancellable = cancellable.map(|c| c.as_ref());
423        let gcancellable = cancellable.to_glib_none();
424        let buffer = buffer.as_mut();
425        let buffer_ptr = buffer.as_mut_ptr();
426        let count = buffer.len();
427        unsafe {
428            let mut error = ptr::null_mut();
429            let ret = ffi::g_socket_receive(
430                self.as_ref().to_glib_none().0,
431                buffer_ptr,
432                count,
433                gcancellable.0,
434                &mut error,
435            );
436            if error.is_null() {
437                Ok(ret as usize)
438            } else {
439                Err(from_glib_full(error))
440            }
441        }
442    }
443    /// Receive data (up to @size bytes) from a socket.
444    ///
445    /// If @address is non-[`None`] then @address will be set equal to the
446    /// source address of the received packet.
447    /// @address is owned by the caller.
448    ///
449    /// See g_socket_receive() for additional information.
450    /// ## `cancellable`
451    /// a `GCancellable` or [`None`]
452    ///
453    /// # Returns
454    ///
455    /// Number of bytes read, or 0 if the connection was closed by
456    /// the peer, or -1 on error
457    ///
458    /// ## `address`
459    /// a pointer to a #GSocketAddress
460    ///     pointer, or [`None`]
461    ///
462    /// ## `buffer`
463    ///
464    ///     a buffer to read data into (which should be at least @size bytes long).
465    #[doc(alias = "g_socket_receive_from")]
466    fn receive_from<B: AsMut<[u8]>, C: IsA<Cancellable>>(
467        &self,
468        mut buffer: B,
469        cancellable: Option<&C>,
470    ) -> Result<(usize, SocketAddress), glib::Error> {
471        let cancellable = cancellable.map(|c| c.as_ref());
472        let gcancellable = cancellable.to_glib_none();
473        let buffer = buffer.as_mut();
474        let buffer_ptr = buffer.as_mut_ptr();
475        let count = buffer.len();
476        unsafe {
477            let mut error = ptr::null_mut();
478            let mut addr_ptr = ptr::null_mut();
479
480            let ret = ffi::g_socket_receive_from(
481                self.as_ref().to_glib_none().0,
482                &mut addr_ptr,
483                buffer_ptr,
484                count,
485                gcancellable.0,
486                &mut error,
487            );
488            if error.is_null() {
489                Ok((ret as usize, from_glib_full(addr_ptr)))
490            } else {
491                Err(from_glib_full(error))
492            }
493        }
494    }
495    /// Receive data from a socket.  For receiving multiple messages, see
496    /// g_socket_receive_messages(); for easier use, see
497    /// g_socket_receive() and g_socket_receive_from().
498    ///
499    /// If @address is non-[`None`] then @address will be set equal to the
500    /// source address of the received packet.
501    /// @address is owned by the caller.
502    ///
503    /// @vector must point to an array of #GInputVector structs and
504    /// @num_vectors must be the length of this array.  These structs
505    /// describe the buffers that received data will be scattered into.
506    /// If @num_vectors is -1, then @vectors is assumed to be terminated
507    /// by a #GInputVector with a [`None`] buffer pointer.
508    ///
509    /// As a special case, if @num_vectors is 0 (in which case, @vectors
510    /// may of course be [`None`]), then a single byte is received and
511    /// discarded. This is to facilitate the common practice of sending a
512    /// single '\0' byte for the purposes of transferring ancillary data.
513    ///
514    /// @messages, if non-[`None`], will be set to point to a newly-allocated
515    /// array of #GSocketControlMessage instances or [`None`] if no such
516    /// messages was received. These correspond to the control messages
517    /// received from the kernel, one #GSocketControlMessage per message
518    /// from the kernel. This array is [`None`]-terminated and must be freed
519    /// by the caller using g_free() after calling g_object_unref() on each
520    /// element. If @messages is [`None`], any control messages received will
521    /// be discarded.
522    ///
523    /// @num_messages, if non-[`None`], will be set to the number of control
524    /// messages received.
525    ///
526    /// If both @messages and @num_messages are non-[`None`], then
527    /// @num_messages gives the number of #GSocketControlMessage instances
528    /// in @messages (ie: not including the [`None`] terminator).
529    ///
530    /// @flags is an in/out parameter. The commonly available arguments
531    /// for this are available in the #GSocketMsgFlags enum, but the
532    /// values there are the same as the system values, and the flags
533    /// are passed in as-is, so you can pass in system-specific flags too
534    /// (and g_socket_receive_message() may pass system-specific flags out).
535    /// Flags passed in to the parameter affect the receive operation; flags returned
536    /// out of it are relevant to the specific returned message.
537    ///
538    /// As with g_socket_receive(), data may be discarded if @self is
539    /// [`SocketType::Datagram`][crate::SocketType::Datagram] or [`SocketType::Seqpacket`][crate::SocketType::Seqpacket] and you do not
540    /// provide enough buffer space to read a complete message. You can pass
541    /// [`SocketMsgFlags::PEEK`][crate::SocketMsgFlags::PEEK] in @flags to peek at the current message without
542    /// removing it from the receive queue, but there is no portable way to find
543    /// out the length of the message other than by reading it into a
544    /// sufficiently-large buffer.
545    ///
546    /// If the socket is in blocking mode the call will block until there
547    /// is some data to receive, the connection is closed, or there is an
548    /// error. If there is no data available and the socket is in
549    /// non-blocking mode, a [`IOErrorEnum::WouldBlock`][crate::IOErrorEnum::WouldBlock] error will be
550    /// returned. To be notified when data is available, wait for the
551    /// [`glib::IOCondition::IN`][crate::glib::IOCondition::IN] condition.
552    ///
553    /// On error -1 is returned and @error is set accordingly.
554    /// ## `vectors`
555    /// an array of #GInputVector structs
556    /// ## `flags`
557    /// a pointer to an int containing #GSocketMsgFlags flags,
558    ///    which may additionally contain
559    ///    [other platform specific flags](http://man7.org/linux/man-pages/man2/recv.2.html)
560    /// ## `cancellable`
561    /// a `GCancellable` or [`None`]
562    ///
563    /// # Returns
564    ///
565    /// Number of bytes read, or 0 if the connection was closed by
566    /// the peer, or -1 on error
567    ///
568    /// ## `address`
569    /// a pointer to a #GSocketAddress
570    ///     pointer, or [`None`]
571    ///
572    /// ## `messages`
573    /// a pointer
574    ///    which may be filled with an array of #GSocketControlMessages, or [`None`]
575    #[doc(alias = "g_socket_receive_message")]
576    fn receive_message<C: IsA<Cancellable>>(
577        &self,
578        mut address: Option<&mut Option<SocketAddress>>,
579        vectors: &mut [InputVector],
580        control_messages: Option<&mut SocketControlMessages>,
581        mut flags: i32,
582        cancellable: Option<&C>,
583    ) -> Result<(usize, i32), glib::Error> {
584        let cancellable = cancellable.map(|c| c.as_ref());
585        let address = address
586            .as_mut()
587            .map(|a| {
588                assert!(a.is_none());
589                *a as *mut _ as *mut _
590            })
591            .unwrap_or_else(ptr::null_mut);
592        let (control_messages, num_control_messages) = control_messages
593            .map(|c| (&mut c.ptr as *mut _, &mut c.len as *mut _ as *mut _))
594            .unwrap_or_else(|| (ptr::null_mut(), ptr::null_mut()));
595        unsafe {
596            let mut error = ptr::null_mut();
597
598            let received = ffi::g_socket_receive_message(
599                self.as_ref().to_glib_none().0,
600                address,
601                vectors.as_mut_ptr() as *mut ffi::GInputVector,
602                vectors.len().try_into().unwrap(),
603                control_messages,
604                num_control_messages,
605                &mut flags,
606                cancellable.to_glib_none().0,
607                &mut error,
608            );
609            if error.is_null() {
610                Ok((received as usize, flags))
611            } else {
612                Err(from_glib_full(error))
613            }
614        }
615    }
616    /// Receive multiple data messages from @self in one go.  This is the most
617    /// complicated and fully-featured version of this call. For easier use, see
618    /// g_socket_receive(), g_socket_receive_from(), and g_socket_receive_message().
619    ///
620    /// @messages must point to an array of #GInputMessage structs and
621    /// @num_messages must be the length of this array. Each #GInputMessage
622    /// contains a pointer to an array of #GInputVector structs describing the
623    /// buffers that the data received in each message will be written to. Using
624    /// multiple #GInputVectors is more memory-efficient than manually copying data
625    /// out of a single buffer to multiple sources, and more system-call-efficient
626    /// than making multiple calls to g_socket_receive(), such as in scenarios where
627    /// a lot of data packets need to be received (e.g. high-bandwidth video
628    /// streaming over RTP/UDP).
629    ///
630    /// @flags modify how all messages are received. The commonly available
631    /// arguments for this are available in the #GSocketMsgFlags enum, but the
632    /// values there are the same as the system values, and the flags
633    /// are passed in as-is, so you can pass in system-specific flags too. These
634    /// flags affect the overall receive operation. Flags affecting individual
635    /// messages are returned in #GInputMessage.flags.
636    ///
637    /// The other members of #GInputMessage are treated as described in its
638    /// documentation.
639    ///
640    /// If #GSocket:blocking is [`true`] the call will block until @num_messages have
641    /// been received, or the end of the stream is reached.
642    ///
643    /// If #GSocket:blocking is [`false`] the call will return up to @num_messages
644    /// without blocking, or [`IOErrorEnum::WouldBlock`][crate::IOErrorEnum::WouldBlock] if no messages are queued in the
645    /// operating system to be received.
646    ///
647    /// In blocking mode, if #GSocket:timeout is positive and is reached before any
648    /// messages are received, [`IOErrorEnum::TimedOut`][crate::IOErrorEnum::TimedOut] is returned, otherwise up to
649    /// @num_messages are returned. (Note: This is effectively the
650    /// behaviour of `MSG_WAITFORONE` with recvmmsg().)
651    ///
652    /// To be notified when messages are available, wait for the
653    /// [`glib::IOCondition::IN`][crate::glib::IOCondition::IN] condition. Note though that you may still receive
654    /// [`IOErrorEnum::WouldBlock`][crate::IOErrorEnum::WouldBlock] from g_socket_receive_messages() even if you were
655    /// previously notified of a [`glib::IOCondition::IN`][crate::glib::IOCondition::IN] condition.
656    ///
657    /// If the remote peer closes the connection, any messages queued in the
658    /// operating system will be returned, and subsequent calls to
659    /// g_socket_receive_messages() will return 0 (with no error set).
660    ///
661    /// On error -1 is returned and @error is set accordingly. An error will only
662    /// be returned if zero messages could be received; otherwise the number of
663    /// messages successfully received before the error will be returned.
664    /// ## `messages`
665    /// an array of #GInputMessage structs
666    /// ## `flags`
667    /// an int containing #GSocketMsgFlags flags for the overall operation,
668    ///    which may additionally contain
669    ///    [other platform specific flags](http://man7.org/linux/man-pages/man2/recv.2.html)
670    /// ## `cancellable`
671    /// a `GCancellable` or [`None`]
672    ///
673    /// # Returns
674    ///
675    /// number of messages received, or -1 on error. Note that the number
676    ///     of messages received may be smaller than @num_messages if in non-blocking
677    ///     mode, if the peer closed the connection, or if @num_messages
678    ///     was larger than `UIO_MAXIOV` (1024), in which case the caller may re-try
679    ///     to receive the remaining messages.
680    #[doc(alias = "g_socket_receive_messages")]
681    fn receive_messages<C: IsA<Cancellable>>(
682        &self,
683        messages: &mut [InputMessage],
684        flags: i32,
685        cancellable: Option<&C>,
686    ) -> Result<usize, glib::Error> {
687        let cancellable = cancellable.map(|c| c.as_ref());
688        unsafe {
689            let mut error = ptr::null_mut();
690
691            let count = ffi::g_socket_receive_messages(
692                self.as_ref().to_glib_none().0,
693                messages.as_mut_ptr() as *mut _,
694                messages.len().try_into().unwrap(),
695                flags,
696                cancellable.to_glib_none().0,
697                &mut error,
698            );
699            if error.is_null() {
700                Ok(count as usize)
701            } else {
702                Err(from_glib_full(error))
703            }
704        }
705    }
706    /// This behaves exactly the same as g_socket_receive(), except that
707    /// the choice of blocking or non-blocking behavior is determined by
708    /// the @blocking argument rather than by @self's properties.
709    /// ## `blocking`
710    /// whether to do blocking or non-blocking I/O
711    /// ## `cancellable`
712    /// a `GCancellable` or [`None`]
713    ///
714    /// # Returns
715    ///
716    /// Number of bytes read, or 0 if the connection was closed by
717    /// the peer, or -1 on error
718    ///
719    /// ## `buffer`
720    ///
721    ///     a buffer to read data into (which should be at least @size bytes long).
722    #[doc(alias = "g_socket_receive_with_blocking")]
723    fn receive_with_blocking<B: AsMut<[u8]>, C: IsA<Cancellable>>(
724        &self,
725        mut buffer: B,
726        blocking: bool,
727        cancellable: Option<&C>,
728    ) -> Result<usize, glib::Error> {
729        let cancellable = cancellable.map(|c| c.as_ref());
730        let gcancellable = cancellable.to_glib_none();
731        let buffer = buffer.as_mut();
732        let buffer_ptr = buffer.as_mut_ptr();
733        let count = buffer.len();
734        unsafe {
735            let mut error = ptr::null_mut();
736            let ret = ffi::g_socket_receive_with_blocking(
737                self.as_ref().to_glib_none().0,
738                buffer_ptr,
739                count,
740                blocking.into_glib(),
741                gcancellable.0,
742                &mut error,
743            );
744            if error.is_null() {
745                Ok(ret as usize)
746            } else {
747                Err(from_glib_full(error))
748            }
749        }
750    }
751
752    /// Tries to send @size bytes from @buffer on the socket. This is
753    /// mainly used by connection-oriented sockets; it is identical to
754    /// g_socket_send_to() with @address set to [`None`].
755    ///
756    /// If the socket is in blocking mode the call will block until there is
757    /// space for the data in the socket queue. If there is no space available
758    /// and the socket is in non-blocking mode a [`IOErrorEnum::WouldBlock`][crate::IOErrorEnum::WouldBlock] error
759    /// will be returned. To be notified when space is available, wait for the
760    /// [`glib::IOCondition::OUT`][crate::glib::IOCondition::OUT] condition. Note though that you may still receive
761    /// [`IOErrorEnum::WouldBlock`][crate::IOErrorEnum::WouldBlock] from g_socket_send() even if you were previously
762    /// notified of a [`glib::IOCondition::OUT`][crate::glib::IOCondition::OUT] condition. (On Windows in particular, this is
763    /// very common due to the way the underlying APIs work.)
764    ///
765    /// On error -1 is returned and @error is set accordingly.
766    /// ## `buffer`
767    /// the buffer
768    ///     containing the data to send.
769    /// ## `cancellable`
770    /// a `GCancellable` or [`None`]
771    ///
772    /// # Returns
773    ///
774    /// Number of bytes written (which may be less than @size), or -1
775    /// on error
776    #[doc(alias = "g_socket_send")]
777    fn send<B: AsRef<[u8]>, C: IsA<Cancellable>>(
778        &self,
779        buffer: B,
780        cancellable: Option<&C>,
781    ) -> Result<usize, glib::Error> {
782        let cancellable = cancellable.map(|c| c.as_ref());
783        let gcancellable = cancellable.to_glib_none();
784        let (count, buffer_ptr) = {
785            let slice = buffer.as_ref();
786            (slice.len(), slice.as_ptr())
787        };
788        unsafe {
789            let mut error = ptr::null_mut();
790            let ret = ffi::g_socket_send(
791                self.as_ref().to_glib_none().0,
792                mut_override(buffer_ptr),
793                count,
794                gcancellable.0,
795                &mut error,
796            );
797            if error.is_null() {
798                Ok(ret as usize)
799            } else {
800                Err(from_glib_full(error))
801            }
802        }
803    }
804    /// Send data to @address on @self.  For sending multiple messages see
805    /// g_socket_send_messages(); for easier use, see
806    /// g_socket_send() and g_socket_send_to().
807    ///
808    /// If @address is [`None`] then the message is sent to the default receiver
809    /// (set by g_socket_connect()).
810    ///
811    /// @vectors must point to an array of #GOutputVector structs and
812    /// @num_vectors must be the length of this array. (If @num_vectors is -1,
813    /// then @vectors is assumed to be terminated by a #GOutputVector with a
814    /// [`None`] buffer pointer.) The #GOutputVector structs describe the buffers
815    /// that the sent data will be gathered from. Using multiple
816    /// #GOutputVectors is more memory-efficient than manually copying
817    /// data from multiple sources into a single buffer, and more
818    /// network-efficient than making multiple calls to g_socket_send().
819    ///
820    /// @messages, if non-[`None`], is taken to point to an array of @num_messages
821    /// #GSocketControlMessage instances. These correspond to the control
822    /// messages to be sent on the socket.
823    /// If @num_messages is -1 then @messages is treated as a [`None`]-terminated
824    /// array.
825    ///
826    /// @flags modify how the message is sent. The commonly available arguments
827    /// for this are available in the #GSocketMsgFlags enum, but the
828    /// values there are the same as the system values, and the flags
829    /// are passed in as-is, so you can pass in system-specific flags too.
830    ///
831    /// If the socket is in blocking mode the call will block until there is
832    /// space for the data in the socket queue. If there is no space available
833    /// and the socket is in non-blocking mode a [`IOErrorEnum::WouldBlock`][crate::IOErrorEnum::WouldBlock] error
834    /// will be returned. To be notified when space is available, wait for the
835    /// [`glib::IOCondition::OUT`][crate::glib::IOCondition::OUT] condition. Note though that you may still receive
836    /// [`IOErrorEnum::WouldBlock`][crate::IOErrorEnum::WouldBlock] from g_socket_send() even if you were previously
837    /// notified of a [`glib::IOCondition::OUT`][crate::glib::IOCondition::OUT] condition. (On Windows in particular, this is
838    /// very common due to the way the underlying APIs work.)
839    ///
840    /// The sum of the sizes of each #GOutputVector in vectors must not be
841    /// greater than `G_MAXSSIZE`. If the message can be larger than this,
842    /// then it is mandatory to use the g_socket_send_message_with_timeout()
843    /// function.
844    ///
845    /// On error -1 is returned and @error is set accordingly.
846    /// ## `address`
847    /// a #GSocketAddress, or [`None`]
848    /// ## `vectors`
849    /// an array of #GOutputVector structs
850    /// ## `messages`
851    /// a pointer to an
852    ///   array of #GSocketControlMessages, or [`None`].
853    /// ## `flags`
854    /// an int containing #GSocketMsgFlags flags, which may additionally
855    ///    contain [other platform specific flags](http://man7.org/linux/man-pages/man2/recv.2.html)
856    /// ## `cancellable`
857    /// a `GCancellable` or [`None`]
858    ///
859    /// # Returns
860    ///
861    /// Number of bytes written (which may be less than @size), or -1
862    /// on error
863    #[doc(alias = "g_socket_send_message")]
864    fn send_message<P: IsA<SocketAddress>, C: IsA<Cancellable>>(
865        &self,
866        address: Option<&P>,
867        vectors: &[OutputVector],
868        messages: &[SocketControlMessage],
869        flags: i32,
870        cancellable: Option<&C>,
871    ) -> Result<usize, glib::Error> {
872        let cancellable = cancellable.map(|c| c.as_ref());
873        unsafe {
874            let mut error = ptr::null_mut();
875            let ret = ffi::g_socket_send_message(
876                self.as_ref().to_glib_none().0,
877                address.map(|p| p.as_ref()).to_glib_none().0,
878                vectors.as_ptr() as *mut ffi::GOutputVector,
879                vectors.len().try_into().unwrap(),
880                messages.as_ptr() as *mut _,
881                messages.len().try_into().unwrap(),
882                flags,
883                cancellable.to_glib_none().0,
884                &mut error,
885            );
886            if error.is_null() {
887                Ok(ret as usize)
888            } else {
889                Err(from_glib_full(error))
890            }
891        }
892    }
893    /// This behaves exactly the same as g_socket_send_message(), except that
894    /// the choice of timeout behavior is determined by the @timeout_us argument
895    /// rather than by @self's properties.
896    ///
897    /// On error [`PollableReturn::Failed`][crate::PollableReturn::Failed] is returned and @error is set accordingly, or
898    /// if the socket is currently not writable [`PollableReturn::WouldBlock`][crate::PollableReturn::WouldBlock] is
899    /// returned. @bytes_written will contain 0 in both cases.
900    /// ## `address`
901    /// a #GSocketAddress, or [`None`]
902    /// ## `vectors`
903    /// an array of #GOutputVector structs
904    /// ## `messages`
905    /// a pointer to an
906    ///   array of #GSocketControlMessages, or [`None`].
907    /// ## `flags`
908    /// an int containing #GSocketMsgFlags flags, which may additionally
909    ///    contain [other platform specific flags](http://man7.org/linux/man-pages/man2/recv.2.html)
910    /// ## `timeout_us`
911    /// the maximum time (in microseconds) to wait, or -1
912    /// ## `cancellable`
913    /// a `GCancellable` or [`None`]
914    ///
915    /// # Returns
916    ///
917    /// [`PollableReturn::Ok`][crate::PollableReturn::Ok] if all data was successfully written,
918    /// [`PollableReturn::WouldBlock`][crate::PollableReturn::WouldBlock] if the socket is currently not writable, or
919    /// [`PollableReturn::Failed`][crate::PollableReturn::Failed] if an error happened and @error is set.
920    ///
921    /// ## `bytes_written`
922    /// location to store the number of bytes that were written to the socket
923    #[cfg(feature = "v2_60")]
924    #[cfg_attr(docsrs, doc(cfg(feature = "v2_60")))]
925    #[doc(alias = "g_socket_send_message_with_timeout")]
926    fn send_message_with_timeout<P: IsA<SocketAddress>, C: IsA<Cancellable>>(
927        &self,
928        address: Option<&P>,
929        vectors: &[OutputVector],
930        messages: &[SocketControlMessage],
931        flags: i32,
932        timeout: Option<Duration>,
933        cancellable: Option<&C>,
934    ) -> Result<(PollableReturn, usize), glib::Error> {
935        let cancellable = cancellable.map(|c| c.as_ref());
936        unsafe {
937            let mut error = ptr::null_mut();
938            let mut bytes_written = 0;
939
940            let ret = ffi::g_socket_send_message_with_timeout(
941                self.as_ref().to_glib_none().0,
942                address.map(|p| p.as_ref()).to_glib_none().0,
943                vectors.as_ptr() as *mut ffi::GOutputVector,
944                vectors.len().try_into().unwrap(),
945                messages.as_ptr() as *mut _,
946                messages.len().try_into().unwrap(),
947                flags,
948                timeout
949                    .map(|t| t.as_micros().try_into().unwrap())
950                    .unwrap_or(-1),
951                &mut bytes_written,
952                cancellable.to_glib_none().0,
953                &mut error,
954            );
955            if error.is_null() {
956                Ok((from_glib(ret), bytes_written))
957            } else {
958                Err(from_glib_full(error))
959            }
960        }
961    }
962    /// Send multiple data messages from @self in one go.  This is the most
963    /// complicated and fully-featured version of this call. For easier use, see
964    /// g_socket_send(), g_socket_send_to(), and g_socket_send_message().
965    ///
966    /// @messages must point to an array of #GOutputMessage structs and
967    /// @num_messages must be the length of this array. Each #GOutputMessage
968    /// contains an address to send the data to, and a pointer to an array of
969    /// #GOutputVector structs to describe the buffers that the data to be sent
970    /// for each message will be gathered from. Using multiple #GOutputVectors is
971    /// more memory-efficient than manually copying data from multiple sources
972    /// into a single buffer, and more network-efficient than making multiple
973    /// calls to g_socket_send(). Sending multiple messages in one go avoids the
974    /// overhead of making a lot of syscalls in scenarios where a lot of data
975    /// packets need to be sent (e.g. high-bandwidth video streaming over RTP/UDP),
976    /// or where the same data needs to be sent to multiple recipients.
977    ///
978    /// @flags modify how the message is sent. The commonly available arguments
979    /// for this are available in the #GSocketMsgFlags enum, but the
980    /// values there are the same as the system values, and the flags
981    /// are passed in as-is, so you can pass in system-specific flags too.
982    ///
983    /// If the socket is in blocking mode the call will block until there is
984    /// space for all the data in the socket queue. If there is no space available
985    /// and the socket is in non-blocking mode a [`IOErrorEnum::WouldBlock`][crate::IOErrorEnum::WouldBlock] error
986    /// will be returned if no data was written at all, otherwise the number of
987    /// messages sent will be returned. To be notified when space is available,
988    /// wait for the [`glib::IOCondition::OUT`][crate::glib::IOCondition::OUT] condition. Note though that you may still receive
989    /// [`IOErrorEnum::WouldBlock`][crate::IOErrorEnum::WouldBlock] from g_socket_send() even if you were previously
990    /// notified of a [`glib::IOCondition::OUT`][crate::glib::IOCondition::OUT] condition. (On Windows in particular, this is
991    /// very common due to the way the underlying APIs work.)
992    ///
993    /// On error -1 is returned and @error is set accordingly. An error will only
994    /// be returned if zero messages could be sent; otherwise the number of messages
995    /// successfully sent before the error will be returned.
996    /// ## `messages`
997    /// an array of #GOutputMessage structs
998    /// ## `flags`
999    /// an int containing #GSocketMsgFlags flags, which may additionally
1000    ///    contain [other platform specific flags](http://man7.org/linux/man-pages/man2/recv.2.html)
1001    /// ## `cancellable`
1002    /// a `GCancellable` or [`None`]
1003    ///
1004    /// # Returns
1005    ///
1006    /// number of messages sent, or -1 on error. Note that the number of
1007    ///     messages sent may be smaller than @num_messages if the socket is
1008    ///     non-blocking or if @num_messages was larger than UIO_MAXIOV (1024),
1009    ///     in which case the caller may re-try to send the remaining messages.
1010    #[doc(alias = "g_socket_send_messages")]
1011    fn send_messages<C: IsA<Cancellable>>(
1012        &self,
1013        messages: &mut [OutputMessage],
1014        flags: i32,
1015        cancellable: Option<&C>,
1016    ) -> Result<usize, glib::Error> {
1017        let cancellable = cancellable.map(|c| c.as_ref());
1018        unsafe {
1019            let mut error = ptr::null_mut();
1020            let count = ffi::g_socket_send_messages(
1021                self.as_ref().to_glib_none().0,
1022                messages.as_mut_ptr() as *mut _,
1023                messages.len().try_into().unwrap(),
1024                flags,
1025                cancellable.to_glib_none().0,
1026                &mut error,
1027            );
1028            if error.is_null() {
1029                Ok(count as usize)
1030            } else {
1031                Err(from_glib_full(error))
1032            }
1033        }
1034    }
1035    /// Tries to send @size bytes from @buffer to @address. If @address is
1036    /// [`None`] then the message is sent to the default receiver (set by
1037    /// g_socket_connect()).
1038    ///
1039    /// See g_socket_send() for additional information.
1040    /// ## `address`
1041    /// a #GSocketAddress, or [`None`]
1042    /// ## `buffer`
1043    /// the buffer
1044    ///     containing the data to send.
1045    /// ## `cancellable`
1046    /// a `GCancellable` or [`None`]
1047    ///
1048    /// # Returns
1049    ///
1050    /// Number of bytes written (which may be less than @size), or -1
1051    /// on error
1052    #[doc(alias = "g_socket_send_to")]
1053    fn send_to<B: AsRef<[u8]>, P: IsA<SocketAddress>, C: IsA<Cancellable>>(
1054        &self,
1055        address: Option<&P>,
1056        buffer: B,
1057        cancellable: Option<&C>,
1058    ) -> Result<usize, glib::Error> {
1059        let cancellable = cancellable.map(|c| c.as_ref());
1060        let gcancellable = cancellable.to_glib_none();
1061        let (count, buffer_ptr) = {
1062            let slice = buffer.as_ref();
1063            (slice.len(), slice.as_ptr())
1064        };
1065        unsafe {
1066            let mut error = ptr::null_mut();
1067
1068            let ret = ffi::g_socket_send_to(
1069                self.as_ref().to_glib_none().0,
1070                address.map(|p| p.as_ref()).to_glib_none().0,
1071                mut_override(buffer_ptr),
1072                count,
1073                gcancellable.0,
1074                &mut error,
1075            );
1076            if error.is_null() {
1077                Ok(ret as usize)
1078            } else {
1079                Err(from_glib_full(error))
1080            }
1081        }
1082    }
1083    /// This behaves exactly the same as g_socket_send(), except that
1084    /// the choice of blocking or non-blocking behavior is determined by
1085    /// the @blocking argument rather than by @self's properties.
1086    /// ## `buffer`
1087    /// the buffer
1088    ///     containing the data to send.
1089    /// ## `blocking`
1090    /// whether to do blocking or non-blocking I/O
1091    /// ## `cancellable`
1092    /// a `GCancellable` or [`None`]
1093    ///
1094    /// # Returns
1095    ///
1096    /// Number of bytes written (which may be less than @size), or -1
1097    /// on error
1098    #[doc(alias = "g_socket_send_with_blocking")]
1099    fn send_with_blocking<B: AsRef<[u8]>, C: IsA<Cancellable>>(
1100        &self,
1101        buffer: B,
1102        blocking: bool,
1103        cancellable: Option<&C>,
1104    ) -> Result<usize, glib::Error> {
1105        let cancellable = cancellable.map(|c| c.as_ref());
1106        let gcancellable = cancellable.to_glib_none();
1107        let (count, buffer_ptr) = {
1108            let slice = buffer.as_ref();
1109            (slice.len(), slice.as_ptr())
1110        };
1111        unsafe {
1112            let mut error = ptr::null_mut();
1113            let ret = ffi::g_socket_send_with_blocking(
1114                self.as_ref().to_glib_none().0,
1115                mut_override(buffer_ptr),
1116                count,
1117                blocking.into_glib(),
1118                gcancellable.0,
1119                &mut error,
1120            );
1121            if error.is_null() {
1122                Ok(ret as usize)
1123            } else {
1124                Err(from_glib_full(error))
1125            }
1126        }
1127    }
1128
1129    /// Returns the underlying OS socket object. On unix this
1130    /// is a socket file descriptor, and on Windows this is
1131    /// a Winsock2 SOCKET handle. This may be useful for
1132    /// doing platform specific or otherwise unusual operations
1133    /// on the socket.
1134    ///
1135    /// # Returns
1136    ///
1137    /// the file descriptor of the socket.
1138    #[cfg(unix)]
1139    #[cfg_attr(docsrs, doc(cfg(unix)))]
1140    #[doc(alias = "get_fd")]
1141    #[doc(alias = "g_socket_get_fd")]
1142    fn fd(&self) -> BorrowedFd<'_> {
1143        self.as_ref().as_fd()
1144    }
1145
1146    #[cfg(windows)]
1147    #[cfg_attr(docsrs, doc(cfg(windows)))]
1148    #[doc(alias = "get_socket")]
1149    #[doc(alias = "g_socket_get_fd")]
1150    fn socket(&self) -> BorrowedSocket<'_> {
1151        self.as_ref().as_socket()
1152    }
1153
1154    #[doc(alias = "g_socket_create_source")]
1155    fn create_source<F, C>(
1156        &self,
1157        condition: glib::IOCondition,
1158        cancellable: Option<&C>,
1159        name: Option<&str>,
1160        priority: glib::Priority,
1161        func: F,
1162    ) -> glib::Source
1163    where
1164        F: FnMut(&Self, glib::IOCondition) -> glib::ControlFlow + 'static,
1165        C: IsA<Cancellable>,
1166    {
1167        unsafe extern "C" fn trampoline<
1168            O: IsA<Socket>,
1169            F: FnMut(&O, glib::IOCondition) -> glib::ControlFlow + 'static,
1170        >(
1171            socket: *mut ffi::GSocket,
1172            condition: glib::ffi::GIOCondition,
1173            func: glib::ffi::gpointer,
1174        ) -> glib::ffi::gboolean {
1175            unsafe {
1176                let func: &RefCell<F> = &*(func as *const RefCell<F>);
1177                let mut func = func.borrow_mut();
1178                (*func)(
1179                    Socket::from_glib_borrow(socket).unsafe_cast_ref(),
1180                    from_glib(condition),
1181                )
1182                .into_glib()
1183            }
1184        }
1185        unsafe extern "C" fn destroy_closure<F>(ptr: glib::ffi::gpointer) {
1186            unsafe {
1187                let _ = Box::<RefCell<F>>::from_raw(ptr as *mut _);
1188            }
1189        }
1190        let cancellable = cancellable.map(|c| c.as_ref());
1191        let gcancellable = cancellable.to_glib_none();
1192        unsafe {
1193            let source = ffi::g_socket_create_source(
1194                self.as_ref().to_glib_none().0,
1195                condition.into_glib(),
1196                gcancellable.0,
1197            );
1198            let trampoline = trampoline::<Self, F> as glib::ffi::gpointer;
1199            glib::ffi::g_source_set_callback(
1200                source,
1201                Some(transmute::<
1202                    glib::ffi::gpointer,
1203                    unsafe extern "C" fn(glib::ffi::gpointer) -> glib::ffi::gboolean,
1204                >(trampoline)),
1205                Box::into_raw(Box::new(RefCell::new(func))) as glib::ffi::gpointer,
1206                Some(destroy_closure::<F>),
1207            );
1208            glib::ffi::g_source_set_priority(source, priority.into_glib());
1209
1210            if let Some(name) = name {
1211                glib::ffi::g_source_set_name(source, name.to_glib_none().0);
1212            }
1213
1214            from_glib_full(source)
1215        }
1216    }
1217
1218    fn create_source_future<C: IsA<Cancellable>>(
1219        &self,
1220        condition: glib::IOCondition,
1221        cancellable: Option<&C>,
1222        priority: glib::Priority,
1223    ) -> Pin<Box<dyn std::future::Future<Output = glib::IOCondition> + 'static>> {
1224        let cancellable: Option<Cancellable> = cancellable.map(|c| c.as_ref()).cloned();
1225
1226        let obj = self.clone();
1227        Box::pin(glib::SourceFuture::new(move |send| {
1228            let mut send = Some(send);
1229            obj.create_source(
1230                condition,
1231                cancellable.as_ref(),
1232                None,
1233                priority,
1234                move |_, condition| {
1235                    let _ = send.take().unwrap().send(condition);
1236                    glib::ControlFlow::Break
1237                },
1238            )
1239        }))
1240    }
1241
1242    fn create_source_stream<C: IsA<Cancellable>>(
1243        &self,
1244        condition: glib::IOCondition,
1245        cancellable: Option<&C>,
1246        priority: glib::Priority,
1247    ) -> Pin<Box<dyn Stream<Item = glib::IOCondition> + 'static>> {
1248        let cancellable: Option<Cancellable> = cancellable.map(|c| c.as_ref()).cloned();
1249
1250        let obj = self.clone();
1251        Box::pin(glib::SourceStream::new(move |send| {
1252            let send = Some(send);
1253            obj.create_source(
1254                condition,
1255                cancellable.as_ref(),
1256                None,
1257                priority,
1258                move |_, condition| {
1259                    if send.as_ref().unwrap().unbounded_send(condition).is_err() {
1260                        glib::ControlFlow::Break
1261                    } else {
1262                        glib::ControlFlow::Continue
1263                    }
1264                },
1265            )
1266        }))
1267    }
1268}
1269
1270impl<O: IsA<Socket>> SocketExtManual for O {}
1271
1272#[cfg(all(docsrs, not(unix)))]
1273pub trait AsRawFd {
1274    fn as_raw_fd(&self) -> RawFd;
1275}
1276
1277#[cfg(all(docsrs, not(unix)))]
1278pub type RawFd = libc::c_int;
1279
1280#[cfg(all(docsrs, not(windows)))]
1281pub trait AsRawSocket {
1282    fn as_raw_socket(&self) -> RawSocket;
1283}
1284
1285#[cfg(all(docsrs, not(windows)))]
1286pub type RawSocket = *mut std::os::raw::c_void;
1287
1288#[cfg(test)]
1289mod tests {
1290    #[test]
1291    #[cfg(unix)]
1292    fn dgram_socket_messages() {
1293        use super::Socket;
1294        use crate::{Cancellable, prelude::*};
1295
1296        let addr = crate::InetSocketAddress::from_string("127.0.0.1", 28351).unwrap();
1297
1298        let out_sock = Socket::new(
1299            crate::SocketFamily::Ipv4,
1300            crate::SocketType::Datagram,
1301            crate::SocketProtocol::Udp,
1302        )
1303        .unwrap();
1304        let in_sock = Socket::new(
1305            crate::SocketFamily::Ipv4,
1306            crate::SocketType::Datagram,
1307            crate::SocketProtocol::Udp,
1308        )
1309        .unwrap();
1310        in_sock.bind(&addr, true).unwrap();
1311
1312        const DATA: [u8; std::mem::size_of::<u64>()] = 1234u64.to_be_bytes();
1313        let out_vec = DATA;
1314        let out_vecs = [super::OutputVector::new(out_vec.as_slice())];
1315        let mut out_msg = [super::OutputMessage::new(
1316            Some(&addr),
1317            out_vecs.as_slice(),
1318            &[],
1319        )];
1320        let written = super::SocketExtManual::send_messages(
1321            &out_sock,
1322            out_msg.as_mut_slice(),
1323            0,
1324            Cancellable::NONE,
1325        )
1326        .unwrap();
1327        assert_eq!(written, 1);
1328        assert_eq!(out_msg[0].bytes_sent() as usize, out_vec.len());
1329
1330        let mut in_addr = None;
1331        let mut in_vec = [0u8; DATA.len()];
1332        let mut in_vecs = [super::InputVector::new(in_vec.as_mut_slice())];
1333        let mut in_msg = [super::InputMessage::new(
1334            Some(&mut in_addr),
1335            in_vecs.as_mut_slice(),
1336            None,
1337        )];
1338        let received = super::SocketExtManual::receive_messages(
1339            &in_sock,
1340            in_msg.as_mut_slice(),
1341            0,
1342            Cancellable::NONE,
1343        )
1344        .unwrap();
1345
1346        assert_eq!(received, 1);
1347        assert_eq!(in_msg[0].bytes_received(), in_vec.len());
1348        assert_eq!(in_vec, out_vec);
1349        let in_addr = in_addr
1350            .unwrap()
1351            .downcast::<crate::InetSocketAddress>()
1352            .unwrap();
1353        assert_eq!(in_addr.address().to_str(), addr.address().to_str());
1354    }
1355}