glib-unix 0.22.8

Rust bindings for the GLibUnix library
Documentation
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
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
// Take a look at the license at the top of the repository in the LICENSE file.

use std::cell::RefCell;
use std::future::Future;
use std::mem::transmute;
use std::os::fd::{FromRawFd, RawFd};
use std::pin::Pin;

use glib::ffi::gpointer;
use glib::thread_guard::ThreadGuard;
use glib::translate::*;
use glib::{ControlFlow, IOCondition, Priority, Source, SourceId};

use crate::ffi;

#[cfg(feature = "futures")]
use glib::{SourceFuture, SourceStream};

#[cfg(feature = "futures")]
use futures_core::stream::Stream;

fn into_raw<F: FnMut() -> ControlFlow + Send + 'static>(func: F) -> gpointer {
    let func: Box<RefCell<F>> = Box::new(RefCell::new(func));
    Box::into_raw(func) as gpointer
}

fn into_raw_local<F: FnMut() -> ControlFlow + 'static>(func: F) -> gpointer {
    let func: Box<ThreadGuard<RefCell<F>>> = Box::new(ThreadGuard::new(RefCell::new(func)));
    Box::into_raw(func) as gpointer
}

unsafe extern "C" fn trampoline<F: FnMut() -> ControlFlow + Send + 'static>(
    func: gpointer,
) -> glib::ffi::gboolean {
    unsafe {
        let func: &RefCell<F> = &*(func as *const RefCell<F>);
        (*func.borrow_mut())().into_glib()
    }
}

unsafe extern "C" fn trampoline_local<F: FnMut() -> ControlFlow + 'static>(
    func: gpointer,
) -> glib::ffi::gboolean {
    unsafe {
        let func: &ThreadGuard<RefCell<F>> = &*(func as *const ThreadGuard<RefCell<F>>);
        (*func.get_ref().borrow_mut())().into_glib()
    }
}

unsafe extern "C" fn destroy_closure<F: FnMut() -> ControlFlow + Send + 'static>(ptr: gpointer) {
    unsafe {
        let _ = Box::<RefCell<F>>::from_raw(ptr as *mut _);
    }
}

unsafe extern "C" fn destroy_closure_local<F: FnMut() -> ControlFlow + 'static>(ptr: gpointer) {
    unsafe {
        let _ = Box::<ThreadGuard<RefCell<F>>>::from_raw(ptr as *mut _);
    }
}

unsafe extern "C" fn trampoline_unix_fd<
    F: FnMut(RawFd, IOCondition) -> ControlFlow + Send + 'static,
>(
    fd: i32,
    condition: glib::ffi::GIOCondition,
    func: gpointer,
) -> glib::ffi::gboolean {
    unsafe {
        let func: &RefCell<F> = &*(func as *const RefCell<F>);
        (*func.borrow_mut())(fd, from_glib(condition)).into_glib()
    }
}

unsafe extern "C" fn trampoline_unix_fd_local<
    F: FnMut(RawFd, IOCondition) -> ControlFlow + 'static,
>(
    fd: i32,
    condition: glib::ffi::GIOCondition,
    func: gpointer,
) -> glib::ffi::gboolean {
    unsafe {
        let func: &ThreadGuard<RefCell<F>> = &*(func as *const ThreadGuard<RefCell<F>>);
        (*func.get_ref().borrow_mut())(fd, from_glib(condition)).into_glib()
    }
}

unsafe extern "C" fn destroy_closure_unix_fd<
    F: FnMut(RawFd, IOCondition) -> ControlFlow + Send + 'static,
>(
    ptr: gpointer,
) {
    unsafe {
        let _ = Box::<RefCell<F>>::from_raw(ptr as *mut _);
    }
}

unsafe extern "C" fn destroy_closure_unix_fd_local<
    F: FnMut(RawFd, IOCondition) -> ControlFlow + 'static,
>(
    ptr: gpointer,
) {
    unsafe {
        let _ = Box::<ThreadGuard<RefCell<F>>>::from_raw(ptr as *mut _);
    }
}

fn into_raw_unix_fd<F: FnMut(RawFd, IOCondition) -> ControlFlow + Send + 'static>(
    func: F,
) -> gpointer {
    let func: Box<RefCell<F>> = Box::new(RefCell::new(func));
    Box::into_raw(func) as gpointer
}

fn into_raw_unix_fd_local<F: FnMut(RawFd, IOCondition) -> ControlFlow + 'static>(
    func: F,
) -> gpointer {
    let func: Box<ThreadGuard<RefCell<F>>> = Box::new(ThreadGuard::new(RefCell::new(func)));
    Box::into_raw(func) as gpointer
}

