broker_tokio/io/util/
split.rs1use crate::io::util::read_until::read_until_internal;
2use crate::io::AsyncBufRead;
3
4use pin_project_lite::pin_project;
5use std::io;
6use std::mem;
7use std::pin::Pin;
8use std::task::{Context, Poll};
9
10pin_project! {
11 #[derive(Debug)]
13 #[must_use = "streams do nothing unless polled"]
14 #[cfg_attr(docsrs, doc(cfg(feature = "io-util")))]
15 pub struct Split<R> {
16 #[pin]
17 reader: R,
18 buf: Vec<u8>,
19 delim: u8,
20 read: usize,
21 }
22}
23
24pub(crate) fn split<R>(reader: R, delim: u8) -> Split<R>
25where
26 R: AsyncBufRead,
27{
28 Split {
29 reader,
30 buf: Vec::new(),
31 delim,
32 read: 0,
33 }
34}
35
36impl<R> Split<R>
37where
38 R: AsyncBufRead + Unpin,
39{
40 pub async fn next_segment(&mut self) -> io::Result<Option<Vec<u8>>> {
58 use crate::future::poll_fn;
59
60 poll_fn(|cx| Pin::new(&mut *self).poll_next_segment(cx)).await
61 }
62}
63
64impl<R> Split<R>
65where
66 R: AsyncBufRead,
67{
68 #[doc(hidden)]
69 pub fn poll_next_segment(
70 self: Pin<&mut Self>,
71 cx: &mut Context<'_>,
72 ) -> Poll<io::Result<Option<Vec<u8>>>> {
73 let me = self.project();
74
75 let n = ready!(read_until_internal(
76 me.reader, cx, *me.delim, me.buf, me.read,
77 ))?;
78
79 if n == 0 && me.buf.is_empty() {
80 return Poll::Ready(Ok(None));
81 }
82
83 if me.buf.last() == Some(me.delim) {
84 me.buf.pop();
85 }
86
87 Poll::Ready(Ok(Some(mem::replace(me.buf, Vec::new()))))
88 }
89}
90
91#[cfg(feature = "stream")]
92impl<R: AsyncBufRead> crate::stream::Stream for Split<R> {
93 type Item = io::Result<Vec<u8>>;
94
95 fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
96 Poll::Ready(match ready!(self.poll_next_segment(cx)) {
97 Ok(Some(segment)) => Some(Ok(segment)),
98 Ok(None) => None,
99 Err(err) => Some(Err(err)),
100 })
101 }
102}
103
104#[cfg(test)]
105mod tests {
106 use super::*;
107
108 #[test]
109 fn assert_unpin() {
110 crate::is_unpin::<Split<()>>();
111 }
112}