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
#![forbid(unsafe_code, future_incompatible)]
#![deny(missing_debug_implementations, bad_style)]
#![deny(missing_docs)]
#![cfg_attr(test, deny(warnings))]

//! Async datagram traits.
//!
//! ## Example
//!
//! ```rust
//! #![feature(futures_api)]
//!
//! use async_datagram::AsyncDatagram;
//! use std::task::{Context, Poll};
//! use std::pin::Pin;
//!
//! struct Udp;
//!
//! impl AsyncDatagram for Udp {
//!   type Sender = std::net::SocketAddr;
//!   type Receiver = std::net::SocketAddr;
//!   type Err = std::io::Error;
//!
//!   fn poll_send_to(
//!     self: Pin<&mut Self>,
//!     cx: &mut Context<'_>,
//!     buf: &[u8],
//!     target: &Self::Receiver,
//!   ) -> Poll<Result<usize, Self::Err>> {
//!     Poll::Ready(Ok(0))
//!   }
//!
//!   fn poll_recv_from(
//!     self: Pin<&mut Self>,
//!     cx: &mut Context<'_>,
//!     buf: &mut [u8],
//!   ) -> Poll<Result<(usize, Self::Sender), Self::Err>> {
//!     Poll::Pending
//!   }
//! }
//! ```

#![feature(futures_api)]

use std::pin::Pin;
use std::task::{Context, Poll};

/// Implement a datagram protocol.
pub trait AsyncDatagram {
  /// Specifies which target to send the data to.
  type Sender;

  /// Specifies which target the data was received from.
  type Receiver;

  /// The type of failures yielded by this trait.
  type Err;

  /// Sends data on the IO interface to the specified target.
  ///
  /// On success, returns the number of bytes written.
  fn poll_send_to(
    self: Pin<&mut Self>,
    cx: &mut Context<'_>,
    buf: &[u8],
    receiver: &Self::Receiver,
  ) -> Poll<Result<usize, Self::Err>>;

  /// Receives data from the IO interface.
  ///
  /// On success, returns the number of bytes read and the target from whence
  /// the data came.
  fn poll_recv_from(
    self: Pin<&mut Self>,
    cx: &mut Context<'_>,
    buf: &mut [u8],
  ) -> Poll<Result<(usize, Self::Sender), Self::Err>>;
}