0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

tokio::io AsyncReadのimpl実装

Posted at

簡単ですがメモしておきます。

poll_readを実装するだけ。

「Readを提供 = こちら側はWriteする」という意識で、buf: &mut io::ReadBufにput等でデータを突っ込んでいく実装を行う。

/*
 HelloってN回Readさせるのを提供するコード
*/

use tokio::io::{self, AsyncRead, AsyncReadExt};

struct Hello {
    count: u64,
    limit: u64,
}

impl Hello {
    fn new(limit: u64) -> Self {
        Self {
            count: 0,
            limit: limit,
        }
    }
}

impl AsyncRead for Hello {
    fn poll_read(
        mut self: std::pin::Pin<&mut Self>,
        cx: &mut std::task::Context<'_>,
        buf: &mut io::ReadBuf<'_>,
    ) -> std::task::Poll<std::io::Result<()>> {
        if self.count > self.limit {
            return std::task::Poll::Ready(Ok(()));
        }
        let s: &str = "Hello";
        let b: &[u8] = s.as_bytes();
        buf.put_slice(b);
        self.count += 1;
        std::task::Poll::Ready(Ok(()))
    }
}

#[tokio::main]
async fn main() {
    let mut r = Hello::new(10);
    let mut buffer = Vec::new();

    if let Err(e) = r.read_to_end(&mut buffer).await {
        println!("Error: {}", e);
    };
    println!("{}", String::from_utf8(buffer).unwrap())
}

以上

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?