compio_driver/poll/
op.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
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
#[cfg(aio)]
use std::ptr::NonNull;
use std::{
    ffi::CString,
    io,
    marker::PhantomPinned,
    os::fd::{FromRawFd, OwnedFd},
    pin::Pin,
    task::Poll,
};

use compio_buf::{
    BufResult, IntoInner, IoBuf, IoBufMut, IoSlice, IoSliceMut, IoVectoredBuf, IoVectoredBufMut,
};
#[cfg(not(gnulinux))]
use libc::open;
#[cfg(gnulinux)]
use libc::open64 as open;
#[cfg(not(any(target_os = "linux", target_os = "android", target_os = "hurd")))]
use libc::{pread, preadv, pwrite, pwritev};
#[cfg(any(target_os = "linux", target_os = "android", target_os = "hurd"))]
use libc::{pread64 as pread, preadv64 as preadv, pwrite64 as pwrite, pwritev64 as pwritev};
use socket2::SockAddr;

use super::{AsRawFd, Decision, OpCode, OpType, sockaddr_storage, socklen_t, syscall};
pub use crate::unix::op::*;
use crate::{SharedFd, op::*};

impl<
    D: std::marker::Send + 'static,
    F: (FnOnce() -> BufResult<usize, D>) + std::marker::Send + std::marker::Sync + 'static,
> OpCode for Asyncify<F, D>
{
    fn pre_submit(self: Pin<&mut Self>) -> io::Result<Decision> {
        Ok(Decision::Blocking)
    }

    fn operate(self: Pin<&mut Self>) -> Poll<io::Result<usize>> {
        // Safety: self won't be moved
        let this = unsafe { self.get_unchecked_mut() };
        let f = this
            .f
            .take()
            .expect("the operate method could only be called once");
        let BufResult(res, data) = f();
        this.data = Some(data);
        Poll::Ready(res)
    }
}

impl OpCode for OpenFile {
    fn pre_submit(self: Pin<&mut Self>) -> io::Result<Decision> {
        Ok(Decision::Blocking)
    }

    fn operate(self: Pin<&mut Self>) -> Poll<io::Result<usize>> {
        Poll::Ready(Ok(syscall!(open(
            self.path.as_ptr(),
            self.flags,
            self.mode as libc::c_int
        ))? as _))
    }
}

impl OpCode for CloseFile {
    fn pre_submit(self: Pin<&mut Self>) -> io::Result<Decision> {
        Ok(Decision::Blocking)
    }

    fn operate(self: Pin<&mut Self>) -> Poll<io::Result<usize>> {
        Poll::Ready(Ok(syscall!(libc::close(self.fd.as_raw_fd()))? as _))
    }
}

/// Get metadata of an opened file.
pub struct FileStat<S> {
    pub(crate) fd: SharedFd<S>,
    pub(crate) stat: libc::stat,
}

impl<S> FileStat<S> {
    /// Create [`FileStat`].
    pub fn new(fd: SharedFd<S>) -> Self {
        Self {
            fd,
            stat: unsafe { std::mem::zeroed() },
        }
    }
}

impl<S: AsRawFd> OpCode for FileStat<S> {
    fn pre_submit(self: Pin<&mut Self>) -> io::Result<Decision> {
        Ok(Decision::Blocking)
    }

    fn operate(mut self: Pin<&mut Self>) -> Poll<io::Result<usize>> {
        #[cfg(gnulinux)]
        {
            let mut s: libc::statx = unsafe { std::mem::zeroed() };
            static EMPTY_NAME: &[u8] = b"\0";
            syscall!(libc::statx(
                self.fd.as_raw_fd(),
                EMPTY_NAME.as_ptr().cast(),
                libc::AT_EMPTY_PATH,
                0,
                &mut s
            ))?;
            self.stat = statx_to_stat(s);
            Poll::Ready(Ok(0))
        }
        #[cfg(not(gnulinux))]
        {
            Poll::Ready(Ok(
                syscall!(libc::fstat(self.fd.as_raw_fd(), &mut self.stat))? as _,
            ))
        }
    }
}

impl<S> IntoInner for FileStat<S> {
    type Inner = libc::stat;

