Simple input parser
This commit is contained in:
65
src/main.rs
Normal file
65
src/main.rs
Normal file
@@ -0,0 +1,65 @@
|
||||
use std::io;
|
||||
use std::io::Write;
|
||||
use std::process::exit;
|
||||
|
||||
struct InputBuffer {
|
||||
buffer: Option<String>,
|
||||
}
|
||||
|
||||
impl InputBuffer {
|
||||
pub fn new() -> Self {
|
||||
return Self {
|
||||
buffer: None
|
||||
};
|
||||
}
|
||||
|
||||
pub(crate) fn print_prompt(&mut self) -> &mut Self {
|
||||
print!("db > ");
|
||||
if let Err(_) = io::stdout().flush() {
|
||||
panic!("could not print to stdout")
|
||||
}
|
||||
self
|
||||
}
|
||||
|
||||
pub(crate) fn read_input(&mut self) -> Result<&mut Self, String> {
|
||||
self.buffer = Some(String::new());
|
||||
match &mut self.buffer {
|
||||
Some(input_buffer) => {
|
||||
if let Ok(_) = io::stdin().read_line(input_buffer) {
|
||||
Ok(self)
|
||||
} else {
|
||||
Err(String::from("could not handle input"))
|
||||
}
|
||||
}
|
||||
_ => { Err(String::from("Could not initialize buffer")) }
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn parse(&self) {
|
||||
match &self.buffer {
|
||||
Some(command) => {
|
||||
match command.as_str().replace("\n", "").trim() {
|
||||
".exit" => {
|
||||
exit(0);
|
||||
}
|
||||
cmd => {
|
||||
println!("Could not handle command: {cmd}")
|
||||
}
|
||||
}
|
||||
}
|
||||
None => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
fn main() -> Result<(), String> {
|
||||
let mut input_buffer = InputBuffer::new();
|
||||
|
||||
loop {
|
||||
input_buffer
|
||||
.print_prompt()
|
||||
.read_input()?
|
||||
.parse()
|
||||
}
|
||||
}
|
Reference in New Issue
Block a user