summary refs log tree commit diff
path: root/examples
diff options
context:
space:
mode:
authorIrene Knapp <ireneista@irenes.space>2024-03-12 22:06:24 -0700
committerIrene Knapp <ireneista@irenes.space>2024-03-12 22:06:24 -0700
commitf25a79763b9ae493598230a109eb0788def17199 (patch)
treedfcee3742e7086985c7392944b0b98308c89b2c7 /examples
parent7be9acd0bb08901c9fdfa45b694b7d3d5a594e70 (diff)
separate the main from the library, move it to an example HEAD main
Change-Id: I3478f222ee4b24d9d1796f0f58986186119bc2f7
Diffstat (limited to 'examples')
-rw-r--r--examples/line-input/error.rs40
-rw-r--r--examples/line-input/main.rs63
2 files changed, 103 insertions, 0 deletions
diff --git a/examples/line-input/error.rs b/examples/line-input/error.rs
new file mode 100644
index 0000000..88e2795
--- /dev/null
+++ b/examples/line-input/error.rs
@@ -0,0 +1,40 @@
+#![forbid(unsafe_code)]
+
+use line_input::error::TerminalError;
+
+pub type Result<T> = std::result::Result<T, Error>;
+
+#[derive(Debug)]
+pub enum Error {
+  IO(std::io::Error),
+  Terminal(TerminalError),
+}
+
+impl std::error::Error for Error { }
+
+impl std::fmt::Display for Error {
+  fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+    match self {
+      Error::IO(e) => e.fmt(f),
+      Error::Terminal(e) => e.fmt(f),
+    }
+  }
+}
+
+impl From<()> for Error {
+  fn from(_: ()) -> Error {
+    unreachable!()
+  }
+}
+
+impl From<std::io::Error> for Error {
+  fn from(e: std::io::Error) -> Error {
+    Error::IO(e)
+  }
+}
+
+impl From<TerminalError> for Error {
+  fn from(e: TerminalError) -> Error {
+    Error::Terminal(e)
+  }
+}
diff --git a/examples/line-input/main.rs b/examples/line-input/main.rs
new file mode 100644
index 0000000..5da00fe
--- /dev/null
+++ b/examples/line-input/main.rs
@@ -0,0 +1,63 @@
+#![forbid(unsafe_code)]
+use crate::error::Result;
+use line_input::{Input, Terminal};
+
+use std::process;
+use tokio::io::{self, AsyncWriteExt};
+
+pub mod error;
+
+
+#[tokio::main]
+async fn main() -> Result<()> {
+  let result = repl().await;
+  process::exit(match result {
+    Ok(()) => 0,
+    Err(ref e) => {
+      eprintln!("{}", e);
+      1
+    }
+  })
+}
+
+
+async fn repl() -> Result<()> {
+  println!("Hello, terminal!");
+
+  let mut terminal = Terminal::init(io::stdin())?;
+
+  loop {
+    prompt().await?;
+
+    let input = terminal.handle_input().await?;
+
+    match input {
+      Input::String(string) => {
+        println!("{:?} {}", string, string.len());
+        execute(&string).await?
+      },
+      Input::End => break,
+    }
+
+    break;
+  }
+
+  terminal.cleanup()?;
+
+  Ok(())
+}
+
+
+async fn prompt() -> Result<()> {
+  let mut stdout = io::stdout();
+  stdout.write_all("\n$ ".as_bytes()).await?;
+  stdout.flush().await?;
+
+  Ok(())
+}
+
+
+async fn execute(_input: &str) -> Result<()> {
+  Ok(())
+}
+