    fn into_inner(self) -> Self::Inner {
        self.stat
    }
}

/// Get metadata from path.
pub struct PathStat {
    pub(crate) path: CString,
    pub(crate) stat: libc::stat,
    pub(crate) follow_symlink: bool,
}

impl PathStat {
    /// Create [`PathStat`].
    pub fn new(path: CString, follow_symlink: bool) -> Self {
        Self {
            path,
            stat: unsafe { std::mem::zeroed() },
            follow_symlink,
        }
    }
}

impl OpCode for PathStat {
    fn pre_submit(self: Pin<&mut Self>) -> io::Result<Decision> {
        Ok(Decision::Blocking)
    }

    fn operate(mut self: Pin<&mut Self>) -> Poll<io::Result<usize>> {
        #[cfg(gnulinux)]
        {
            let mut flags = libc::AT_EMPTY_PATH;
            if !self.follow_symlink {
                flags |= libc::AT_SYMLINK_NOFOLLOW;
            }
            let mut s: libc::statx = unsafe { std::mem::zeroed() };
            syscall!(libc::statx(
                libc::AT_FDCWD,
                self.path.as_ptr(),
                flags,
                0,
                &mut s
            ))?;
            self.stat = statx_to_stat(s);
            Poll::Ready(Ok(0))
        }
        #[cfg(not(gnulinux))]
        {
            let f = if self.follow_symlink {
                libc::stat
            } else {
                libc::lstat
            };
            Poll::Ready(Ok(syscall!(f(self.path.as_ptr(), &mut self.stat))? as _))
        }
    }
}

impl IntoInner for PathStat {
    type Inner = libc::stat;

    fn into_inner(self) -> Self::Inner {
        self.stat
    }
}

impl<T: IoBufMut, S: AsRawFd> OpCode for ReadAt<T, S> {
    fn pre_submit(self: Pin<&mut Self>) -> io::Result<Decision> {
        #[cfg(aio)]
        {
            let this = unsafe { self.get_unchecked_mut() };
            let slice = this.buffer.as_mut_slice();

            this.aiocb.aio_fildes = this.fd.as_raw_fd();
            this.aiocb.aio_offset = this.offset as _;
            this.aiocb.aio_buf = slice.as_mut_ptr().cast();
            this.aiocb.aio_nbytes = slice.len();

            Ok(Decision::aio(&mut this.aiocb, libc::aio_read))
        }
        #[cfg(not(aio))]
        {
            Ok(Decision::Blocking)
        }
    }

    #[cfg(aio)]
    fn op_type(self: Pin<&mut Self>) -> Option<crate::OpType> {
        Some(OpType::Aio(NonNull::from(
            &mut unsafe { self.get_unchecked_mut() }.aiocb,
        )))
    }

    fn operate(self: Pin<&mut Self>) -> Poll<io::Result<usize>> {
        let fd = self.fd.as_raw_fd();
        let offset = self.offset;
        let slice = unsafe { self.get_unchecked_mut() }.buffer.as_mut_slice();
        syscall!(break pread(fd, slice.as_mut_ptr() as _, slice.len() as _, offset as _,))
    }
}

impl<T: IoVectoredBufMut, S: AsRawFd> OpCode for ReadVectoredAt<T, S> {
    fn pre_submit(self: Pin<&mut Self>) -> io::Result<Decision> {
        #[cfg(freebsd)]
        {
            let this = unsafe { self.get_unchecked_mut() };
            this.slices = unsafe { this.buffer.io_slices_mut() };

            this.aiocb.aio_fildes = this.fd.as_raw_fd();
            this.aiocb.aio_offset = this.offset as _;
            this.aiocb.aio_buf = this.slices.as_mut_ptr().cast();
            this.aiocb.aio_nbytes = this.slices.len();

            Ok(Decision::aio(&mut this.aiocb, libc::aio_readv))
        }
        #[cfg(not(freebsd))]
        {
            Ok(Decision::Blocking)
        }
    }

    #[cfg(freebsd)]
    fn op_type(self: Pin<&mut Self>) -> Option<crate::OpType> {
        Some(OpType::Aio(NonNull::from(
            &mut unsafe { self.get_unchecked_mut() }.aiocb,
        )))
    }

