gio/datagram_based.rs
1// Take a look at the license at the top of the repository in the LICENSE file.
2
3use std::{cell::RefCell, mem::transmute, pin::Pin, ptr, time::Duration};
4
5use futures_core::stream::Stream;
6use glib::{prelude::*, translate::*};
7
8use crate::{ffi, Cancellable, DatagramBased, InputMessage, OutputMessage};
9
10pub trait DatagramBasedExtManual: IsA<DatagramBased> + Sized {
11 /// Creates a #GSource that can be attached to a #GMainContext to monitor for
12 /// the availability of the specified @condition on the #GDatagramBased. The
13 /// #GSource keeps a reference to the @self.
14 ///
15 /// The callback on the source is of the #GDatagramBasedSourceFunc type.
16 ///
17 /// It is meaningless to specify [`glib::IOCondition::ERR`][crate::glib::IOCondition::ERR] or [`glib::IOCondition::HUP`][crate::glib::IOCondition::HUP] in @condition; these
18 /// conditions will always be reported in the callback if they are true.
19 ///
20 /// If non-[`None`], @cancellable can be used to cancel the source, which will
21 /// cause the source to trigger, reporting the current condition (which is
22 /// likely 0 unless cancellation happened at the same time as a condition
23 /// change). You can check for this in the callback using
24 /// g_cancellable_is_cancelled().
25 /// ## `condition`
26 /// a #GIOCondition mask to monitor
27 /// ## `cancellable`
28 /// a #GCancellable
29 ///
30 /// # Returns
31 ///
32 /// a newly allocated #GSource
33 #[doc(alias = "g_datagram_based_create_source")]
34 fn create_source<F, C>(
35 &self,
36 condition: glib::IOCondition,
37 cancellable: Option<&C>,
38 name: Option<&str>,
39 priority: glib::Priority,
40 func: F,
41 ) -> glib::Source
42 where
43 F: FnMut(&Self, glib::IOCondition) -> glib::ControlFlow + 'static,
44 C: IsA<Cancellable>,
45 {
46 unsafe extern "C" fn trampoline<
47 O: IsA<DatagramBased>,
48 F: FnMut(&O, glib::IOCondition) -> glib::ControlFlow + 'static,
49 >(
50 datagram_based: *mut ffi::GDatagramBased,
51 condition: glib::ffi::GIOCondition,
52 func: glib::ffi::gpointer,
53 ) -> glib::ffi::gboolean {
54 let func: &RefCell<F> = &*(func as *const RefCell<F>);
55 let mut func = func.borrow_mut();
56 (*func)(
57 DatagramBased::from_glib_borrow(datagram_based).unsafe_cast_ref(),
58 from_glib(condition),
59 )
60 .into_glib()
61 }
62 unsafe extern "C" fn destroy_closure<F>(ptr: glib::ffi::gpointer) {
63 let _ = Box::<RefCell<F>>::from_raw(ptr as *mut _);
64 }
65 let cancellable = cancellable.map(|c| c.as_ref());
66 let gcancellable = cancellable.to_glib_none();
67 unsafe {
68 let source = ffi::g_datagram_based_create_source(
69 self.as_ref().to_glib_none().0,
70 condition.into_glib(),
71 gcancellable.0,
72 );
73 let trampoline = trampoline::<Self, F> as glib::ffi::gpointer;
74 glib::ffi::g_source_set_callback(
75 source,
76 Some(transmute::<
77 glib::ffi::gpointer,
78 unsafe extern "C" fn(glib::ffi::gpointer) -> glib::ffi::gboolean,
79 >(trampoline)),
80 Box::into_raw(Box::new(RefCell::new(func))) as glib::ffi::gpointer,
81 Some(destroy_closure::<F>),
82 );
83 glib::ffi::g_source_set_priority(source, priority.into_glib());
84
85 if let Some(name) = name {
86 glib::ffi::g_source_set_name(source, name.to_glib_none().0);
87 }
88
89 from_glib_full(source)
90 }
91 }
92
93 fn create_source_future<C: IsA<Cancellable>>(
94 &self,
95 condition: glib::IOCondition,
96 cancellable: Option<&C>,
97 priority: glib::Priority,
98 ) -> Pin<Box<dyn std::future::Future<Output = glib::IOCondition> + 'static>> {
99 let cancellable: Option<Cancellable> = cancellable.map(|c| c.as_ref()).cloned();
100
101 let obj = self.clone();
102 Box::pin(glib::SourceFuture::new(move |send| {
103 let mut send = Some(send);
104 obj.create_source(
105 condition,
106 cancellable.as_ref(),
107 None,
108 priority,
109 move |_, condition| {
110 let _ = send.take().unwrap().send(condition);
111 glib::ControlFlow::Break
112 },
113 )
114 }))
115 }
116
117 fn create_source_stream<C: IsA<Cancellable>>(
118 &self,
119 condition: glib::IOCondition,
120 cancellable: Option<&C>,
121 priority: glib::Priority,
122 ) -> Pin<Box<dyn Stream<Item = glib::IOCondition> + 'static>> {
123 let cancellable: Option<Cancellable> = cancellable.map(|c| c.as_ref()).cloned();
124
125 let obj = self.clone();
126 Box::pin(glib::SourceStream::new(move |send| {
127 let send = Some(send);
128 obj.create_source(
129 condition,
130 cancellable.as_ref(),
131 None,
132 priority,
133 move |_, condition| {
134 if send.as_ref().unwrap().unbounded_send(condition).is_err() {
135 glib::ControlFlow::Break
136 } else {
137 glib::ControlFlow::Continue
138 }
139 },
140 )
141 }))
142 }
143
144 /// Waits for up to @timeout microseconds for condition to become true on
145 /// @self. If the condition is met, [`true`] is returned.
146 ///
147 /// If @cancellable is cancelled before the condition is met, or if @timeout is
148 /// reached before the condition is met, then [`false`] is returned and @error is
149 /// set appropriately ([`IOErrorEnum::Cancelled`][crate::IOErrorEnum::Cancelled] or [`IOErrorEnum::TimedOut`][crate::IOErrorEnum::TimedOut]).
150 /// ## `condition`
151 /// a #GIOCondition mask to wait for
152 /// ## `timeout`
153 /// the maximum time (in microseconds) to wait, 0 to not block, or -1
154 /// to block indefinitely
155 /// ## `cancellable`
156 /// a #GCancellable
157 ///
158 /// # Returns
159 ///
160 /// [`true`] if the condition was met, [`false`] otherwise
161 #[doc(alias = "g_datagram_based_condition_wait")]
162 fn condition_wait(
163 &self,
164 condition: glib::IOCondition,
165 timeout: Option<Duration>,
166 cancellable: Option<&impl IsA<Cancellable>>,
167 ) -> Result<(), glib::Error> {
168 unsafe {
169 let mut error = ptr::null_mut();
170 let is_ok = ffi::g_datagram_based_condition_wait(
171 self.as_ref().to_glib_none().0,
172 condition.into_glib(),
173 timeout
174 .map(|t| t.as_micros().try_into().unwrap())
175 .unwrap_or(-1),
176 cancellable.map(|p| p.as_ref()).to_glib_none().0,
177 &mut error,
178 );
179 debug_assert_eq!(is_ok == glib::ffi::GFALSE, !error.is_null());
180 if error.is_null() {
181 Ok(())
182 } else {
183 Err(from_glib_full(error))
184 }
185 }
186 }
187
188 /// Receive one or more data messages from @self in one go.
189 ///
190 /// @messages must point to an array of #GInputMessage structs and
191 /// @num_messages must be the length of this array. Each #GInputMessage
192 /// contains a pointer to an array of #GInputVector structs describing the
193 /// buffers that the data received in each message will be written to.
194 ///
195 /// @flags modify how all messages are received. The commonly available
196 /// arguments for this are available in the #GSocketMsgFlags enum, but the
197 /// values there are the same as the system values, and the flags
198 /// are passed in as-is, so you can pass in system-specific flags too. These
199 /// flags affect the overall receive operation. Flags affecting individual
200 /// messages are returned in #GInputMessage.flags.
201 ///
202 /// The other members of #GInputMessage are treated as described in its
203 /// documentation.
204 ///
205 /// If @timeout is negative the call will block until @num_messages have been
206 /// received, the connection is closed remotely (EOS), @cancellable is cancelled,
207 /// or an error occurs.
208 ///
209 /// If @timeout is 0 the call will return up to @num_messages without blocking,
210 /// or [`IOErrorEnum::WouldBlock`][crate::IOErrorEnum::WouldBlock] if no messages are queued in the operating system
211 /// to be received.
212 ///
213 /// If @timeout is positive the call will block on the same conditions as if
214 /// @timeout were negative. If the timeout is reached
215 /// before any messages are received, [`IOErrorEnum::TimedOut`][crate::IOErrorEnum::TimedOut] is returned,
216 /// otherwise it will return the number of messages received before timing out.
217 /// (Note: This is effectively the behaviour of `MSG_WAITFORONE` with
218 /// recvmmsg().)
219 ///
220 /// To be notified when messages are available, wait for the [`glib::IOCondition::IN`][crate::glib::IOCondition::IN] condition.
221 /// Note though that you may still receive [`IOErrorEnum::WouldBlock`][crate::IOErrorEnum::WouldBlock] from
222 /// g_datagram_based_receive_messages() even if you were previously notified of a
223 /// [`glib::IOCondition::IN`][crate::glib::IOCondition::IN] condition.
224 ///
225 /// If the remote peer closes the connection, any messages queued in the
226 /// underlying receive buffer will be returned, and subsequent calls to
227 /// g_datagram_based_receive_messages() will return 0 (with no error set).
228 ///
229 /// If the connection is shut down or closed (by calling g_socket_close() or
230 /// g_socket_shutdown() with @shutdown_read set, if it’s a #GSocket, for
231 /// example), all calls to this function will return [`IOErrorEnum::Closed`][crate::IOErrorEnum::Closed].
232 ///
233 /// On error -1 is returned and @error is set accordingly. An error will only
234 /// be returned if zero messages could be received; otherwise the number of
235 /// messages successfully received before the error will be returned. If
236 /// @cancellable is cancelled, [`IOErrorEnum::Cancelled`][crate::IOErrorEnum::Cancelled] is returned as with any
237 /// other error.
238 /// ## `messages`
239 /// an array of #GInputMessage structs
240 /// ## `flags`
241 /// an int containing #GSocketMsgFlags flags for the overall operation
242 /// ## `timeout`
243 /// the maximum time (in microseconds) to wait, 0 to not block, or -1
244 /// to block indefinitely
245 /// ## `cancellable`
246 /// a `GCancellable`
247 ///
248 /// # Returns
249 ///
250 /// number of messages received, or -1 on error. Note that the number
251 /// of messages received may be smaller than @num_messages if @timeout is
252 /// zero or positive, if the peer closed the connection, or if @num_messages
253 /// was larger than `UIO_MAXIOV` (1024), in which case the caller may re-try
254 /// to receive the remaining messages.
255 #[doc(alias = "g_datagram_based_receive_messages")]
256 fn receive_messages<'v, V: IntoIterator<Item = &'v mut [&'v mut [u8]]>, C: IsA<Cancellable>>(
257 &self,
258 messages: &mut [InputMessage],
259 flags: i32,
260 timeout: Option<Duration>,
261 cancellable: Option<&C>,
262 ) -> Result<usize, glib::Error> {
263 let cancellable = cancellable.map(|c| c.as_ref());
264 unsafe {
265 let mut error = ptr::null_mut();
266
267 let count = ffi::g_datagram_based_receive_messages(
268 self.as_ref().to_glib_none().0,
269 messages.as_mut_ptr() as *mut _,
270 messages.len().try_into().unwrap(),
271 flags,
272 timeout
273 .map(|t| t.as_micros().try_into().unwrap())
274 .unwrap_or(-1),
275 cancellable.to_glib_none().0,
276 &mut error,
277 );
278 if error.is_null() {
279 Ok(count as usize)
280 } else {
281 Err(from_glib_full(error))
282 }
283 }
284 }
285
286 /// Send one or more data messages from @self in one go.
287 ///
288 /// @messages must point to an array of #GOutputMessage structs and
289 /// @num_messages must be the length of this array. Each #GOutputMessage
290 /// contains an address to send the data to, and a pointer to an array of
291 /// #GOutputVector structs to describe the buffers that the data to be sent
292 /// for each message will be gathered from.
293 ///
294 /// @flags modify how the message is sent. The commonly available arguments
295 /// for this are available in the #GSocketMsgFlags enum, but the
296 /// values there are the same as the system values, and the flags
297 /// are passed in as-is, so you can pass in system-specific flags too.
298 ///
299 /// The other members of #GOutputMessage are treated as described in its
300 /// documentation.
301 ///
302 /// If @timeout is negative the call will block until @num_messages have been
303 /// sent, @cancellable is cancelled, or an error occurs.
304 ///
305 /// If @timeout is 0 the call will send up to @num_messages without blocking,
306 /// or will return [`IOErrorEnum::WouldBlock`][crate::IOErrorEnum::WouldBlock] if there is no space to send messages.
307 ///
308 /// If @timeout is positive the call will block on the same conditions as if
309 /// @timeout were negative. If the timeout is reached before any messages are
310 /// sent, [`IOErrorEnum::TimedOut`][crate::IOErrorEnum::TimedOut] is returned, otherwise it will return the number
311 /// of messages sent before timing out.
312 ///
313 /// To be notified when messages can be sent, wait for the [`glib::IOCondition::OUT`][crate::glib::IOCondition::OUT] condition.
314 /// Note though that you may still receive [`IOErrorEnum::WouldBlock`][crate::IOErrorEnum::WouldBlock] from
315 /// g_datagram_based_send_messages() even if you were previously notified of a
316 /// [`glib::IOCondition::OUT`][crate::glib::IOCondition::OUT] condition. (On Windows in particular, this is very common due to
317 /// the way the underlying APIs work.)
318 ///
319 /// If the connection is shut down or closed (by calling g_socket_close() or
320 /// g_socket_shutdown() with @shutdown_write set, if it’s a #GSocket, for
321 /// example), all calls to this function will return [`IOErrorEnum::Closed`][crate::IOErrorEnum::Closed].
322 ///
323 /// On error -1 is returned and @error is set accordingly. An error will only
324 /// be returned if zero messages could be sent; otherwise the number of messages
325 /// successfully sent before the error will be returned. If @cancellable is
326 /// cancelled, [`IOErrorEnum::Cancelled`][crate::IOErrorEnum::Cancelled] is returned as with any other error.
327 /// ## `messages`
328 /// an array of #GOutputMessage structs
329 /// ## `flags`
330 /// an int containing #GSocketMsgFlags flags
331 /// ## `timeout`
332 /// the maximum time (in microseconds) to wait, 0 to not block, or -1
333 /// to block indefinitely
334 /// ## `cancellable`
335 /// a `GCancellable`
336 ///
337 /// # Returns
338 ///
339 /// number of messages sent, or -1 on error. Note that the number of
340 /// messages sent may be smaller than @num_messages if @timeout is zero
341 /// or positive, or if @num_messages was larger than `UIO_MAXIOV` (1024), in
342 /// which case the caller may re-try to send the remaining messages.
343 #[doc(alias = "g_datagram_based_send_messages")]
344 fn send_messages<C: IsA<Cancellable>>(
345 &self,
346 messages: &mut [OutputMessage],
347 flags: i32,
348 timeout: Option<Duration>,
349 cancellable: Option<&C>,
350 ) -> Result<usize, glib::Error> {
351 let cancellable = cancellable.map(|c| c.as_ref());
352 unsafe {
353 let mut error = ptr::null_mut();
354 let count = ffi::g_datagram_based_send_messages(
355 self.as_ref().to_glib_none().0,
356 messages.as_mut_ptr() as *mut _,
357 messages.len().try_into().unwrap(),
358 flags,
359 timeout
360 .map(|t| t.as_micros().try_into().unwrap())
361 .unwrap_or(-1),
362 cancellable.to_glib_none().0,
363 &mut error,
364 );
365 if error.is_null() {
366 Ok(count as usize)
367 } else {
368 Err(from_glib_full(error))
369 }
370 }
371 }
372}
373
374impl<O: IsA<DatagramBased>> DatagramBasedExtManual for O {}