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
// Take a look at the license at the top of the repository in the LICENSE file.

use std::{ptr, sync::OnceLock};

use glib::{prelude::*, subclass::prelude::*, translate::*, Error};

use crate::{Cancellable, IOStream, InputStream, OutputStream};

pub trait IOStreamImpl: ObjectImpl + IOStreamImplExt + Send {
    /// Gets the input stream for this object. This is used
    /// for reading.
    ///
    /// # Returns
    ///
    /// a #GInputStream, owned by the #GIOStream.
    /// Do not free.
    fn input_stream(&self) -> InputStream {
        self.parent_input_stream()
    }

    /// Gets the output stream for this object. This is used for
    /// writing.
    ///
    /// # Returns
    ///
    /// a #GOutputStream, owned by the #GIOStream.
    /// Do not free.
    fn output_stream(&self) -> OutputStream {
        self.parent_output_stream()
    }

    fn close(&self, cancellable: Option<&Cancellable>) -> Result<(), Error> {
        self.parent_close(cancellable)
    }
}

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

pub trait IOStreamImplExt: sealed::Sealed + ObjectSubclass {
    fn parent_input_stream(&self) -> InputStream {
        unsafe {
            let data = Self::type_data();
            let parent_class = data.as_ref().parent_class() as *mut ffi::GIOStreamClass;
            let f = (*parent_class)
                .get_input_stream
                .expect("No parent class implementation for \"input_stream\"");
            from_glib_none(f(self.obj().unsafe_cast_ref::<IOStream>().to_glib_none().0))
        }
    }

    fn parent_output_stream(&self) -> OutputStream {
        unsafe {
            let data = Self::type_data();
            let parent_class = data.as_ref().parent_class() as *mut ffi::GIOStreamClass;
            let f = (*parent_class)
                .get_output_stream
                .expect("No parent class implementation for \"output_stream\"");
            from_glib_none(f(self.obj().unsafe_cast_ref::<IOStream>().to_glib_none().0))
        }
    }

    fn parent_close(&self, cancellable: Option<&Cancellable>) -> Result<(), Error> {
        unsafe {
            let data = Self::type_data();
            let parent_class = data.as_ref().parent_class() as *mut ffi::GIOStreamClass;
            let mut err = ptr::null_mut();
            if let Some(f) = (*parent_class).close_fn {
                if from_glib(f(
                    self.obj().unsafe_cast_ref::<IOStream>().to_glib_none().0,
                    cancellable.to_glib_none().0,
                    &mut err,
                )) {
                    Ok(())
                } else {
                    Err(from_glib_full(err))
                }
            } else {
                Ok(())
            }
        }
    }
}

impl<T: IOStreamImpl> IOStreamImplExt for T {}

unsafe impl<T: IOStreamImpl> IsSubclassable<T> for IOStream {
    fn class_init(class: &mut ::glib::Class<Self>) {
        Self::parent_class_init::<T>(class);

        let klass = class.as_mut();
        klass.get_input_stream = Some(stream_get_input_stream::<T>);
        klass.get_output_stream = Some(stream_get_output_stream::<T>);
        klass.close_fn = Some(stream_close::<T>);
    }
}

unsafe extern "C" fn stream_get_input_stream<T: IOStreamImpl>(
    ptr: *mut ffi::GIOStream,
) -> *mut ffi::GInputStream {
    let instance = &*(ptr as *mut T::Instance);
    let imp = instance.imp();

    let ret = imp.input_stream();

    let instance = imp.obj();
    // Ensure that a) the stream stays alive as long as the IO stream instance and
    // b) that the same stream is returned every time. This is a requirement by the
    // IO stream API.
    let input_stream_quark = {
        static QUARK: OnceLock<glib::Quark> = OnceLock::new();
        *QUARK.get_or_init(|| glib::Quark::from_str("gtk-rs-subclass-input-stream"))
    };
    if let Some(old_stream) = instance.qdata::<InputStream>(input_stream_quark) {
        assert_eq!(
            old_stream.as_ref(),
            &ret,
            "Did not return same input stream again"
        );
    }
    instance.set_qdata(input_stream_quark, ret.clone());
    ret.to_glib_none().0
}

unsafe extern "C" fn stream_get_output_stream<T: IOStreamImpl>(
    ptr: *mut ffi::GIOStream,
) -> *mut ffi::GOutputStream {
    let instance = &*(ptr as *mut T::Instance);
    let imp = instance.imp();

    let ret = imp.output_stream();

    let instance = imp.obj();
    // Ensure that a) the stream stays alive as long as the IO stream instance and
    // b) that the same stream is returned every time. This is a requirement by the
    // IO stream API.
    let output_stream_quark = {
        static QUARK: OnceLock<glib::Quark> = OnceLock::new();
        *QUARK.get_or_init(|| glib::Quark::from_str("gtk-rs-subclass-output-stream"))
    };
    if let Some(old_stream) = instance.qdata::<OutputStream>(output_stream_quark) {
        assert_eq!(
            old_stream.as_ref(),
            &ret,
            "Did not return same output stream again"
        );
    }
    instance.set_qdata(output_stream_quark, ret.clone());
    ret.to_glib_none().0
}

unsafe extern "C" fn stream_close<T: IOStreamImpl>(
    ptr: *mut ffi::GIOStream,
    cancellable: *mut ffi::GCancellable,
    err: *mut *mut glib::ffi::GError,
) -> glib::ffi::gboolean {
    let instance = &*(ptr as *mut T::Instance);
    let imp = instance.imp();

    match imp.close(
        Option::<Cancellable>::from_glib_borrow(cancellable)
            .as_ref()
            .as_ref(),
    ) {
        Ok(_) => glib::ffi::GTRUE,
        Err(e) => {
            if !err.is_null() {
                *err = e.into_glib_ptr();
            }
            glib::ffi::GFALSE
        }
    }
}