    fn operate(self: Pin<&mut Self>) -> Poll<io::Result<usize>> {
        let this = unsafe { self.get_unchecked_mut() };
        this.slices = unsafe { this.buffer.io_slices_mut() };
        syscall!(
            break preadv(
                this.fd.as_raw_fd(),
                this.slices.as_ptr() as _,
                this.slices.len() as _,
                this.offset as _,
            )
        )
    }
}

impl<T: IoBuf, S: AsRawFd> OpCode for WriteAt<T, S> {
    fn pre_submit(self: Pin<&mut Self>) -> io::Result<Decision> {
        #[cfg(aio)]
        {
            let this = unsafe { self.get_unchecked_mut() };
            let slice = this.buffer.as_slice();

            this.aiocb.aio_fildes = this.fd.as_raw_fd();
            this.aiocb.aio_offset = this.offset as _;
            this.aiocb.aio_buf = slice.as_ptr().cast_mut().cast();
            this.aiocb.aio_nbytes = slice.len();

            Ok(Decision::aio(&mut this.aiocb, libc::aio_write))
        }
        #[cfg(not(aio))]
        {
            Ok(Decision::Blocking)
        }
    }

    #[cfg(aio)]
    fn op_type(self: Pin<&mut Self>) -> Option<crate::OpType> {
        Some(OpType::Aio(NonNull::from(
            &mut unsafe { self.get_unchecked_mut() }.aiocb,
        )))
    }

    fn operate(self: Pin<&mut Self>) -> Poll<io::Result<usize>> {
        let slice = self.buffer.as_slice();
        syscall!(
            break pwrite(
                self.fd.as_raw_fd(),
                slice.as_ptr() as _,
                slice.len() as _,
                self.offset as _,
            )
        )
    }
}

impl<T: IoVectoredBuf, S: AsRawFd> OpCode for WriteVectoredAt<T, S> {
    fn pre_submit(self: Pin<&mut Self>) -> io::Result<Decision> {
        #[cfg(freebsd)]
        {
            let this = unsafe { self.get_unchecked_mut() };
            this.slices = unsafe { this.buffer.io_slices() };

            this.aiocb.aio_fildes = this.fd.as_raw_fd();
            this.aiocb.aio_offset = this.offset as _;
            this.aiocb.aio_buf = this.slices.as_ptr().cast_mut().cast();
            this.aiocb.aio_nbytes = this.slices.len();

            Ok(Decision::aio(&mut this.aiocb, libc::aio_writev))
        }
        #[cfg(not(freebsd))]
        {
            Ok(Decision::Blocking)
        }
    }

    #[cfg(freebsd)]
    fn op_type(self: Pin<&mut Self>) -> Option<crate::OpType> {
        Some(OpType::Aio(NonNull::from(
            &mut unsafe { self.get_unchecked_mut() }.aiocb,
        )))
    }

    fn operate(self: Pin<&mut Self>) -> Poll<io::Result<usize>> {
        let this = unsafe { self.get_unchecked_mut() };
        this.slices = unsafe { this.buffer.io_slices() };
        syscall!(
            break pwritev(
                this.fd.as_raw_fd(),
                this.slices.as_ptr() as _,
                this.slices.len() as _,
                this.offset as _,
            )
        )
    }
}

impl<S: AsRawFd> OpCode for Sync<S> {
    fn pre_submit(self: Pin<&mut Self>) -> io::Result<Decision> {
        #[cfg(aio)]
        {
            unsafe extern "C" fn aio_fsync(aiocbp: *mut libc::aiocb) -> i32 {
                libc::aio_fsync(libc::O_SYNC, aiocbp)
            }
            unsafe extern "C" fn aio_fdatasync(aiocbp: *mut libc::aiocb) -> i32 {
                libc::aio_fsync(libc::O_DSYNC, aiocbp)
            }

            let this = unsafe { self.get_unchecked_mut() };
            this.aiocb.aio_fildes = this.fd.as_raw_fd();

            let f = if this.datasync {
                aio_fdatasync
            } else {
                aio_fsync
            };

            Ok(Decision::aio(&mut this.aiocb, f))
        }
        #[cfg(not(aio))]
        {
            Ok(Decision::Blocking)
        }
    }

