]> git.proxmox.com Git - rustc.git/blame - vendor/clap/examples/tutorial_builder/04_02_validate.rs
New upstream version 1.63.0+dfsg1
[rustc.git] / vendor / clap / examples / tutorial_builder / 04_02_validate.rs
CommitLineData
923072b8
FG
1// Note: this requires the `cargo` feature
2
04454e1e 3use std::ops::RangeInclusive;
04454e1e 4
923072b8 5use clap::{arg, command};
04454e1e
FG
6
7fn 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
23const PORT_RANGE: RangeInclusive<usize> = 1..=65535;
24
25fn 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}