iroh_relay/client/
util.rs1use std::{
6 fmt, io,
7 pin::Pin,
8 task::{Context, Poll, ready},
9};
10
11use pin_project::pin_project;
12use tokio::io::{AsyncBufRead, AsyncRead, ReadBuf};
13
14#[must_use = "streams do nothing unless polled"]
16#[pin_project]
17pub(crate) struct Chain<T, U> {
18 #[pin]
19 first: T,
20 #[pin]
21 second: U,
22 done_first: bool,
23}
24
25pub(crate) fn chain<T, U>(first: T, second: U) -> Chain<T, U>
27where
28 T: AsyncRead,
29 U: AsyncRead,
30{
31 Chain {
32 first,
33 second,
34 done_first: false,
35 }
36}
37
38impl<T, U> Chain<T, U>
39where
40 T: AsyncRead,
41 U: AsyncRead,
42{
43 pub(crate) fn get_ref(&self) -> (&T, &U) {
45 (&self.first, &self.second)
46 }
47
48 pub(crate) fn get_mut(&mut self) -> (&mut T, &mut U) {
54 (&mut self.first, &mut self.second)
55 }
56}
57
58impl<T, U> fmt::Debug for Chain<T, U>
59where
60 T: fmt::Debug,
61 U: fmt::Debug,
62{
63 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
64 f.debug_struct("Chain")
65 .field("t", &self.first)
66 .field("u", &self.second)
67 .finish()
68 }
69}
70
71impl<T, U> AsyncRead for Chain<T, U>
72where
73 T: AsyncRead,
74 U: AsyncRead,
75{
76 fn poll_read(
77 self: Pin<&mut Self>,
78 cx: &mut Context<'_>,
79 buf: &mut ReadBuf<'_>,
80 ) -> Poll<io::Result<()>> {
81 let me = self.project();
82
83 if !*me.done_first {
84 let rem = buf.remaining();
85 ready!(me.first.poll_read(cx, buf))?;
86 if buf.remaining() == rem {
87 *me.done_first = true;
88 } else {
89 return Poll::Ready(Ok(()));
90 }
91 }
92 me.second.poll_read(cx, buf)
93 }
94}
95
96impl<T, U> AsyncBufRead for Chain<T, U>
97where
98 T: AsyncBufRead,
99 U: AsyncBufRead,
100{
101 fn poll_fill_buf(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<&[u8]>> {
102 let me = self.project();
103
104 if !*me.done_first {
105 match ready!(me.first.poll_fill_buf(cx)?) {
106 [] => {
107 *me.done_first = true;
108 }
109 buf => return Poll::Ready(Ok(buf)),
110 }
111 }
112 me.second.poll_fill_buf(cx)
113 }
114
115 fn consume(self: Pin<&mut Self>, amt: usize) {
116 let me = self.project();
117 if !*me.done_first {
118 me.first.consume(amt)
119 } else {
120 me.second.consume(amt)
121 }
122 }
123}