    #[cfg(aio)]
    fn op_type(self: Pin<&mut Self>) -> Option<crate::OpType> {
        Some(OpType::Aio(NonNull::from(
            &mut unsafe { self.get_unchecked_mut() }.aiocb,
        )))
    }

    fn operate(self: Pin<&mut Self>) -> Poll<io::Result<usize>> {
        #[cfg(datasync)]
        {
            Poll::Ready(Ok(syscall!(if self.datasync {
                libc::fdatasync(self.fd.as_raw_fd())
            } else {
                libc::fsync(self.fd.as_raw_fd())
            })? as _))
        }
        #[cfg(not(datasync))]
        {
            Poll::Ready(Ok(syscall!(libc::fsync(self.fd.as_raw_fd()))? as _))
        }
    }
}

impl OpCode for Unlink {
    fn pre_submit(self: Pin<&mut Self>) -> io::Result<Decision> {
        Ok(Decision::Blocking)
    }

    fn operate(self: Pin<&mut Self>) -> Poll<io::Result<usize>> {
        if self.dir {
            syscall!(libc::rmdir(self.path.as_ptr()))?;
        } else {
            syscall!(libc::unlink(self.path.as_ptr()))?;
        }
        Poll::Ready(Ok(0))
    }
}

impl OpCode for CreateDir {
    fn pre_submit(self: Pin<&mut Self>) -> io::Result<Decision> {
        Ok(Decision::Blocking)
    }

    fn operate(self: Pin<&mut Self>) -> Poll<io::Result<usize>> {
        syscall!(libc::mkdir(self.path.as_ptr(), self.mode))?;
        Poll::Ready(Ok(0))
    }
}

impl OpCode for Rename {
    fn pre_submit(self: Pin<&mut Self>) -> io::Result<Decision> {
        Ok(Decision::Blocking)
    }

    fn operate(self: Pin<&mut Self>) -> Poll<io::Result<usize>> {
        syscall!(libc::rename(self.old_path.as_ptr(), self.new_path.as_ptr()))?;
        Poll::Ready(Ok(0))
    }
}

impl OpCode for Symlink {
    fn pre_submit(self: Pin<&mut Self>) -> io::Result<Decision> {
        Ok(Decision::Blocking)
    }

    fn operate(self: Pin<&mut Self>) -> Poll<io::Result<usize>> {
        syscall!(libc::symlink(self.source.as_ptr(), self.target.as_ptr()))?;
        Poll::Ready(Ok(0))
    }
}

impl OpCode for HardLink {
    fn pre_submit(self: Pin<&mut Self>) -> io::Result<Decision> {
        Ok(Decision::Blocking)
    }

    fn operate(self: Pin<&mut Self>) -> Poll<io::Result<usize>> {
        syscall!(libc::link(self.source.as_ptr(), self.target.as_ptr()))?;
        Poll::Ready(Ok(0))
    }
}

impl OpCode for CreateSocket {
    fn pre_submit(self: Pin<&mut Self>) -> io::Result<Decision> {
        Ok(Decision::Blocking)
    }

    fn operate(self: Pin<&mut Self>) -> Poll<io::Result<usize>> {
        Poll::Ready(Ok(
            syscall!(libc::socket(self.domain, self.socket_type, self.protocol))? as _,
        ))
    }
}

impl<S: AsRawFd> OpCode for ShutdownSocket<S> {
    fn pre_submit(self: Pin<&mut Self>) -> io::Result<Decision> {
        Ok(Decision::Blocking)
    }

    fn operate(self: Pin<&mut Self>) -> Poll<io::Result<usize>> {
        Poll::Ready(Ok(
            syscall!(libc::shutdown(self.fd.as_raw_fd(), self.how()))? as _,
        ))
    }
}

impl OpCode for CloseSocket {
    fn pre_submit(self: Pin<&mut Self>) -> io::Result<Decision> {
        Ok(Decision::Blocking)
    }

    fn operate(self: Pin<&mut Self>) -> Poll<io::Result<usize>> {
        Poll::Ready(Ok(syscall!(libc::close(self.fd.as_raw_fd()))? as _))
    }
}

