rasi 0.1.11

An implementation of Rust Asynchronous System Interface(RASI)
Documentation
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
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
//! Networking primitives for TCP/UDP communication.
//!
//! This module provides networking functionality for the Transmission Control and User Datagram Protocols, as well as types for IP and socket addresses.
//!
//! This module is an async version of std::net.
//!
use std::{
    fmt::{Debug, Display},
    io,
    net::{Ipv4Addr, Ipv6Addr, SocketAddr, ToSocketAddrs},
    sync::Arc,
    task::Poll,
};

use futures::{AsyncRead, AsyncWrite};
use rasi_syscall::{global_network, Handle, Network};

use crate::utils::cancelable_would_block;

/// A TCP socket server, listening for connections.
/// After creating a TcpListener by binding it to a socket address,
/// it listens for incoming TCP connections. These can be accepted
/// by awaiting elements from the async stream of incoming connections.
///
/// The socket will be closed when the value is dropped.
/// The Transmission Control Protocol is specified in IETF RFC 793.
/// This type is an async version of std::net::TcpListener.
pub struct TcpListener {
    /// syscall socket handle.
    sys_socket: rasi_syscall::Handle,

    /// a reference to syscall interface .
    syscall: &'static dyn Network,
}

impl TcpListener {
    /// Creates a new TcpListener with custom [syscall](rasi_syscall::Network) which will be bound to the specified address.
    /// The returned listener is ready for accepting connections.
    /// Binding with a port number of 0 will request that the OS assigns a port to this listener.
    /// The port allocated can be queried via the local_addr method.
    ///
    /// See [`bind`](TcpListener::bind) for more information.
    pub async fn bind_with<A: ToSocketAddrs>(
        laddrs: A,
        syscall: &'static dyn Network,
    ) -> io::Result<Self> {
        let laddrs = laddrs.to_socket_addrs()?.collect::<Vec<_>>();

        let sys_socket =
            cancelable_would_block(|cx| syscall.tcp_listener_bind(cx.waker().clone(), &laddrs))
                .await?;

        Ok(TcpListener {
            sys_socket,
            syscall,
        })
    }

    /// Creates a new TcpListener with global [syscall](rasi_syscall::Network) which will be bound to the specified address.
    /// The returned listener is ready for accepting connections.
    /// Binding with a port number of 0 will request that the OS assigns a port to this listener.
    /// The port allocated can be queried via the local_addr method.
    ///
    /// Use function [`bind`](TcpListener::bind_with) to specified custom [syscall](rasi_syscall::Network)
    ///
    /// # Examples
    /// Create a TCP listener bound to 127.0.0.1:0:
    ///
    /// ```no_run
    /// # fn main() -> std::io::Result<()> { futures::executor::block_on(async {
    /// #
    /// use rasi::net::TcpListener;
    ///
    /// let listener = TcpListener::bind("127.0.0.1:0").await?;
    /// #
    /// # Ok(()) }) }
    /// ```
    pub async fn bind<A: ToSocketAddrs>(laddrs: A) -> io::Result<Self> {
        Self::bind_with(laddrs, global_network()).await
    }

    /// Accepts a new incoming connection to this listener.
    ///
    /// When a connection is established, the corresponding stream and address will be returned.
    ///
    /// ## Examples
    ///
    /// ```no_run
    /// # fn main() -> std::io::Result<()> { futures::executor::block_on(async {
    /// #
    /// use rasi::net::TcpListener;
    ///
    /// let listener = TcpListener::bind("127.0.0.1:0").await?;
    /// let (stream, addr) = listener.accept().await?;
    /// #
    /// # Ok(()) }) }
    pub async fn accept(&self) -> io::Result<(TcpStream, SocketAddr)> {
        let (sys_socket, raddr) = cancelable_would_block(|cx| {
            self.syscall
                .tcp_listener_accept(cx.waker().clone(), &self.sys_socket)
        })
        .await?;

        Ok((TcpStream::new(sys_socket, self.syscall), raddr))
    }

    /// Returns the local address that this listener is bound to.
    ///
    /// This can be useful, for example, to identify when binding to port 0 which port was assigned
    /// by the OS.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # fn main() -> std::io::Result<()> { futures::executor::block_on(async {
    /// #
    /// use rasi::net::TcpListener;
    ///
    /// let listener = TcpListener::bind("127.0.0.1:8080").await?;
    /// let addr = listener.local_addr()?;
    /// #
    /// # Ok(()) }) }
    /// ```
    pub fn local_addr(&self) -> io::Result<SocketAddr> {
        self.syscall.tcp_listener_local_addr(&self.sys_socket)
    }

    /// Gets the value of the IP_TTL option for this socket.
    /// For more information about this option, see [`set_ttl`](Self::set_ttl).
    pub fn ttl(&self) -> io::Result<u32> {
        self.syscall.tcp_listener_ttl(&self.sys_socket)
    }

