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

use crate::error::to_std_io_result;
use crate::prelude::*;
use crate::Cancellable;
use crate::OutputStream;
use crate::Seekable;
use glib::object::IsA;
use glib::translate::*;
use glib::Priority;
use std::io;
use std::mem;
use std::pin::Pin;
use std::ptr;

pub trait OutputStreamExtManual: Sized + OutputStreamExt {
    /// Request an asynchronous write of `count` bytes from `buffer` into
    /// the stream. When the operation is finished `callback` will be called.
    /// You can then call `g_output_stream_write_finish()` to get the result of the
    /// operation.
    ///
    /// During an async request no other sync and async calls are allowed,
    /// and will result in [`IOErrorEnum::Pending`][crate::IOErrorEnum::Pending] errors.
    ///
    /// A value of `count` larger than `G_MAXSSIZE` will cause a
    /// [`IOErrorEnum::InvalidArgument`][crate::IOErrorEnum::InvalidArgument] error.
    ///
    /// On success, the number of bytes written will be passed to the
    /// `callback`. It is not an error if this is not the same as the
    /// requested size, as it can happen e.g. on a partial I/O error,
    /// but generally we try to write as many bytes as requested.
    ///
    /// You are guaranteed that this method will never fail with
    /// [`IOErrorEnum::WouldBlock`][crate::IOErrorEnum::WouldBlock] - if `self` can't accept more data, the
    /// method will just wait until this changes.
    ///
    /// Any outstanding I/O request with higher priority (lower numerical
    /// value) will be executed before an outstanding request with lower
    /// priority. Default priority is `G_PRIORITY_DEFAULT`.
    ///
    /// The asynchronous methods have a default fallback that uses threads
    /// to implement asynchronicity, so they are optional for inheriting
    /// classes. However, if you override one you must override all.
    ///
    /// For the synchronous, blocking version of this function, see
    /// [`OutputStreamExt::write()`][crate::prelude::OutputStreamExt::write()].
    ///
    /// Note that no copy of `buffer` will be made, so it must stay valid
    /// until `callback` is called. See [`OutputStreamExt::write_bytes_async()`][crate::prelude::OutputStreamExt::write_bytes_async()]
    /// for a [`glib::Bytes`][crate::glib::Bytes] version that will automatically hold a reference to
    /// the contents (without copying) for the duration of the call.
    /// ## `buffer`
    /// the buffer containing the data to write.
    /// ## `io_priority`
    /// the io priority of the request.
    /// ## `cancellable`
    /// optional [`Cancellable`][crate::Cancellable] object, [`None`] to ignore.
    /// ## `callback`
    /// callback to call when the request is satisfied
    #[doc(alias = "g_output_stream_write_async")]
    fn write_async<
        B: AsRef<[u8]> + Send + 'static,
        Q: FnOnce(Result<(B, usize), (B, glib::Error)>) + Send + 'static,
        C: IsA<Cancellable>,
    >(
        &self,
        buffer: B,
        io_priority: Priority,
        cancellable: Option<&C>,
        callback: Q,
    );

    /// Tries to write `count` bytes from `buffer` into the stream. Will block
    /// during the operation.
    ///
    /// This function is similar to [`OutputStreamExt::write()`][crate::prelude::OutputStreamExt::write()], except it tries to
    /// write as many bytes as requested, only stopping on an error.
    ///
    /// On a successful write of `count` bytes, [`true`] is returned, and `bytes_written`
    /// is set to `count`.
    ///
    /// If there is an error during the operation [`false`] is returned and `error`
    /// is set to indicate the error status.
    ///
    /// As a special exception to the normal conventions for functions that
    /// use [`glib::Error`][crate::glib::Error], if this function returns [`false`] (and sets `error`) then
    /// `bytes_written` will be set to the number of bytes that were
    /// successfully written before the error was encountered. This
    /// functionality is only available from C. If you need it from another
    /// language then you must write your own loop around
    /// [`OutputStreamExt::write()`][crate::prelude::OutputStreamExt::write()].
    /// ## `buffer`
    /// the buffer containing the data to write.
    /// ## `cancellable`
    /// optional [`Cancellable`][crate::Cancellable] object, [`None`] to ignore.
    ///
    /// # Returns
    ///
    /// [`true`] on success, [`false`] if there was an error
    ///
    /// ## `bytes_written`
    /// location to store the number of bytes that was
    ///  written to the stream
    #[doc(alias = "g_output_stream_write_all")]
    fn write_all<C: IsA<Cancellable>>(
        &self,
        buffer: &[u8],
        cancellable: Option<&C>,
    ) -> Result<(usize, Option<glib::Error>), glib::Error>;

