Skip to content

Commit

Permalink
Add TcpListener::from_std
Browse files Browse the repository at this point in the history
Converts a TcpListener from std lib to Heph's version.
  • Loading branch information
Thomasdezeeuw committed Dec 30, 2023
1 parent 5153c92 commit c071aff
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 1 deletion.
12 changes: 12 additions & 0 deletions rt/src/net/tcp/listener.rs
Original file line number Diff line number Diff line change
Expand Up @@ -147,6 +147,18 @@ impl TcpListener {
Ok(socket)
}

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

/// Returns the local socket address of this listener.
pub fn local_addr(&self) -> io::Result<SocketAddr> {
self.with_ref(|socket| socket.local_addr().and_then(convert_address))
Expand Down
20 changes: 19 additions & 1 deletion rt/tests/functional/tcp/listener.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
use std::io;
use std::net::SocketAddr;
use std::time::Duration;

Expand All @@ -6,7 +7,7 @@ use heph::supervisor::NoSupervisor;
use heph::ActorRef;
use heph_rt::net::{TcpListener, TcpStream};
use heph_rt::spawn::ActorOptions;
use heph_rt::test::{join, join_many, try_spawn_local};
use heph_rt::test::{block_on_local_actor, join, join_many, try_spawn_local};
use heph_rt::util::next;
use heph_rt::{self as rt, ThreadLocal};

Expand Down Expand Up @@ -70,6 +71,23 @@ fn ttl() {
join(&actor_ref, Duration::from_secs(1)).unwrap();
}

#[test]
fn listener_from_std() {
async fn actor(ctx: actor::Context<!, ThreadLocal>) -> io::Result<()> {
let listener = std::net::TcpListener::bind(any_local_address())?;
let listener = TcpListener::from_std(ctx.runtime_ref(), listener);

let initial = listener.ttl()?;
let expected = initial + 10;
listener.set_ttl(expected)?;
assert_eq!(listener.ttl()?, expected);

Ok(())
}

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

const DATA: &[u8] = b"Hello world";

async fn stream_actor<RT>(mut ctx: actor::Context<SocketAddr, RT>)
Expand Down

0 comments on commit c071aff

Please sign in to comment.