    /// Sets the value for the IP_TTL option on this socket.
    /// This value sets the time-to-live field that is used in every packet sent from this socket.
    pub fn set_ttl(&self, ttl: u32) -> io::Result<()> {
        self.syscall.tcp_listener_set_ttl(&self.sys_socket, ttl)
    }
}

/// A TCP stream between a local and a remote socket.
///
/// A `TcpStream` can either be created by connecting to an endpoint, via the [`connect`] method,
/// or by [accepting] a connection from a [listener].  It can be read or written to using the
/// [`AsyncRead`], [`AsyncWrite`], and related extension traits in [`futures::io`].
///
/// The connection will be closed when the value is dropped. The reading and writing portions of
/// the connection can also be shut down individually with the [`shutdown`] method.
///
/// This type is an async version of [`std::net::TcpStream`].
///
/// [`connect`]: struct.TcpStream.html#method.connect
/// [accepting]: struct.TcpListener.html#method.accept
/// [listener]: struct.TcpListener.html
/// [`AsyncRead`]: https://docs.rs/futures/0.3/futures/io/trait.AsyncRead.html
/// [`AsyncWrite`]: https://docs.rs/futures/0.3/futures/io/trait.AsyncWrite.html
/// [`futures::io`]: https://docs.rs/futures/0.3/futures/io/index.html
/// [`shutdown`]: struct.TcpStream.html#method.shutdown
/// [`std::net::TcpStream`]: https://doc.rust-lang.org/std/net/struct.TcpStream.html
///
/// ## Examples
///
/// ```no_run
/// # fn main() -> std::io::Result<()> { futures::executor::block_on(async {
/// #
/// use rasi::net::TcpStream;
/// use rasi::prelude::*;
///
/// let mut stream = TcpStream::connect("127.0.0.1:8080").await?;
/// stream.write_all(b"hello world").await?;
///
/// let mut buf = vec![0u8; 1024];
/// let n = stream.read(&mut buf).await?;
/// #
/// # Ok(()) }) }
/// ```
pub struct TcpStream {
    /// syscall socket handle.
    sys_socket: rasi_syscall::Handle,

    /// a reference to syscall interface .
    syscall: &'static dyn Network,

    /// The cancel handle reference to latest pending write ops.
    write_cancel_handle: Option<Handle>,

    /// The cancel handle reference to latest pending read ops.
    read_cancel_handle: Option<Handle>,
}

impl Debug for TcpStream {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("TcpStream")
            .field("socket", &self.sys_socket)
            .field(
                "syscall",
                &format!("{:?}", self.syscall as *const dyn Network),
            )
            .finish()
    }
}

impl TcpStream {
    fn new(sys_socket: Handle, syscall: &'static dyn Network) -> Self {
        Self {
            sys_socket,
            syscall,
            write_cancel_handle: None,
            read_cancel_handle: None,
        }
    }
    /// Using custom [`syscall`](rasi_syscall::Network) interface to create a new TCP
    /// stream connected to the specified address.
    ///
    /// see [`connect`](TcpStream::connect) for more information.
    pub async fn connect_with<A: ToSocketAddrs>(
        raddrs: A,
        syscall: &'static dyn Network,
    ) -> io::Result<Self> {
        let raddrs = raddrs.to_socket_addrs()?.collect::<Vec<_>>();

        let sys_socket =
            cancelable_would_block(|cx| syscall.tcp_stream_connect(cx.waker().clone(), &raddrs))
                .await?;

        Ok(Self::new(sys_socket, syscall))
    }

    /// Using global [`syscall`](rasi_syscall::Network) interface to create a new TCP
    /// stream connected to the specified address.
    ///
    /// This method will create a new TCP socket and attempt to connect it to the `addr`
    /// provided. The [returned future] will be resolved once the stream has successfully
    /// connected, or it will return an error if one occurs.
    ///
    /// [returned future]: struct.Connect.html
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # fn main() -> std::io::Result<()> { futures::executor::block_on(async {
    /// #
    /// use rasi::net::TcpStream;
    ///
    /// let stream = TcpStream::connect("127.0.0.1:0").await?;
    /// #
    /// # Ok(()) }) }
    /// ```
    pub async fn connect<A: ToSocketAddrs>(raddrs: A) -> io::Result<Self> {
        Self::connect_with(raddrs, global_network()).await
    }

    /// Returns the local address that this stream is connected to.
    ///
    /// ## Examples
    ///
    /// ```no_run
    /// # fn main() -> std::io::Result<()> { futures::executor::block_on(async {
    /// #
    /// use rasi::net::TcpStream;
    ///
    /// let stream = TcpStream::connect("127.0.0.1:8080").await?;
    /// let addr = stream.local_addr()?;
    /// #
    /// # Ok(()) }) }
    /// ```
    pub fn local_addr(&self) -> io::Result<SocketAddr> {
        self.syscall.tcp_stream_local_addr(&self.sys_socket)
    }

