gio/subclass/
output_stream.rs

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

use std::ptr;

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

use crate::{ffi, Cancellable, InputStream, OutputStream, OutputStreamSpliceFlags};

pub trait OutputStreamImpl: ObjectImpl + OutputStreamImplExt + Send {
    fn write(&self, buffer: &[u8], cancellable: Option<&Cancellable>) -> Result<usize, Error> {
        self.parent_write(buffer, cancellable)
    }

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

    /// Forces a write of all user-space buffered data for the given
    /// @self. Will block during the operation. Closing the stream will
    /// implicitly cause a flush.
    ///
    /// This function is optional for inherited classes.
    ///
    /// If @cancellable is not [`None`], then the operation can be cancelled by
    /// triggering the cancellable object from another thread. If the operation
    /// was cancelled, the error [`IOErrorEnum::Cancelled`][crate::IOErrorEnum::Cancelled] will be returned.
    /// ## `cancellable`
    /// optional cancellable object
    ///
    /// # Returns
    ///
    /// [`true`] on success, [`false`] on error
    fn flush(&self, cancellable: Option<&Cancellable>) -> Result<(), Error> {
        self.parent_flush(cancellable)
    }

    /// Splices an input stream into an output stream.
    /// ## `source`
    /// a #GInputStream.
    /// ## `flags`
    /// a set of #GOutputStreamSpliceFlags.
    /// ## `cancellable`
    /// optional #GCancellable object, [`None`] to ignore.
    ///
    /// # Returns
    ///
    /// a #gssize containing the size of the data spliced, or
    ///     -1 if an error occurred. Note that if the number of bytes
    ///     spliced is greater than `G_MAXSSIZE`, then that will be
    ///     returned, and there is no way to determine the actual number
    ///     of bytes spliced.
    fn splice(
        &self,
        input_stream: &InputStream,
        flags: OutputStreamSpliceFlags,
        cancellable: Option<&Cancellable>,
    ) -> Result<usize, Error> {
        self.parent_splice(input_stream, flags, cancellable)
    }
}

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

pub trait OutputStreamImplExt: sealed::Sealed + ObjectSubclass {
    fn parent_write(
        &self,
        buffer: &[u8],
        cancellable: Option<&Cancellable>,
    ) -> Result<usize, Error> {
        unsafe {
            let data = Self::type_data();
            let parent_class = data.as_ref().parent_class() as *mut ffi::GOutputStreamClass;
            let f = (*parent_class)
                .write_fn
                .expect("No parent class implementation for \"write\"");
            let mut err = ptr::null_mut();
            let res = f(
                self.obj()
                    .unsafe_cast_ref::<OutputStream>()
                    .to_glib_none()
                    .0,
                mut_override(buffer.as_ptr()),
                buffer.len(),
                cancellable.to_glib_none().0,
                &mut err,
            );
            if res == -1 {
                Err(from_glib_full(err))
            } else {
                debug_assert!(res >= 0);
                let res = res as usize;
                debug_assert!(res <= buffer.len());
                Ok(res)
            }
        }
    }

    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::GOutputStreamClass;
            let mut err = ptr::null_mut();
            if let Some(f) = (*parent_class).close_fn {
                if from_glib(f(
                    self.obj()
                        .unsafe_cast_ref::<OutputStream>()
                        .to_glib_none()
                        .0,
                    cancellable.to_glib_none().0,
                    &mut err,
                )) {
                    Ok(())
                } else {
                    Err(from_glib_full(err))
                }
            } else {
                Ok(())
            }
        }
    }

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

    fn parent_splice(
        &self,
        input_stream: &InputStream,
        flags: OutputStreamSpliceFlags,
        cancellable: Option<&Cancellable>,
    ) -> Result<usize, Error> {
        unsafe {
            let data = Self::type_data();
            let parent_class = data.as_ref().parent_class() as *mut ffi::GOutputStreamClass;
            let mut err = ptr::null_mut();
            let f = (*parent_class)
                .splice
                .expect("No parent class implementation for \"splice\"");
            let res = f(
                self.obj()
                    .unsafe_cast_ref::<OutputStream>()
                    .to_glib_none()
                    .0,
                input_stream.to_glib_none().0,
                flags.into_glib(),
                cancellable.to_glib_none().0,
                &mut err,
            );
            if res == -1 {
                Err(from_glib_full(err))
            } else {
                debug_assert!(res >= 0);
                let res = res as usize;
                Ok(res)
            }
        }
    }
}

