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
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
// Take a look at the license at the top of the repository in the LICENSE file.

use std::{future::Future, io, mem, pin::Pin, ptr};

use futures_core::task::{Context, Poll};
use futures_io::{AsyncBufRead, AsyncRead};
use glib::{prelude::*, translate::*, Priority};

use crate::{error::to_std_io_result, prelude::*, Cancellable, InputStream, Seekable};

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

pub trait InputStreamExtManual: sealed::Sealed + IsA<InputStream> + Sized {
    /// Tries to read @count bytes from the stream into the buffer starting at
    /// @buffer. Will block during this read.
    ///
    /// If count is zero returns zero and does nothing. A value of @count
    /// larger than `G_MAXSSIZE` will cause a [`IOErrorEnum::InvalidArgument`][crate::IOErrorEnum::InvalidArgument] error.
    ///
    /// On success, the number of bytes read into the buffer is returned.
    /// It is not an error if this is not the same as the requested size, as it
    /// can happen e.g. near the end of a file. Zero is returned on end of file
    /// (or if @count is zero),  but never otherwise.
    ///
    /// The returned @buffer is not a nul-terminated string, it can contain nul bytes
    /// at any position, and this function doesn't nul-terminate the @buffer.
    ///
    /// 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. If an
    /// operation was partially finished when the operation was cancelled the
    /// partial result will be returned, without an error.
    ///
    /// On error -1 is returned and @error is set accordingly.
    /// ## `cancellable`
    /// optional #GCancellable object, [`None`] to ignore.
    ///
    /// # Returns
    ///
    /// Number of bytes read, or -1 on error, or 0 on end of file.
    ///
    /// ## `buffer`
    ///
    ///     a buffer to read data into (which should be at least count bytes long).
    #[doc(alias = "g_input_stream_read")]
    fn read<B: AsMut<[u8]>, C: IsA<Cancellable>>(
        &self,
        mut buffer: B,
        cancellable: Option<&C>,
    ) -> Result<usize, glib::Error> {
        let cancellable = cancellable.map(|c| c.as_ref());
        let gcancellable = cancellable.to_glib_none();
        let buffer = buffer.as_mut();
        let buffer_ptr = buffer.as_mut_ptr();
        let count = buffer.len();
        unsafe {
            let mut error = ptr::null_mut();
            let ret = ffi::g_input_stream_read(
                self.as_ref().to_glib_none().0,
                buffer_ptr,
                count,
                gcancellable.0,
                &mut error,
            );
            if error.is_null() {
                Ok(ret as usize)
            } else {
                Err(from_glib_full(error))
            }
        }
    }