    /// Returns the remote address that this stream is connected to.
    ///
    /// ## Examples
    ///
    /// ```no_run
    /// # fn main() -> std::io::Result<()> { futures::executor::block_on(async {
    /// #
    /// use rasi::net::TcpStream;
    ///
    /// let stream = TcpStream::connect("127.0.0.1:8080").await?;
    /// let peer = stream.peer_addr()?;
    /// #
    /// # Ok(()) }) }
    /// ```
    pub fn peer_addr(&self) -> io::Result<SocketAddr> {
        self.syscall.tcp_stream_remote_addr(&self.sys_socket)
    }

    /// Gets the value of the `IP_TTL` option for this socket.
    ///
    /// For more information about this option, see [`set_ttl`].
    ///
    /// [`set_ttl`]: #method.set_ttl
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # fn main() -> std::io::Result<()> { futures::executor::block_on(async {
    /// #
    /// use rasi::net::TcpStream;
    ///
    /// let stream = TcpStream::connect("127.0.0.1:8080").await?;
    ///
    /// stream.set_ttl(100)?;
    /// assert_eq!(stream.ttl()?, 100);
    /// #
    /// # Ok(()) }) }
    /// ```
    pub fn ttl(&self) -> io::Result<u32> {
        self.syscall.tcp_stream_ttl(&self.sys_socket)
    }

    /// Sets the value for the `IP_TTL` option on this socket.
    ///
    /// This value sets the time-to-live field that is used in every packet sent
    /// from this socket.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # fn main() -> std::io::Result<()> { futures::executor::block_on(async {
    /// #
    /// use rasi::net::TcpStream;
    ///
    /// let stream = TcpStream::connect("127.0.0.1:8080").await?;
    ///
    /// stream.set_ttl(100)?;
    /// assert_eq!(stream.ttl()?, 100);
    /// #
    /// # Ok(()) }) }
    /// ```
    pub fn set_ttl(&self, ttl: u32) -> io::Result<()> {
        self.syscall.tcp_stream_set_ttl(&self.sys_socket, ttl)
    }

    /// Gets the value of the `TCP_NODELAY` option on this socket.
    ///
    /// For more information about this option, see [`set_nodelay`].
    ///
    /// [`set_nodelay`]: #method.set_nodelay
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # fn main() -> std::io::Result<()> { futures::executor::block_on(async {
    /// #
    /// use rasi::net::TcpStream;
    ///
    /// let stream = TcpStream::connect("127.0.0.1:8080").await?;
    ///
    /// stream.set_nodelay(true)?;
    /// assert_eq!(stream.nodelay()?, true);
    /// #
    /// # Ok(()) }) }
    /// ```
    pub fn nodelay(&self) -> io::Result<bool> {
        self.syscall.tcp_stream_nodelay(&self.sys_socket)
    }

    /// Sets the value of the `TCP_NODELAY` option on this socket.
    ///
    /// If set, this option disables the Nagle algorithm. This means that
    /// segments are always sent as soon as possible, even if there is only a
    /// small amount of data. When not set, data is buffered until there is a
    /// sufficient amount to send out, thereby avoiding the frequent sending of
    /// small packets.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # fn main() -> std::io::Result<()> { futures::executor::block_on(async {
    /// #
    /// use rasi::net::TcpStream;
    ///
    /// let stream = TcpStream::connect("127.0.0.1:8080").await?;
    ///
    /// stream.set_nodelay(true)?;
    /// assert_eq!(stream.nodelay()?, true);
    /// #
    /// # Ok(()) }) }
    /// ```
    pub fn set_nodelay(&self, nodelay: bool) -> io::Result<()> {
        self.syscall
            .tcp_stream_set_nodelay(&self.sys_socket, nodelay)
    }

    /// Shuts down the read, write, or both halves of this connection.
    ///
    /// This method will cause all pending and future I/O on the specified portions to return
    /// immediately with an appropriate value (see the documentation of [`Shutdown`]).
    ///
    /// [`Shutdown`]: https://doc.rust-lang.org/std/net/enum.Shutdown.html
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # fn main() -> std::io::Result<()> { futures::executor::block_on(async {
    /// #
    /// use std::net::Shutdown;
    ///
    /// use rasi::net::TcpStream;
    ///
    /// let stream = TcpStream::connect("127.0.0.1:8080").await?;
    /// stream.shutdown(Shutdown::Both)?;
    /// #
    /// # Ok(()) }) }
    /// ```
    pub fn shutdown(&self, how: std::net::Shutdown) -> std::io::Result<()> {
        self.syscall.tcp_stream_shutdown(&self.sys_socket, how)
    }