impl<S: AsRawFd> Accept<S> {
    unsafe fn call(self: Pin<&mut Self>) -> libc::c_int {
        let this = self.get_unchecked_mut();
        libc::accept(
            this.fd.as_raw_fd(),
            &mut this.buffer as *mut _ as *mut _,
            &mut this.addr_len,
        )
    }
}

impl<S: AsRawFd> OpCode for Accept<S> {
    fn pre_submit(mut self: Pin<&mut Self>) -> io::Result<Decision> {
        let fd = self.fd.as_raw_fd();
        syscall!(self.as_mut().call(), wait_readable(fd))
    }

    fn op_type(self: Pin<&mut Self>) -> Option<OpType> {
        Some(OpType::Fd(self.fd.as_raw_fd()))
    }

    fn operate(mut self: Pin<&mut Self>) -> Poll<io::Result<usize>> {
        let res = syscall!(break self.as_mut().call());
        if let Poll::Ready(Ok(fd)) = res {
            unsafe {
                self.get_unchecked_mut().accepted_fd = Some(OwnedFd::from_raw_fd(fd as _));
            }
        }
        res
    }
}

impl<S: AsRawFd> OpCode for Connect<S> {
    fn pre_submit(self: Pin<&mut Self>) -> io::Result<Decision> {
        syscall!(
            libc::connect(self.fd.as_raw_fd(), self.addr.as_ptr(), self.addr.len()),
            wait_writable(self.fd.as_raw_fd())
        )
    }

    fn op_type(self: Pin<&mut Self>) -> Option<OpType> {
        Some(OpType::Fd(self.fd.as_raw_fd()))
    }

    fn operate(self: Pin<&mut Self>) -> Poll<io::Result<usize>> {
        let mut err: libc::c_int = 0;
        let mut err_len = std::mem::size_of::<libc::c_int>() as libc::socklen_t;

        syscall!(libc::getsockopt(
            self.fd.as_raw_fd(),
            libc::SOL_SOCKET,
            libc::SO_ERROR,
            &mut err as *mut _ as *mut _,
            &mut err_len
        ))?;

        let res = if err == 0 {
            Ok(0)
        } else {
            Err(io::Error::from_raw_os_error(err))
        };
        Poll::Ready(res)
    }
}

impl<T: IoBufMut, S: AsRawFd> OpCode for Recv<T, S> {
    fn pre_submit(self: Pin<&mut Self>) -> io::Result<Decision> {
        Ok(Decision::wait_readable(self.fd.as_raw_fd()))
    }

    fn op_type(self: Pin<&mut Self>) -> Option<OpType> {
        Some(OpType::Fd(self.fd.as_raw_fd()))
    }

    fn operate(self: Pin<&mut Self>) -> Poll<io::Result<usize>> {
        let fd = self.fd.as_raw_fd();
        let slice = unsafe { self.get_unchecked_mut() }.buffer.as_mut_slice();
        syscall!(break libc::read(fd, slice.as_mut_ptr() as _, slice.len()))
    }
}

impl<T: IoVectoredBufMut, S: AsRawFd> OpCode for RecvVectored<T, S> {
    fn pre_submit(self: Pin<&mut Self>) -> io::Result<Decision> {
        Ok(Decision::wait_readable(self.fd.as_raw_fd()))
    }

    fn op_type(self: Pin<&mut Self>) -> Option<OpType> {
        Some(OpType::Fd(self.fd.as_raw_fd()))
    }

    fn operate(self: Pin<&mut Self>) -> Poll<io::Result<usize>> {
        let this = unsafe { self.get_unchecked_mut() };
        this.slices = unsafe { this.buffer.io_slices_mut() };
        syscall!(
            break libc::readv(
                this.fd.as_raw_fd(),
                this.slices.as_ptr() as _,
                this.slices.len() as _
            )
        )
    }
}

impl<T: IoBuf, S: AsRawFd> OpCode for Send<T, S> {
    fn pre_submit(self: Pin<&mut Self>) -> io::Result<Decision> {
        Ok(Decision::wait_writable(self.fd.as_raw_fd()))
    }

