Skip to content

Commit

Permalink
Add UnixListener::from_std
Browse files Browse the repository at this point in the history
Converts a std::os::unix::net::UnixListener to a
heph::net::UnixListener.
  • Loading branch information
Thomasdezeeuw committed Dec 30, 2023
1 parent df79795 commit 39e4207
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 1 deletion.
13 changes: 13 additions & 0 deletions rt/src/net/uds/listener.rs
Original file line number Diff line number Diff line change
Expand Up @@ -132,6 +132,19 @@ impl UnixListener {
Ok(socket)
}

/// Converts a [`std::os::unix::net::UnixListener`] to a
/// [`heph_rt::net::UnixListener`].
///
/// [`heph_rt::net::UnixListener`]: UnixListener
pub fn from_std<RT>(rt: &RT, listener: std::os::unix::net::UnixListener) -> UnixListener
where
RT: Access,
{
UnixListener {
fd: AsyncFd::new(listener.into(), rt.submission_queue()),
}
}

/// Returns the socket address of the local half of this socket.
pub fn local_addr(&self) -> io::Result<UnixAddr> {
self.with_ref(|socket| socket.local_addr().map(|a| UnixAddr { inner: a }))
Expand Down
28 changes: 27 additions & 1 deletion rt/tests/functional/uds/listener.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,9 @@ use std::time::Duration;
use heph::actor::{self, actor_fn};
use heph_rt::net::uds::{UnixAddr, UnixListener, UnixStream};
use heph_rt::spawn::ActorOptions;
use heph_rt::test::{join, try_spawn_local, PanicSupervisor};
use heph_rt::test::{block_on_local_actor, join, try_spawn_local, PanicSupervisor};
use heph_rt::util::next;
use heph_rt::ThreadLocal;
use heph_rt::{self as rt};

use crate::util::temp_file;
Expand Down Expand Up @@ -81,3 +82,28 @@ fn incoming() {
let actor_ref = try_spawn_local(PanicSupervisor, actor, (), ActorOptions::default()).unwrap();
join(&actor_ref, Duration::from_secs(1)).unwrap();
}

#[test]
fn listener_from_std() {
async fn actor(ctx: actor::Context<!, ThreadLocal>) -> io::Result<()> {
let path = temp_file("uds.listener_from_std");

let listener = std::os::unix::net::UnixListener::bind(path)?;
let listener = UnixListener::from_std(ctx.runtime_ref(), listener);

let address = listener.local_addr()?;
let stream = UnixStream::connect(ctx.runtime_ref(), address).await?;

let (client, _) = listener.accept().await?;

let (_, n) = stream.send(DATA).await?;
assert_eq!(n, DATA.len());
let buf = client.recv(Vec::with_capacity(DATA.len() + 1)).await?;
assert_eq!(buf.len(), DATA.len());
assert_eq!(buf, DATA);

Ok(())
}

block_on_local_actor(actor_fn(actor), ()).unwrap();
}

0 comments on commit 39e4207

Please sign in to comment.