    /// Helper method for splitting `TcpStream` object into two halves.
    ///
    /// The two halves returned implement the AsyncRead and AsyncWrite traits, respectively.
    pub fn split(self) -> (TcpStreamRead, TcpStreamWrite) {
        let sys_socket = Arc::new(self.sys_socket);
        (
            TcpStreamRead {
                sys_socket: sys_socket.clone(),
                syscall: self.syscall,
                read_cancel_handle: self.read_cancel_handle,
            },
            TcpStreamWrite {
                sys_socket,
                syscall: self.syscall,
                write_cancel_handle: self.write_cancel_handle,
            },
        )
    }
}

impl AsyncRead for TcpStream {
    fn poll_read(
        mut self: std::pin::Pin<&mut Self>,
        cx: &mut std::task::Context<'_>,
        buf: &mut [u8],
    ) -> std::task::Poll<io::Result<usize>> {
        match self
            .syscall
            .tcp_stream_read(cx.waker().clone(), &self.sys_socket, buf)
        {
            rasi_syscall::CancelablePoll::Ready(r) => Poll::Ready(r),
            rasi_syscall::CancelablePoll::Pending(read_cancel_handle) => {
                self.read_cancel_handle = Some(read_cancel_handle);
                Poll::Pending
            }
        }
    }
}

impl AsyncWrite for TcpStream {
    fn poll_write(
        mut self: std::pin::Pin<&mut Self>,
        cx: &mut std::task::Context<'_>,
        buf: &[u8],
    ) -> Poll<io::Result<usize>> {
        match self
            .syscall
            .tcp_stream_write(cx.waker().clone(), &self.sys_socket, buf)
        {
            rasi_syscall::CancelablePoll::Ready(r) => Poll::Ready(r),
            rasi_syscall::CancelablePoll::Pending(write_cancel_handle) => {
                self.write_cancel_handle = Some(write_cancel_handle);
                Poll::Pending
            }
        }
    }

    fn poll_flush(
        self: std::pin::Pin<&mut Self>,
        _cx: &mut std::task::Context<'_>,
    ) -> Poll<io::Result<()>> {
        Poll::Ready(Ok(()))
    }

    fn poll_close(
        self: std::pin::Pin<&mut Self>,
        _cx: &mut std::task::Context<'_>,
    ) -> Poll<io::Result<()>> {
        self.shutdown(std::net::Shutdown::Both)?;
        Poll::Ready(Ok(()))
    }
}

/// The read half of [`TcpStream`] created by [`split`](TcpStream::split) function.
///
/// # Examples
///
/// ```no_run
/// # fn main() -> std::io::Result<()> { futures::executor::block_on(async {
/// #
/// use rasi::net::TcpStream;
///
/// let stream = TcpStream::connect("127.0.0.1:8080").await?;
/// let (read,write) = stream.split();
/// #
/// # Ok(()) }) }
/// ```
pub struct TcpStreamRead {
    /// syscall socket handle.
    sys_socket: Arc<rasi_syscall::Handle>,

    /// a reference to syscall interface .
    syscall: &'static dyn Network,

    /// The cancel handle reference to latest pending read ops.
    read_cancel_handle: Option<Handle>,
}

impl AsyncRead for TcpStreamRead {
    fn poll_read(
        mut self: std::pin::Pin<&mut Self>,
        cx: &mut std::task::Context<'_>,
        buf: &mut [u8],
    ) -> std::task::Poll<io::Result<usize>> {
        match self
            .syscall
            .tcp_stream_read(cx.waker().clone(), &self.sys_socket, buf)
        {
            rasi_syscall::CancelablePoll::Ready(r) => Poll::Ready(r),
            rasi_syscall::CancelablePoll::Pending(read_cancel_handle) => {
                self.read_cancel_handle = Some(read_cancel_handle);
                Poll::Pending
            }
        }
    }
}

/// The write half of [`TcpStream`] created by [`split`](TcpStream::split) function.
///
/// # Examples
///
/// ```no_run
/// # fn main() -> std::io::Result<()> { futures::executor::block_on(async {
/// #
/// use rasi::net::TcpStream;
///
/// let stream = TcpStream::connect("127.0.0.1:8080").await?;
/// let (read,write) = stream.split();
/// #
/// # Ok(()) }) }
/// ```
pub struct TcpStreamWrite {
    /// syscall socket handle.
    sys_socket: Arc<rasi_syscall::Handle>,

    /// a reference to syscall interface .
    syscall: &'static dyn Network,

    /// The cancel handle reference to latest pending write ops.
    write_cancel_handle: Option<Handle>,
}

impl AsyncWrite for TcpStreamWrite {
    fn poll_write(
        mut self: std::pin::Pin<&mut Self>,
        cx: &mut std::task::Context<'_>,
        buf: &[u8],
    ) -> Poll<io::Result<usize>> {
        match self
            .syscall
            .tcp_stream_write(cx.waker().clone(), &self.sys_socket, buf)
        {
            rasi_syscall::CancelablePoll::Ready(r) => Poll::Ready(r),
            rasi_syscall::CancelablePoll::Pending(write_cancel_handle) => {
                self.write_cancel_handle = Some(write_cancel_handle);
                Poll::Pending
            }
        }
    }

