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 1 commit
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
67 changes: 59 additions & 8 deletions bin/reth/src/args/types.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,19 +2,28 @@

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

/// A helper type that maps `0` to `None` when parsing CLI arguments.
/// A helper type that maps `u32::MAX` to `None` when parsing CLI arguments.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct ZeroAsNone(pub Option<u64>);
pub struct MaxAsNone(pub Option<u32>);
DoTheBestToGetTheBest marked this conversation as resolved.
Show resolved Hide resolved

impl ZeroAsNone {
impl MaxAsNone {
/// Returns the inner value.
pub const fn new(value: u64) -> Self {
pub const fn new(value: u32) -> Self {
Self(Some(value))
}

/// Returns the inner value or `u64::MAX` if `None`.
pub fn unwrap_or_max(self) -> u64 {
self.0.unwrap_or(u64::MAX)
/// Returns the inner value or `u32::MAX` if `None`.
pub fn unwrap_or_max(self) -> u32 {
self.0.unwrap_or(u32::MAX)
}
}

impl fmt::Display for MaxAsNone {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self.0 {
Some(value) => write!(f, "{}", value),
None => write!(f, "max"),
}
}
}

Expand All @@ -26,7 +35,6 @@ impl fmt::Display for ZeroAsNone {
}
}
}

impl FromStr for ZeroAsNone {
type Err = std::num::ParseIntError;

Expand All @@ -36,6 +44,42 @@ impl FromStr for ZeroAsNone {
}
}

/// A helper type that maps `0` to `None` when parsing CLI arguments.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct ZeroAsNone(pub Option<u64>);

impl ZeroAsNone {
/// Returns the inner value.
pub const fn new(value: u64) -> Self {
Self(Some(value))
}

/// Returns the inner value or `u64::MAX` if `None`.
pub fn unwrap_or_max(self) -> u64 {
self.0.unwrap_or(u64::MAX)
}
}

impl FromStr for MaxAsNone {
type Err = std::num::ParseIntError;

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

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

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