plug/
plug.rs

1use crate::connection::{self, Connection};
2
3use tokio::io;
4use tokio::net;
5
6use std::marker::PhantomData;
7
8/// A type-safe connection endpoint with a name.
9#[derive(Debug, Clone, Copy)]
10pub struct Plug<I, O> {
11    pub(crate) name: &'static str,
12    _types: PhantomData<(I, O)>,
13}
14
15impl<I, O> Plug<I, O> {
16    /// Creates a new [`Plug`] with the given name.
17    pub const fn new(name: &'static str) -> Self {
18        Self {
19            name,
20            _types: PhantomData,
21        }
22    }
23
24    /// Connects to the [`Plug`] in the given server address, producing a type-safe [`Connection`].
25    pub async fn connect(self, address: impl net::ToSocketAddrs) -> io::Result<Connection<I, O>> {
26        let stream = net::TcpStream::connect(address).await?;
27
28        self.seize(stream).await
29    }
30
31    /// Seizes an existing TCP connection and redirects it through the [`Plug`].
32    pub async fn seize(self, mut stream: net::TcpStream) -> io::Result<Connection<I, O>> {
33        connection::write_json(&mut stream, self.name).await?;
34
35        Ok(Connection::seize(stream))
36    }
37}