    /// Tries to read @count bytes from the stream into the buffer starting at
    /// @buffer. Will block during this read.
    ///
    /// This function is similar to g_input_stream_read(), except it tries to
    /// read as many bytes as requested, only stopping on an error or end of stream.
    ///
    /// On a successful read of @count bytes, or if we reached the end of the
    /// stream,  [`true`] is returned, and @bytes_read is set to the number of bytes
    /// read into @buffer.
    ///
    /// 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 #GError, if this function returns [`false`] (and sets @error) then
    /// @bytes_read will be set to the number of bytes that were successfully
    /// read 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 g_input_stream_read().
    /// ## `cancellable`
    /// optional #GCancellable object, [`None`] to ignore.
    ///
    /// # Returns
    ///
    /// [`true`] on success, [`false`] if there was an error
    ///
    /// ## `buffer`
    ///
    ///     a buffer to read data into (which should be at least count bytes long).
    ///
    /// ## `bytes_read`
    /// location to store the number of bytes that was read from the stream
    #[doc(alias = "g_input_stream_read_all")]
    fn read_all<B: AsMut<[u8]>, C: IsA<Cancellable>>(
        &self,
        mut buffer: B,
        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 buffer = buffer.as_mut();
        let buffer_ptr = buffer.as_mut_ptr();
        let count = buffer.len();
        unsafe {
            let mut bytes_read = mem::MaybeUninit::uninit();
            let mut error = ptr::null_mut();
            let _ = ffi::g_input_stream_read_all(
                self.as_ref().to_glib_none().0,
                buffer_ptr,
                count,
                bytes_read.as_mut_ptr(),
                gcancellable.0,
                &mut error,
            );

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

    /// Request an asynchronous read of @count bytes from the stream into the
    /// buffer starting at @buffer.
    ///
    /// This is the asynchronous equivalent of g_input_stream_read_all().
    ///
    /// Call g_input_stream_read_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`.
    /// ## `io_priority`
    /// the [I/O priority][io-priority] of the request
    /// ## `cancellable`
    /// optional #GCancellable object, [`None`] to ignore
    /// ## `callback`
    /// a #GAsyncReadyCallback
    ///   to call when the request is satisfied
    ///
    /// # Returns
    ///
    ///
    /// ## `buffer`
    ///
    ///     a buffer to read data into (which should be at least count bytes long)
    #[doc(alias = "g_input_stream_read_all_async")]
    fn read_all_async<
        B: AsMut<[u8]> + Send + 'static,
        Q: FnOnce(Result<(B, usize, Option<glib::Error>), (B, glib::Error)>) + 'static,
        C: IsA<Cancellable>,
    >(
        &self,
        buffer: B,
        io_priority: Priority,
        cancellable: Option<&C>,
        callback: Q,
    ) {
        let main_context = glib::MainContext::ref_thread_default();
        let is_main_context_owner = main_context.is_owner();
        let has_acquired_main_context = (!is_main_context_owner)
            .then(|| main_context.acquire().ok())
            .flatten();
        assert!(
            is_main_context_owner || has_acquired_main_context.is_some(),
            "Async operations only allowed if the thread is owning the MainContext"
        );

        let cancellable = cancellable.map(|c| c.as_ref());
        let gcancellable = cancellable.to_glib_none();
        let mut user_data: Box<(glib::thread_guard::ThreadGuard<Q>, B)> =
            Box::new((glib::thread_guard::ThreadGuard::new(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 = &mut user_data.1;
            let slice = (*buffer).as_mut();
            (slice.len(), slice.as_mut_ptr())
        };
        unsafe extern "C" fn read_all_async_trampoline<
            B: AsMut<[u8]> + Send + 'static,
            Q: FnOnce(Result<(B, usize, Option<glib::Error>), (B, glib::Error)>) + 'static,
        >(
            _source_object: *mut glib::gobject_ffi::GObject,
            res: *mut ffi::GAsyncResult,
            user_data: glib::ffi::gpointer,
        ) {
            let user_data: Box<(glib::thread_guard::ThreadGuard<Q>, B)> =
                Box::from_raw(user_data as *mut _);
            let (callback, buffer) = *user_data;
            let callback = callback.into_inner();

            let mut error = ptr::null_mut();
            let mut bytes_read = mem::MaybeUninit::uninit();
            let _ = ffi::g_input_stream_read_all_finish(
                _source_object as *mut _,
                res,
                bytes_read.as_mut_ptr(),
                &mut error,
            );

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

            callback(result);
        }
        let callback = read_all_async_trampoline::<B, Q>;
        unsafe {
            ffi::g_input_stream_read_all_async(
                self.as_ref().to_glib_none().0,
                buffer_ptr,
                count,
                io_priority.into_glib(),
                gcancellable.0,
                Some(callback),
                Box::into_raw(user_data) as *mut _,
            );
        }
    }

    /// Request an asynchronous read of @count bytes from the stream into the buffer
    /// starting at @buffer. When the operation is finished @callback will be called.
    /// You can then call g_input_stream_read_finish() to get the result of the
    /// operation.
    ///
    /// During an async request no other sync and async calls are allowed on @self, 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 read into the buffer 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. near the end of a file, but generally we try to read
    /// as many bytes as requested. Zero is returned on end of file
    /// (or if @count is zero),  but never otherwise.
    ///
    /// 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.
    /// ## `io_priority`
    /// the [I/O priority][io-priority]
    /// of the request.
    /// ## `cancellable`
    /// optional #GCancellable object, [`None`] to ignore.
    /// ## `callback`
    /// a #GAsyncReadyCallback
    ///   to call when the request is satisfied
    ///
    /// # Returns
    ///
    ///
    /// ## `buffer`
    ///
    ///     a buffer to read data into (which should be at least count bytes long).
    #[doc(alias = "g_input_stream_read_async")]
    fn read_async<
        B: AsMut<[u8]> + Send + 'static,
        Q: FnOnce(Result<(B, usize), (B, glib::Error)>) + 'static,
        C: IsA<Cancellable>,
    >(
        &self,
        buffer: B,
        io_priority: Priority,
        cancellable: Option<&C>,
        callback: Q,
    ) {
        let main_context = glib::MainContext::ref_thread_default();
        let is_main_context_owner = main_context.is_owner();
        let has_acquired_main_context = (!is_main_context_owner)
            .then(|| main_context.acquire().ok())
            .flatten();
        assert!(
            is_main_context_owner || has_acquired_main_context.is_some(),
            "Async operations only allowed if the thread is owning the MainContext"
        );

        let cancellable = cancellable.map(|c| c.as_ref());
        let gcancellable = cancellable.to_glib_none();
        let mut user_data: Box<(glib::thread_guard::ThreadGuard<Q>, B)> =
            Box::new((glib::thread_guard::ThreadGuard::new(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 = &mut user_data.1;
            let slice = (*buffer).as_mut();
            (slice.len(), slice.as_mut_ptr())
        };
        unsafe extern "C" fn read_async_trampoline<
            B: AsMut<[u8]> + Send + 'static,
            Q: FnOnce(Result<(B, usize), (B, glib::Error)>) + 'static,
        >(
            _source_object: *mut glib::gobject_ffi::GObject,
            res: *mut ffi::GAsyncResult,
            user_data: glib::ffi::gpointer,
        ) {
            let user_data: Box<(glib::thread_guard::ThreadGuard<Q>, B)> =
                Box::from_raw(user_data as *mut _);
            let (callback, buffer) = *user_data;
            let callback = callback.into_inner();

            let mut error = ptr::null_mut();
            let ret = ffi::g_input_stream_read_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 = read_async_trampoline::<B, Q>;
        unsafe {
            ffi::g_input_stream_read_async(
                self.as_ref().to_glib_none().0,
                buffer_ptr,
                count,
                io_priority.into_glib(),
                gcancellable.0,
                Some(callback),
                Box::into_raw(user_data) as *mut _,
            );
        }
    }

    fn read_all_future<B: AsMut<[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.read_all_async(buffer, io_priority, Some(cancellable), move |res| {
                    send.resolve(res);
                });
            },
        ))
    }

    fn read_future<B: AsMut<[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.read_async(buffer, io_priority, Some(cancellable), move |res| {
                    send.resolve(res);
                });
            },
        ))
    }

    fn into_read(self) -> InputStreamRead<Self>
    where
        Self: IsA<InputStream>,
    {
        InputStreamRead(self)
    }

    fn into_async_buf_read(self, buffer_size: usize) -> InputStreamAsyncBufRead<Self>
    where
        Self: IsA<InputStream>,
    {
        InputStreamAsyncBufRead::new(self, buffer_size)
    }
}

impl<O: IsA<InputStream>> InputStreamExtManual for O {}

#[derive(Debug)]
pub struct InputStreamRead<T: IsA<InputStream>>(T);

impl<T: IsA<InputStream>> InputStreamRead<T> {
    pub fn into_input_stream(self) -> T {
        self.0
    }

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

impl<T: IsA<InputStream>> io::Read for InputStreamRead<T> {
    fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
        let gio_result = self.0.as_ref().read(buf, crate::Cancellable::NONE);
        to_std_io_result(gio_result)
    }
}

impl<T: IsA<InputStream> + IsA<Seekable>> io::Seek for InputStreamRead<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::Cancellable::NONE)
            .map(|_| seekable.tell() as u64);
        to_std_io_result(gio_result)
    }
}