    fn poll_flush(
        self: std::pin::Pin<&mut Self>,
        _cx: &mut std::task::Context<'_>,
    ) -> Poll<io::Result<()>> {
        Poll::Ready(Ok(()))
    }

    fn poll_close(
        self: std::pin::Pin<&mut Self>,
        _cx: &mut std::task::Context<'_>,
    ) -> Poll<io::Result<()>> {
        self.syscall
            .tcp_stream_shutdown(&self.sys_socket, std::net::Shutdown::Both)?;

        Poll::Ready(Ok(()))
    }
}

/// A UDP socket.
///
/// After creating a `UdpSocket` by [`bind`]ing it to a socket address, data can be [sent to] and
/// [received from] any other socket address.
///
/// As stated in the User Datagram Protocol's specification in [IETF RFC 768], UDP is an unordered,
/// unreliable protocol. Refer to [`TcpListener`] and [`TcpStream`] for async TCP primitives.
///
/// This type is an async version of [`std::net::UdpSocket`].
///
/// [`bind`]: #method.bind
/// [received from]: #method.recv_from
/// [sent to]: #method.send_to
/// [`TcpListener`]: struct.TcpListener.html
/// [`TcpStream`]: struct.TcpStream.html
/// [`std::net`]: https://doc.rust-lang.org/std/net/index.html
/// [IETF RFC 768]: https://tools.ietf.org/html/rfc768
/// [`std::net::UdpSocket`]: https://doc.rust-lang.org/std/net/struct.UdpSocket.html
///
/// ## Examples
///
/// ```no_run
/// # fn main() -> std::io::Result<()> { futures::executor::block_on(async {
/// #
/// use rasi::net::UdpSocket;
///
/// let socket = UdpSocket::bind("127.0.0.1:8080").await?;
/// let mut buf = vec![0u8; 1024];
///
/// loop {
///     let (n, peer) = socket.recv_from(&mut buf).await?;
///     socket.send_to(&buf[..n], peer).await?;
/// }
/// #
/// # }) }
/// ```
pub struct UdpSocket {
    /// syscall socket handle.
    sys_socket: rasi_syscall::Handle,

    /// a reference to syscall interface .
    syscall: &'static dyn Network,
}

impl Display for UdpSocket {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "UdpSocket({:?})", self.local_addr())
    }
}

impl UdpSocket {
    /// Use global register syscall interface [`Network`] to create a UDP socket from the given address.
    ///
    /// Binding with a port number of 0 will request that the OS assigns a port to this socket. The
    /// port allocated can be queried via the [`local_addr`] method.
    ///
    /// [`local_addr`]: #method.local_addr
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # fn main() -> std::io::Result<()> { futures::executor::block_on(async {
    /// #
    /// use rasi::net::UdpSocket;
    ///
    /// let socket = UdpSocket::bind("127.0.0.1:0").await?;
    /// #
    /// # Ok(()) }) }
    /// ```
    pub async fn bind<A: ToSocketAddrs>(laddrs: A) -> io::Result<Self> {
        Self::bind_with(laddrs, global_network()).await
    }
    /// Use custom syscall interface [`Network`] to create a UDP socket from the given address.
    ///
    /// Binding with a port number of 0 will request that the OS assigns a port to this socket. The
    /// port allocated can be queried via the [`local_addr`] method.
    ///
    /// [`local_addr`]: #method.local_addr
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # fn main() -> std::io::Result<()> { futures::executor::block_on(async {
    /// #
    /// use rasi::net::UdpSocket;
    ///
    /// let socket = UdpSocket::bind("127.0.0.1:0").await?;
    /// #
    /// # Ok(()) }) }
    /// ```
    pub async fn bind_with<A: ToSocketAddrs>(
        laddrs: A,
        syscall: &'static dyn Network,
    ) -> io::Result<Self> {
        let laddrs = laddrs.to_socket_addrs()?.collect::<Vec<_>>();

        let sys_socket =
            cancelable_would_block(|cx| syscall.udp_bind(cx.waker().clone(), &laddrs)).await?;

        Ok(UdpSocket {
            sys_socket,
            syscall,
        })
    }
    /// Returns the local address that this listener is bound to.
    ///
    /// This can be useful, for example, when binding to port 0 to figure out which port was
    /// actually bound.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # fn main() -> std::io::Result<()> { futures::executor::block_on(async {
    /// #
    /// use rasi::net::UdpSocket;
    ///
    /// let socket = UdpSocket::bind("127.0.0.1:0").await?;
    /// let addr = socket.local_addr()?;
    /// #
    /// # Ok(()) }) }
    /// ```
    pub fn local_addr(&self) -> io::Result<SocketAddr> {
        self.syscall.udp_local_addr(&self.sys_socket)
    }