#[inline(always)]
fn fnmut_callback_wrapper(
    func: impl FnOnce() + Send + 'static,
) -> impl FnMut() -> ControlFlow + Send + 'static {
    let mut func = Some(func);
    move || {
        let func = func
            .take()
            .expect("GSource closure called after returning ControlFlow::Break");
        func();
        ControlFlow::Break
    }
}

#[inline(always)]
fn fnmut_callback_wrapper_local(
    func: impl FnOnce() + 'static,
) -> impl FnMut() -> ControlFlow + 'static {
    let mut func = Some(func);
    move || {
        let func = func
            .take()
            .expect("GSource closure called after returning glib::ControlFlow::Break");
        func();
        ControlFlow::Break
    }
}

#[doc(alias = "g_unix_open_pipe")]
pub fn unix_open_pipe(flags: i32) -> Result<(RawFd, RawFd), glib::Error> {
    unsafe {
        let mut fds = [0, 2];
        let mut error = std::ptr::null_mut();
        let _ = ffi::g_unix_open_pipe(&mut fds, flags, &mut error);
        if error.is_null() {
            Ok((
                FromRawFd::from_raw_fd(fds[0]),
                FromRawFd::from_raw_fd(fds[1]),
            ))
        } else {
            Err(from_glib_full(error))
        }
    }
}

// rustdoc-stripper-ignore-next
/// Create a `Stream` that will provide a value whenever the given UNIX signal is raised
///
/// The `Stream` must be spawned on an `Executor` backed by a `glib::MainContext`.
#[cfg(feature = "futures")]
pub fn signal_stream(signum: i32) -> Pin<Box<dyn Stream<Item = ()> + Send + 'static>> {
    signal_stream_with_priority(Priority::default(), signum)
}

// rustdoc-stripper-ignore-next
/// Create a `Stream` that will provide a value whenever the given UNIX signal is raised
///
/// The `Stream` must be spawned on an `Executor` backed by a `glib::MainContext`.
#[cfg(feature = "futures")]
pub fn signal_stream_with_priority(
    priority: Priority,
    signum: i32,
) -> Pin<Box<dyn Stream<Item = ()> + Send + 'static>> {
    Box::pin(SourceStream::new(move |send| {
        signal_source_new(signum, None, priority, move || {
            if send.unbounded_send(()).is_err() {
                ControlFlow::Break
            } else {
                ControlFlow::Continue
            }
        })
    }))
}

// rustdoc-stripper-ignore-next
/// Create a `Future` that will resolve once the given UNIX signal is raised
///
/// The `Future` must be spawned on an `Executor` backed by a `glib::MainContext`.
#[cfg(feature = "futures")]
pub fn signal_future_with_priority(
    priority: Priority,
    signum: i32,
) -> Pin<Box<dyn Future<Output = ()> + Send + 'static>> {
    Box::pin(SourceFuture::new(move |send| {
        let mut send = Some(send);
        signal_source_new(signum, None, priority, move || {
            let _ = send.take().unwrap().send(());
            ControlFlow::Break
        })
    }))
}

// rustdoc-stripper-ignore-next
/// Adds a closure to be called by the main loop the returned `Source` is attached to whenever a
/// UNIX signal is raised.
///
/// `func` will be called repeatedly every time `signum` is raised until it
/// returns `ControlFlow::Break`.
#[doc(alias = "g_unix_signal_source_new")]
pub fn signal_source_new<F>(
    signum: i32,
    name: Option<&str>,
    priority: Priority,
    func: F,
) -> glib::Source
where
    F: FnMut() -> glib::ControlFlow + Send + 'static,
{
    unsafe {
        let source = ffi::g_unix_signal_source_new(signum);
        glib::ffi::g_source_set_callback(
            source,
            Some(trampoline::<F>),
            into_raw(func),
            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)
    }
}

