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
mod engine;
use std::io;
use std::os::unix::io::AsRawFd;
use std::pin::Pin;
use std::task::{Context, Poll};
use futures_core::ready;
use futures_io::{AsyncRead, AsyncBufRead, AsyncWrite};
use crate::drive::Drive;
use crate::drive::demo::DemoDriver;
use engine::Engine;
pub struct Ring<IO, D = DemoDriver<'static>> {
engine: Engine,
io: IO,
driver: D,
}
impl<IO: AsRawFd, D: Drive + Default> Ring<IO, D> {
pub fn new(io: IO) -> Ring<IO, D> {
Ring::on_driver(io, D::default())
}
}
impl<IO: AsRawFd, D: Drive> Ring<IO, D> {
pub fn on_driver(io: IO, driver: D) -> Ring<IO, D> {
let engine = Engine::new();
Ring { engine, io, driver }
}
pub fn cancel(&mut self) {
self.engine.cancel();
}
}
impl<IO, D> Ring<IO, D> {
fn split(self: Pin<&mut Self>) -> (&mut Engine, Pin<&mut IO>, Pin<&mut D>) {
unsafe {
let this = Pin::get_unchecked_mut(self);
let engine = &mut this.engine;
let io = Pin::new_unchecked(&mut this.io);
let driver = Pin::new_unchecked(&mut this.driver);
(engine, io, driver)
}
}
}
impl<IO: io::Read + AsRawFd, D: Drive> AsyncBufRead for Ring<IO, D> {
fn poll_fill_buf(self: Pin<&mut Self>, ctx: &mut Context<'_>) -> Poll<io::Result<&[u8]>> {
let (engine, io, driver) = self.split();
engine.poll_fill_read_buf(ctx, driver, io.as_raw_fd())
}
fn consume(self: Pin<&mut Self>, amt: usize) {
let (engine, ..) = self.split();
engine.consume(amt);
}
}
impl<IO: io::Read + AsRawFd, D: Drive> AsyncRead for Ring<IO, D> {
fn poll_read(mut self: Pin<&mut Self>, ctx: &mut Context<'_>, buf: &mut [u8])
-> Poll<io::Result<usize>>
{
let mut inner = ready!(self.as_mut().poll_fill_buf(ctx))?;
let len = io::Read::read(&mut inner, buf)?;
self.consume(len);
Poll::Ready(Ok(len))
}
}
impl<IO: io::Write + AsRawFd, D: Drive> AsyncWrite for Ring<IO, D> {
fn poll_write(self: Pin<&mut Self>, ctx: &mut Context<'_>, buf: &[u8]) -> Poll<io::Result<usize>> {
let (engine, io, driver) = self.split();
engine.poll_write(ctx, driver, io.as_raw_fd(), buf)
}
fn poll_flush(self: Pin<&mut Self>, ctx: &mut Context<'_>) -> Poll<io::Result<()>> {
let (engine, io, driver) = self.split();
engine.poll_flush_write_buf(ctx, driver, io.as_raw_fd())
}
fn poll_close(self: Pin<&mut Self>, ctx: &mut Context<'_>) -> Poll<io::Result<()>> {
let (engine, io, driver) = self.split();
engine.poll_flush_write_buf(ctx, driver, io.as_raw_fd())
}
}