1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
use crate::algorithms::{self, Algorithm};
const ALGORITHM_ARG: &str = "ALGORITHM";
const LENGTH_OPT: &str = "LENGTH";
const ORDER_OPT: &str = "ORDER";
const SPEED_OPT: &str = "SPEED";
const LIST_OPT: &str = "LIST";
pub struct Options {
pub algorithm: Box<dyn Algorithm + Send>,
pub length: u32,
pub order: Order,
pub speed: f64,
}
pub enum Order {
Sorted,
Reversed,
Shuffled,
}
pub fn parse_options() -> Options {
use clap::*;
let mut algorithms = algorithms::all();
let algorithm_ids: Vec<&str> =
algorithms.keys().map(|s| &s as &str).collect();
let parser = app_from_crate!()
.setting(AppSettings::NextLineHelp)
.setting(AppSettings::ColoredHelp)
.arg(
Arg::with_name(LIST_OPT)
.long("list")
.help("lists all available algorithms"),
)
.arg(
Arg::with_name(LENGTH_OPT)
.short("l")
.long("length")
.help("Sets number of elements in the array")
.default_value("100"),
)
.arg(
Arg::with_name(ORDER_OPT)
.short("o")
.long("order")
.help("Sets order of elements in the array")
.possible_values(&["sorted", "reversed", "shuffled"])
.case_insensitive(true)
.default_value("shuffled"),
)
.arg(
Arg::with_name(ALGORITHM_ARG)
.help("Sets sorting algorithm")
.possible_values(&algorithm_ids)
.case_insensitive(true)
.required_unless(LIST_OPT),
)
.arg(
Arg::with_name(SPEED_OPT)
.short("s")
.long("speed")
.help("Sets animation speed")
.default_value("1.0"),
);
let matches = parser.get_matches();
if matches.is_present(LIST_OPT) {
println!("Available algorithms:");
for id in algorithm_ids {
println!("- {}", id);
}
use std::process;
process::exit(0);
}
Options {
algorithm: {
let id = matches.value_of(ALGORITHM_ARG).unwrap();
algorithms.remove(id).unwrap()
},
length: value_t_or_exit!(matches, LENGTH_OPT, u32),
order: match matches.value_of(ORDER_OPT).unwrap() {
"sorted" => Order::Sorted,
"reversed" => Order::Reversed,
"shuffled" => Order::Shuffled,
_ => unreachable!(),
},
speed: value_t_or_exit!(matches, SPEED_OPT, f64),
}
}