Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- use std::io;
- use std::io::Write;
- use std::collections::HashMap;
- struct Employee {
- name: String,
- department: String,
- }
- enum Operation {
- Add(Employee),
- List(String),
- ListAll,
- }
- fn main() {
- let mut departments = HashMap::new();
- loop {
- let mut line = String::new();
- print!("> ");
- if let Err(_) = io::stdout().lock().flush() {
- println!("Could not flush stdout.");
- std::process::exit(-1);
- }
- io::stdin().read_line(&mut line).expect("Failed to read line");
- if line.len() == 0 || line.trim().to_lowercase() == "quit" {
- break;
- }
- match parse_cmd(line) {
- Ok(Operation::Add(employee)) => {
- let employees = departments.entry(employee.department.clone()).or_insert(Vec::new());
- if employees.contains(&employee.name) {
- println!("Employee {} already exists in {}", employee.name, employee.department);
- break;
- } else {
- employees.push(employee.name.clone());
- println!("Added {} to {}.", employee.name, employee.department);
- }
- }
- Ok(Operation::List(department)) => {
- if let Some(employees) = departments.get(&department) {
- for (i, employee) in employees.iter().enumerate() {
- println!("{}: {}", i, employee);
- }
- } else {
- println!("Could not find department {}", department);
- }
- }
- Ok(Operation::ListAll) => {
- for (k, v) in departments.iter() {
- println!("department {}:", k);
- for (i, employee) in v.iter().enumerate() {
- println!("{}: {}", i, employee);
- }
- println!();
- }
- }
- Err(msg) => {
- println!("Parse Error: {}", msg);
- },
- }
- }
- }
- fn parse_cmd(cmd: String) -> Result<Operation, String> {
- let cmd = cmd.to_lowercase();
- let mut tokens = cmd.split_whitespace();
- match tokens.next() {
- Some("add") => {
- // Add command
- if tokens.clone().count() < 3 {
- return Err(String::from("Invalid add command."));
- }
- let employee_name;
- let department;
- // Employee name
- employee_name = tokens.next().expect("Getting next token failed").to_string();
- if let Some(to) = tokens.next() {
- if to != "to" {
- return Err(String::from("expected keyword \"to\""));
- }
- }
- // department name
- department = tokens.next().expect("Getting next token failed").to_string();
- Ok(Operation::Add(Employee {
- name: employee_name,
- department: department,
- }))
- },
- Some("list") => {
- // List command
- if tokens.clone().count() < 1 {
- return Err(String::from("List what?"));
- }
- let arg = tokens.next().expect("Getting next token failed").to_string();
- if arg == "all" {
- Ok(Operation::ListAll)
- } else {
- Ok(Operation::List(arg))
- }
- },
- Some(s) => {
- Err(format!("\"{}\" is an invalid command.", s))
- },
- None => Err(String::from("No command given")),
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement