use core::future::Future;
use crate::base::channel::{Channel, SelectResult};
use crate::base::destination::{self, DestinationError};
use crate::base::error::Error;
use crate::base::session::Session;
fn write_destination(buf: &mut [u8], command: &str) -> Result<usize, DestinationError> {
destination::write_destination(buf, &[b"shell:", command.as_bytes()], &[])
}
pub struct Shell<'a, S> {
channel: Channel<'a, S>,
}
impl<'a, S: Session> Shell<'a, S> {
pub async fn read(&mut self, buf: &mut [u8]) -> Result<usize, Error<S::IoError>> {
self.channel.read(buf).await
}
pub async fn write_stdin(&mut self, data: &[u8]) -> Result<(), Error<S::IoError>> {
self.channel.write(data).await
}
pub async fn select<F: Future>(
&mut self,
buf: &mut [u8],
interrupt: F,
) -> Result<SelectResult<F::Output>, Error<S::IoError>> {
self.channel.select(buf, interrupt).await
}
pub async fn close(self) -> Result<(), Error<S::IoError>> {
self.channel.close().await
}
}
pub async fn open<'a, S: Session>(
session: &'a mut S,
command: &str,
dest_buf: &mut [u8],
) -> Result<Shell<'a, S>, Error<S::IoError>> {
let dest_len = write_destination(dest_buf, command)?;
let channel = session.open(&dest_buf[..dest_len]).await?;
Ok(Shell { channel })
}
pub async fn exec<S: Session>(
session: &mut S,
command: &str,
buf: &mut [u8],
) -> Result<usize, Error<S::IoError>> {
let dest_len = write_destination(buf, command)?;
let channel = session.open(&buf[..dest_len]).await?;
let mut shell = Shell { channel };
let mut tail = 0;
loop {
if tail >= buf.len() {
return Err(Error::ReceiveBufferFull);
}
match shell.read(&mut buf[tail..]).await {
Ok(n) => tail += n,
Err(Error::ChannelClosed) => {
let _ = shell.close().await;
return Ok(tail);
}
Err(e) => return Err(e),
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn destination_empty_command() {
let mut buf = [0u8; 32];
let n = write_destination(&mut buf, "").unwrap();
assert_eq!(&buf[..n], b"shell:\0");
}
#[test]
fn destination_with_command() {
let mut buf = [0u8; 32];
let n = write_destination(&mut buf, "ls /sdcard").unwrap();
assert_eq!(&buf[..n], b"shell:ls /sdcard\0");
}
#[test]
fn destination_buffer_exact_fit() {
let mut buf = [0u8; 8];
let n = write_destination(&mut buf, "x").unwrap();
assert_eq!(&buf[..n], b"shell:x\0");
}
#[test]
fn destination_buffer_too_small() {
let mut buf = [0u8; 7];
assert_eq!(
write_destination(&mut buf, "x"),
Err(DestinationError::TooLong)
);
}
}