1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
// Take a look at the license at the top of the repository in the LICENSE file.

use std::{cell::RefCell, mem::transmute, pin::Pin, ptr, time::Duration};

use futures_core::stream::Stream;
use glib::{prelude::*, translate::*};

use crate::{Cancellable, DatagramBased, InputMessage, OutputMessage};

mod sealed {
    pub trait Sealed {}
    impl<T: super::IsA<super::DatagramBased>> Sealed for T {}
}

pub trait DatagramBasedExtManual: sealed::Sealed + IsA<DatagramBased> + Sized {
    /// Creates a #GSource that can be attached to a #GMainContext to monitor for
    /// the availability of the specified @condition on the #GDatagramBased. The
    /// #GSource keeps a reference to the @self.
    ///
    /// The callback on the source is of the #GDatagramBasedSourceFunc type.
    ///
    /// It is meaningless to specify [`glib::IOCondition::ERR`][crate::glib::IOCondition::ERR] or [`glib::IOCondition::HUP`][crate::glib::IOCondition::HUP] in @condition; these
    /// conditions will always be reported in the callback if they are true.
    ///
    /// If non-[`None`], @cancellable can be used to cancel the source, which will
    /// cause the source to trigger, reporting the current condition (which is
    /// likely 0 unless cancellation happened at the same time as a condition
    /// change). You can check for this in the callback using
    /// g_cancellable_is_cancelled().
    /// ## `condition`
    /// a #GIOCondition mask to monitor
    /// ## `cancellable`
    /// a #GCancellable
    ///
    /// # Returns
    ///
    /// a newly allocated #GSource
    #[doc(alias = "g_datagram_based_create_source")]
    fn create_source<F, C>(
        &self,
        condition: glib::IOCondition,
        cancellable: Option<&C>,
        name: Option<&str>,
        priority: glib::Priority,
        func: F,
    ) -> glib::Source
    where
        F: FnMut(&Self, glib::IOCondition) -> glib::ControlFlow + 'static,
        C: IsA<Cancellable>,
    {
        unsafe extern "C" fn trampoline<
            O: IsA<DatagramBased>,
            F: FnMut(&O, glib::IOCondition) -> glib::ControlFlow + 'static,
        >(
            datagram_based: *mut ffi::GDatagramBased,
            condition: glib::ffi::GIOCondition,
            func: glib::ffi::gpointer,
        ) -> glib::ffi::gboolean {
            let func: &RefCell<F> = &*(func as *const RefCell<F>);
            let mut func = func.borrow_mut();
            (*func)(
                DatagramBased::from_glib_borrow(datagram_based).unsafe_cast_ref(),
                from_glib(condition),
            )
            .into_glib()
        }
        unsafe extern "C" fn destroy_closure<F>(ptr: glib::ffi::gpointer) {
            let _ = Box::<RefCell<F>>::from_raw(ptr as *mut _);
        }
        let cancellable = cancellable.map(|c| c.as_ref());
        let gcancellable = cancellable.to_glib_none();
        unsafe {
            let source = ffi::g_datagram_based_create_source(
                self.as_ref().to_glib_none().0,
                condition.into_glib(),
                gcancellable.0,
            );
            let trampoline = trampoline::<Self, F> as glib::ffi::gpointer;
            glib::ffi::g_source_set_callback(
                source,
                Some(transmute::<
                    _,
                    unsafe extern "C" fn(glib::ffi::gpointer) -> glib::ffi::gboolean,
                >(trampoline)),
                Box::into_raw(Box::new(RefCell::new(func))) as glib::ffi::gpointer,
                Some(destroy_closure::<F>),
            );
            glib::ffi::g_source_set_priority(source, priority.into_glib());

            if let Some(name) = name {
                glib::ffi::g_source_set_name(source, name.to_glib_none().0);
            }

            from_glib_full(source)
        }
    }

