1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419
//! clap number parsers.
//!
//! This crate contains functions to validate and parse numerical values from
//! strings provided by [clap].
//!
//! * `maybe_hex`
//! Validates an unsigned integer value that can be base-10 or base-16.
//! * `maybe_hex_range`
//! Validates an unsigned integer value that can be base-10 or base-16 within a range.
//! * `number_range`
//! Validate a signed or unsigned integer value.
//! * `si_number`
//! Validate a signed or unsigned integer value with a metric prefix.
//! * `si_number_range`
//! Validate a signed or unsigned integer value with a metric prefix within a range.
//!
//! [clap]: https://github.com/clap-rs/clap
#![deny(missing_docs)]
use core::{iter, str::FromStr};
use num_traits::identities::Zero;
use num_traits::{sign, CheckedAdd, CheckedMul, CheckedSub, Num};
fn check_range<T: Ord + std::fmt::Display>(val: T, min: T, max: T) -> Result<T, String>
where
T: FromStr,
<T as FromStr>::Err: std::fmt::Display,
{
if val > max {
Err(format!("exceeds maximum of {max}"))
} else if val < min {
Err(format!("less than minimum of {min}"))
} else {
Ok(val)
}
}
/// Validate a signed or unsigned integer value.
///
/// # Arguments
///
/// * `s` - String to parse.
/// * `min` - Minimum value, inclusive.
/// * `max` - Maximum value, inclusive.
///
/// # Example
///
/// This allows for a number of cents to be passed in the range of 0-99
/// (inclusive).
///
/// ```
/// use clap::Parser;
/// use clap_num::number_range;
///
/// fn less_than_100(s: &str) -> Result<u8, String> {
/// number_range(s, 0, 99)
/// }
///
/// #[derive(Parser)]
/// struct Change {
/// #[clap(long, value_parser=less_than_100)]
/// cents: u8,
/// }
/// # let args = Change::parse_from(&["", "--cents", "99"]);
/// # assert_eq!(args.cents, 99);
/// ```
///
/// To run this example run `cargo run --example change`, giving arguments to
/// the program after `--`, for example:
///
/// ```text
/// $ cargo run --example change -- --cents 99
/// Change: 99 cents
/// ```
///
/// ## Error Messages
///
/// Values that are not numbers will show an error message similar to this:
///
/// ```text
/// error: Invalid value for '--cents <cents>': invalid digit found in string
/// ```
///
/// Values resulting in integer overflow will show an error message similar to this:
///
/// ```text
/// error: Invalid value for '--cents <cents>': number too large to fit in target type
/// ```
///
/// Values exceeding the limits will show an error message similar to this:
///
/// ```text
/// error: Invalid value for '--cents <cents>': exceeds maximum of 99
/// ```
pub fn number_range<T: Ord + PartialOrd + std::fmt::Display>(
s: &str,
min: T,
max: T,
) -> Result<T, String>
where
T: FromStr,
<T as FromStr>::Err: std::fmt::Display,
{
debug_assert!(min <= max, "minimum of {min} exceeds maximum of {max}");
let val = s.parse::<T>().map_err(stringify)?;
check_range(val, min, max)
}
static OVERFLOW_MSG: &str = "number too large to fit in target type";
// helper for mapping errors to strings
fn stringify<T: std::fmt::Display>(e: T) -> String {
format!("{e}")
}
#[derive(Copy, Clone)]
enum SiPrefix {
Yotta,
Zetta,
Exa,
Peta,
Tera,
Giga,
Mega,
Kilo,
}
impl SiPrefix {
fn from_char(symbol: char) -> Option<Self> {
match symbol {
'Y' => Some(Self::Yotta),
'Z' => Some(Self::Zetta),
'E' => Some(Self::Exa),
'P' => Some(Self::Peta),
'T' => Some(Self::Tera),
'G' => Some(Self::Giga),
'M' => Some(Self::Mega),
'k' | 'K' => Some(Self::Kilo),
_ => None,
}
}
fn multiplier(&self) -> u128 {
match self {
SiPrefix::Yotta => 1_000_000_000_000_000_000_000_000,
SiPrefix::Zetta => 1_000_000_000_000_000_000_000,
SiPrefix::Exa => 1_000_000_000_000_000_000,
SiPrefix::Peta => 1_000_000_000_000_000,
SiPrefix::Tera => 1_000_000_000_000,
SiPrefix::Giga => 1_000_000_000,
SiPrefix::Mega => 1_000_000,
SiPrefix::Kilo => 1_000,
}
}
fn digits(&self) -> usize {
match self {
SiPrefix::Yotta => 24,
SiPrefix::Zetta => 21,
SiPrefix::Exa => 18,
SiPrefix::Peta => 15,
SiPrefix::Tera => 12,
SiPrefix::Giga => 9,
SiPrefix::Mega => 6,
SiPrefix::Kilo => 3,
}
}
}
fn parse_post<T>(mut post: String, digits: usize) -> Result<T, String>
where
<T as FromStr>::Err: std::fmt::Display,
T: PartialOrd + FromStr,
{
if let Some(zeros) = digits.checked_sub(post.len()) {
post.extend(iter::repeat('0').take(zeros));
post.parse::<T>().map_err(stringify)
} else {
Err(String::from("not an integer"))
}
}
/// Validate a signed or unsigned integer value with a [metric prefix].
///
/// This can accept strings with the (case sensitive) SI symbols.
///
/// | Symbol | Name | Value |
/// |--------|-------|-----------------------------------|
/// | Y | yotta | 1_000_000_000_000_000_000_000_000 |
/// | Z | zetta | 1_000_000_000_000_000_000_000 |
/// | E | exa | 1_000_000_000_000_000_000 |
/// | P | peta | 1_000_000_000_000_000 |
/// | T | tera | 1_000_000_000_000 |
/// | G | giga | 1_000_000_000 |
/// | M | mega | 1_000_000 |
/// | k | kilo | 1_000 |
///
/// The strings can be provided with a decimal, or using the SI symbol as the
/// decimal separator.
///
/// | String | Value |
/// |--------|-----------|
/// | 3k3 | 3300 |
/// | 3.3k | 3300 |
/// | 1M | 1_000_000 |
///
/// # Example
///
/// This allows for resistance value to be passed using SI symbols.
///
/// ```
/// use clap::Parser;
/// use clap_num::si_number;
///
/// #[derive(Parser)]
/// struct Args {
/// #[clap(short, long, value_parser=si_number::<u128>)]
/// resistance: u128,
/// }
/// # let args = Args::parse_from(&["", "--resistance", "1M1"]);
/// # assert_eq!(args.resistance, 1_100_000);
/// ```
///
/// To run this example use `cargo run --example resistance`, giving arguments
/// to the program after `--`, for example:
///
/// ```text
/// $ cargo run --example resistance -- --resistance 1M1
/// Resistance: 1100000 ohms
/// ```
///
/// [metric prefix]: https://en.wikipedia.org/wiki/Metric_prefix
pub fn si_number<T>(s: &str) -> Result<T, String>
where
<T as TryFrom<u128>>::Error: std::fmt::Display,
<T as FromStr>::Err: std::fmt::Display,
T: CheckedAdd,
T: CheckedMul,
T: CheckedSub,
T: FromStr,
T: PartialOrd,
T: TryFrom<u128>,
T: Zero,
{
// contains SI symbol
if let Some(si_prefix_index) = s.find(|c| SiPrefix::from_char(c).is_some()) {
let si_prefix = SiPrefix::from_char(s.as_bytes()[si_prefix_index] as char).unwrap();
let multiplier: T = T::try_from(si_prefix.multiplier()).map_err(|_| OVERFLOW_MSG)?;
let (pre_si, post_si) = s.split_at(si_prefix_index);
let post_si = &post_si[1..];
if pre_si.is_empty() {
return Err("no value found before SI symbol".to_string());
}
// in the format of "1k234" for 1_234
let (pre, post) = if !post_si.is_empty() {
(
pre_si.parse::<T>().map_err(stringify)?,
parse_post(post_si.to_string(), si_prefix.digits())?,
)
// in the format of "1.234k" for 1_234
} else if let Some((pre_dec, post_dec)) = s.split_once('.') {
let mut post_dec: String = post_dec.to_string();
post_dec.pop(); // remove SI symbol
let post_dec = parse_post(post_dec, si_prefix.digits())?;
(pre_dec.parse::<T>().map_err(stringify)?, post_dec)
// no decimal
} else {
(pre_si.parse::<T>().map_err(stringify)?, T::zero())
};
let pre = pre.checked_mul(&multiplier).ok_or(OVERFLOW_MSG)?;
if pre >= T::zero() {
pre.checked_add(&post)
} else {
pre.checked_sub(&post)
}
.ok_or_else(|| OVERFLOW_MSG.to_string())
} else {
// no SI symbol, parse normally
s.chars()
.filter(|&c| c != '_')
.collect::<String>()
.parse::<T>()
.map_err(stringify)
}
}
/// Validate a signed or unsigned integer value with a [metric prefix] within
/// a range.
///
/// This combines [`si_number`] and [`number_range`], see the
/// documentation for those functions for details.
///
/// # Example
///
/// This extends the example in [`si_number`], and only allows a range of
/// resistances from 1k to 999.999k.
///
/// ```
/// use clap::Parser;
/// use clap_num::si_number_range;
///
/// fn kilo(s: &str) -> Result<u32, String> {
/// si_number_range(s, 1_000, 999_999)
/// }
///
/// #[derive(Parser)]
/// struct Args {
/// #[clap(short, long, value_parser=kilo)]
/// resistance: u32,
/// }
/// # let args = Args::parse_from(&["", "--resistance", "999k999"]);
/// # assert_eq!(args.resistance, 999_999);
/// ```
///
/// [metric prefix]: https://en.wikipedia.org/wiki/Metric_prefix
pub fn si_number_range<T: Ord + PartialOrd + std::fmt::Display>(
s: &str,
min: T,
max: T,
) -> Result<T, String>
where
<T as TryFrom<u128>>::Error: std::fmt::Display,
<T as FromStr>::Err: std::fmt::Display,
T: CheckedAdd,
T: CheckedMul,
T: CheckedSub,
T: FromStr,
T: PartialOrd,
T: TryFrom<u128>,
T: Zero,
{
let val = si_number(s)?;
check_range(val, min, max)
}
/// Validates an unsigned integer value that can be base-10 or base-16.
///
/// The number is assumed to be base-10 by default, it is parsed as hex if the
/// number is prefixed with `0x`, case insensitive.
///
/// # Example
///
/// This allows base-10 addresses to be passed normally, or base-16 values to
/// be passed when prefixed with `0x`.
///
/// ```
/// use clap::Parser;
/// use clap_num::maybe_hex;
///
/// #[derive(Parser)]
/// struct Args {
/// #[clap(short, long, value_parser=maybe_hex::<u32>)]
/// address: u32,
/// }
/// # let args = Args::parse_from(&["", "-a", "0x10"]);
/// # assert_eq!(args.address, 16);
/// ```
pub fn maybe_hex<T: Num + sign::Unsigned>(s: &str) -> Result<T, String>
where
<T as Num>::FromStrRadixErr: std::fmt::Display,
{
const HEX_PREFIX: &str = "0x";
const HEX_PREFIX_UPPER: &str = "0X";
const HEX_PREFIX_LEN: usize = HEX_PREFIX.len();
let result = if s.starts_with(HEX_PREFIX) || s.starts_with(HEX_PREFIX_UPPER) {
T::from_str_radix(&s[HEX_PREFIX_LEN..], 16)
} else {
T::from_str_radix(s, 10)
};
result.map_err(stringify)
}
/// Validates an unsigned integer value that can be base-10 or base-16 within
/// a range.
///
/// This combines [`maybe_hex`] and [`number_range`], see the
/// documentation for those functions for details.
///
/// # Example
///
/// This extends the example in [`maybe_hex`], and only allows a range of
/// addresses from `0x100` to `0x200`.
///
/// ```
/// use clap::Parser;
/// use clap_num::maybe_hex_range;
///
/// fn address_in_range(s: &str) -> Result<u32, String> {
/// maybe_hex_range(s, 0x100, 0x200)
/// }
///
/// #[derive(Parser)]
/// struct Args {
/// #[clap(short, long, value_parser=address_in_range)]
/// address: u32,
/// }
/// # let args = Args::parse_from(&["", "-a", "300"]);
/// # assert_eq!(args.address, 300);
/// ```
pub fn maybe_hex_range<T: Num + sign::Unsigned>(s: &str, min: T, max: T) -> Result<T, String>
where
<T as Num>::FromStrRadixErr: std::fmt::Display,
<T as FromStr>::Err: std::fmt::Display,
T: FromStr,
T: std::fmt::Display,
T: Ord,
{
let val = maybe_hex(s)?;
check_range(val, min, max)
}