impl<T: OutputStreamImpl> OutputStreamImplExt for T {}

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

        let klass = class.as_mut();
        klass.write_fn = Some(stream_write::<T>);
        klass.close_fn = Some(stream_close::<T>);
        klass.flush = Some(stream_flush::<T>);
        klass.splice = Some(stream_splice::<T>);
    }
}

unsafe extern "C" fn stream_write<T: OutputStreamImpl>(
    ptr: *mut ffi::GOutputStream,
    buffer: *mut u8,
    count: usize,
    cancellable: *mut ffi::GCancellable,
    err: *mut *mut glib::ffi::GError,
) -> isize {
    debug_assert!(count <= isize::MAX as usize);

    let instance = &*(ptr as *mut T::Instance);
    let imp = instance.imp();

    match imp.write(
        if count == 0 {
            &[]
        } else {
            std::slice::from_raw_parts(buffer as *const u8, count)
        },
        Option::<Cancellable>::from_glib_borrow(cancellable)
            .as_ref()
            .as_ref(),
    ) {
        Ok(res) => {
            assert!(res <= isize::MAX as usize);
            assert!(res <= count);
            res as isize
        }
        Err(e) => {
            if !err.is_null() {
                *err = e.into_glib_ptr();
            }
            -1
        }
    }
}

unsafe extern "C" fn stream_close<T: OutputStreamImpl>(
    ptr: *mut ffi::GOutputStream,
    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
        }
    }
}

unsafe extern "C" fn stream_flush<T: OutputStreamImpl>(
    ptr: *mut ffi::GOutputStream,
    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.flush(
        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
        }
    }
}

unsafe extern "C" fn stream_splice<T: OutputStreamImpl>(
    ptr: *mut ffi::GOutputStream,
    input_stream: *mut ffi::GInputStream,
    flags: ffi::GOutputStreamSpliceFlags,
    cancellable: *mut ffi::GCancellable,
    err: *mut *mut glib::ffi::GError,
) -> isize {
    let instance = &*(ptr as *mut T::Instance);
    let imp = instance.imp();

    match imp.splice(
        &from_glib_borrow(input_stream),
        from_glib(flags),
        Option::<Cancellable>::from_glib_borrow(cancellable)
            .as_ref()
            .as_ref(),
    ) {
        Ok(res) => {
            assert!(res <= isize::MAX as usize);
            res as isize
        }
        Err(e) => {
            if !err.is_null() {
                *err = e.into_glib_ptr();
            }
            -1
        }
    }
}

#[cfg(test)]
mod tests {
    use std::cell::RefCell;

    use super::*;
    use crate::prelude::*;

    mod imp {
        use super::*;

        #[derive(Default)]
        pub struct SimpleOutputStream {
            pub sum: RefCell<usize>,
        }

        #[glib::object_subclass]
        impl ObjectSubclass for SimpleOutputStream {
            const NAME: &'static str = "SimpleOutputStream";
            type Type = super::SimpleOutputStream;
            type ParentType = OutputStream;
        }

        impl ObjectImpl for SimpleOutputStream {}

        impl OutputStreamImpl for SimpleOutputStream {
            fn write(
                &self,
                buffer: &[u8],
                _cancellable: Option<&Cancellable>,
            ) -> Result<usize, Error> {
                let mut sum = self.sum.borrow_mut();
                for b in buffer {
                    *sum += *b as usize;
                }

                Ok(buffer.len())
            }
        }
    }

    glib::wrapper! {
        pub struct SimpleOutputStream(ObjectSubclass<imp::SimpleOutputStream>)
            @extends OutputStream;
    }

    #[test]
    fn test_simple_stream() {
        let stream = glib::Object::new::<SimpleOutputStream>();

        assert_eq!(*stream.imp().sum.borrow(), 0);
        assert_eq!(
            stream.write(&[1, 2, 3, 4, 5], crate::Cancellable::NONE),
            Ok(5)
        );
        assert_eq!(*stream.imp().sum.borrow(), 15);
    }
}