// rustdoc-stripper-ignore-next
/// Adds a closure to be called by the main loop the returned `Source` is attached to whenever a
/// UNIX file descriptor reaches the given IO condition.
///
/// `func` will be called repeatedly while the file descriptor matches the given IO condition
/// until it returns `ControlFlow::Break`.
#[doc(alias = "g_unix_fd_source_new")]
pub fn fd_source_new<F>(
    fd: RawFd,
    condition: IOCondition,
    name: Option<&str>,
    priority: Priority,
    func: F,
) -> Source
where
    F: FnMut(RawFd, IOCondition) -> ControlFlow + Send + 'static,
{
    unsafe {
        let source = ffi::g_unix_fd_source_new(fd, condition.into_glib());
        glib::ffi::g_source_set_callback(
            source,
            Some(transmute::<
                *const (),
                unsafe extern "C" fn(glib::ffi::gpointer) -> glib::ffi::gboolean,
            >(trampoline_unix_fd::<F> as *const ())),
            into_raw_unix_fd(func),
            Some(destroy_closure_unix_fd::<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)
    }
}

// rustdoc-stripper-ignore-next
/// Create a `Future` that will resolve once the given UNIX signal is raised
///
/// The `Future` must be spawned on an `Executor` backed by a `glib::MainContext`.
pub fn signal_future(signum: i32) -> Pin<Box<dyn Future<Output = ()> + Send + 'static>> {
    signal_future_with_priority(Priority::default(), signum)
}

// rustdoc-stripper-ignore-next
/// Adds a closure to be called by the default main loop whenever a UNIX signal is raised.
///
/// `func` will be called repeatedly every time `signum` is raised until it
/// returns `ControlFlow::Break`.
///
/// The default main loop almost always is the main loop of the main thread.
/// Thus, the closure is called on the main thread.
#[doc(alias = "g_unix_signal_add_full")]
pub fn unix_signal_add<F>(signum: i32, func: F) -> SourceId
where
    F: FnMut() -> ControlFlow + Send + 'static,
{
    unsafe {
        from_glib(ffi::g_unix_signal_add_full(
            Priority::default().into_glib(),
            signum,
            Some(trampoline::<F>),
            into_raw(func),
            Some(destroy_closure::<F>),
        ))
    }
}

// rustdoc-stripper-ignore-next
/// Adds a closure to be called by the default main loop whenever a UNIX signal is raised.
///
/// `func` will be called repeatedly every time `signum` is raised until it
/// returns `ControlFlow::Break`.
///
/// The default main loop almost always is the main loop of the main thread.
/// Thus, the closure is called on the main thread.
///
/// In comparison to `unix_signal_add()`, this only requires `func` to be
/// `FnOnce`, and will automatically return `ControlFlow::Break`.
#[doc(alias = "g_unix_signal_add_full")]
pub fn unix_signal_add_once<F>(signum: i32, func: F) -> SourceId
where
    F: FnOnce() + Send + 'static,
{
    unix_signal_add(signum, fnmut_callback_wrapper(func))
}

// rustdoc-stripper-ignore-next
/// Adds a closure to be called by the default main loop whenever a UNIX signal is raised.
///
/// `func` will be called repeatedly every time `signum` is raised until it
/// returns `ControlFlow::Break`.
///
/// The default main loop almost always is the main loop of the main thread.
/// Thus, the closure is called on the main thread.
///
/// Different to `unix_signal_add()`, this does not require `func` to be
/// `Send` but can only be called from the thread that owns the main context.
///
/// This function panics if called from a different thread than the one that
/// owns the main context.
#[doc(alias = "g_unix_signal_add_full")]
pub fn unix_signal_add_local<F>(signum: i32, func: F) -> SourceId
where
    F: FnMut() -> ControlFlow + 'static,
{
    unsafe {
        let context = glib::MainContext::default();
        let _acquire = context
            .acquire()
            .expect("default main context already acquired by another thread");
        from_glib(ffi::g_unix_signal_add_full(
            Priority::default().into_glib(),
            signum,
            Some(trampoline_local::<F>),
            into_raw_local(func),
            Some(destroy_closure_local::<F>),
        ))
    }
}

// rustdoc-stripper-ignore-next
/// Adds a closure to be called by the default main loop whenever a UNIX signal is raised.
///
/// `func` will be called repeatedly every time `signum` is raised until it
/// returns `ControlFlow::Break`.
///
/// The default main loop almost always is the main loop of the main thread.
/// Thus, the closure is called on the main thread.
///
/// Different to `unix_signal_add()`, this does not require `func` to be
/// `Send` but can only be called from the thread that owns the main context.
///
/// This function panics if called from a different thread than the one that
/// owns the main context.
///
/// In comparison to `unix_signal_add_local()`, this only requires `func` to be
/// `FnOnce`, and will automatically return `ControlFlow::Break`.
#[doc(alias = "g_unix_signal_add_full")]
pub fn unix_signal_add_local_once<F>(signum: i32, func: F) -> SourceId
where
    F: FnOnce() + 'static,
{
    unix_signal_add_local(signum, fnmut_callback_wrapper_local(func))
}

