Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(util): impl listener for either #6206

Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
52 changes: 31 additions & 21 deletions tokio-util/src/net/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -62,36 +62,46 @@ where
}
}

impl<L, R> Either<L, R>
impl<L, R> Listener for Either<L, R>
where
L: Listener,
R: Listener,
{
/// Accepts a new incoming connection from this listener.
pub async fn accept(&mut self) -> Result<Either<(L::Io, L::Addr), (R::Io, R::Addr)>> {
type Io = Either<L::Io, R::Io>;

type Addr = Either<L::Addr, R::Addr>;

fn poll_accept(&mut self, cx: &mut Context<'_>) -> Poll<Result<(Self::Io, Self::Addr)>> {
match self {
Either::Left(listener) => {
let (stream, addr) = listener.accept().await?;
Ok(Either::Left((stream, addr)))
}
Either::Right(listener) => {
let (stream, addr) = listener.accept().await?;
Ok(Either::Right((stream, addr)))
}
Self::Left(l) => l
.poll_accept(cx)
.map(|res| res.map(|(io, addr)| (Either::Left(io), Either::Left(addr)))),
Self::Right(r) => r
.poll_accept(cx)
.map(|res| res.map(|(io, addr)| (Either::Right(io), Either::Right(addr)))),
}
}

/// Returns the local address that this listener is bound to.
pub fn local_addr(&self) -> Result<Either<L::Addr, R::Addr>> {
fn local_addr(&self) -> Result<Self::Addr> {
match self {
Either::Left(listener) => {
let addr = listener.local_addr()?;
Ok(Either::Left(addr))
}
Either::Right(listener) => {
let addr = listener.local_addr()?;
Ok(Either::Right(addr))
}
Either::Left(l) => l.local_addr().map(Either::Left),
Either::Right(r) => r.local_addr().map(Either::Right),
}
}
}

impl<L, R> Either<L, R>
where
L: Listener,
R: Listener,
{
/// Accepts a new incoming connection from this listener.
pub fn accept(&mut self) -> ListenerAcceptFut<'_, Self> {
ListenerAcceptFut { listener: self }
}

/// Returns the local address that this listener is bound to.
pub fn local_addr(&self) -> Result<Either<L::Addr, R::Addr>> {
Listener::local_addr(self)
}
}
Loading