    /// Sends data on the socket to the given address.
    ///
    /// On success, returns the number of bytes written.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # fn main() -> std::io::Result<()> { futures::executor::block_on(async {
    /// #
    /// use rasi::net::UdpSocket;
    ///
    /// const THE_MERCHANT_OF_VENICE: &[u8] = b"
    ///     If you prick us, do we not bleed?
    ///     If you tickle us, do we not laugh?
    ///     If you poison us, do we not die?
    ///     And if you wrong us, shall we not revenge?
    /// ";
    ///
    /// let socket = UdpSocket::bind("127.0.0.1:0").await?;
    ///
    /// let addr = "127.0.0.1:7878".parse().unwrap();
    /// let sent = socket.send_to(THE_MERCHANT_OF_VENICE, addr).await?;
    /// log::trace!("Sent {} bytes to {}", sent, addr);
    /// #
    /// # Ok(()) }) }
    /// ```
    pub async fn send_to(&self, buf: &[u8], addr: SocketAddr) -> io::Result<usize> {
        cancelable_would_block(|cx| {
            self.syscall
                .udp_send_to(cx.waker().clone(), &self.sys_socket, buf, addr)
        })
        .await
    }

    /// Receives data from the socket.
    ///
    /// On success, returns the number of bytes read and the origin.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # fn main() -> std::io::Result<()> { futures::executor::block_on(async {
    /// #
    /// use rasi::net::UdpSocket;
    ///
    /// let socket = UdpSocket::bind("127.0.0.1:0").await?;
    ///
    /// let mut buf = vec![0; 1024];
    /// let (n, peer) = socket.recv_from(&mut buf).await?;
    /// log::trace!("Received {} bytes from {}", n, peer);
    /// #
    /// # Ok(()) }) }
    /// ```
    pub async fn recv_from(&self, buf: &mut [u8]) -> io::Result<(usize, SocketAddr)> {
        cancelable_would_block(|cx| {
            self.syscall
                .udp_recv_from(cx.waker().clone(), &self.sys_socket, buf)
        })
        .await
    }

    /// Gets the value of the `SO_BROADCAST` option for this socket.
    ///
    /// For more information about this option, see [`set_broadcast`].
    ///
    /// [`set_broadcast`]: #method.set_broadcast
    pub fn broadcast(&self) -> io::Result<bool> {
        self.syscall.udp_broadcast(&self.sys_socket)
    }

    /// Sets the value of the `SO_BROADCAST` option for this socket.
    ///
    /// When enabled, this socket is allowed to send packets to a broadcast address.
    pub fn set_broadcast(&self, on: bool) -> io::Result<()> {
        self.syscall.udp_set_broadcast(&self.sys_socket, on)
    }

    /// Gets the value of the `IP_TTL` option for this socket.
    ///
    /// For more information about this option, see [`set_ttl`].
    ///
    /// [`set_ttl`]: #method.set_ttl
    pub fn ttl(&self) -> io::Result<u32> {
        self.syscall.udp_ttl(&self.sys_socket)
    }

    /// Sets the value for the `IP_TTL` option on this socket.
    ///
    /// This value sets the time-to-live field that is used in every packet sent
    /// from this socket.
    pub fn set_ttl(&self, ttl: u32) -> io::Result<()> {
        self.syscall.udp_set_ttl(&self.sys_socket, ttl)
    }

    /// Executes an operation of the `IP_ADD_MEMBERSHIP` type.
    ///
    /// This method specifies a new multicast group for this socket to join. The address must be
    /// a valid multicast address, and `interface` is the address of the local interface with which
    /// the system should join the multicast group. If it's equal to `INADDR_ANY` then an
    /// appropriate interface is chosen by the system.
    pub fn join_multicast_v4(&self, multiaddr: &Ipv4Addr, interface: &Ipv4Addr) -> io::Result<()> {
        self.syscall
            .udp_join_multicast_v4(&self.sys_socket, multiaddr, interface)
    }

    /// Executes an operation of the `IPV6_ADD_MEMBERSHIP` type.
    ///
    /// This function specifies a new multicast group for this socket to join.
    /// The address must be a valid multicast address, and `interface` is the
    /// index of the interface to join/leave (or 0 to indicate any interface).
    pub fn join_multicast_v6(&self, multiaddr: Ipv6Addr, interface: u32) -> io::Result<()> {
        self.syscall
            .udp_join_multicast_v6(&self.sys_socket, &multiaddr, interface)
    }

    /// Executes an operation of the `IP_DROP_MEMBERSHIP` type.
    ///
    /// For more information about this option, see
    /// [`join_multicast_v4`][link].
    ///
    /// [link]: #method.join_multicast_v4
    pub fn leave_multicast_v4(&self, multiaddr: &Ipv4Addr, interface: &Ipv4Addr) -> io::Result<()> {
        self.syscall
            .udp_leave_multicast_v4(&self.sys_socket, multiaddr, interface)
    }

