summary refs log tree commit diff
path: root/src/commands.rs
diff options
context:
space:
mode:
Diffstat (limited to 'src/commands.rs')
-rw-r--r--src/commands.rs56
1 files changed, 56 insertions, 0 deletions
diff --git a/src/commands.rs b/src/commands.rs
new file mode 100644
index 0000000..56cc853
--- /dev/null
+++ b/src/commands.rs
@@ -0,0 +1,56 @@
+#![forbid(unsafe_code)]
+use crate::error::*;
+
+use std::collections::HashMap;
+use std::ops::Deref;
+
+
+pub struct Command<M: Mode + ?Sized> {
+  name: String,
+  pub implementation: fn(mode: Box<M>, params: &[&str])
+    -> Result<Option<Box<dyn Mode>>>,
+}
+
+
+pub struct CommandMap<M: Mode + ?Sized>(HashMap<String, Command<M>>);
+
+impl<M: Mode> CommandMap<M> {
+  pub fn new() -> CommandMap<M> {
+    CommandMap(HashMap::new())
+  }
+
+  pub fn get(self: &Self, name: &str) -> Option<&Command<M>> {
+    self.0.get(name)
+  }
+
+  pub fn insert(self: &mut Self, command: Command<M>)
+    -> Result<()>
+  {
+    let name = command.name.to_string();
+
+    let _ = self.0.insert(name, command);
+
+    Ok(())
+  }
+}
+
+
+pub trait Mode {
+  fn prompt_text(&self) -> Result<&str>;
+  fn dispatch(self: Box<Self>, params: &[&str])
+    -> Result<Option<Box<dyn Mode>>>;
+}
+
+impl<M: Mode> Command<M> {
+  pub fn new(name: impl Deref<Target=str>,
+             implementation: fn(mode: Box<M>, params: &[&str])
+                               -> Result<Option<Box<dyn Mode>>>)
+    -> Self
+  {
+    Command {
+      name: name.to_string(),
+      implementation: implementation,
+    }
+  }
+}
+