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 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599
//! `parse-size` is an accurate, customizable, allocation-free library for //! parsing byte size into integer. //! //! ```rust //! use parse_size::parse_size; //! //! assert_eq!(parse_size("0.2 MiB"), Ok(209715)); //! assert_eq!(parse_size("14.2e+8"), Ok(14_2000_0000)); //! ``` //! //! # Features //! //! Supports both binary and decimal based prefix up to exabytes. //! //! ```rust //! # use parse_size::parse_size; //! assert_eq!(parse_size("1 B"), Ok(1)); //! assert_eq!(parse_size("1 KiB"), Ok(1 << 10)); //! assert_eq!(parse_size("1 MiB"), Ok(1 << 20)); //! assert_eq!(parse_size("1 GiB"), Ok(1 << 30)); //! assert_eq!(parse_size("1 TiB"), Ok(1 << 40)); //! assert_eq!(parse_size("1 PiB"), Ok(1 << 50)); //! assert_eq!(parse_size("1 EiB"), Ok(1 << 60)); //! assert_eq!(parse_size("1 KB"), Ok(1_000)); //! assert_eq!(parse_size("1 MB"), Ok(1_000_000)); //! assert_eq!(parse_size("1 GB"), Ok(1_000_000_000)); //! assert_eq!(parse_size("1 TB"), Ok(1_000_000_000_000)); //! assert_eq!(parse_size("1 PB"), Ok(1_000_000_000_000_000)); //! assert_eq!(parse_size("1 EB"), Ok(1_000_000_000_000_000_000)); //! ``` //! //! Numbers can be fractional and/or in scientific notation. //! `parse-size` can accurately parse the input using the full 64-bit precision. //! //! ```rust //! # use parse_size::parse_size; //! assert_eq!(parse_size("2.999999999999999999e18"), Ok(2999999999999999999)); //! assert_eq!(parse_size("3.000000000000000001 EB"), Ok(3000000000000000001)); //! ``` //! //! The unit is case-insensitive. The "B" suffix is also optional. //! //! ```rust //! # use parse_size::parse_size; //! assert_eq!(parse_size("5gb"), Ok(5_000_000_000)); //! assert_eq!(parse_size("2ki"), Ok(2048)); //! ``` //! //! Fractional bytes are allowed, and rounded to nearest integer. //! //! ```rust //! # use parse_size::parse_size; //! assert_eq!(parse_size("0.333333 KB"), Ok(333)); //! assert_eq!(parse_size("2.666666 KB"), Ok(2667)); //! ``` //! //! Underscores and spaces in the numbers are ignored to support digit grouping. //! //! ```rust //! # use parse_size::parse_size; //! assert_eq!(parse_size(" 69_420_000"), Ok(69_420_000)); //! ``` //! //! Conventional units (KB, GB, ...) can be configured to use the binary system. //! //! ```rust //! use parse_size::Config; //! //! let cfg = Config::new().with_binary(); //! assert_eq!(cfg.parse_size("1 KB"), Ok(1024)); //! assert_eq!(cfg.parse_size("1 KiB"), Ok(1024)); //! assert_eq!(cfg.parse_size("1 MB"), Ok(1048576)); //! assert_eq!(cfg.parse_size("1 MiB"), Ok(1048576)); //! ``` //! //! # Integration examples //! //! Use with `structopt` v0.3: //! //! ```rust,ignore //! use structopt::StructOpt; //! use parse_size::parse_size; //! //! #[derive(StructOpt)] //! pub struct Opt { //! #[structopt(long, parse(try_from_str = parse_size))] //! pub size: u64, //! } //! //! let opt = Opt::from_iter(&["./app", "--size", "2.5 K"]); //! assert_eq!(opt.size, 2500); //! ``` #![cfg_attr(not(feature = "std"), no_std)] use core::{convert::TryFrom, fmt}; /// The system to use when parsing prefixes like "KB" and "GB". #[derive(Copy, Clone, PartialEq, Eq, Debug)] pub enum UnitSystem { /// Use powers of 1000 for prefixes. Parsing "1 KB" returns 1000. Decimal, /// Use powers of 1024 for prefixes. Parsing "1 KB" returns 1024. Binary, } impl UnitSystem { /// Obtains the power factor for the given prefix character. /// /// Returns None if the input is not a valid prefix. /// /// The only valid prefixes are K, M, G, T, P and E. The higher powers Z and /// Y exceed the `u64` range and thus considered invalid. fn factor(self, prefix: u8) -> Option<u64> { Some(match (self, prefix) { (Self::Decimal, b'k') | (Self::Decimal, b'K') => 1_000, (Self::Decimal, b'm') | (Self::Decimal, b'M') => 1_000_000, (Self::Decimal, b'g') | (Self::Decimal, b'G') => 1_000_000_000, (Self::Decimal, b't') | (Self::Decimal, b'T') => 1_000_000_000_000, (Self::Decimal, b'p') | (Self::Decimal, b'P') => 1_000_000_000_000_000, (Self::Decimal, b'e') | (Self::Decimal, b'E') => 1_000_000_000_000_000_000, (Self::Binary, b'k') | (Self::Binary, b'K') => 1_u64 << 10, (Self::Binary, b'm') | (Self::Binary, b'M') => 1_u64 << 20, (Self::Binary, b'g') | (Self::Binary, b'G') => 1_u64 << 30, (Self::Binary, b't') | (Self::Binary, b'T') => 1_u64 << 40, (Self::Binary, b'p') | (Self::Binary, b'P') => 1_u64 << 50, (Self::Binary, b'e') | (Self::Binary, b'E') => 1_u64 << 60, _ => return None, }) } } /// How to deal with the "B" suffix. #[derive(Copy, Clone, PartialEq, Eq, Debug)] pub enum ByteSuffix { /// The "B" suffix must never appear. Parsing a string with the "B" suffix /// causes [`Error::InvalidDigit`] error. Deny, /// The "B" suffix is optional. Allow, /// The "B" suffix is required. Parsing a string without the "B" suffix /// causes [`Error::InvalidDigit`] error. Require, } /// Configuration of the parser. #[derive(Clone, Debug)] pub struct Config { unit_system: UnitSystem, default_factor: u64, byte_suffix: ByteSuffix, } impl Config { /// Creates a new parser configuration. pub const fn new() -> Self { Self { unit_system: UnitSystem::Decimal, default_factor: 1, byte_suffix: ByteSuffix::Allow, } } /// Changes the configuration's unit system. /// /// The default system is decimal (powers of 1000). pub const fn with_unit_system(mut self, unit_system: UnitSystem) -> Self { self.unit_system = unit_system; self } /// Changes the configuration to use the binary unit system, which are /// defined to be powers of 1024. /// /// # Examples /// /// ```rust /// use parse_size::Config; /// /// let cfg = Config::new().with_binary(); /// assert_eq!(cfg.parse_size("1 KB"), Ok(1024)); /// assert_eq!(cfg.parse_size("1 KiB"), Ok(1024)); /// assert_eq!(cfg.parse_size("1 MB"), Ok(1048576)); /// assert_eq!(cfg.parse_size("1 MiB"), Ok(1048576)); /// ``` pub const fn with_binary(self) -> Self { self.with_unit_system(UnitSystem::Binary) } /// Changes the configuration to use the decimal unit system, which are /// defined to be powers of 1000. This is the default setting. /// /// # Examples /// /// ```rust /// use parse_size::Config; /// /// let cfg = Config::new().with_decimal(); /// assert_eq!(cfg.parse_size("1 KB"), Ok(1000)); /// assert_eq!(cfg.parse_size("1 KiB"), Ok(1024)); /// assert_eq!(cfg.parse_size("1 MB"), Ok(1000000)); /// assert_eq!(cfg.parse_size("1 MiB"), Ok(1048576)); /// ``` pub const fn with_decimal(self) -> Self { self.with_unit_system(UnitSystem::Decimal) } /// Changes the default factor when a byte unit is not provided. /// /// This is useful for keeping backward compatibility when migrating from an /// old user interface expecting non-byte input. /// /// The default value is 1. /// /// # Examples /// /// If the input is a pure number, we treat that as mebibytes. /// /// ```rust /// use parse_size::Config; /// /// let cfg = Config::new().with_default_factor(1048576); /// assert_eq!(cfg.parse_size("10"), Ok(10485760)); /// assert_eq!(cfg.parse_size("0.5"), Ok(524288)); /// assert_eq!(cfg.parse_size("128 B"), Ok(128)); // explicit units overrides the default /// assert_eq!(cfg.parse_size("16 KiB"), Ok(16384)); /// ``` pub const fn with_default_factor(mut self, factor: u64) -> Self { self.default_factor = factor; self } /// Changes the handling of the "B" suffix. /// /// Normally, the character "B" at the end of the input is optional. This /// can be changed to deny or require such suffix. /// /// Power prefixes (K, Ki, M, Mi, ...) are not affected. /// /// # Examples /// /// Deny the suffix. /// /// ```rust /// use parse_size::{ByteSuffix, Config, Error}; /// /// let cfg = Config::new().with_byte_suffix(ByteSuffix::Deny); /// assert_eq!(cfg.parse_size("123"), Ok(123)); /// assert_eq!(cfg.parse_size("123k"), Ok(123000)); /// assert_eq!(cfg.parse_size("123B"), Err(Error::InvalidDigit)); /// assert_eq!(cfg.parse_size("123KB"), Err(Error::InvalidDigit)); /// ``` /// /// Require the suffix. /// /// ```rust /// use parse_size::{ByteSuffix, Config, Error}; /// /// let cfg = Config::new().with_byte_suffix(ByteSuffix::Require); /// assert_eq!(cfg.parse_size("123"), Err(Error::InvalidDigit)); /// assert_eq!(cfg.parse_size("123k"), Err(Error::InvalidDigit)); /// assert_eq!(cfg.parse_size("123B"), Ok(123)); /// assert_eq!(cfg.parse_size("123KB"), Ok(123000)); /// ``` pub const fn with_byte_suffix(mut self, byte_suffix: ByteSuffix) -> Self { self.byte_suffix = byte_suffix; self } /// Parses the string input into the number of bytes it represents. /// /// # Examples /// /// ```rust /// use parse_size::{Config, Error}; /// /// let cfg = Config::new().with_binary(); /// assert_eq!(cfg.parse_size("10 KB"), Ok(10240)); /// assert_eq!(cfg.parse_size("20000"), Ok(20000)); /// assert_eq!(cfg.parse_size("^_^"), Err(Error::InvalidDigit)); /// ``` pub fn parse_size<T: AsRef<[u8]>>(&self, src: T) -> Result<u64, Error> { parse_size_inner(self, src.as_ref()) } } impl Default for Config { fn default() -> Self { Self::new() } } // TODO: Switch to IntErrorKind once it is stable. /// The error returned when parse failed. #[derive(Copy, Clone, PartialEq, Eq, Debug)] #[non_exhaustive] pub enum Error { /// The input contains no numbers. Empty, /// An invalid character is encountered while parsing. InvalidDigit, /// The resulting number is too large to fit into a `u64`. PosOverflow, } impl fmt::Display for Error { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.write_str(match self { Self::Empty => "cannot parse integer from empty string", Self::InvalidDigit => "invalid digit found in string", Self::PosOverflow => "number too large to fit in target type", }) } } #[cfg(feature = "std")] impl std::error::Error for Error {} /// Parses the string input into the number of bytes it represents using the /// default configuration. /// /// Equivalent to calling [`Config::parse_size()`] with the default /// configuration ([`Config::new()`]). /// /// # Examples /// /// ```rust /// use parse_size::{parse_size, Error}; /// /// assert_eq!(parse_size("10 KB"), Ok(10000)); /// assert_eq!(parse_size("20000"), Ok(20000)); /// assert_eq!(parse_size("0.2 MiB"), Ok(209715)); /// assert_eq!(parse_size("^_^"), Err(Error::InvalidDigit)); /// ``` pub fn parse_size<T: AsRef<[u8]>>(src: T) -> Result<u64, Error> { parse_size_inner(&Config::new(), src.as_ref()) } fn parse_size_inner(cfg: &Config, mut src: &[u8]) -> Result<u64, Error> { // if it ends with 'B' the default factor is always 1. let mut multiply = cfg.default_factor; match src { [init @ .., b'b'] | [init @ .., b'B'] => { if cfg.byte_suffix == ByteSuffix::Deny { return Err(Error::InvalidDigit); } src = init; multiply = 1; } _ => { if cfg.byte_suffix == ByteSuffix::Require { return Err(Error::InvalidDigit); } } } // if it ends with an 'i' we always use binary prefix. let mut unit_system = cfg.unit_system; match src { [init @ .., b'i'] | [init @ .., b'I'] => { src = init; unit_system = UnitSystem::Binary; } _ => {} } if let [init @ .., prefix] = src { if let Some(f) = unit_system.factor(*prefix) { multiply = f; src = init; } } #[derive(Copy, Clone, PartialEq)] enum Ps { Empty, Integer, IntegerOverflow, Fraction, FractionOverflow, PosExponent, NegExponent, } macro_rules! append_digit { ($before:expr, $method:ident, $digit_char:expr) => { $before .checked_mul(10) .and_then(|v| v.$method(($digit_char - b'0').into())) }; } let mut mantissa = 0_u64; let mut fractional_exponent = 0; let mut exponent = 0_i32; let mut state = Ps::Empty; for b in src { match (state, *b) { (Ps::Integer, b'0'..=b'9') | (Ps::Empty, b'0'..=b'9') => { if let Some(m) = append_digit!(mantissa, checked_add, *b) { mantissa = m; state = Ps::Integer; } else { if *b >= b'5' { mantissa += 1; } state = Ps::IntegerOverflow; fractional_exponent += 1; } } (Ps::IntegerOverflow, b'0'..=b'9') => { fractional_exponent += 1; } (Ps::Fraction, b'0'..=b'9') => { if let Some(m) = append_digit!(mantissa, checked_add, *b) { mantissa = m; fractional_exponent -= 1; } else { if *b >= b'5' { mantissa += 1; } state = Ps::FractionOverflow; } } (Ps::FractionOverflow, b'0'..=b'9') => {} (Ps::PosExponent, b'0'..=b'9') => { if let Some(e) = append_digit!(exponent, checked_add, *b) { exponent = e; } else { return Err(Error::PosOverflow); } } (Ps::NegExponent, b'0'..=b'9') => { if let Some(e) = append_digit!(exponent, checked_sub, *b) { exponent = e; } } (_, b'_') | (_, b' ') | (Ps::PosExponent, b'+') => {} (Ps::Integer, b'e') | (Ps::Integer, b'E') | (Ps::Fraction, b'e') | (Ps::Fraction, b'E') | (Ps::IntegerOverflow, b'e') | (Ps::IntegerOverflow, b'E') | (Ps::FractionOverflow, b'e') | (Ps::FractionOverflow, b'E') => state = Ps::PosExponent, (Ps::PosExponent, b'-') => state = Ps::NegExponent, (Ps::Integer, b'.') => state = Ps::Fraction, (Ps::IntegerOverflow, b'.') => state = Ps::FractionOverflow, _ => return Err(Error::InvalidDigit), } } if state == Ps::Empty { return Err(Error::Empty); } let exponent = exponent.saturating_add(fractional_exponent); if exponent >= 0 { let power = 10_u64 .checked_pow(exponent as u32) .ok_or(Error::PosOverflow)?; let multiply = multiply.checked_mul(power).ok_or(Error::PosOverflow)?; mantissa.checked_mul(multiply).ok_or(Error::PosOverflow) } else if exponent >= -38 { let power = 10_u128.pow(-exponent as u32); let result = (u128::from(mantissa) * u128::from(multiply) + power / 2) / power; u64::try_from(result).map_err(|_| Error::PosOverflow) } else { // (2^128) * 1e-39 < 1, always, and thus saturate to 0. Ok(0) } } #[test] fn test_passes() { assert_eq!(parse_size("0"), Ok(0)); assert_eq!(parse_size("3"), Ok(3)); assert_eq!(parse_size("30"), Ok(30)); assert_eq!(parse_size("32"), Ok(32)); assert_eq!(parse_size("_5_"), Ok(5)); assert_eq!(parse_size("1 234 567"), Ok(1_234_567)); assert_eq!( parse_size("18_446_744_073_709_551_581"), Ok(18_446_744_073_709_551_581) ); assert_eq!( parse_size("18_446_744_073_709_551_615"), Ok(18_446_744_073_709_551_615) ); assert_eq!( parse_size("18_446_744_073_709_551_616"), Err(Error::PosOverflow) ); assert_eq!( parse_size("18_446_744_073_709_551_620"), Err(Error::PosOverflow) ); assert_eq!(parse_size("1kB"), Ok(1_000)); assert_eq!(parse_size("2MB"), Ok(2_000_000)); assert_eq!(parse_size("3GB"), Ok(3_000_000_000)); assert_eq!(parse_size("4TB"), Ok(4_000_000_000_000)); assert_eq!(parse_size("5PB"), Ok(5_000_000_000_000_000)); assert_eq!(parse_size("6EB"), Ok(6_000_000_000_000_000_000)); assert_eq!(parse_size("7 KiB"), Ok(7 << 10)); assert_eq!(parse_size("8 MiB"), Ok(8 << 20)); assert_eq!(parse_size("9 GiB"), Ok(9 << 30)); assert_eq!(parse_size("10 TiB"), Ok(10 << 40)); assert_eq!(parse_size("11 PiB"), Ok(11 << 50)); assert_eq!(parse_size("12 EiB"), Ok(12 << 60)); assert_eq!(parse_size("1mib"), Ok(1_048_576)); assert_eq!(parse_size("5k"), Ok(5000)); assert_eq!(parse_size("1.1 K"), Ok(1100)); assert_eq!(parse_size("1.2345 K"), Ok(1235)); assert_eq!(parse_size("1.2345m"), Ok(1_234_500)); assert_eq!(parse_size("5.k"), Ok(5000)); assert_eq!(parse_size("0.0025KB"), Ok(3)); assert_eq!( parse_size("3.141_592_653_589_793_238e"), Ok(3_141_592_653_589_793_238) ); assert_eq!( parse_size("18.446_744_073_709_551_615 EB"), Ok(18_446_744_073_709_551_615) ); assert_eq!( parse_size("18.446_744_073_709_551_616 EB"), Err(Error::PosOverflow) ); assert_eq!( parse_size("1.000_000_000_000_000_001 EB"), Ok(1_000_000_000_000_000_001) ); assert_eq!(parse_size("1e2 KIB"), Ok(102_400)); assert_eq!(parse_size("1E+6"), Ok(1_000_000)); assert_eq!(parse_size("1e-4 MiB"), Ok(105)); assert_eq!(parse_size("1.1e2"), Ok(110)); assert_eq!(parse_size("5.7E3"), Ok(5700)); assert_eq!(parse_size("20_000_000_000_000_000_000e-18"), Ok(20)); assert_eq!(parse_size("98_765_432_109_876_543_210e-16"), Ok(9877)); assert_eq!(parse_size("1e21"), Err(Error::PosOverflow)); assert_eq!(parse_size("0.01e21"), Ok(10_000_000_000_000_000_000)); assert_eq!( parse_size("3.333_333_333_333_333_333_333_333_333_333_333_333_333_333_333_333 EB"), Ok(3_333_333_333_333_333_333) ); assert_eq!(parse_size("2e+0_9"), Ok(2_000_000_000)); assert_eq!( parse_size("3e+66666666666666666666"), Err(Error::PosOverflow) ); assert_eq!(parse_size("4e-77777777777777777777"), Ok(0)); assert_eq!(parse_size("5e-88888888888888888888 EiB"), Ok(0)); assert_eq!( parse_size("123_456_789_012_345_678_901_234_567.890e-16"), Ok(12_345_678_901) ); assert_eq!(parse_size("0.1e-2147483648"), Ok(0)); assert_eq!(parse_size("184467440737095516150e-38EiB"), Ok(2)); } #[test] fn test_parse_errors() { assert_eq!(parse_size(""), Err(Error::Empty)); assert_eq!(parse_size("."), Err(Error::InvalidDigit)); assert_eq!(parse_size(".5k"), Err(Error::InvalidDigit)); assert_eq!(parse_size("k"), Err(Error::Empty)); assert_eq!(parse_size("kb"), Err(Error::Empty)); assert_eq!(parse_size("kib"), Err(Error::Empty)); assert_eq!(parse_size(" "), Err(Error::Empty)); assert_eq!(parse_size("__"), Err(Error::Empty)); assert_eq!(parse_size("a"), Err(Error::InvalidDigit)); assert_eq!(parse_size("-1"), Err(Error::InvalidDigit)); assert_eq!(parse_size("1,5"), Err(Error::InvalidDigit)); assert_eq!(parse_size("1e+f"), Err(Error::InvalidDigit)); assert_eq!(parse_size("1e0.5"), Err(Error::InvalidDigit)); assert_eq!(parse_size("1 ZiB"), Err(Error::InvalidDigit)); assert_eq!(parse_size("1 YiB"), Err(Error::InvalidDigit)); } #[test] fn test_config() { let cfg = Config::new().with_binary().with_default_factor(1_048_576); assert_eq!(cfg.parse_size("3.5"), Ok(3_670_016)); assert_eq!(cfg.parse_size("35 B"), Ok(35)); assert_eq!(cfg.parse_size("5K"), Ok(5120)); }