enum State {
    Waiting {
        buffer: Vec<u8>,
    },
    Transitioning,
    Reading {
        pending: Pin<
            Box<
                dyn std::future::Future<Output = Result<(Vec<u8>, usize), (Vec<u8>, glib::Error)>>
                    + 'static,
            >,
        >,
    },
    HasData {
        buffer: Vec<u8>,
        valid: (usize, usize), // first index is inclusive, second is exclusive
    },
    Failed(crate::IOErrorEnum),
}

impl State {
    fn into_buffer(self) -> Vec<u8> {
        match self {
            State::Waiting { buffer } => buffer,
            _ => panic!("Invalid state"),
        }
    }

    #[doc(alias = "get_pending")]
    fn pending(
        &mut self,
    ) -> &mut Pin<
        Box<
            dyn std::future::Future<Output = Result<(Vec<u8>, usize), (Vec<u8>, glib::Error)>>
                + 'static,
        >,
    > {
        match self {
            State::Reading { ref mut pending } => pending,
            _ => panic!("Invalid state"),
        }
    }
}
pub struct InputStreamAsyncBufRead<T: IsA<InputStream>> {
    stream: T,
    state: State,
}

impl<T: IsA<InputStream>> InputStreamAsyncBufRead<T> {
    pub fn into_input_stream(self) -> T {
        self.stream
    }

