From f25a79763b9ae493598230a109eb0788def17199 Mon Sep 17 00:00:00 2001 From: Irene Knapp Date: Tue, 12 Mar 2024 22:06:24 -0700 Subject: separate the main from the library, move it to an example Change-Id: I3478f222ee4b24d9d1796f0f58986186119bc2f7 --- examples/line-input/error.rs | 40 ++++++++++++++++++++++++++++ examples/line-input/main.rs | 63 ++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 103 insertions(+) create mode 100644 examples/line-input/error.rs create mode 100644 examples/line-input/main.rs (limited to 'examples') 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 = std::result::Result; + +#[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 for Error { + fn from(e: std::io::Error) -> Error { + Error::IO(e) + } +} + +impl From 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(()) +} + -- cgit 1.4.1