    fn op_type(self: Pin<&mut Self>) -> Option<OpType> {
        Some(OpType::Fd(self.fd.as_raw_fd()))
    }

    fn operate(self: Pin<&mut Self>) -> Poll<io::Result<usize>> {
        let slice = self.buffer.as_slice();
        syscall!(break libc::write(self.fd.as_raw_fd(), slice.as_ptr() as _, slice.len()))
    }
}

impl<T: IoVectoredBuf, S: AsRawFd> OpCode for SendVectored<T, S> {
    fn pre_submit(self: Pin<&mut Self>) -> io::Result<Decision> {
        Ok(Decision::wait_writable(self.fd.as_raw_fd()))
    }

    fn op_type(self: Pin<&mut Self>) -> Option<OpType> {
        Some(OpType::Fd(self.fd.as_raw_fd()))
    }

    fn operate(self: Pin<&mut Self>) -> Poll<io::Result<usize>> {
        let this = unsafe { self.get_unchecked_mut() };
        this.slices = unsafe { this.buffer.io_slices() };
        syscall!(
            break libc::writev(
                this.fd.as_raw_fd(),
                this.slices.as_ptr() as _,
                this.slices.len() as _
            )
        )
    }
}

/// Receive data and source address.
pub struct RecvFrom<T: IoBufMut, S> {
    pub(crate) fd: SharedFd<S>,
    pub(crate) buffer: T,
    pub(crate) addr: sockaddr_storage,
    pub(crate) addr_len: socklen_t,
    _p: PhantomPinned,
}

impl<T: IoBufMut, S> RecvFrom<T, S> {
    /// Create [`RecvFrom`].
    pub fn new(fd: SharedFd<S>, buffer: T) -> Self {
        Self {
            fd,
            buffer,
            addr: unsafe { std::mem::zeroed() },
            addr_len: std::mem::size_of::<sockaddr_storage>() as _,
            _p: PhantomPinned,
        }
    }
}

impl<T: IoBufMut, S: AsRawFd> RecvFrom<T, S> {
    unsafe fn call(self: Pin<&mut Self>) -> libc::ssize_t {
        let this = self.get_unchecked_mut();
        let fd = this.fd.as_raw_fd();
        let slice = this.buffer.as_mut_slice();
        libc::recvfrom(
            fd,
            slice.as_mut_ptr() as _,
            slice.len(),
            0,
            &mut this.addr as *mut _ as _,
            &mut this.addr_len,
        )
    }
}

impl<T: IoBufMut, S: AsRawFd> OpCode for RecvFrom<T, S> {
    fn pre_submit(mut self: Pin<&mut Self>) -> io::Result<Decision> {
        let fd = self.fd.as_raw_fd();
        syscall!(self.as_mut().call(), wait_readable(fd))
    }

    fn op_type(self: Pin<&mut Self>) -> Option<OpType> {
        Some(OpType::Fd(self.fd.as_raw_fd()))
    }

    fn operate(mut self: Pin<&mut Self>) -> Poll<io::Result<usize>> {
        syscall!(break self.as_mut().call())
    }
}

impl<T: IoBufMut, S> IntoInner for RecvFrom<T, S> {
    type Inner = (T, sockaddr_storage, socklen_t);

    fn into_inner(self) -> Self::Inner {
        (self.buffer, self.addr, self.addr_len)
    }
}

/// Receive data and source address into vectored buffer.
pub struct RecvFromVectored<T: IoVectoredBufMut, S> {
    pub(crate) fd: SharedFd<S>,
    pub(crate) buffer: T,
    pub(crate) slices: Vec<IoSliceMut>,
    pub(crate) addr: sockaddr_storage,
    pub(crate) msg: libc::msghdr,
    _p: PhantomPinned,
}

impl<T: IoVectoredBufMut, S> RecvFromVectored<T, S> {
    /// Create [`RecvFromVectored`].
    pub fn new(fd: SharedFd<S>, buffer: T) -> Self {
        Self {
            fd,
            buffer,
            slices: vec![],
            addr: unsafe { std::mem::zeroed() },
            msg: unsafe { std::mem::zeroed() },
            _p: PhantomPinned,
        }
    }
}

