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