hq9_plus_rs/
lib.rs

1use std::io::{self, Write};
2
3pub fn run_shell() {
4    let mut accumulator: u64 = 0;
5
6    loop {
7        print!(">>> ");
8        io::stdout().flush().expect("Error flushing stdout");
9
10        let input = read_line();
11
12        if !input.is_empty() {
13            run(&mut accumulator, &input)
14        }
15    }
16}
17
18pub fn run_once(code: &str) {
19    let mut accumulator: u64 = 0;
20
21    run(&mut accumulator, code);
22}
23
24fn run(accumulator: &mut u64, code: &str) {
25    let tokens: Vec<_> = code
26        .split("")
27        .map(str::to_lowercase)
28        .filter(|x| x != "" && x != " ")
29        .collect();
30
31    for token in tokens {
32        match token.as_str() {
33            "h" => println!("Hello, sailor!"),
34            "q" => println!("{}", code),
35            "9" => {
36                for x in (3..=99).rev() {
37                    println!(
38                        "{0} bottles of root beer on the wall, \
39                         {0} bottles of root beer. Take one down, pass it around. \
40                         {1} bottles of root beer on the wall.",
41                        x,
42                        x - 1
43                    )
44                }
45                println!(
46                    "2 bottles of root beer on the wall, \
47                     2 bottles of root beer. Take one down, pass it around. \
48                     1 bottle of root beer on the wall.\n\
49                     1 bottle of root beer on the wall, \
50                     1 bottle of root beer. Take one down, pass it around. \
51                     Now there are no bottles of root beer on the wall."
52                );
53            }
54            "+" => *accumulator += 1,
55            _ => {
56                println!("Invalid character in sequence!");
57                break;
58            }
59        }
60    }
61}
62
63fn read_line() -> String {
64    let mut input = String::new();
65    io::stdin()
66        .read_line(&mut input)
67        .expect("Error reading stdin");
68    input.trim().to_owned()
69}