0

I'm currently restricted to clap 4.0.9 and I have the following code:

#[derive(Debug, clap::Parser)]
pub struct RunCmd {
    #[clap(long, default_value_t = 7000)]
    pub port: u16,
}

I want to create a function that validates the port that is passed like this:

fn validate_port(p: &str) -> Result<u16, String> {
    let port = p.parse::<u16>().map_err(|_| "Invalid port number")?;
    if port >= 1024 {
        Ok(port)
    } else {
        Err("Port number must be between 1024 and 65535".to_owned())
    }
}

is there a way to call validate_port to validate the port?

Stargateur
  • 24,473
  • 8
  • 65
  • 91
ezio
  • 359
  • 2
  • 13
  • 1
    Does [this](https://docs.rs/clap/4.0.9/clap/_derive/_tutorial/index.html#validated-values) help? – isaactfa May 11 '23 at 18:20
  • 1
    That seems like a really weird validation rule. Port numbers below 1024 are valid. – cdhowie May 11 '23 at 18:25
  • @cdhowie, yes but they usually require root privileges which might not be desirable for OPs usecase – cafce25 May 11 '23 at 19:17
  • @cafce25 Yes, I know they are privileged ports, but it seems silly and unnecessary to deny them at the configuration level. The OS can deny the bind attempt if the process is not privileged. – cdhowie May 11 '23 at 19:22
  • @isaactfa can you provide an example how can that be used in my case? – ezio May 11 '23 at 19:30
  • @cdhowie those are reservred port number, best practices is to avoid them, dont want to confuse users of the program more by seeing uncommon port number – ezio May 11 '23 at 19:32
  • @ezio Hmm... best practice IMO is not foisting decisions upon your users when unnecessary. If I wanted to bind to a privileged port and found out that I couldn't because you made that decision for me, I wouldn't be very happy. – cdhowie May 11 '23 at 20:05
  • @cdhowie make a pull request and we'll change it, but the mainstream narative according to the majority is that those ports are reserved – ezio May 11 '23 at 21:00
  • I'm not sure who "we" is or what project this is for, I'm just indicating that needless validation is... needless. (Nobody said those ports were not privileged, so I'm not sure why that's being brought up.) – cdhowie May 11 '23 at 21:05
  • "in our project" its needed, thanks for the advice, care to help regarding the actual problem? – ezio May 11 '23 at 21:13

1 Answers1

0

Thanks to the comment of @isaactfa this is how it worked:

#[clap(long, default_value_t = 7000, value_parse = validate_port)]
ezio
  • 359
  • 2
  • 13