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
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
// Take a look at the license at the top of the repository in the LICENSE file.

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

use glib::{prelude::*, translate::*, Priority};

#[cfg(any(feature = "v2_60", feature = "dox"))]
use crate::OutputVector;
use crate::{error::to_std_io_result, prelude::*, Cancellable, OutputStream, Seekable};

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)>) + '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)>) + 'static,
        C: IsA<Cancellable>,
    >(
        &self,
        buffer: B,
        io_priority: Priority,
        cancellable: Option<&C>,
        callback: Q,
    );

    fn write_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_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,
        >,
    >;

    /// Tries to write the bytes contained in the `n_vectors` `vectors` into the
    /// stream. Will block during the operation.
    ///
    /// If `n_vectors` is 0 or the sum of all bytes in `vectors` is 0, returns 0 and
    /// does nothing.
    ///
    /// On success, the number of bytes written to the stream is returned.
    /// 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, or if there is not enough
    /// storage in the stream. All writes block until at least one byte
    /// is written or an error occurs; 0 is never returned (unless
    /// `n_vectors` is 0 or the sum of all bytes in `vectors` is 0).
    ///
    /// 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.
    ///
    /// Some implementations of [`OutputStreamExtManual::writev()`][crate::prelude::OutputStreamExtManual::writev()] may have limitations on the
    /// aggregate buffer size, and will return [`IOErrorEnum::InvalidArgument`][crate::IOErrorEnum::InvalidArgument] if these
    /// are exceeded. For example, when writing to a local file on UNIX platforms,
    /// the aggregate buffer size must not exceed `G_MAXSSIZE` bytes.
    /// ## `vectors`
    /// the buffer containing the `GOutputVectors` to write.
    /// ## `cancellable`
    /// optional cancellable object
    ///
    /// # Returns
    ///
    /// [`true`] on success, [`false`] if there was an error
    ///
    /// ## `bytes_written`
    /// location to store the number of bytes that were
    ///  written to the stream
    #[cfg(any(feature = "v2_60", feature = "dox"))]
    #[cfg_attr(feature = "dox", doc(cfg(feature = "v2_60")))]
    #[doc(alias = "g_output_stream_writev")]
    fn writev(
        &self,
        vectors: &[OutputVector],
        cancellable: Option<&impl IsA<Cancellable>>,
    ) -> Result<usize, glib::Error>;

    /// Request an asynchronous write of the bytes contained in `n_vectors` `vectors` into
    /// the stream. When the operation is finished `callback` will be called.
    /// You can then call `g_output_stream_writev_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.
    ///
    /// 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
    /// [`OutputStreamExtManual::writev()`][crate::prelude::OutputStreamExtManual::writev()].
    ///
    /// Note that no copy of `vectors` will be made, so it must stay valid
    /// until `callback` is called.
    /// ## `vectors`
    /// the buffer containing the `GOutputVectors` to write.
    /// ## `io_priority`
    /// the I/O priority of the request.
    /// ## `cancellable`
    /// optional [`Cancellable`][crate::Cancellable] object, [`None`] to ignore.
    /// ## `callback`
    /// callback to call when the request is satisfied
    #[cfg(any(feature = "v2_60", feature = "dox"))]
    #[cfg_attr(feature = "dox", doc(cfg(feature = "v2_60")))]
    #[doc(alias = "g_output_stream_writev_async")]
    fn writev_async<
        B: AsRef<[u8]> + Send + 'static,
        P: FnOnce(Result<(Vec<B>, usize), (Vec<B>, glib::Error)>) + 'static,
    >(
        &self,
        vectors: impl IntoIterator<Item = B> + 'static,
        io_priority: glib::Priority,
        cancellable: Option<&impl IsA<Cancellable>>,
        callback: P,
    );

    #[cfg(any(feature = "v2_60", feature = "dox"))]
    #[cfg_attr(feature = "dox", doc(cfg(feature = "v2_60")))]
    fn writev_future<B: AsRef<[u8]> + Send + 'static>(
        &self,
        vectors: impl IntoIterator<Item = B> + 'static,
        io_priority: glib::Priority,
    ) -> Pin<
        Box<
            dyn std::future::Future<Output = Result<(Vec<B>, usize), (Vec<B>, glib::Error)>>
                + 'static,
        >,
    >;

    /// Tries to write the bytes contained in the `n_vectors` `vectors` into the
    /// stream. Will block during the operation.
    ///
    /// This function is similar to [`OutputStreamExtManual::writev()`][crate::prelude::OutputStreamExtManual::writev()], except it tries to
    /// write as many bytes as requested, only stopping on an error.
    ///
    /// On a successful write of all `n_vectors` vectors, [`true`] is returned, and
    /// `bytes_written` is set to the sum of all the sizes of `vectors`.
    ///
    /// 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()].
    ///
    /// The content of the individual elements of `vectors` might be changed by this
    /// function.
    /// ## `vectors`
    /// the buffer containing the `GOutputVectors` 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 were
    ///  written to the stream
    #[cfg(any(feature = "v2_60", feature = "dox"))]
    #[cfg_attr(feature = "dox", doc(cfg(feature = "v2_60")))]
    #[doc(alias = "g_output_stream_writev_all")]
    fn writev_all(
        &self,
        vectors: &[OutputVector],
        cancellable: Option<&impl IsA<Cancellable>>,
    ) -> Result<(usize, Option<glib::Error>), glib::Error>;

    /// Request an asynchronous write of the bytes contained in the `n_vectors` `vectors` into
    /// the stream. When the operation is finished `callback` will be called.
    /// You can then call `g_output_stream_writev_all_finish()` to get the result of the
    /// operation.
    ///
    /// This is the asynchronous version of [`OutputStreamExtManual::writev_all()`][crate::prelude::OutputStreamExtManual::writev_all()].
    ///
    /// Call `g_output_stream_writev_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 `vectors` will be made, so it must stay valid
    /// until `callback` is called. The content of the individual elements
    /// of `vectors` might be changed by this function.
    /// ## `vectors`
    /// the buffer containing the `GOutputVectors` to write.
    /// ## `io_priority`
    /// the I/O priority of the request
    /// ## `cancellable`
    /// optional [`Cancellable`][crate::Cancellable] object, [`None`] to ignore
    /// ## `callback`
    /// callback to call when the request is satisfied
    #[cfg(any(feature = "v2_60", feature = "dox"))]
    #[cfg_attr(feature = "dox", doc(cfg(feature = "v2_60")))]
    #[doc(alias = "g_output_stream_writev_all_async")]
    fn writev_all_async<
        B: AsRef<[u8]> + Send + 'static,
        P: FnOnce(Result<(Vec<B>, usize, Option<glib::Error>), (Vec<B>, glib::Error)>) + 'static,
    >(
        &self,
        vectors: impl IntoIterator<Item = B> + 'static,
        io_priority: glib::Priority,
        cancellable: Option<&impl IsA<Cancellable>>,
        callback: P,
    );

    #[cfg(any(feature = "v2_60", feature = "dox"))]
    #[cfg_attr(feature = "dox", doc(cfg(feature = "v2_60")))]
    fn writev_all_future<B: AsRef<[u8]> + Send + 'static>(
        &self,
        vectors: impl IntoIterator<Item = B> + 'static,
        io_priority: glib::Priority,
    ) -> Pin<
        Box<
            dyn std::future::Future<
                    Output = Result<(Vec<B>, usize, Option<glib::Error>), (Vec<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)>) + '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 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 = &user_data.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)>) + '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_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();
        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)>) + '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 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 = &user_data.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)>) + '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_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_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_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);
                });
            },
        ))
    }

    #[cfg(any(feature = "v2_60", feature = "dox"))]
    #[cfg_attr(feature = "dox", doc(cfg(feature = "v2_60")))]
    fn writev(
        &self,
        vectors: &[OutputVector],
        cancellable: Option<&impl IsA<Cancellable>>,
    ) -> Result<usize, glib::Error> {
        unsafe {
            let mut error = ptr::null_mut();
            let mut bytes_written = mem::MaybeUninit::uninit();

            ffi::g_output_stream_writev(
                self.as_ref().to_glib_none().0,
                vectors.as_ptr() as *const _,
                vectors.len(),
                bytes_written.as_mut_ptr(),
                cancellable.map(|p| p.as_ref()).to_glib_none().0,
                &mut error,
            );
            if error.is_null() {
                Ok(bytes_written.assume_init())
            } else {
                Err(from_glib_full(error))
            }
        }
    }

    #[cfg(any(feature = "v2_60", feature = "dox"))]
    #[cfg_attr(feature = "dox", doc(cfg(feature = "v2_60")))]
    fn writev_async<
        B: AsRef<[u8]> + Send + 'static,
        P: FnOnce(Result<(Vec<B>, usize), (Vec<B>, glib::Error)>) + 'static,
    >(
        &self,
        vectors: impl IntoIterator<Item = B> + 'static,
        io_priority: glib::Priority,
        cancellable: Option<&impl IsA<Cancellable>>,
        callback: P,
    ) {
        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 buffers = vectors.into_iter().collect::<Vec<_>>();
        let vectors = buffers
            .iter()
            .map(|v| ffi::GOutputVector {
                buffer: v.as_ref().as_ptr() as *const _,
                size: v.as_ref().len(),
            })
            .collect::<Vec<_>>();
        let vectors_ptr = vectors.as_ptr();
        let num_vectors = vectors.len();
        let user_data: Box<(
            glib::thread_guard::ThreadGuard<P>,
            Vec<B>,
            Vec<ffi::GOutputVector>,
        )> = Box::new((
            glib::thread_guard::ThreadGuard::new(callback),
            buffers,
            vectors,
        ));

        unsafe extern "C" fn writev_async_trampoline<
            B: AsRef<[u8]> + Send + 'static,
            P: FnOnce(Result<(Vec<B>, usize), (Vec<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<P>,
                Vec<B>,
                Vec<ffi::GOutputVector>,
            )> = Box::from_raw(user_data as *mut _);
            let (callback, buffers, _) = *user_data;
            let callback = callback.into_inner();

            let mut error = ptr::null_mut();
            let mut bytes_written = mem::MaybeUninit::uninit();
            ffi::g_output_stream_writev_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((buffers, bytes_written))
            } else {
                Err((buffers, from_glib_full(error)))
            };
            callback(result);
        }
        let callback = writev_async_trampoline::<B, P>;
        unsafe {
            ffi::g_output_stream_writev_async(
                self.as_ref().to_glib_none().0,
                vectors_ptr,
                num_vectors,
                io_priority.into_glib(),
                gcancellable.0,
                Some(callback),
                Box::into_raw(user_data) as *mut _,
            );
        }
    }

    #[cfg(any(feature = "v2_60", feature = "dox"))]
    #[cfg_attr(feature = "dox", doc(cfg(feature = "v2_60")))]
    fn writev_future<B: AsRef<[u8]> + Send + 'static>(
        &self,
        vectors: impl IntoIterator<Item = B> + 'static,
        io_priority: glib::Priority,
    ) -> Pin<
        Box<
            dyn std::future::Future<Output = Result<(Vec<B>, usize), (Vec<B>, glib::Error)>>
                + 'static,
        >,
    > {
        Box::pin(crate::GioFuture::new(
            self,
            move |obj, cancellable, send| {
                obj.writev_async(vectors, io_priority, Some(cancellable), move |res| {
                    send.resolve(res);
                });
            },
        ))
    }

    #[cfg(any(feature = "v2_60", feature = "dox"))]
    #[cfg_attr(feature = "dox", doc(cfg(feature = "v2_60")))]
    fn writev_all(
        &self,
        vectors: &[OutputVector],
        cancellable: Option<&impl IsA<Cancellable>>,
    ) -> Result<(usize, Option<glib::Error>), glib::Error> {
        unsafe {
            let mut error = ptr::null_mut();
            let mut bytes_written = mem::MaybeUninit::uninit();

            ffi::g_output_stream_writev_all(
                self.as_ref().to_glib_none().0,
                mut_override(vectors.as_ptr() as *const _),
                vectors.len(),
                bytes_written.as_mut_ptr(),
                cancellable.map(|p| p.as_ref()).to_glib_none().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))
            }
        }
    }

    #[cfg(any(feature = "v2_60", feature = "dox"))]
    #[cfg_attr(feature = "dox", doc(cfg(feature = "v2_60")))]
    fn writev_all_async<
        B: AsRef<[u8]> + Send + 'static,
        P: FnOnce(Result<(Vec<B>, usize, Option<glib::Error>), (Vec<B>, glib::Error)>) + 'static,
    >(
        &self,
        vectors: impl IntoIterator<Item = B> + 'static,
        io_priority: glib::Priority,
        cancellable: Option<&impl IsA<Cancellable>>,
        callback: P,
    ) {
        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 buffers = vectors.into_iter().collect::<Vec<_>>();
        let vectors = buffers
            .iter()
            .map(|v| ffi::GOutputVector {
                buffer: v.as_ref().as_ptr() as *const _,
                size: v.as_ref().len(),
            })
            .collect::<Vec<_>>();
        let vectors_ptr = vectors.as_ptr();
        let num_vectors = vectors.len();
        let user_data: Box<(
            glib::thread_guard::ThreadGuard<P>,
            Vec<B>,
            Vec<ffi::GOutputVector>,
        )> = Box::new((
            glib::thread_guard::ThreadGuard::new(callback),
            buffers,
            vectors,
        ));

        unsafe extern "C" fn writev_all_async_trampoline<
            B: AsRef<[u8]> + Send + 'static,
            P: FnOnce(Result<(Vec<B>, usize, Option<glib::Error>), (Vec<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<P>,
                Vec<B>,
                Vec<ffi::GOutputVector>,
            )> = Box::from_raw(user_data as *mut _);
            let (callback, buffers, _) = *user_data;
            let callback = callback.into_inner();

            let mut error = ptr::null_mut();
            let mut bytes_written = mem::MaybeUninit::uninit();
            ffi::g_output_stream_writev_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((buffers, bytes_written, None))
            } else if bytes_written != 0 {
                Ok((buffers, bytes_written, from_glib_full(error)))
            } else {
                Err((buffers, from_glib_full(error)))
            };
            callback(result);
        }
        let callback = writev_all_async_trampoline::<B, P>;
        unsafe {
            ffi::g_output_stream_writev_all_async(
                self.as_ref().to_glib_none().0,
                mut_override(vectors_ptr),
                num_vectors,
                io_priority.into_glib(),
                gcancellable.0,
                Some(callback),
                Box::into_raw(user_data) as *mut _,
            );
        }
    }

    #[cfg(any(feature = "v2_60", feature = "dox"))]
    #[cfg_attr(feature = "dox", doc(cfg(feature = "v2_60")))]
    fn writev_all_future<B: AsRef<[u8]> + Send + 'static>(
        &self,
        vectors: impl IntoIterator<Item = B> + 'static,
        io_priority: glib::Priority,
    ) -> Pin<
        Box<
            dyn std::future::Future<
                    Output = Result<(Vec<B>, usize, Option<glib::Error>), (Vec<B>, glib::Error)>,
                > + 'static,
        >,
    > {
        Box::pin(crate::GioFuture::new(
            self,
            move |obj, cancellable, send| {
                obj.writev_all_async(vectors, 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::Cancellable::NONE)
            .map(|size| size as usize);
        to_std_io_result(result)
    }

    fn write_all(&mut self, buf: &[u8]) -> io::Result<()> {
        let result = self
            .0
            .as_ref()
            .write_all(buf, crate::Cancellable::NONE)
            .and_then(|(_, e)| e.map(Err).unwrap_or(Ok(())));
        to_std_io_result(result)
    }

    #[cfg(any(feature = "v2_60", feature = "dox"))]
    #[cfg_attr(feature = "dox", doc(cfg(feature = "v2_60")))]
    fn write_vectored(&mut self, bufs: &[io::IoSlice<'_>]) -> io::Result<usize> {
        let vectors = bufs
            .iter()
            .map(|v| OutputVector::new(v))
            .collect::<smallvec::SmallVec<[_; 2]>>();
        let result = self.0.as_ref().writev(&vectors, crate::Cancellable::NONE);
        to_std_io_result(result)
    }

    fn flush(&mut self) -> io::Result<()> {
        let gio_result = self.0.as_ref().flush(crate::Cancellable::NONE);
        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::Cancellable::NONE)
            .map(|_| seekable.tell() as u64);
        to_std_io_result(gio_result)
    }
}

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

    use glib::Bytes;

    #[cfg(feature = "v2_60")]
    use crate::OutputVector;
    use crate::{prelude::*, test_util::run_async, MemoryInputStream, MemoryOutputStream};

    #[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::Cancellable::NONE,
                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::Cancellable::NONE,
                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::Cancellable::NONE,
                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::Cancellable::NONE,
                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::Cancellable::NONE).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);
    }

    #[test]
    #[cfg(feature = "v2_60")]
    fn writev() {
        let stream = MemoryOutputStream::new_resizable();

        let ret = stream.writev(
            &[OutputVector::new(&[1, 2, 3]), OutputVector::new(&[4, 5, 6])],
            crate::Cancellable::NONE,
        );
        assert_eq!(ret.unwrap(), 6);
        stream.close(crate::Cancellable::NONE).unwrap();
        assert_eq!(stream.steal_as_bytes(), [1, 2, 3, 4, 5, 6].as_ref());
    }

    #[test]
    #[cfg(feature = "v2_60")]
    fn writev_async() {
        let ret = run_async(|tx, l| {
            let strm = MemoryOutputStream::new_resizable();

            let strm_clone = strm.clone();
            strm.writev_async(
                [vec![1, 2, 3], vec![4, 5, 6]],
                glib::PRIORITY_DEFAULT_IDLE,
                crate::Cancellable::NONE,
                move |ret| {
                    tx.send(ret).unwrap();
                    strm_clone.close(crate::Cancellable::NONE).unwrap();
                    assert_eq!(strm_clone.steal_as_bytes(), [1, 2, 3, 4, 5, 6].as_ref());
                    l.quit();
                },
            );
        });

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

    #[test]
    #[cfg(feature = "v2_60")]
    fn writev_all_async() {
        let ret = run_async(|tx, l| {
            let strm = MemoryOutputStream::new_resizable();

            let strm_clone = strm.clone();
            strm.writev_all_async(
                [vec![1, 2, 3], vec![4, 5, 6]],
                glib::PRIORITY_DEFAULT_IDLE,
                crate::Cancellable::NONE,
                move |ret| {
                    tx.send(ret).unwrap();
                    strm_clone.close(crate::Cancellable::NONE).unwrap();
                    assert_eq!(strm_clone.steal_as_bytes(), [1, 2, 3, 4, 5, 6].as_ref());
                    l.quit();
                },
            );
        });

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