    /// Executes an operation of the `IPV6_DROP_MEMBERSHIP` type.
    ///
    /// For more information about this option, see
    /// [`join_multicast_v6`][link].
    ///
    /// [link]: #method.join_multicast_v6
    pub fn leave_multicast_v6(&self, multiaddr: &Ipv6Addr, interface: u32) -> io::Result<()> {
        self.syscall
            .udp_leave_multicast_v6(&self.sys_socket, multiaddr, interface)
    }
}

#[cfg(all(unix, feature = "unix_socket"))]
mod unix {
    use std::{fmt::Debug, io, os::unix::net::SocketAddr, path::Path, task::Poll};

    use futures::{AsyncRead, AsyncWrite};
    use rasi_syscall::{global_network, Handle, Network};

    use crate::utils::cancelable_would_block;

    /// A Unix socket server, listening for connections.
    /// After creating a UnixListener by binding it to a socket address,
    /// it listens for incoming Unix connections. These can be accepted
    /// by awaiting elements from the async stream of incoming connections.
    ///
    /// The socket will be closed when the value is dropped.
    /// The Transmission Control Protocol is specified in IETF RFC 793.
    /// This type is an async version of [`std::os::unix::net::UnixListener`].
    pub struct UnixListener {
        /// syscall socket handle.
        sys_socket: rasi_syscall::Handle,

        /// a reference to syscall interface .
        syscall: &'static dyn Network,
    }

    impl UnixListener {
        /// Creates a new UnixListener with custom [syscall](rasi_syscall::Network) which will be bound to the specified address.
        ///
        /// See [`bind`](UnixListener::bind) for more information.
        pub async fn bind_with<P: AsRef<Path>>(
            path: P,
            syscall: &'static dyn Network,
        ) -> io::Result<Self> {
            let path = path.as_ref();

            let sys_socket = cancelable_would_block(move |cx| {
                syscall.unix_listener_bind(cx.waker().clone(), path)
            })
            .await?;

            Ok(UnixListener {
                sys_socket,
                syscall,
            })
        }

        /// Creates a new TcpListener with global [syscall](rasi_syscall::Network) which will be bound to the specified address.
        ///
        /// Use function [`bind`](UnixListener::bind_with) to specified custom [syscall](rasi_syscall::Network)
        ///
        /// # Examples
        /// Create a unix socket listener
        ///
        /// ```no_run
        /// # fn main() -> std::io::Result<()> { futures::executor::block_on(async {
        /// #
        /// use rasi::net::UnixListener;
        ///
        /// let listener = UnixListener::bind("/tmp/sock").await?;
        /// #
        /// # Ok(()) }) }
        /// ```
        pub async fn bind<P: AsRef<Path>>(path: P) -> io::Result<Self> {
            Self::bind_with(path, global_network()).await
        }

        /// Accepts a new incoming connection to this listener.
        ///
        /// When a connection is established, the corresponding stream and address will be returned.
        ///
        /// ## Examples
        ///
        /// ```no_run
        /// # fn main() -> std::io::Result<()> { futures::executor::block_on(async {
        /// #
        /// use rasi::net::UnixListener;
        ///
        /// let listener = UnixListener::bind("/tmp/sock").await?;
        /// let (stream, addr) = listener.accept().await?;
        /// #
        /// # Ok(()) }) }
        pub async fn accept(&self) -> io::Result<(UnixStream, SocketAddr)> {
            let (sys_socket, raddr) = cancelable_would_block(|cx| {
                self.syscall
                    .unix_listener_accept(cx.waker().clone(), &self.sys_socket)
            })
            .await?;

            Ok((UnixStream::new(sys_socket, self.syscall), raddr))
        }

        /// Returns the local address that this listener is bound to.
        ///
        /// This can be useful, for example, to identify when binding to port 0 which port was assigned
        /// by the OS.
        ///
        /// # Examples
        ///
        /// ```no_run
        /// # fn main() -> std::io::Result<()> { futures::executor::block_on(async {
        /// #
        /// use rasi::net::TcpListener;
        ///
        /// let listener = TcpListener::bind("127.0.0.1:8080").await?;
        /// let addr = listener.local_addr()?;
        /// #
        /// # Ok(()) }) }
        /// ```
        pub fn local_addr(&self) -> io::Result<SocketAddr> {
            self.syscall.unix_listener_local_addr(&self.sys_socket)
        }
    }

    pub struct UnixStream {
        /// syscall socket handle.
        sys_socket: rasi_syscall::Handle,

        /// a reference to syscall interface .
        syscall: &'static dyn Network,

        /// The cancel handle reference to latest pending write ops.
        write_cancel_handle: Option<Handle>,

        /// The cancel handle reference to latest pending read ops.
        read_cancel_handle: Option<Handle>,
    }

