1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54
use std::{any::Any, fmt, io};
// TODO: Look into why this works!
pub trait AToAny: 'static {
fn as_any(&self) -> &dyn Any;
}
impl<T: 'static> AToAny for T {
fn as_any(&self) -> &dyn Any {
self
}
}
/// Interface for creating new commands
///
/// Defines io::Stdout as the default generic type
///
/// # Examples
///
/// ```rust
/// // CommandHandler that prints out help message
/// use std::io;
/// use std::io::Write;
/// use cmd::command_handler::CommandHandler;
///
/// #[derive(Debug, Default)]
/// pub struct Help;
///
/// impl CommandHandler for Help {
/// fn execute(&self, _stdout: &mut io::Stdout, _args: String) -> usize {
/// writeln!(_stdout, "Help message").unwrap();
/// 1
/// }
/// }
///
/// /// CommandHandler that prints out a greeting
/// #[derive(Debug, Default)]
/// pub struct Greet;
///
/// impl<W: io::Write> CommandHandler<W> for Greet {
/// fn execute(&self, _stdout: &mut W, _args: String) -> usize {
/// match _args.len() {
/// 0 => _stdout.write(format!("Hello, {}!", _args).as_bytes()).unwrap(),
/// _ => _stdout.write(b"Hello!").unwrap(),
/// };
/// 1
/// }
/// }
/// ```
pub trait CommandHandler<W = io::Stdout>: fmt::Debug + AToAny {
/// Required method to execute a command
fn execute(&self, _stdout: &mut W, _args: String) -> usize;
}