gio/subclass/
io_stream.rs

1// Take a look at the license at the top of the repository in the LICENSE file.
2
3use std::{ptr, sync::OnceLock};
4
5use glib::{prelude::*, subclass::prelude::*, translate::*, Error};
6
7use crate::{ffi, Cancellable, IOStream, InputStream, OutputStream};
8
9pub trait IOStreamImpl: Send + ObjectImpl + ObjectSubclass<Type: IsA<IOStream>> {
10    /// Gets the input stream for this object. This is used
11    /// for reading.
12    ///
13    /// # Returns
14    ///
15    /// a #GInputStream, owned by the #GIOStream.
16    /// Do not free.
17    fn input_stream(&self) -> InputStream {
18        self.parent_input_stream()
19    }
20
21    /// Gets the output stream for this object. This is used for
22    /// writing.
23    ///
24    /// # Returns
25    ///
26    /// a #GOutputStream, owned by the #GIOStream.
27    /// Do not free.
28    fn output_stream(&self) -> OutputStream {
29        self.parent_output_stream()
30    }
31
32    fn close(&self, cancellable: Option<&Cancellable>) -> Result<(), Error> {
33        self.parent_close(cancellable)
34    }
35}
36
37pub trait IOStreamImplExt: IOStreamImpl {
38    fn parent_input_stream(&self) -> InputStream {
39        unsafe {
40            let data = Self::type_data();
41            let parent_class = data.as_ref().parent_class() as *mut ffi::GIOStreamClass;
42            let f = (*parent_class)
43                .get_input_stream
44                .expect("No parent class implementation for \"input_stream\"");
45            from_glib_none(f(self.obj().unsafe_cast_ref::<IOStream>().to_glib_none().0))
46        }
47    }
48
49    fn parent_output_stream(&self) -> OutputStream {
50        unsafe {
51            let data = Self::type_data();
52            let parent_class = data.as_ref().parent_class() as *mut ffi::GIOStreamClass;
53            let f = (*parent_class)
54                .get_output_stream
55                .expect("No parent class implementation for \"output_stream\"");
56            from_glib_none(f(self.obj().unsafe_cast_ref::<IOStream>().to_glib_none().0))
57        }
58    }
59
60    fn parent_close(&self, cancellable: Option<&Cancellable>) -> Result<(), Error> {
61        unsafe {
62            let data = Self::type_data();
63            let parent_class = data.as_ref().parent_class() as *mut ffi::GIOStreamClass;
64            let mut err = ptr::null_mut();
65            if let Some(f) = (*parent_class).close_fn {
66                if from_glib(f(
67                    self.obj().unsafe_cast_ref::<IOStream>().to_glib_none().0,
68                    cancellable.to_glib_none().0,
69                    &mut err,
70                )) {
71                    Ok(())
72                } else {
73                    Err(from_glib_full(err))
74                }
75            } else {
76                Ok(())
77            }
78        }
79    }
80}
81
82impl<T: IOStreamImpl> IOStreamImplExt for T {}
83
84unsafe impl<T: IOStreamImpl> IsSubclassable<T> for IOStream {
85    fn class_init(class: &mut ::glib::Class<Self>) {
86        Self::parent_class_init::<T>(class);
87
88        let klass = class.as_mut();
89        klass.get_input_stream = Some(stream_get_input_stream::<T>);
90        klass.get_output_stream = Some(stream_get_output_stream::<T>);
91        klass.close_fn = Some(stream_close::<T>);
92    }
93}
94
95unsafe extern "C" fn stream_get_input_stream<T: IOStreamImpl>(
96    ptr: *mut ffi::GIOStream,
97) -> *mut ffi::GInputStream {
98    let instance = &*(ptr as *mut T::Instance);
99    let imp = instance.imp();
100
101    let ret = imp.input_stream();
102
103    let instance = imp.obj();
104    // Ensure that a) the stream stays alive as long as the IO stream instance and
105    // b) that the same stream is returned every time. This is a requirement by the
106    // IO stream API.
107    let input_stream_quark = {
108        static QUARK: OnceLock<glib::Quark> = OnceLock::new();
109        *QUARK.get_or_init(|| glib::Quark::from_str("gtk-rs-subclass-input-stream"))
110    };
111    if let Some(old_stream) = instance.qdata::<InputStream>(input_stream_quark) {
112        assert_eq!(
113            old_stream.as_ref(),
114            &ret,
115            "Did not return same input stream again"
116        );
117    }
118    instance.set_qdata(input_stream_quark, ret.clone());
119    ret.to_glib_none().0
120}
121
122unsafe extern "C" fn stream_get_output_stream<T: IOStreamImpl>(
123    ptr: *mut ffi::GIOStream,
124) -> *mut ffi::GOutputStream {
125    let instance = &*(ptr as *mut T::Instance);
126    let imp = instance.imp();
127
128    let ret = imp.output_stream();
129
130    let instance = imp.obj();
131    // Ensure that a) the stream stays alive as long as the IO stream instance and
132    // b) that the same stream is returned every time. This is a requirement by the
133    // IO stream API.
134    let output_stream_quark = {
135        static QUARK: OnceLock<glib::Quark> = OnceLock::new();
136        *QUARK.get_or_init(|| glib::Quark::from_str("gtk-rs-subclass-output-stream"))
137    };
138    if let Some(old_stream) = instance.qdata::<OutputStream>(output_stream_quark) {
139        assert_eq!(
140            old_stream.as_ref(),
141            &ret,
142            "Did not return same output stream again"
143        );
144    }
145    instance.set_qdata(output_stream_quark, ret.clone());
146    ret.to_glib_none().0
147}
148
149unsafe extern "C" fn stream_close<T: IOStreamImpl>(
150    ptr: *mut ffi::GIOStream,
151    cancellable: *mut ffi::GCancellable,
152    err: *mut *mut glib::ffi::GError,
153) -> glib::ffi::gboolean {
154    let instance = &*(ptr as *mut T::Instance);
155    let imp = instance.imp();
156
157    match imp.close(
158        Option::<Cancellable>::from_glib_borrow(cancellable)
159            .as_ref()
160            .as_ref(),
161    ) {
162        Ok(_) => glib::ffi::GTRUE,
163        Err(e) => {
164            if !err.is_null() {
165                *err = e.into_glib_ptr();
166            }
167            glib::ffi::GFALSE
168        }
169    }
170}