    impl Debug for UnixStream {
        fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
            f.debug_struct("UnixStream")
                .field("socket", &self.sys_socket)
                .field(
                    "syscall",
                    &format!("{:?}", self.syscall as *const dyn Network),
                )
                .finish()
        }
    }

    impl UnixStream {
        fn new(sys_socket: rasi_syscall::Handle, syscall: &'static dyn Network) -> Self {
            Self {
                sys_socket,
                syscall,
                write_cancel_handle: None,
                read_cancel_handle: None,
            }
        }

        /// Using custom [`syscall`](rasi_syscall::Network) interface to create a new TCP
        /// stream connected to the specified address.
        ///
        /// see [`connect`](UnixStream::connect) for more information.
        pub async fn connect_with<P: AsRef<Path>>(
            path: P,
            syscall: &'static dyn Network,
        ) -> io::Result<Self> {
            let path = path.as_ref();

            let sys_socket =
                cancelable_would_block(|cx| syscall.unix_stream_connect(cx.waker().clone(), path))
                    .await?;

            Ok(Self::new(sys_socket, syscall))
        }

        /// Using global [`syscall`](rasi_syscall::Network) interface to create a new TCP
        /// stream connected to the specified address.
        ///
        /// This method will create a new Unix socket and attempt to connect it to the `path`
        /// provided. The [returned future] will be resolved once the stream has successfully
        /// connected, or it will return an error if one occurs.
        ///
        /// [returned future]: struct.Connect.html
        ///
        /// # Examples
        ///
        /// ```no_run
        /// # fn main() -> std::io::Result<()> { futures::executor::block_on(async {
        /// #
        /// use rasi::net::UnixStream;
        ///
        /// let stream = UnixStream::connect("/tmp/socket").await?;
        /// #
        /// # Ok(()) }) }
        /// ```
        pub async fn connect<P: AsRef<Path>>(path: P) -> io::Result<Self> {
            Self::connect_with(path, global_network()).await
        }

        /// Returns the local address that this stream is connected to.
        ///
        /// ## Examples
        ///
        /// ```no_run
        /// # fn main() -> std::io::Result<()> { futures::executor::block_on(async {
        /// #
        /// use rasi::net::UnixStream;
        ///
        /// let stream = UnixStream::connect("/tmp/socket").await?;
        /// let addr = stream.local_addr()?;
        /// #
        /// # Ok(()) }) }
        /// ```
        pub fn local_addr(&self) -> io::Result<SocketAddr> {
            self.syscall.unix_stream_local_addr(&self.sys_socket)
        }

        /// Returns the remote address that this stream is connected to.
        ///
        /// ## Examples
        ///
        /// ```no_run
        /// # fn main() -> std::io::Result<()> { futures::executor::block_on(async {
        /// #
        /// use rasi::net::TcpStream;
        ///
        /// let stream = TcpStream::connect("127.0.0.1:8080").await?;
        /// let peer = stream.peer_addr()?;
        /// #
        /// # Ok(()) }) }
        /// ```
        pub fn peer_addr(&self) -> io::Result<SocketAddr> {
            self.syscall.unix_stream_peer_addr(&self.sys_socket)
        }
    }

    impl AsyncRead for UnixStream {
        fn poll_read(
            mut self: std::pin::Pin<&mut Self>,
            cx: &mut std::task::Context<'_>,
            buf: &mut [u8],
        ) -> std::task::Poll<io::Result<usize>> {
            match self
                .syscall
                .unix_stream_read(cx.waker().clone(), &self.sys_socket, buf)
            {
                rasi_syscall::CancelablePoll::Ready(r) => Poll::Ready(r),
                rasi_syscall::CancelablePoll::Pending(read_cancel_handle) => {
                    self.read_cancel_handle = Some(read_cancel_handle);
                    Poll::Pending
                }
            }
        }
    }

    impl AsyncWrite for UnixStream {
        fn poll_write(
            mut self: std::pin::Pin<&mut Self>,
            cx: &mut std::task::Context<'_>,
            buf: &[u8],
        ) -> Poll<io::Result<usize>> {
            match self
                .syscall
                .unix_stream_write(cx.waker().clone(), &self.sys_socket, buf)
            {
                rasi_syscall::CancelablePoll::Ready(r) => Poll::Ready(r),
                rasi_syscall::CancelablePoll::Pending(write_cancel_handle) => {
                    self.write_cancel_handle = Some(write_cancel_handle);
                    Poll::Pending
                }
            }
        }

        fn poll_flush(
            self: std::pin::Pin<&mut Self>,
            _cx: &mut std::task::Context<'_>,
        ) -> Poll<io::Result<()>> {
            Poll::Ready(Ok(()))
        }

        fn poll_close(
            self: std::pin::Pin<&mut Self>,
            _cx: &mut std::task::Context<'_>,
        ) -> Poll<io::Result<()>> {
            self.syscall
                .unix_stream_shutdown(&self.sys_socket, std::net::Shutdown::Both)?;

            Poll::Ready(Ok(()))
        }
    }
}

#[cfg(all(unix, feature = "unix_socket"))]
pub use unix::*;