    fn create_source_future<C: IsA<Cancellable>>(
        &self,
        condition: glib::IOCondition,
        cancellable: Option<&C>,
        priority: glib::Priority,
    ) -> Pin<Box<dyn std::future::Future<Output = glib::IOCondition> + 'static>> {
        let cancellable: Option<Cancellable> = cancellable.map(|c| c.as_ref()).cloned();

        let obj = self.clone();
        Box::pin(glib::SourceFuture::new(move |send| {
            let mut send = Some(send);
            obj.create_source(
                condition,
                cancellable.as_ref(),
                None,
                priority,
                move |_, condition| {
                    let _ = send.take().unwrap().send(condition);
                    glib::ControlFlow::Break
                },
            )
        }))
    }

    fn create_source_stream<C: IsA<Cancellable>>(
        &self,
        condition: glib::IOCondition,
        cancellable: Option<&C>,
        priority: glib::Priority,
    ) -> Pin<Box<dyn Stream<Item = glib::IOCondition> + 'static>> {
        let cancellable: Option<Cancellable> = cancellable.map(|c| c.as_ref()).cloned();

        let obj = self.clone();
        Box::pin(glib::SourceStream::new(move |send| {
            let send = Some(send);
            obj.create_source(
                condition,
                cancellable.as_ref(),
                None,
                priority,
                move |_, condition| {
                    if send.as_ref().unwrap().unbounded_send(condition).is_err() {
                        glib::ControlFlow::Break
                    } else {
                        glib::ControlFlow::Continue
                    }
                },
            )
        }))
    }

    /// Waits for up to @timeout microseconds for condition to become true on
    /// @self. If the condition is met, [`true`] is returned.
    ///
    /// If @cancellable is cancelled before the condition is met, or if @timeout is
    /// reached before the condition is met, then [`false`] is returned and @error is
    /// set appropriately ([`IOErrorEnum::Cancelled`][crate::IOErrorEnum::Cancelled] or [`IOErrorEnum::TimedOut`][crate::IOErrorEnum::TimedOut]).
    /// ## `condition`
    /// a #GIOCondition mask to wait for
    /// ## `timeout`
    /// the maximum time (in microseconds) to wait, 0 to not block, or -1
    ///   to block indefinitely
    /// ## `cancellable`
    /// a #GCancellable
    ///
    /// # Returns
    ///
    /// [`true`] if the condition was met, [`false`] otherwise
    #[doc(alias = "g_datagram_based_condition_wait")]
    fn condition_wait(
        &self,
        condition: glib::IOCondition,
        timeout: Option<Duration>,
        cancellable: Option<&impl IsA<Cancellable>>,
    ) -> Result<(), glib::Error> {
        unsafe {
            let mut error = ptr::null_mut();
            let is_ok = ffi::g_datagram_based_condition_wait(
                self.as_ref().to_glib_none().0,
                condition.into_glib(),
                timeout
                    .map(|t| t.as_micros().try_into().unwrap())
                    .unwrap_or(-1),
                cancellable.map(|p| p.as_ref()).to_glib_none().0,
                &mut error,
            );
            debug_assert_eq!(is_ok == glib::ffi::GFALSE, !error.is_null());
            if error.is_null() {
                Ok(())
            } else {
                Err(from_glib_full(error))
            }
        }
    }

    /// Receive one or more data messages from @self in one go.
    ///
    /// @messages must point to an array of #GInputMessage structs and
    /// @num_messages must be the length of this array. Each #GInputMessage
    /// contains a pointer to an array of #GInputVector structs describing the
    /// buffers that the data received in each message will be written to.
    ///
    /// @flags modify how all messages are received. The commonly available
    /// arguments for this are available in the #GSocketMsgFlags enum, but the
    /// values there are the same as the system values, and the flags
    /// are passed in as-is, so you can pass in system-specific flags too. These
    /// flags affect the overall receive operation. Flags affecting individual
    /// messages are returned in #GInputMessage.flags.
    ///
    /// The other members of #GInputMessage are treated as described in its
    /// documentation.
    ///
    /// If @timeout is negative the call will block until @num_messages have been
    /// received, the connection is closed remotely (EOS), @cancellable is cancelled,
    /// or an error occurs.
    ///
    /// If @timeout is 0 the call will return up to @num_messages without blocking,
    /// or [`IOErrorEnum::WouldBlock`][crate::IOErrorEnum::WouldBlock] if no messages are queued in the operating system
    /// to be received.
    ///
    /// If @timeout is positive the call will block on the same conditions as if
    /// @timeout were negative. If the timeout is reached
    /// before any messages are received, [`IOErrorEnum::TimedOut`][crate::IOErrorEnum::TimedOut] is returned,
    /// otherwise it will return the number of messages received before timing out.
    /// (Note: This is effectively the behaviour of `MSG_WAITFORONE` with
    /// recvmmsg().)
    ///
    /// To be notified when messages are available, wait for the [`glib::IOCondition::IN`][crate::glib::IOCondition::IN] condition.
    /// Note though that you may still receive [`IOErrorEnum::WouldBlock`][crate::IOErrorEnum::WouldBlock] from
    /// g_datagram_based_receive_messages() even if you were previously notified of a
    /// [`glib::IOCondition::IN`][crate::glib::IOCondition::IN] condition.
    ///
    /// If the remote peer closes the connection, any messages queued in the
    /// underlying receive buffer will be returned, and subsequent calls to
    /// g_datagram_based_receive_messages() will return 0 (with no error set).
    ///
    /// If the connection is shut down or closed (by calling g_socket_close() or
    /// g_socket_shutdown() with @shutdown_read set, if it’s a #GSocket, for
    /// example), all calls to this function will return [`IOErrorEnum::Closed`][crate::IOErrorEnum::Closed].
    ///
    /// On error -1 is returned and @error is set accordingly. An error will only
    /// be returned if zero messages could be received; otherwise the number of
    /// messages successfully received before the error will be returned. If
    /// @cancellable is cancelled, [`IOErrorEnum::Cancelled`][crate::IOErrorEnum::Cancelled] is returned as with any
    /// other error.
    /// ## `messages`
    /// an array of #GInputMessage structs
    /// ## `flags`
    /// an int containing #GSocketMsgFlags flags for the overall operation
    /// ## `timeout`
    /// the maximum time (in microseconds) to wait, 0 to not block, or -1
    ///   to block indefinitely
    /// ## `cancellable`
    /// a `GCancellable`
    ///
    /// # Returns
    ///
    /// number of messages received, or -1 on error. Note that the number
    ///     of messages received may be smaller than @num_messages if @timeout is
    ///     zero or positive, if the peer closed the connection, or if @num_messages
    ///     was larger than `UIO_MAXIOV` (1024), in which case the caller may re-try
    ///     to receive the remaining messages.
    #[doc(alias = "g_datagram_based_receive_messages")]
    fn receive_messages<'v, V: IntoIterator<Item = &'v mut [&'v mut [u8]]>, C: IsA<Cancellable>>(
        &self,
        messages: &mut [InputMessage],
        flags: i32,
        timeout: Option<Duration>,
        cancellable: Option<&C>,
    ) -> Result<usize, glib::Error> {
        let cancellable = cancellable.map(|c| c.as_ref());
        unsafe {
            let mut error = ptr::null_mut();

            let count = ffi::g_datagram_based_receive_messages(
                self.as_ref().to_glib_none().0,
                messages.as_mut_ptr() as *mut _,
                messages.len().try_into().unwrap(),
                flags,
                timeout
                    .map(|t| t.as_micros().try_into().unwrap())
                    .unwrap_or(-1),
                cancellable.to_glib_none().0,
                &mut error,
            );
            if error.is_null() {
                Ok(count as usize)
            } else {
                Err(from_glib_full(error))
            }
        }
    }

    /// Send one or more data messages from @self in one go.
    ///
    /// @messages must point to an array of #GOutputMessage structs and
    /// @num_messages must be the length of this array. Each #GOutputMessage
    /// contains an address to send the data to, and a pointer to an array of
    /// #GOutputVector structs to describe the buffers that the data to be sent
    /// for each message will be gathered from.
    ///
    /// @flags modify how the message is sent. The commonly available arguments
    /// for this are available in the #GSocketMsgFlags enum, but the
    /// values there are the same as the system values, and the flags
    /// are passed in as-is, so you can pass in system-specific flags too.
    ///
    /// The other members of #GOutputMessage are treated as described in its
    /// documentation.
    ///
    /// If @timeout is negative the call will block until @num_messages have been
    /// sent, @cancellable is cancelled, or an error occurs.
    ///
    /// If @timeout is 0 the call will send up to @num_messages without blocking,
    /// or will return [`IOErrorEnum::WouldBlock`][crate::IOErrorEnum::WouldBlock] if there is no space to send messages.
    ///
    /// If @timeout is positive the call will block on the same conditions as if
    /// @timeout were negative. If the timeout is reached before any messages are
    /// sent, [`IOErrorEnum::TimedOut`][crate::IOErrorEnum::TimedOut] is returned, otherwise it will return the number
    /// of messages sent before timing out.
    ///
    /// To be notified when messages can be sent, wait for the [`glib::IOCondition::OUT`][crate::glib::IOCondition::OUT] condition.
    /// Note though that you may still receive [`IOErrorEnum::WouldBlock`][crate::IOErrorEnum::WouldBlock] from
    /// g_datagram_based_send_messages() even if you were previously notified of a
    /// [`glib::IOCondition::OUT`][crate::glib::IOCondition::OUT] condition. (On Windows in particular, this is very common due to
    /// the way the underlying APIs work.)
    ///
    /// If the connection is shut down or closed (by calling g_socket_close() or
    /// g_socket_shutdown() with @shutdown_write set, if it’s a #GSocket, for
    /// example), all calls to this function will return [`IOErrorEnum::Closed`][crate::IOErrorEnum::Closed].
    ///
    /// On error -1 is returned and @error is set accordingly. An error will only
    /// be returned if zero messages could be sent; otherwise the number of messages
    /// successfully sent before the error will be returned. If @cancellable is
    /// cancelled, [`IOErrorEnum::Cancelled`][crate::IOErrorEnum::Cancelled] is returned as with any other error.
    /// ## `messages`
    /// an array of #GOutputMessage structs
    /// ## `flags`
    /// an int containing #GSocketMsgFlags flags
    /// ## `timeout`
    /// the maximum time (in microseconds) to wait, 0 to not block, or -1
    ///   to block indefinitely
    /// ## `cancellable`
    /// a `GCancellable`
    ///
    /// # Returns
    ///
    /// number of messages sent, or -1 on error. Note that the number of
    ///     messages sent may be smaller than @num_messages if @timeout is zero
    ///     or positive, or if @num_messages was larger than `UIO_MAXIOV` (1024), in
    ///     which case the caller may re-try to send the remaining messages.
    #[doc(alias = "g_datagram_based_send_messages")]
    fn send_messages<C: IsA<Cancellable>>(
        &self,
        messages: &mut [OutputMessage],
        flags: i32,
        timeout: Option<Duration>,
        cancellable: Option<&C>,
    ) -> Result<usize, glib::Error> {
        let cancellable = cancellable.map(|c| c.as_ref());
        unsafe {
            let mut error = ptr::null_mut();
            let count = ffi::g_datagram_based_send_messages(
                self.as_ref().to_glib_none().0,
                messages.as_mut_ptr() as *mut _,
                messages.len().try_into().unwrap(),
                flags,
                timeout
                    .map(|t| t.as_micros().try_into().unwrap())
                    .unwrap_or(-1),
                cancellable.to_glib_none().0,
                &mut error,
            );
            if error.is_null() {
                Ok(count as usize)
            } else {
                Err(from_glib_full(error))
            }
        }
    }
}

impl<O: IsA<DatagramBased>> DatagramBasedExtManual for O {}