    /// Request an asynchronous write of `count` bytes from `buffer` into
    /// the stream. When the operation is finished `callback` will be called.
    /// You can then call `g_output_stream_write_all_finish()` to get the result of the
    /// operation.
    ///
    /// This is the asynchronous version of [`OutputStreamExtManual::write_all()`][crate::prelude::OutputStreamExtManual::write_all()].
    ///
    /// Call `g_output_stream_write_all_finish()` to collect the result.
    ///
    /// Any outstanding I/O request with higher priority (lower numerical
    /// value) will be executed before an outstanding request with lower
    /// priority. Default priority is `G_PRIORITY_DEFAULT`.
    ///
    /// Note that no copy of `buffer` will be made, so it must stay valid
    /// until `callback` is called.
    /// ## `buffer`
    /// the buffer containing the data to write
    /// ## `io_priority`
    /// the io priority of the request
    /// ## `cancellable`
    /// optional [`Cancellable`][crate::Cancellable] object, [`None`] to ignore
    /// ## `callback`
    /// callback to call when the request is satisfied
    #[doc(alias = "g_output_stream_write_all_async")]
    fn write_all_async<
        B: AsRef<[u8]> + Send + 'static,
        Q: FnOnce(Result<(B, usize, Option<glib::Error>), (B, glib::Error)>) + Send + 'static,
        C: IsA<Cancellable>,
    >(
        &self,
        buffer: B,
        io_priority: Priority,
        cancellable: Option<&C>,
        callback: Q,
    );

    fn write_async_future<B: AsRef<[u8]> + Send + 'static>(
        &self,
        buffer: B,
        io_priority: Priority,
    ) -> Pin<Box<dyn std::future::Future<Output = Result<(B, usize), (B, glib::Error)>> + 'static>>;

    fn write_all_async_future<B: AsRef<[u8]> + Send + 'static>(
        &self,
        buffer: B,
        io_priority: Priority,
    ) -> Pin<
        Box<
            dyn std::future::Future<
                    Output = Result<(B, usize, Option<glib::Error>), (B, glib::Error)>,
                > + 'static,
        >,
    >;

    fn into_write(self) -> OutputStreamWrite<Self>
    where
        Self: IsA<OutputStream>,
    {
        OutputStreamWrite(self)
    }
}

impl<O: IsA<OutputStream>> OutputStreamExtManual for O {
    fn write_async<
        B: AsRef<[u8]> + Send + 'static,
        Q: FnOnce(Result<(B, usize), (B, glib::Error)>) + Send + 'static,
        C: IsA<Cancellable>,
    >(
        &self,
        buffer: B,
        io_priority: Priority,
        cancellable: Option<&C>,
        callback: Q,
    ) {
        let cancellable = cancellable.map(|c| c.as_ref());
        let gcancellable = cancellable.to_glib_none();
        let user_data: Box<Option<(Q, B)>> = Box::new(Some((callback, buffer)));
        // Need to do this after boxing as the contents pointer might change by moving into the box
        let (count, buffer_ptr) = {
            let buffer = &(*user_data).as_ref().unwrap().1;
            let slice = buffer.as_ref();
            (slice.len(), slice.as_ptr())
        };
        unsafe extern "C" fn write_async_trampoline<
            B: AsRef<[u8]> + Send + 'static,
            Q: FnOnce(Result<(B, usize), (B, glib::Error)>) + Send + 'static,
        >(
            _source_object: *mut glib::gobject_ffi::GObject,
            res: *mut ffi::GAsyncResult,
            user_data: glib::ffi::gpointer,
        ) {
            let mut user_data: Box<Option<(Q, B)>> = Box::from_raw(user_data as *mut _);
            let (callback, buffer) = user_data.take().unwrap();

            let mut error = ptr::null_mut();
            let ret = ffi::g_output_stream_write_finish(_source_object as *mut _, res, &mut error);
            let result = if error.is_null() {
                Ok((buffer, ret as usize))
            } else {
                Err((buffer, from_glib_full(error)))
            };
            callback(result);
        }
        let callback = write_async_trampoline::<B, Q>;
        unsafe {
            ffi::g_output_stream_write_async(
                self.as_ref().to_glib_none().0,
                mut_override(buffer_ptr),
                count,
                io_priority.into_glib(),
                gcancellable.0,
                Some(callback),
                Box::into_raw(user_data) as *mut _,
            );
        }
    }

