Skip to content

Commit

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

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

/// Automatically set the CPU affinity based on the runtime access `rt`.
///
/// For non-Linux OSs this is a no-op. If `rt` is not local this is also a
Expand Down
21 changes: 20 additions & 1 deletion rt/tests/functional/tcp/stream.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ use heph::actor_ref::ActorRef;
use heph::supervisor::NoSupervisor;
use heph_rt::net::{TcpListener, TcpStream};
use heph_rt::spawn::ActorOptions;
use heph_rt::test::{join, join_many, try_spawn_local, PanicSupervisor};
use heph_rt::test::{block_on_local_actor, join, join_many, try_spawn_local, PanicSupervisor};
use heph_rt::ThreadLocal;

use crate::util::{any_local_address, refused_address};
Expand Down Expand Up @@ -107,6 +107,25 @@ fn connect() {
join(&actor_ref, Duration::from_secs(1)).unwrap();
}

#[test]
fn stream_from_std() {
async fn actor(ctx: actor::Context<!, ThreadLocal>, address: SocketAddr) -> io::Result<()> {
let listener = std::net::TcpStream::connect(address)?;
let listener = TcpStream::from_std(ctx.runtime_ref(), listener);

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

Ok(())
}

let listener = net::TcpListener::bind(any_local_address()).unwrap();
let address = listener.local_addr().unwrap();
block_on_local_actor(actor_fn(actor), address).unwrap();
}

#[test]
#[cfg_attr(
target_os = "freebsd",
Expand Down

0 comments on commit 3e35fcb

Please sign in to comment.