Skip to content
Open
Show file tree
Hide file tree
Changes from all 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
4 changes: 4 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,10 @@ All significant changes to this software be documented in this file.

## Unreleased

### New features

* Added `RoundMode`, `ParseOptions`, and `ByteSize::parse_with` for selecting ceil, floor, half-ceil, half-floor, or half-even rounding of fractional byte counts. Standard parsing uses the default options with half-ceil rounding.

### Bug fixes

* Parse arbitrarily precise fractional byte sizes without double rounding or false overflow.
Expand Down
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ This crate provides multiple semantic wrappers and utilities for byte size repre

* `#![no_std]`-capable, no heap allocation, and no runtime dependencies by default.
* `ByteSize<T>` wrappers over supported unsigned integer base types, with `BSize` as the `usize` alias and `BSize8`, `BSize16`, `BSize32`, and `BSize64` aliases for fixed-width base types.
* `FromStr` impl for `ByteSize`, allowing for parsing string size representations like "1.5 KiB" and "521 TB".
* `FromStr` impl for `ByteSize`, allowing for parsing string size representations like "1.5 KiB" and "521 TB". Fractional values default to half-ceil rounding, and the supported rounding modes can be selected explicitly with `ByteSize::parse_with` and `ParseOptions`.
* Exact `Display` impl for `ByteSize`, rendering the underlying byte count in base bytes (e.g., "1572864 B").
* Configurable, approximate human-readable formatting in both binary (e.g., "1.5 MiB") and decimal (e.g., "1.6 MB") styles.
* Optional `serde` support for binary and human-readable format.
Expand Down
4 changes: 4 additions & 0 deletions bsize/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -53,5 +53,9 @@ toml = { version = "1.1.2" }
harness = false
name = "parse"

[[bench]]
harness = false
name = "parse_with"

[lints]
workspace = true
69 changes: 69 additions & 0 deletions bsize/benches/parse_with.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
// Copyright 2026 FastLabs Developers
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

use std::fmt;

use bsize::BSize64;
use bsize::ParseError;
use bsize::ParseOptions;
use bsize::RoundMode;

#[derive(Clone, Copy)]
struct ParseWithCase {
name: &'static str,
mode: RoundMode,
}

impl fmt::Display for ParseWithCase {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(self.name)
}
}

const CASES: [ParseWithCase; 5] = [
ParseWithCase {
name: "ceil",
mode: RoundMode::Ceil,
},
ParseWithCase {
name: "floor",
mode: RoundMode::Floor,
},
ParseWithCase {
name: "half-ceil",
mode: RoundMode::HalfCeil,
},
ParseWithCase {
name: "half-floor",
mode: RoundMode::HalfFloor,
},
ParseWithCase {
name: "half-even",
mode: RoundMode::HalfEven,
},
];

const HIGH_PRECISION_BINARY: &str =
"0.0000000000000000004336808689942017736029811203479766845703125 EiB";

fn main() {
divan::main();
}

#[divan::bench(args = CASES, sample_size = 1024)]
fn parse_with(case: ParseWithCase) -> Result<BSize64, ParseError> {
let mut options = ParseOptions::default();
options.round_mode = divan::black_box(case.mode);
BSize64::parse_with(divan::black_box(HIGH_PRECISION_BINARY), options)
}
43 changes: 42 additions & 1 deletion bsize/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,8 @@
//! the `usize` alias and [`BSize8`], [`BSize16`], [`BSize32`], and [`BSize64`] as shorter aliases
//! for fixed-width base types.
//! * `FromStr` impl for `ByteSize`, allowing for parsing string size representations like "1.5 KiB"
//! and "521 TB".
//! and "521 TB". Fractional values default to half-ceil rounding, and all [`RoundMode`] variants
//! can be selected explicitly with [`ByteSize::parse_with`] and [`ParseOptions`].
//! * Exact [`core::fmt::Display`] impl for [`ByteSize`], rendering the underlying byte count in
//! base bytes (e.g., "1572864 B").
//! * Configurable, approximate human-readable formatting in both binary (e.g., "1.5 MiB") and
Expand Down Expand Up @@ -133,6 +134,8 @@ pub use self::display::DisplayScale;
pub use self::display::DisplayUnitSystem;
pub use self::display::display;
pub use self::parse::ParseError;
pub use self::parse::ParseOptions;
pub use self::parse::RoundMode;
pub use self::traits::BaseByteSize;
pub use self::traits::ExaByteSize;
pub use self::traits::GigaByteSize;
Expand All @@ -147,6 +150,44 @@ pub use self::traits::TeraByteSize;
/// the exact underlying byte count. Its standard [`core::fmt::Display`] implementation renders
/// that exact count in base bytes. Use [`ByteSize::display`] for configurable, approximate
/// human-readable formatting.
///
/// # Parsing and rounding
///
/// Parsing applies the unit multiplier before rounding the resulting value once to a whole number
/// of bytes. The standard [`core::str::FromStr`] implementation uses [`RoundMode::HalfCeil`]: the
/// nearest whole byte is selected, and a value exactly halfway between two byte counts is rounded
/// toward the larger byte count. Use [`ByteSize::parse_with`] and [`ParseOptions`] to select
/// another mode.
///
/// Decimal fractions are evaluated exactly without first converting them to floating point.
/// Overflow is checked after rounding, both against `u64` and against the integer type backing the
/// parsed [`ByteSize`].
///
/// ```
/// use bsize::BSize8;
/// use bsize::BSize64;
/// use bsize::ParseError;
/// use bsize::ParseOptions;
/// use bsize::RoundMode;
///
/// assert_eq!(BSize64::b(0), "0.499 B".parse().unwrap());
/// assert_eq!(BSize64::b(1), "0.5 B".parse().unwrap());
/// assert_eq!(BSize64::b(1_235), "1.2345 kB".parse().unwrap());
/// let mut options = ParseOptions::default();
/// options.round_mode = RoundMode::HalfEven;
/// assert_eq!(
/// BSize64::b(2),
/// BSize64::parse_with("2.5 B", options).unwrap(),
/// );
///
/// // The rounded result fits in u8.
/// assert_eq!(BSize8::b(255), "255.4 B".parse().unwrap());
/// // The rounded result does not.
/// assert_eq!(
/// ParseError::Overflow,
/// "255.5 B".parse::<BSize8>().unwrap_err(),
/// );
/// ```
#[derive(Default, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct ByteSize<T: BaseByteSize>(T);

Expand Down
Loading