    fn write_all<C: IsA<Cancellable>>(
        &self,
        buffer: &[u8],
        cancellable: Option<&C>,
    ) -> Result<(usize, Option<glib::Error>), glib::Error> {
        let cancellable = cancellable.map(|c| c.as_ref());
        let gcancellable = cancellable.to_glib_none();
        let count = buffer.len() as usize;
        unsafe {
            let mut bytes_written = mem::MaybeUninit::uninit();
            let mut error = ptr::null_mut();
            let _ = ffi::g_output_stream_write_all(
                self.as_ref().to_glib_none().0,
                buffer.to_glib_none().0,
                count,
                bytes_written.as_mut_ptr(),
                gcancellable.0,
                &mut error,
            );

            let bytes_written = bytes_written.assume_init();
            if error.is_null() {
                Ok((bytes_written, None))
            } else if bytes_written != 0 {
                Ok((bytes_written, Some(from_glib_full(error))))
            } else {
                Err(from_glib_full(error))
            }
        }
    }

    fn write_all_async<
        B: AsRef<[u8]> + Send + 'static,
        Q: FnOnce(Result<(B, usize, Option<glib::Error>), (B, glib::Error)>) + Send + 'static,
        C: IsA<Cancellable>,
    >(
        &self,
        buffer: B,
        io_priority: Priority,
        cancellable: Option<&C>,
        callback: Q,
    ) {
        let cancellable = cancellable.map(|c| c.as_ref());
        let gcancellable = cancellable.to_glib_none();
        let user_data: Box<Option<(Q, B)>> = Box::new(Some((callback, buffer)));
        // Need to do this after boxing as the contents pointer might change by moving into the box
        let (count, buffer_ptr) = {
            let buffer = &(*user_data).as_ref().unwrap().1;
            let slice = buffer.as_ref();
            (slice.len(), slice.as_ptr())
        };
        unsafe extern "C" fn write_all_async_trampoline<
            B: AsRef<[u8]> + Send + 'static,
            Q: FnOnce(Result<(B, usize, Option<glib::Error>), (B, glib::Error)>) + Send + 'static,
        >(
            _source_object: *mut glib::gobject_ffi::GObject,
            res: *mut ffi::GAsyncResult,
            user_data: glib::ffi::gpointer,
        ) {
            let mut user_data: Box<Option<(Q, B)>> = Box::from_raw(user_data as *mut _);
            let (callback, buffer) = user_data.take().unwrap();

            let mut error = ptr::null_mut();
            let mut bytes_written = mem::MaybeUninit::uninit();
            let _ = ffi::g_output_stream_write_all_finish(
                _source_object as *mut _,
                res,
                bytes_written.as_mut_ptr(),
                &mut error,
            );
            let bytes_written = bytes_written.assume_init();
            let result = if error.is_null() {
                Ok((buffer, bytes_written, None))
            } else if bytes_written != 0 {
                Ok((buffer, bytes_written, from_glib_full(error)))
            } else {
                Err((buffer, from_glib_full(error)))
            };
            callback(result);
        }
        let callback = write_all_async_trampoline::<B, Q>;
        unsafe {
            ffi::g_output_stream_write_all_async(
                self.as_ref().to_glib_none().0,
                mut_override(buffer_ptr),
                count,
                io_priority.into_glib(),
                gcancellable.0,
                Some(callback),
                Box::into_raw(user_data) as *mut _,
            );
        }
    }

    fn write_async_future<'a, B: AsRef<[u8]> + Send + 'static>(
        &self,
        buffer: B,
        io_priority: Priority,
    ) -> Pin<Box<dyn std::future::Future<Output = Result<(B, usize), (B, glib::Error)>> + 'static>>
    {
        Box::pin(crate::GioFuture::new(
            self,
            move |obj, cancellable, send| {
                obj.write_async(buffer, io_priority, Some(cancellable), move |res| {
                    send.resolve(res);
                });
            },
        ))
    }

    fn write_all_async_future<'a, B: AsRef<[u8]> + Send + 'static>(
        &self,
        buffer: B,
        io_priority: Priority,
    ) -> Pin<
        Box<
            dyn std::future::Future<
                    Output = Result<(B, usize, Option<glib::Error>), (B, glib::Error)>,
                > + 'static,
        >,
    > {
        Box::pin(crate::GioFuture::new(
            self,
            move |obj, cancellable, send| {
                obj.write_all_async(buffer, io_priority, Some(cancellable), move |res| {
                    send.resolve(res);
                });
            },
        ))
    }
}

#[derive(Debug)]
pub struct OutputStreamWrite<T: IsA<OutputStream>>(T);

impl<T: IsA<OutputStream>> OutputStreamWrite<T> {
    pub fn into_output_stream(self) -> T {
        self.0
    }

