Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(bin) : max_values Macro for CLI args parsing #5379

Merged
merged 8 commits into from
Nov 10, 2023
Merged
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
36 changes: 35 additions & 1 deletion bin/reth/src/args/types.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
//! Additional helper types for CLI parsing.

use std::{fmt, str::FromStr};
use std::{fmt, num::ParseIntError, str::FromStr};

/// A helper type that maps `0` to `None` when parsing CLI arguments.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
Expand Down Expand Up @@ -36,6 +36,28 @@ impl FromStr for ZeroAsNone {
}
}

/// A helper type for parsing "max" as `u32::MAX`.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct MaxU32(pub u32);

impl fmt::Display for MaxU32 {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}", self.0)
}
}

impl FromStr for MaxU32 {
type Err = ParseIntError;

fn from_str(s: &str) -> Result<Self, Self::Err> {
if s == "max" {
Ok(MaxU32(u32::MAX))
} else {
s.parse::<u32>().map(MaxU32)
}
}
}

#[cfg(test)]
mod tests {
use super::*;
Expand All @@ -46,4 +68,16 @@ mod tests {
assert_eq!(val, ZeroAsNone(None));
assert_eq!(val.unwrap_or_max(), u64::MAX);
}

#[test]
fn test_max_parse() {
let val = "max".parse::<MaxU32>().unwrap();
assert_eq!(val, MaxU32(u32::MAX));
}

#[test]
fn test_number_parse() {
let val = "123".parse::<MaxU32>().unwrap();
assert_eq!(val, MaxU32(123));
}
}