]>
Commit | Line | Data |
---|---|---|
923072b8 FG |
1 | // Note: this requires the `cargo` feature |
2 | ||
04454e1e | 3 | use std::ops::RangeInclusive; |
04454e1e | 4 | |
923072b8 | 5 | use clap::{arg, command}; |
04454e1e FG |
6 | |
7 | fn main() { | |
8 | let matches = command!() | |
923072b8 FG |
9 | .arg( |
10 | arg!(<PORT>) | |
11 | .help("Network port to use") | |
12 | .value_parser(port_in_range), | |
13 | ) | |
04454e1e FG |
14 | .get_matches(); |
15 | ||
16 | // Note, it's safe to call unwrap() because the arg is required | |
923072b8 FG |
17 | let port: u16 = *matches |
18 | .get_one::<u16>("PORT") | |
04454e1e FG |
19 | .expect("'PORT' is required and parsing will fail if its missing"); |
20 | println!("PORT = {}", port); | |
21 | } | |
923072b8 FG |
22 | |
23 | const PORT_RANGE: RangeInclusive<usize> = 1..=65535; | |
24 | ||
25 | fn port_in_range(s: &str) -> Result<u16, String> { | |
26 | let port: usize = s | |
27 | .parse() | |
28 | .map_err(|_| format!("`{}` isn't a port number", s))?; | |
29 | if PORT_RANGE.contains(&port) { | |
30 | Ok(port as u16) | |
31 | } else { | |
32 | Err(format!( | |
33 | "Port not in range {}-{}", | |
34 | PORT_RANGE.start(), | |
35 | PORT_RANGE.end() | |
36 | )) | |
37 | } | |
38 | } |