Skip to main content

sparrow/cli/
mod.rs

1// Copyright [2020] [Donatien Criaud]
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//       http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15mod commands;
16
17use crate::core;
18use commands::{Command, GetCommand, InsertCommand, PopCommand};
19use std::error;
20use std::io;
21
22pub struct Cli<'a> {
23  engine: &'a mut core::Sparrow,
24}
25
26impl Cli<'_> {
27  pub fn new(engine: &'_ mut core::Sparrow) -> Cli {
28    Cli { engine }
29  }
30}
31
32impl Cli<'_> {
33  pub fn run(&mut self) -> Result<(), Box<dyn error::Error>> {
34    loop {
35      let mut input = String::new();
36      io::stdin().read_line(&mut input)?;
37
38      let input: Vec<&str> = input.trim().split(' ').collect();
39      if let Some(command_type) = input.get(0) {
40        let command_args: Vec<&str> = input[1..].to_vec();
41        let result = match *command_type {
42          "insert" => InsertCommand::new(command_args).execute(&mut self.engine),
43          "get" => GetCommand::new(command_args).execute(&mut self.engine),
44          "pop" => PopCommand::new(command_args).execute(&mut self.engine),
45          _ => Box::new("Woops, this command does not exists"),
46        };
47        println!("{}", result);
48      }
49    }
50  }
51}