    pub fn input_stream(&self) -> &T {
        &self.stream
    }

    fn new(stream: T, buffer_size: usize) -> Self {
        let buffer = vec![0; buffer_size];

        Self {
            stream,
            state: State::Waiting { buffer },
        }
    }
    fn set_reading(
        &mut self,
    ) -> &mut Pin<
        Box<
            dyn std::future::Future<Output = Result<(Vec<u8>, usize), (Vec<u8>, glib::Error)>>
                + 'static,
        >,
    > {
        match self.state {
            State::Waiting { .. } => {
                let waiting = mem::replace(&mut self.state, State::Transitioning);
                let buffer = waiting.into_buffer();
                let pending = self.input_stream().read_future(buffer, Priority::default());
                self.state = State::Reading { pending };
            }
            State::Reading { .. } => {}
            _ => panic!("Invalid state"),
        };

        self.state.pending()
    }

    #[doc(alias = "get_data")]
    fn data(&self) -> Poll<io::Result<&[u8]>> {
        if let State::HasData {
            ref buffer,
            valid: (i, j),
        } = self.state
        {
            return Poll::Ready(Ok(&buffer[i..j]));
        }
        panic!("Invalid state")
    }

    fn set_waiting(&mut self, buffer: Vec<u8>) {
        match self.state {
            State::Reading { .. } | State::Transitioning => self.state = State::Waiting { buffer },
            _ => panic!("Invalid state"),
        }
    }

    fn set_has_data(&mut self, buffer: Vec<u8>, valid: (usize, usize)) {
        match self.state {
            State::Reading { .. } | State::Transitioning { .. } => {
                self.state = State::HasData { buffer, valid }
            }
            _ => panic!("Invalid state"),
        }
    }

    fn poll_fill_buf(&mut self, cx: &mut Context) -> Poll<Result<&[u8], futures_io::Error>> {
        match self.state {
            State::Failed(kind) => Poll::Ready(Err(io::Error::new(
                io::ErrorKind::from(kind),
                BufReadError::Failed,
            ))),
            State::HasData { .. } => self.data(),
            State::Transitioning => panic!("Invalid state"),
            State::Waiting { .. } | State::Reading { .. } => {
                let pending = self.set_reading();
                match Pin::new(pending).poll(cx) {
                    Poll::Ready(Ok((buffer, res))) => {
                        if res == 0 {
                            self.set_waiting(buffer);
                            Poll::Ready(Ok(&[]))
                        } else {
                            self.set_has_data(buffer, (0, res));
                            self.data()
                        }
                    }
                    Poll::Ready(Err((_, err))) => {
                        let kind = err
                            .kind::<crate::IOErrorEnum>()
                            .unwrap_or(crate::IOErrorEnum::Failed);
                        self.state = State::Failed(kind);
                        Poll::Ready(Err(io::Error::new(io::ErrorKind::from(kind), err)))
                    }
                    Poll::Pending => Poll::Pending,
                }
            }
        }
    }

    fn consume(&mut self, amt: usize) {
        if amt == 0 {
            return;
        }

        if let State::HasData { .. } = self.state {
            let has_data = mem::replace(&mut self.state, State::Transitioning);
            if let State::HasData {
                buffer,
                valid: (i, j),
            } = has_data
            {
                let available = j - i;
                if amt > available {
                    panic!("Cannot consume {amt} bytes as only {available} are available",)
                }
                let remaining = available - amt;
                if remaining == 0 {
                    return self.set_waiting(buffer);
                } else {
                    return self.set_has_data(buffer, (i + amt, j));
                }
            }
        }

        panic!("Invalid state")
    }
}

#[derive(thiserror::Error, Debug)]
enum BufReadError {
    #[error("Previous read operation failed")]
    Failed,
}

impl<T: IsA<InputStream>> AsyncRead for InputStreamAsyncBufRead<T> {
    fn poll_read(
        self: Pin<&mut Self>,
        cx: &mut Context,
        out_buf: &mut [u8],
    ) -> Poll<io::Result<usize>> {
        let reader = self.get_mut();
        let poll = reader.poll_fill_buf(cx);

        let poll = poll.map_ok(|buffer| {
            let copied = buffer.len().min(out_buf.len());
            out_buf[..copied].copy_from_slice(&buffer[..copied]);
            copied
        });

        if let Poll::Ready(Ok(consumed)) = poll {
            reader.consume(consumed);
        }
        poll
    }
}