impl<T: IoVectoredBufMut, S: AsRawFd> RecvFromVectored<T, S> {
    fn set_msg(&mut self) {
        self.slices = unsafe { self.buffer.io_slices_mut() };
        self.msg = libc::msghdr {
            msg_name: &mut self.addr as *mut _ as _,
            msg_namelen: std::mem::size_of_val(&self.addr) as _,
            msg_iov: self.slices.as_mut_ptr() as _,
            msg_iovlen: self.slices.len() as _,
            msg_control: std::ptr::null_mut(),
            msg_controllen: 0,
            msg_flags: 0,
        };
    }

    unsafe fn call(&mut self) -> libc::ssize_t {
        libc::recvmsg(self.fd.as_raw_fd(), &mut self.msg, 0)
    }
}

impl<T: IoVectoredBufMut, S: AsRawFd> OpCode for RecvFromVectored<T, S> {
    fn pre_submit(self: Pin<&mut Self>) -> io::Result<Decision> {
        let this = unsafe { self.get_unchecked_mut() };
        this.set_msg();
        syscall!(this.call(), wait_readable(this.fd.as_raw_fd()))
    }

    fn op_type(self: Pin<&mut Self>) -> Option<OpType> {
        Some(OpType::Fd(self.fd.as_raw_fd()))
    }

    fn operate(self: Pin<&mut Self>) -> Poll<io::Result<usize>> {
        let this = unsafe { self.get_unchecked_mut() };
        syscall!(break this.call())
    }
}

impl<T: IoVectoredBufMut, S> IntoInner for RecvFromVectored<T, S> {
    type Inner = (T, sockaddr_storage, socklen_t);

    fn into_inner(self) -> Self::Inner {
        (self.buffer, self.addr, self.msg.msg_namelen)
    }
}

/// Send data to specified address.
pub struct SendTo<T: IoBuf, S> {
    pub(crate) fd: SharedFd<S>,
    pub(crate) buffer: T,
    pub(crate) addr: SockAddr,
    _p: PhantomPinned,
}

impl<T: IoBuf, S> SendTo<T, S> {
    /// Create [`SendTo`].
    pub fn new(fd: SharedFd<S>, buffer: T, addr: SockAddr) -> Self {
        Self {
            fd,
            buffer,
            addr,
            _p: PhantomPinned,
        }
    }
}

impl<T: IoBuf, S: AsRawFd> SendTo<T, S> {
    unsafe fn call(&self) -> libc::ssize_t {
        let slice = self.buffer.as_slice();
        libc::sendto(
            self.fd.as_raw_fd(),
            slice.as_ptr() as _,
            slice.len(),
            0,
            self.addr.as_ptr(),
            self.addr.len(),
        )
    }
}

impl<T: IoBuf, S: AsRawFd> OpCode for SendTo<T, S> {
    fn pre_submit(self: Pin<&mut Self>) -> io::Result<Decision> {
        syscall!(self.call(), wait_writable(self.fd.as_raw_fd()))
    }

    fn op_type(self: Pin<&mut Self>) -> Option<OpType> {
        Some(OpType::Fd(self.fd.as_raw_fd()))
    }

    fn operate(self: Pin<&mut Self>) -> Poll<io::Result<usize>> {
        syscall!(break self.call())
    }
}

impl<T: IoBuf, S> IntoInner for SendTo<T, S> {
    type Inner = T;

    fn into_inner(self) -> Self::Inner {
        self.buffer
    }
}

/// Send data to specified address from vectored buffer.
pub struct SendToVectored<T: IoVectoredBuf, S> {
    pub(crate) fd: SharedFd<S>,
    pub(crate) buffer: T,
    pub(crate) addr: SockAddr,
    pub(crate) slices: Vec<IoSlice>,
    pub(crate) msg: libc::msghdr,
    _p: PhantomPinned,
}

impl<T: IoVectoredBuf, S> SendToVectored<T, S> {
    /// Create [`SendToVectored`].
    pub fn new(fd: SharedFd<S>, buffer: T, addr: SockAddr) -> Self {
        Self {
            fd,
            buffer,
            addr,
            slices: vec![],
            msg: unsafe { std::mem::zeroed() },
            _p: PhantomPinned,
        }
    }
}