    pub fn output_stream(&self) -> &T {
        &self.0
    }
}

impl<T: IsA<OutputStream>> io::Write for OutputStreamWrite<T> {
    fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
        let result = self
            .0
            .as_ref()
            .write(buf, crate::NONE_CANCELLABLE)
            .map(|size| size as usize);
        to_std_io_result(result)
    }

    fn flush(&mut self) -> io::Result<()> {
        let gio_result = self.0.as_ref().flush(crate::NONE_CANCELLABLE);
        to_std_io_result(gio_result)
    }
}

impl<T: IsA<OutputStream> + IsA<Seekable>> io::Seek for OutputStreamWrite<T> {
    fn seek(&mut self, pos: io::SeekFrom) -> io::Result<u64> {
        let (pos, type_) = match pos {
            io::SeekFrom::Start(pos) => (pos as i64, glib::SeekType::Set),
            io::SeekFrom::End(pos) => (pos, glib::SeekType::End),
            io::SeekFrom::Current(pos) => (pos, glib::SeekType::Cur),
        };
        let seekable: &Seekable = self.0.as_ref();
        let gio_result = seekable
            .seek(pos, type_, crate::NONE_CANCELLABLE)
            .map(|_| seekable.tell() as u64);
        to_std_io_result(gio_result)
    }
}

#[cfg(test)]
mod tests {
    use crate::prelude::*;
    use crate::test_util::run_async;
    use crate::MemoryInputStream;
    use crate::MemoryOutputStream;
    use glib::Bytes;
    use std::io::Write;

    #[test]
    fn splice_async() {
        let ret = run_async(|tx, l| {
            let input = MemoryInputStream::new();
            let b = Bytes::from_owned(vec![1, 2, 3]);
            input.add_bytes(&b);

            let strm = MemoryOutputStream::new_resizable();
            strm.splice_async(
                &input,
                crate::OutputStreamSpliceFlags::CLOSE_SOURCE,
                glib::PRIORITY_DEFAULT_IDLE,
                crate::NONE_CANCELLABLE,
                move |ret| {
                    tx.send(ret).unwrap();
                    l.quit();
                },
            );
        });

        assert_eq!(ret.unwrap(), 3);
    }

    #[test]
    fn write_async() {
        let ret = run_async(|tx, l| {
            let strm = MemoryOutputStream::new_resizable();

            let buf = vec![1, 2, 3];
            strm.write_async(
                buf,
                glib::PRIORITY_DEFAULT_IDLE,
                crate::NONE_CANCELLABLE,
                move |ret| {
                    tx.send(ret).unwrap();
                    l.quit();
                },
            );
        });

        let (buf, size) = ret.unwrap();
        assert_eq!(buf, vec![1, 2, 3]);
        assert_eq!(size, 3);
    }

    #[test]
    fn write_all_async() {
        let ret = run_async(|tx, l| {
            let strm = MemoryOutputStream::new_resizable();

            let buf = vec![1, 2, 3];
            strm.write_all_async(
                buf,
                glib::PRIORITY_DEFAULT_IDLE,
                crate::NONE_CANCELLABLE,
                move |ret| {
                    tx.send(ret).unwrap();
                    l.quit();
                },
            );
        });

        let (buf, size, err) = ret.unwrap();
        assert_eq!(buf, vec![1, 2, 3]);
        assert_eq!(size, 3);
        assert!(err.is_none());
    }

    #[test]
    fn write_bytes_async() {
        let ret = run_async(|tx, l| {
            let strm = MemoryOutputStream::new_resizable();

            let b = Bytes::from_owned(vec![1, 2, 3]);
            strm.write_bytes_async(
                &b,
                glib::PRIORITY_DEFAULT_IDLE,
                crate::NONE_CANCELLABLE,
                move |ret| {
                    tx.send(ret).unwrap();
                    l.quit();
                },
            );
        });

        assert_eq!(ret.unwrap(), 3);
    }

    #[test]
    fn std_io_write() {
        let b = Bytes::from_owned(vec![1, 2, 3]);
        let mut write = MemoryOutputStream::new_resizable().into_write();

        let ret = write.write(&b);

        let stream = write.into_output_stream();
        stream.close(crate::NONE_CANCELLABLE).unwrap();
        assert_eq!(ret.unwrap(), 3);
        assert_eq!(stream.steal_as_bytes(), [1, 2, 3].as_ref());
    }

    #[test]
    fn into_output_stream() {
        let stream = MemoryOutputStream::new_resizable();
        let stream_clone = stream.clone();
        let stream = stream.into_write().into_output_stream();

        assert_eq!(stream, stream_clone);
    }
}