#![cfg(all(feature = "async", not(feature = "sync")))]
use crate::{
options::SessionOptions,
style::{private, SessionStyle},
DestinationKind,
};
use tokio::{
io::{AsyncBufReadExt, AsyncWriteExt, BufReader},
net::TcpStream,
};
use std::future::Future;
pub struct Stream {
stream: BufReader<TcpStream>,
options: SessionOptions,
_forwarding_stream: Option<TcpStream>,
}
impl Stream {
pub(crate) fn store_forwarded(&mut self, stream: TcpStream) {
self._forwarding_stream = Some(stream);
}
}
impl private::SessionStyle for Stream {
fn new(options: SessionOptions) -> impl Future<Output = crate::Result<Self>>
where
Self: Sized,
{
async {
Ok(Self {
stream: BufReader::new(
TcpStream::connect(format!("127.0.0.1:{}", options.samv3_tcp_port)).await?,
),
options,
_forwarding_stream: None,
})
}
}
fn write_command(&mut self, command: &[u8]) -> impl Future<Output = crate::Result<()>> {
async { self.stream.write_all(command).await.map_err(From::from) }
}
fn read_command(&mut self) -> impl Future<Output = crate::Result<String>> {
async {
let mut response = String::new();
self.stream.read_line(&mut response).await.map(|_| response).map_err(From::from)
}
}
fn create_session(&self) -> String {
match &self.options.destination {
DestinationKind::Transient => format!(
"SESSION CREATE \
STYLE=STREAM \
ID={} \
DESTINATION=TRANSIENT \
SIGNATURE_TYPE=7 \
i2cp.leaseSetEncType=4\n",
self.options.nickname
),
DestinationKind::Persistent { private_key } => format!(
"SESSION CREATE \
STYLE=STREAM \
ID={} \
DESTINATION={private_key} \
SIGNATURE_TYPE=7 \
i2cp.leaseSetEncType=4\n",
self.options.nickname
),
}
}
}
impl SessionStyle for Stream {}