impl<T: IsA<InputStream>> AsyncBufRead for InputStreamAsyncBufRead<T> {
    fn poll_fill_buf(
        self: Pin<&mut Self>,
        cx: &mut Context,
    ) -> Poll<Result<&[u8], futures_io::Error>> {
        self.get_mut().poll_fill_buf(cx)
    }

    fn consume(self: Pin<&mut Self>, amt: usize) {
        self.get_mut().consume(amt);
    }
}

impl<T: IsA<InputStream>> Unpin for InputStreamAsyncBufRead<T> {}

#[cfg(test)]
mod tests {
    use std::io::Read;

    use glib::Bytes;

    use crate::{prelude::*, test_util::run_async, MemoryInputStream};

    #[test]
    fn read_all_async() {
        let ret = run_async(|tx, l| {
            let b = Bytes::from_owned(vec![1, 2, 3]);
            let strm = MemoryInputStream::from_bytes(&b);

            let buf = vec![0; 10];
            strm.read_all_async(
                buf,
                glib::Priority::DEFAULT_IDLE,
                crate::Cancellable::NONE,
                move |ret| {
                    tx.send(ret).unwrap();
                    l.quit();
                },
            );
        });

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

    #[test]
    fn read_all() {
        let b = Bytes::from_owned(vec![1, 2, 3]);
        let strm = MemoryInputStream::from_bytes(&b);
        let mut buf = vec![0; 10];

        let ret = strm.read_all(&mut buf, crate::Cancellable::NONE).unwrap();

        assert_eq!(ret.0, 3);
        assert!(ret.1.is_none());
        assert_eq!(buf[0], 1);
        assert_eq!(buf[1], 2);
        assert_eq!(buf[2], 3);
    }

    #[test]
    fn read() {
        let b = Bytes::from_owned(vec![1, 2, 3]);
        let strm = MemoryInputStream::from_bytes(&b);
        let mut buf = vec![0; 10];

        let ret = strm.read(&mut buf, crate::Cancellable::NONE);

        assert_eq!(ret.unwrap(), 3);
        assert_eq!(buf[0], 1);
        assert_eq!(buf[1], 2);
        assert_eq!(buf[2], 3);
    }

    #[test]
    fn read_async() {
        let ret = run_async(|tx, l| {
            let b = Bytes::from_owned(vec![1, 2, 3]);
            let strm = MemoryInputStream::from_bytes(&b);

            let buf = vec![0; 10];
            strm.read_async(
                buf,
                glib::Priority::DEFAULT_IDLE,
                crate::Cancellable::NONE,
                move |ret| {
                    tx.send(ret).unwrap();
                    l.quit();
                },
            );
        });

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

    #[test]
    fn read_bytes_async() {
        let ret = run_async(|tx, l| {
            let b = Bytes::from_owned(vec![1, 2, 3]);
            let strm = MemoryInputStream::from_bytes(&b);

            strm.read_bytes_async(
                10,
                glib::Priority::DEFAULT_IDLE,
                crate::Cancellable::NONE,
                move |ret| {
                    tx.send(ret).unwrap();
                    l.quit();
                },
            );
        });

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

    #[test]
    fn skip_async() {
        let ret = run_async(|tx, l| {
            let b = Bytes::from_owned(vec![1, 2, 3]);
            let strm = MemoryInputStream::from_bytes(&b);

            strm.skip_async(
                10,
                glib::Priority::DEFAULT_IDLE,
                crate::Cancellable::NONE,
                move |ret| {
                    tx.send(ret).unwrap();
                    l.quit();
                },
            );
        });

        let skipped = ret.unwrap();
        assert_eq!(skipped, 3);
    }

    #[test]
    fn std_io_read() {
        let b = Bytes::from_owned(vec![1, 2, 3]);
        let mut read = MemoryInputStream::from_bytes(&b).into_read();
        let mut buf = [0u8; 10];

        let ret = read.read(&mut buf);

        assert_eq!(ret.unwrap(), 3);
        assert_eq!(buf[0], 1);
        assert_eq!(buf[1], 2);
        assert_eq!(buf[2], 3);
    }

    #[test]
    fn into_input_stream() {
        let b = Bytes::from_owned(vec![1, 2, 3]);
        let stream = MemoryInputStream::from_bytes(&b);
        let stream_clone = stream.clone();
        let stream = stream.into_read().into_input_stream();

        assert_eq!(stream, stream_clone);
    }
}