// rustdoc-stripper-ignore-next
/// Adds a closure to be called by the main loop the returned `Source` is attached to whenever a
/// UNIX file descriptor reaches the given IO condition.
///
/// `func` will be called repeatedly while the file descriptor matches the given IO condition
/// until it returns `ControlFlow::Break`.
///
/// The default main loop almost always is the main loop of the main thread.
/// Thus, the closure is called on the main thread.
#[doc(alias = "g_unix_fd_add_full")]
pub fn unix_fd_add<F>(fd: RawFd, condition: IOCondition, func: F) -> SourceId
where
    F: FnMut(RawFd, IOCondition) -> ControlFlow + Send + 'static,
{
    unsafe {
        from_glib(ffi::g_unix_fd_add_full(
            Priority::default().into_glib(),
            fd,
            condition.into_glib(),
            Some(trampoline_unix_fd::<F>),
            into_raw_unix_fd(func),
            Some(destroy_closure_unix_fd::<F>),
        ))
    }
}

// rustdoc-stripper-ignore-next
/// Adds a closure to be called by the main loop the returned `Source` is attached to whenever a
/// UNIX file descriptor reaches the given IO condition.
///
/// `func` will be called repeatedly with `priority` while the file descriptor matches the given IO condition
/// until it returns `ControlFlow::Break`.
///
/// The default main loop almost always is the main loop of the main thread.
/// Thus, the closure is called on the main thread.
#[doc(alias = "g_unix_fd_add_full")]
pub fn unix_fd_add_full<F>(
    fd: RawFd,
    priority: Priority,
    condition: IOCondition,
    func: F,
) -> SourceId
where
    F: FnMut(RawFd, IOCondition) -> ControlFlow + Send + 'static,
{
    unsafe {
        from_glib(ffi::g_unix_fd_add_full(
            priority.into_glib(),
            fd,
            condition.into_glib(),
            Some(trampoline_unix_fd::<F>),
            into_raw_unix_fd(func),
            Some(destroy_closure_unix_fd::<F>),
        ))
    }
}

// rustdoc-stripper-ignore-next
/// Adds a closure to be called by the main loop the returned `Source` is attached to whenever a
/// UNIX file descriptor reaches the given IO condition.
///
/// `func` will be called repeatedly while the file descriptor matches the given IO condition
/// until it returns `ControlFlow::Break`.
///
/// The default main loop almost always is the main loop of the main thread.
/// Thus, the closure is called on the main thread.
///
/// Different to `unix_fd_add()`, this does not require `func` to be
/// `Send` but can only be called from the thread that owns the main context.
///
/// This function panics if called from a different thread than the one that
/// owns the main context.
#[doc(alias = "g_unix_fd_add_full")]
pub fn unix_fd_add_local<F>(fd: RawFd, condition: IOCondition, func: F) -> SourceId
where
    F: FnMut(RawFd, IOCondition) -> ControlFlow + 'static,
{
    unsafe {
        let context = glib::MainContext::default();
        let _acquire = context
            .acquire()
            .expect("default main context already acquired by another thread");
        from_glib(ffi::g_unix_fd_add_full(
            Priority::default().into_glib(),
            fd,
            condition.into_glib(),
            Some(trampoline_unix_fd_local::<F>),
            into_raw_unix_fd_local(func),
            Some(destroy_closure_unix_fd_local::<F>),
        ))
    }
}

// rustdoc-stripper-ignore-next
/// Adds a closure to be called by the main loop the returned `Source` is attached to whenever a
/// UNIX file descriptor reaches the given IO condition.
///
/// `func` will be called repeatedly with `priority` while the file descriptor matches the given IO condition
/// until it returns `ControlFlow::Break`.
///
/// The default main loop almost always is the main loop of the main thread.
/// Thus, the closure is called on the main thread.
///
/// Different to `unix_fd_add()`, this does not require `func` to be
/// `Send` but can only be called from the thread that owns the main context.
///
/// This function panics if called from a different thread than the one that
/// owns the main context.
#[doc(alias = "g_unix_fd_add_full")]
pub fn unix_fd_add_local_full<F>(
    fd: RawFd,
    priority: Priority,
    condition: IOCondition,
    func: F,
) -> SourceId
where
    F: FnMut(RawFd, IOCondition) -> ControlFlow + 'static,
{
    unsafe {
        let context = glib::MainContext::default();
        let _acquire = context
            .acquire()
            .expect("default main context already acquired by another thread");
        from_glib(ffi::g_unix_fd_add_full(
            priority.into_glib(),
            fd,
            condition.into_glib(),
            Some(trampoline_unix_fd_local::<F>),
            into_raw_unix_fd_local(func),
            Some(destroy_closure_unix_fd_local::<F>),
        ))
    }
}