impl<T: IoVectoredBuf, S: AsRawFd> SendToVectored<T, S> {
    fn set_msg(&mut self) {
        self.slices = unsafe { self.buffer.io_slices() };
        self.msg = libc::msghdr {
            msg_name: &mut self.addr as *mut _ as _,
            msg_namelen: std::mem::size_of_val(&self.addr) as _,
            msg_iov: self.slices.as_mut_ptr() as _,
            msg_iovlen: self.slices.len() as _,
            msg_control: std::ptr::null_mut(),
            msg_controllen: 0,
            msg_flags: 0,
        };
    }

    unsafe fn call(&self) -> libc::ssize_t {
        libc::sendmsg(self.fd.as_raw_fd(), &self.msg, 0)
    }
}

impl<T: IoVectoredBuf, S: AsRawFd> OpCode for SendToVectored<T, S> {
    fn pre_submit(self: Pin<&mut Self>) -> io::Result<Decision> {
        let this = unsafe { self.get_unchecked_mut() };
        this.set_msg();
        syscall!(this.call(), wait_writable(this.fd.as_raw_fd()))
    }

    fn op_type(self: Pin<&mut Self>) -> Option<OpType> {
        Some(OpType::Fd(self.fd.as_raw_fd()))
    }

    fn operate(self: Pin<&mut Self>) -> Poll<io::Result<usize>> {
        syscall!(break self.call())
    }
}

impl<T: IoVectoredBuf, S> IntoInner for SendToVectored<T, S> {
    type Inner = T;

    fn into_inner(self) -> Self::Inner {
        self.buffer
    }
}

impl<T: IoVectoredBufMut, C: IoBufMut, S: AsRawFd> RecvMsg<T, C, S> {
    unsafe fn call(&mut self) -> libc::ssize_t {
        libc::recvmsg(self.fd.as_raw_fd(), &mut self.msg, 0)
    }
}

impl<T: IoVectoredBufMut, C: IoBufMut, S: AsRawFd> OpCode for RecvMsg<T, C, S> {
    fn pre_submit(self: Pin<&mut Self>) -> io::Result<Decision> {
        let this = unsafe { self.get_unchecked_mut() };
        unsafe { this.set_msg() };
        syscall!(this.call(), wait_readable(this.fd.as_raw_fd()))
    }

    fn op_type(self: Pin<&mut Self>) -> Option<OpType> {
        Some(OpType::Fd(self.fd.as_raw_fd()))
    }

    fn operate(self: Pin<&mut Self>) -> Poll<io::Result<usize>> {
        let this = unsafe { self.get_unchecked_mut() };
        syscall!(break this.call())
    }
}

impl<T: IoVectoredBuf, C: IoBuf, S: AsRawFd> SendMsg<T, C, S> {
    unsafe fn call(&self) -> libc::ssize_t {
        libc::sendmsg(self.fd.as_raw_fd(), &self.msg, 0)
    }
}

impl<T: IoVectoredBuf, C: IoBuf, S: AsRawFd> OpCode for SendMsg<T, C, S> {
    fn pre_submit(self: Pin<&mut Self>) -> io::Result<Decision> {
        let this = unsafe { self.get_unchecked_mut() };
        unsafe { this.set_msg() };
        syscall!(this.call(), wait_writable(this.fd.as_raw_fd()))
    }

    fn op_type(self: Pin<&mut Self>) -> Option<OpType> {
        Some(OpType::Fd(self.fd.as_raw_fd()))
    }

    fn operate(self: Pin<&mut Self>) -> Poll<io::Result<usize>> {
        syscall!(break self.call())
    }
}

impl<S: AsRawFd> OpCode for PollOnce<S> {
    fn pre_submit(self: Pin<&mut Self>) -> io::Result<Decision> {
        Ok(Decision::wait_for(self.fd.as_raw_fd(), self.interest))
    }

    fn op_type(self: Pin<&mut Self>) -> Option<OpType> {
        Some(OpType::Fd(self.fd.as_raw_fd()))
    }

    fn operate(self: Pin<&mut Self>) -> Poll<io::Result<usize>> {
        Poll::Ready(Ok(0))
    }
}