bytesize-2.3.1/.cargo_vcs_info.json0000644000000001360000000000100126750ustar { "git": { "sha1": "01217417db306cf1bc7635fe036e21590e0e3eef" }, "path_in_vcs": "" }bytesize-2.3.1/.cspell.yml000064400000000000000000000000721046102023000135470ustar 00000000000000version: 0.2 words: - bytesize - quickcheck - serde bytesize-2.3.1/.github/dependabot.yml000064400000000000000000000003051046102023000156530ustar 00000000000000version: 2 updates: - package-ecosystem: github-actions directory: / schedule: interval: monthly - package-ecosystem: cargo directory: / schedule: interval: monthly bytesize-2.3.1/.github/workflows/ci.yml000064400000000000000000000030611046102023000162000ustar 00000000000000name: CI on: pull_request: types: [opened, synchronize, reopened, ready_for_review] merge_group: types: [checks_requested] push: branches: [master] permissions: contents: read concurrency: group: ${{ github.workflow }}-${{ github.ref }} cancel-in-progress: true env: CARGO_TERM_COLOR: always jobs: read_msrv: name: Read MSRV uses: actions-rust-lang/msrv/.github/workflows/msrv.yml@v0.1.0 rust: needs: read_msrv strategy: fail-fast: false matrix: os: - { name: Linux, runner: ubuntu-latest } - { name: macOS, runner: macos-latest } - { name: Windows, runner: windows-latest } toolchain: - { name: stable, version: stable } - { name: msrv, version: "${{ needs.read_msrv.outputs.msrv }}" } name: ${{ matrix.os.name }} / ${{ matrix.toolchain.name }} runs-on: ${{ matrix.os.runner }} steps: - uses: actions/checkout@v5 - name: Install Rust (${{ matrix.toolchain.name }}) uses: actions-rust-lang/setup-rust-toolchain@v1.15.2 with: toolchain: ${{ matrix.toolchain.version }} target: thumbv6m-none-eabi - name: Install just, nextest uses: taiki-e/install-action@v2.62.43 with: tool: just,nextest - name: Work around MSRV issues if: matrix.toolchain.name == 'msrv' run: just downgrade-for-msrv - name: Test run: just test - name: Build (no-std) if: matrix.toolchain.name == 'stable' run: just build-no-std bytesize-2.3.1/.github/workflows/coverage.yml000064400000000000000000000015511046102023000174020ustar 00000000000000name: Coverage on: push: branches: [master] permissions: contents: read concurrency: group: ${{ github.workflow }}-${{ github.ref }} cancel-in-progress: true jobs: coverage: runs-on: ubuntu-latest steps: - uses: actions/checkout@v5 - name: Install Rust uses: actions-rust-lang/setup-rust-toolchain@v1.15.2 with: components: llvm-tools-preview - name: Install just & cargo-llvm-cov uses: taiki-e/install-action@v2.62.43 with: tool: just,cargo-llvm-cov - name: Generate code coverage run: just test-coverage-codecov - name: Upload coverage to Codecov uses: codecov/codecov-action@v5.5.1 with: fail_ci_if_error: true files: codecov.json slug: bytesize-rs/bytesize token: ${{ secrets.CODECOV_TOKEN }} bytesize-2.3.1/.github/workflows/lint.yml000064400000000000000000000035441046102023000165610ustar 00000000000000name: Lint on: pull_request: types: [opened, synchronize, reopened, ready_for_review] permissions: contents: read concurrency: group: ${{ github.workflow }}-${{ github.ref }} cancel-in-progress: true jobs: clippy: runs-on: ubuntu-latest permissions: contents: read checks: write steps: - uses: actions/checkout@v5 - name: Install Rust uses: actions-rust-lang/setup-rust-toolchain@v1.15.2 with: components: clippy - name: Install just, cargo-hack uses: taiki-e/install-action@v2.62.43 with: tool: just,cargo-hack - name: Check with Clippy run: just clippy rustfmt: runs-on: ubuntu-latest steps: - uses: actions/checkout@v5 - name: Install Rust (nightly) uses: actions-rust-lang/setup-rust-toolchain@v1.15.2 with: toolchain: nightly components: rustfmt - name: Check with Rustfmt run: cargo fmt -- --check docs: runs-on: ubuntu-latest steps: - uses: actions/checkout@v5 - name: Install Rust (nightly) uses: actions-rust-lang/setup-rust-toolchain@v1.15.2 with: toolchain: nightly components: rust-docs - name: Check for broken intra-doc links env: RUSTDOCFLAGS: -D warnings run: cargo doc --workspace --no-deps --all-features sorted-deps: runs-on: ubuntu-latest steps: - uses: actions/checkout@v5 - name: Install Rust uses: actions-rust-lang/setup-rust-toolchain@v1.15.2 with: components: clippy - name: Install just, cargo-sort uses: taiki-e/install-action@v2.62.43 with: tool: just,cargo-sort - name: Check dependency requirements are sorted lexicographically run: cargo sort --workspace --check bytesize-2.3.1/.github/workflows/release.yml000064400000000000000000000017511046102023000172310ustar 00000000000000name: Release on: push: branches: [master] permissions: contents: write pull-requests: write id-token: write jobs: release: name: Release runs-on: ubuntu-latest steps: - uses: actions/checkout@v5 with: fetch-depth: 0 - name: Install Rust uses: actions-rust-lang/setup-rust-toolchain@v1.15.2 - name: release-plz uses: MarcoIeni/release-plz-action@v0.5.118 env: GITHUB_TOKEN: ${{ github.token }} id: release-plz - name: Bump changelog versions if: ${{ steps.release-plz.outputs.prs_created == 'true' }} env: GH_TOKEN: ${{ github.token }} run: scripts/bump-changelogs '${{ steps.release-plz.outputs.pr }}' - name: Update release notes if: ${{ steps.release-plz.outputs.releases_created == 'true' }} env: GH_TOKEN: ${{ github.token }} run: scripts/update-release-notes '${{ steps.release-plz.outputs.releases }}' bytesize-2.3.1/.gitignore000064400000000000000000000000251046102023000134520ustar 00000000000000target .idea .vscode bytesize-2.3.1/.prettierrc.yml000064400000000000000000000001301046102023000144430ustar 00000000000000overrides: - files: '*.md' options: proseWrap: never printWidth: 9999 bytesize-2.3.1/.release-plz.toml000064400000000000000000000003461046102023000146660ustar 00000000000000[workspace] changelog_update = false dependencies_update = false pr_draft = true pr_labels = ["release"] publish_all_features = true git_tag_name = "{{ package }}-v{{ version }}" git_release_name = "{{ package }}: v{{ version }}" bytesize-2.3.1/CHANGELOG.md000064400000000000000000000017541046102023000133050ustar 00000000000000# Changelog ## Unreleased ## 2.3.1 - Fix unit truncation in error strings. ## 2.3.0 - Add `Unit` enum. - Add `UnitParseError` type. ## 2.2.0 - Add `ByteSize::as_*()` methods to return equivalent sizes in KB, GiB, etc. ## 2.1.0 - Support parsing and formatting exabytes (EB) & exbibytes (EiB). - Migrate `serde` dependency to `serde_core`. ## 2.0.1 - Add support for precision in `Display` implementations. ## v2.0.0 - Add support for `no_std` targets. - Use IEC (binary) format by default with `Display`. - Use "kB" for SI unit. - Add `Display` type for customizing printed format. - Add `ByteSize::display()` method. - Implement `Sub` for `ByteSize`. - Implement `Sub>` for `ByteSize`. - Implement `SubAssign` for `ByteSize`. - Implement `SubAssign>` for `ByteSize`. - Reject parsing non-unit characters after whitespace. - Remove `ByteSize::to_string_as()` method. - Remove top-level `to_string()` method. - Remove top-level `B` constant. bytesize-2.3.1/Cargo.lock0000644000000326200000000000100106530ustar # This file is automatically @generated by Cargo. # It is not intended for manual editing. version = 3 [[package]] name = "aho-corasick" version = "1.1.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8e60d3430d3a69478ad0993f19238d2df97c507009a52b3c10addcd7f6bcb916" dependencies = [ "memchr", ] [[package]] name = "anstyle" version = "1.0.11" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "862ed96ca487e809f1c8e5a8447f6ee2cf102f846893800b20cebdf541fc6bbd" [[package]] name = "arbitrary" version = "1.4.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c3d036a3c4ab069c7b410a2ce876bd74808d2d0888a82667669f8e783a898bf1" [[package]] name = "bitflags" version = "2.9.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2261d10cca569e4643e526d8dc2e62e433cc8aba21ab764233731f8d369bf394" [[package]] name = "bytesize" version = "2.3.1" dependencies = [ "arbitrary", "divan", "quickcheck", "serde", "serde_core", "serde_json", "toml", ] [[package]] name = "cfg-if" version = "1.0.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2fd1289c04a9ea8cb22300a459a72a385d7c73d3259e2ed7dcb2af674838cfa9" [[package]] name = "clap" version = "4.5.47" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7eac00902d9d136acd712710d71823fb8ac8004ca445a89e73a41d45aa712931" dependencies = [ "clap_builder", ] [[package]] name = "clap_builder" version = "4.5.47" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2ad9bbf750e73b5884fb8a211a9424a1906c1e156724260fdae972f31d70e1d6" dependencies = [ "anstyle", "clap_lex", "terminal_size", ] [[package]] name = "clap_lex" version = "0.7.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b94f61472cee1439c0b966b47e3aca9ae07e45d070759512cd390ea2bebc6675" [[package]] name = "condtype" version = "1.3.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "baf0a07a401f374238ab8e2f11a104d2851bf9ce711ec69804834de8af45c7af" [[package]] name = "divan" version = "0.1.21" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a405457ec78b8fe08b0e32b4a3570ab5dff6dd16eb9e76a5ee0a9d9cbd898933" dependencies = [ "cfg-if", "clap", "condtype", "divan-macros", "libc", "regex-lite", ] [[package]] name = "divan-macros" version = "0.1.21" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9556bc800956545d6420a640173e5ba7dfa82f38d3ea5a167eb555bc69ac3323" dependencies = [ "proc-macro2", "quote", "syn", ] [[package]] name = "env_logger" version = "0.8.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a19187fea3ac7e84da7dacf48de0c45d63c6a76f9490dae389aead16c243fce3" dependencies = [ "log", "regex", ] [[package]] name = "equivalent" version = "1.0.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "877a4ace8713b0bcf2a4e7eec82529c029f1d0619886d18145fea96c3ffe5c0f" [[package]] name = "errno" version = "0.3.14" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb" dependencies = [ "libc", "windows-sys 0.61.0", ] [[package]] name = "getrandom" version = "0.2.16" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "335ff9f135e4384c8150d6f27c6daed433577f86b4750418338c01a1a2528592" dependencies = [ "cfg-if", "libc", "wasi", ] [[package]] name = "hashbrown" version = "0.15.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9229cfe53dfd69f0609a49f65461bd93001ea1ef889cd5529dd176593f5338a1" [[package]] name = "indexmap" version = "2.11.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "206a8042aec68fa4a62e8d3f7aa4ceb508177d9324faf261e1959e495b7a1921" dependencies = [ "equivalent", "hashbrown", ] [[package]] name = "itoa" version = "1.0.15" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4a5f13b858c8d314ee3e8f639011f7ccefe71f97f96e50151fb991f267928e2c" [[package]] name = "libc" version = "0.2.175" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6a82ae493e598baaea5209805c49bbf2ea7de956d50d7da0da1164f9c6d28543" [[package]] name = "linux-raw-sys" version = "0.11.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "df1d3c3b53da64cf5760482273a98e575c651a67eec7f77df96b5b642de8f039" [[package]] name = "log" version = "0.4.28" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "34080505efa8e45a4b816c349525ebe327ceaa8559756f0356cba97ef3bf7432" [[package]] name = "memchr" version = "2.7.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "32a282da65faaf38286cf3be983213fcf1d2e2a58700e808f83f4ea9a4804bc0" [[package]] name = "proc-macro2" version = "1.0.101" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "89ae43fd86e4158d6db51ad8e2b80f313af9cc74f5c0e03ccb87de09998732de" dependencies = [ "unicode-ident", ] [[package]] name = "quickcheck" version = "1.0.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "588f6378e4dd99458b60ec275b4477add41ce4fa9f64dcba6f15adccb19b50d6" dependencies = [ "env_logger", "log", "rand", ] [[package]] name = "quote" version = "1.0.40" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1885c039570dc00dcb4ff087a89e185fd56bae234ddc7f056a945bf36467248d" dependencies = [ "proc-macro2", ] [[package]] name = "rand" version = "0.8.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "34af8d1a0e25924bc5b7c43c079c942339d8f0a8b57c39049bef581b46327404" dependencies = [ "rand_core", ] [[package]] name = "rand_core" version = "0.6.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ec0be4795e2f6a28069bec0b5ff3e2ac9bafc99e6a9a7dc3547996c5c816922c" dependencies = [ "getrandom", ] [[package]] name = "regex" version = "1.11.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "23d7fd106d8c02486a8d64e778353d1cffe08ce79ac2e82f540c86d0facf6912" dependencies = [ "aho-corasick", "memchr", "regex-automata", "regex-syntax", ] [[package]] name = "regex-automata" version = "0.4.10" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6b9458fa0bfeeac22b5ca447c63aaf45f28439a709ccd244698632f9aa6394d6" dependencies = [ "aho-corasick", "memchr", "regex-syntax", ] [[package]] name = "regex-lite" version = "0.1.7" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "943f41321c63ef1c92fd763bfe054d2668f7f225a5c29f0105903dc2fc04ba30" [[package]] name = "regex-syntax" version = "0.8.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "caf4aa5b0f434c91fe5c7f1ecb6a5ece2130b02ad2a590589dda5146df959001" [[package]] name = "rustix" version = "1.1.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "cd15f8a2c5551a84d56efdc1cd049089e409ac19a3072d5037a17fd70719ff3e" dependencies = [ "bitflags", "errno", "libc", "linux-raw-sys", "windows-sys 0.61.0", ] [[package]] name = "ryu" version = "1.0.20" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "28d3b2b1366ec20994f1fd18c3c594f05c5dd4bc44d8bb0c1c632c8d6829481f" [[package]] name = "serde" version = "1.0.228" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9a8e94ea7f378bd32cbbd37198a4a91436180c5bb472411e48b5ec2e2124ae9e" dependencies = [ "serde_core", "serde_derive", ] [[package]] name = "serde_core" version = "1.0.228" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "41d385c7d4ca58e59fc732af25c3983b67ac852c1a25000afe1175de458b67ad" dependencies = [ "serde_derive", ] [[package]] name = "serde_derive" version = "1.0.228" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d540f220d3187173da220f885ab66608367b6574e925011a9353e4badda91d79" dependencies = [ "proc-macro2", "quote", "syn", ] [[package]] name = "serde_json" version = "1.0.145" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "402a6f66d8c709116cf22f558eab210f5a50187f702eb4d7e5ef38d9a7f1c79c" dependencies = [ "itoa", "memchr", "ryu", "serde", "serde_core", ] [[package]] name = "serde_spanned" version = "1.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "40734c41988f7306bb04f0ecf60ec0f3f1caa34290e4e8ea471dcd3346483b83" dependencies = [ "serde", ] [[package]] name = "syn" version = "2.0.106" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ede7c438028d4436d71104916910f5bb611972c5cfd7f89b8300a8186e6fada6" dependencies = [ "proc-macro2", "quote", "unicode-ident", ] [[package]] name = "terminal_size" version = "0.4.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "60b8cb979cb11c32ce1603f8137b22262a9d131aaa5c37b5678025f22b8becd0" dependencies = [ "rustix", "windows-sys 0.60.2", ] [[package]] name = "toml" version = "0.9.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "75129e1dc5000bfbaa9fee9d1b21f974f9fbad9daec557a521ee6e080825f6e8" dependencies = [ "indexmap", "serde", "serde_spanned", "toml_datetime", "toml_parser", "toml_writer", "winnow", ] [[package]] name = "toml_datetime" version = "0.7.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "bade1c3e902f58d73d3f294cd7f20391c1cb2fbcb643b73566bc773971df91e3" dependencies = [ "serde", ] [[package]] name = "toml_parser" version = "1.0.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b551886f449aa90d4fe2bdaa9f4a2577ad2dde302c61ecf262d80b116db95c10" dependencies = [ "winnow", ] [[package]] name = "toml_writer" version = "1.0.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "fcc842091f2def52017664b53082ecbbeb5c7731092bad69d2c63050401dfd64" [[package]] name = "unicode-ident" version = "1.0.19" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f63a545481291138910575129486daeaf8ac54aee4387fe7906919f7830c7d9d" [[package]] name = "wasi" version = "0.11.1+wasi-snapshot-preview1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ccf3ec651a847eb01de73ccad15eb7d99f80485de043efb2f370cd654f4ea44b" [[package]] name = "windows-link" version = "0.1.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "5e6ad25900d524eaabdbbb96d20b4311e1e7ae1699af4fb28c17ae66c80d798a" [[package]] name = "windows-link" version = "0.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "45e46c0661abb7180e7b9c281db115305d49ca1709ab8242adf09666d2173c65" [[package]] name = "windows-sys" version = "0.60.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f2f500e4d28234f72040990ec9d39e3a6b950f9f22d3dba18416c35882612bcb" dependencies = [ "windows-targets", ] [[package]] name = "windows-sys" version = "0.61.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e201184e40b2ede64bc2ea34968b28e33622acdbbf37104f0e4a33f7abe657aa" dependencies = [ "windows-link 0.2.0", ] [[package]] name = "windows-targets" version = "0.53.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d5fe6031c4041849d7c496a8ded650796e7b6ecc19df1a431c1a363342e5dc91" dependencies = [ "windows-link 0.1.3", "windows_aarch64_gnullvm", "windows_aarch64_msvc", "windows_i686_gnu", "windows_i686_gnullvm", "windows_i686_msvc", "windows_x86_64_gnu", "windows_x86_64_gnullvm", "windows_x86_64_msvc", ] [[package]] name = "windows_aarch64_gnullvm" version = "0.53.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "86b8d5f90ddd19cb4a147a5fa63ca848db3df085e25fee3cc10b39b6eebae764" [[package]] name = "windows_aarch64_msvc" version = "0.53.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c7651a1f62a11b8cbd5e0d42526e55f2c99886c77e007179efff86c2b137e66c" [[package]] name = "windows_i686_gnu" version = "0.53.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c1dc67659d35f387f5f6c479dc4e28f1d4bb90ddd1a5d3da2e5d97b42d6272c3" [[package]] name = "windows_i686_gnullvm" version = "0.53.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9ce6ccbdedbf6d6354471319e781c0dfef054c81fbc7cf83f338a4296c0cae11" [[package]] name = "windows_i686_msvc" version = "0.53.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "581fee95406bb13382d2f65cd4a908ca7b1e4c2f1917f143ba16efe98a589b5d" [[package]] name = "windows_x86_64_gnu" version = "0.53.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2e55b5ac9ea33f2fc1716d1742db15574fd6fc8dadc51caab1c16a3d3b4190ba" [[package]] name = "windows_x86_64_gnullvm" version = "0.53.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0a6e035dd0599267ce1ee132e51c27dd29437f63325753051e71dd9e42406c57" [[package]] name = "windows_x86_64_msvc" version = "0.53.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "271414315aff87387382ec3d271b52d7ae78726f5d44ac98b4f4030c91880486" [[package]] name = "winnow" version = "0.7.13" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "21a0236b59786fed61e2a80582dd500fe61f18b5dca67a4a067d0bc9039339cf" bytesize-2.3.1/Cargo.toml0000644000000041260000000000100106760ustar # THIS FILE IS AUTOMATICALLY GENERATED BY CARGO # # When uploading crates to the registry Cargo will automatically # "normalize" Cargo.toml files for maximal compatibility # with all versions of Cargo and also rewrite `path` dependencies # to registry (e.g., crates.io) dependencies. # # If you are reading this file be aware that the original Cargo.toml # will likely look very different (and much more reasonable). # See Cargo.toml.orig for the original contents. [package] edition = "2021" rust-version = "1.70" name = "bytesize" version = "2.3.1" authors = [ "Hyunsik Choi ", "MrCroxx ", "Rob Ede ", ] build = false autolib = false autobins = false autoexamples = false autotests = false autobenches = false description = "Semantic wrapper for byte count representations" readme = "README.md" keywords = [ "byte", "byte-size", "utility", "human-readable", "format", ] categories = [ "development-tools", "filesystem", "no-std", ] license = "Apache-2.0" repository = "https://github.com/bytesize-rs/bytesize" [package.metadata.cargo_check_external_types] allowed_external_types = [ "arbitrary::*", "serde_core::*", ] [package.metadata.docs.rs] all-features = true [features] arbitrary = ["dep:arbitrary"] default = ["std"] serde = ["dep:serde_core"] std = [] [lib] name = "bytesize" path = "src/lib.rs" [[example]] name = "ls" path = "examples/ls.rs" [[bench]] name = "display" path = "benches/display.rs" harness = false [dependencies.arbitrary] version = "1" optional = true [dependencies.serde_core] version = "1" optional = true [dev-dependencies.divan] version = "0.1" [dev-dependencies.quickcheck] version = "1" [dev-dependencies.serde] version = "1" features = ["derive"] [dev-dependencies.serde_json] version = "1" [dev-dependencies.toml] version = "0.9" [lints.rust.future-incompatible] level = "deny" priority = 0 [lints.rust.missing-docs] level = "warn" priority = 0 [lints.rust.nonstandard-style] level = "deny" priority = 0 [lints.rust.rust-2018-idioms] level = "deny" priority = 0 bytesize-2.3.1/Cargo.toml.orig000064400000000000000000000022501046102023000143530ustar 00000000000000[package] name = "bytesize" description = "Semantic wrapper for byte count representations" version = "2.3.1" authors = [ "Hyunsik Choi ", "MrCroxx ", "Rob Ede ", ] keywords = ["byte", "byte-size", "utility", "human-readable", "format"] categories = ["development-tools", "filesystem", "no-std"] repository = "https://github.com/bytesize-rs/bytesize" license = "Apache-2.0" edition = "2021" rust-version = "1.70" [package.metadata.cargo_check_external_types] allowed_external_types = ["arbitrary::*", "serde_core::*"] [package.metadata.docs.rs] all-features = true [features] default = ["std"] std = [] arbitrary = ["dep:arbitrary"] serde = ["dep:serde_core"] [dependencies] arbitrary = { version = "1", optional = true } serde_core = { version = "1", optional = true } [dev-dependencies] divan = "0.1" quickcheck = "1" serde = { version = "1", features = ["derive"] } serde_json = "1" toml = "0.9" [[bench]] name = "display" harness = false [lints.rust] rust-2018-idioms = { level = "deny" } future-incompatible = { level = "deny" } nonstandard-style = { level = "deny" } missing-docs = { level = "warn" } bytesize-2.3.1/LICENSE000064400000000000000000000261361046102023000125020ustar 00000000000000 Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "{}" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright {yyyy} {name of copyright owner} 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. bytesize-2.3.1/README.md000064400000000000000000000034221046102023000127450ustar 00000000000000## ByteSize [![crates.io](https://img.shields.io/crates/v/bytesize?label=latest)](https://crates.io/crates/bytesize) [![Documentation](https://docs.rs/bytesize/badge.svg?version=2.3.1)](https://docs.rs/bytesize/2.3.1) ![Version](https://img.shields.io/badge/rustc-1.70+-ab6000.svg) ![Apache 2.0 licensed](https://img.shields.io/crates/l/bytesize.svg)
[![Dependency Status](https://deps.rs/crate/bytesize/2.3.1/status.svg)](https://deps.rs/crate/bytesize/2.3.1) [![Download](https://img.shields.io/crates/d/bytesize.svg)](https://crates.io/crates/bytesize) `ByteSize` is a semantic wrapper for byte count representations. Features: - Pre-defined constants for various size units (e.g., B, Kb, Kib, Mb, Mib, Gb, Gib, ... PB). - `ByteSize` type which presents size units convertible to different size units. - Arithmetic operations for `ByteSize`. - `FromStr` impl for `ByteSize`, allowing for parsing string size representations like "1.5KiB" and "521TiB". - Serde support for binary and human-readable deserializers like JSON. ### Examples Construction using SI or IEC helpers. ```rust use bytesize::ByteSize; assert!(ByteSize::kib(4) > ByteSize::kb(4)); ``` Display as human-readable string. ```rust use bytesize::ByteSize; assert_eq!("518.0 GiB", ByteSize::gib(518).display().iec().to_string()); assert_eq!("556.2 GB", ByteSize::gib(518).display().si().to_string()); assert_eq!("518.0G", ByteSize::gib(518).display().iec_short().to_string()); ``` Arithmetic operations are supported. ```rust use bytesize::ByteSize; let plus = ByteSize::mb(1) + ByteSize::kb(100); println!("{plus}"); let minus = ByteSize::tb(1) - ByteSize::gb(4); assert_eq!(ByteSize::gb(996), minus); ``` bytesize-2.3.1/benches/display.rs000064400000000000000000000021411046102023000151050ustar 00000000000000#![allow(missing_docs)] use std::{env, fmt, hint::black_box}; struct ByteSizeAlwaysPad(bytesize::ByteSize); impl fmt::Display for ByteSizeAlwaysPad { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.pad(&self.0.display().to_string()) } } #[divan::bench] fn display_inner_display() { black_box(format!( "{}", black_box(bytesize::ByteSize::kib(42).display()), )); } #[divan::bench] fn display_bytesize_standard() { black_box(format!( "{}", black_box(bytesize::ByteSize::kib(42).display()), )); } #[divan::bench] fn display_bytesize_custom() { black_box(format!("|{:-^10}|", black_box(bytesize::ByteSize::kib(42)))); } #[divan::bench] fn display_always_pad_standard() { black_box(format!( "{}", black_box(ByteSizeAlwaysPad(bytesize::ByteSize::kib(42))), )); } #[divan::bench] fn display_always_pad_custom() { black_box(format!( "|{:-^10}|", black_box(ByteSizeAlwaysPad(bytesize::ByteSize::kib(42))), )); } fn main() { env::set_var("DIVAN_SAMPLE_COUNT", "1000"); divan::main(); } bytesize-2.3.1/codecov.yml000064400000000000000000000004171046102023000136340ustar 00000000000000comment: false coverage: status: project: default: threshold: 100% # make CI green patch: default: threshold: 100% # make CI green # ignore code coverage on following paths ignore: - "**/tests" - "**/benches" - "**/examples" bytesize-2.3.1/examples/ls.rs000064400000000000000000000012171046102023000142700ustar 00000000000000//! Emulates running `ls -la` in the terminal, showing human-readable file sizes and file names. use std::{fs, io}; fn main() -> io::Result<()> { let dir = fs::read_dir(".")?; for entry in dir { let entry = entry?; let md = entry.metadata()?; let file_name = entry.file_name(); let file_name = file_name.to_string_lossy(); if md.is_file() { let file_size = md.len(); let file_size = bytesize::ByteSize::b(file_size).display().iec_short(); println!("{file_size}\t{file_name}"); } else { println!("-\t{file_name}"); } } Ok(()) } bytesize-2.3.1/justfile000064400000000000000000000046131046102023000132410ustar 00000000000000_list: @just --list msrv := ``` cargo metadata --format-version=1 \ | jq -r 'first(.packages[] | select(.source == null and .rust_version)) | .rust_version' \ | sed -E 's/^1\.([0-9]{2})$/1\.\1\.0/' ``` msrv_rustup := "+" + msrv # Check project. [group("lint")] check: && clippy just --unstable --fmt --check # fd --hidden -e=toml --exec-batch taplo format --check # fd --hidden -e=toml --exec-batch taplo lint # fd --hidden --type=file -e=md -e=yml --exec-batch prettier --check cargo +nightly fmt -- --check # Format project. [group("lint")] fmt: just --unstable --fmt # fd --hidden -e=toml --exec-batch taplo format # fd --hidden --type=file -e=md -e=yml --exec-batch prettier --write cargo +nightly fmt # Update READMEs from crate root documentation. [group("lint")] update-readme: cargo rdme --force npx -y prettier --write README.md # Lint workspace with Clippy. [group("lint")] clippy: cargo clippy --workspace --all-targets --no-default-features cargo clippy --workspace --all-targets --all-features # Test workspace. [group("test")] test toolchain="": cargo {{ toolchain }} nextest run --workspace --no-default-features cargo {{ toolchain }} nextest run --workspace --all-features cargo {{ toolchain }} test --doc --workspace --all-features RUSTDOCFLAGS="-D warnings" cargo {{ toolchain }} doc --workspace --no-deps --all-features # Downgrade dev-dependencies necessary to run MSRV checks/tests. [private] downgrade-for-msrv: cargo update -p=divan --precise=0.1.15 cargo update -p=clap --precise=4.3.24 cargo update -p=clap_lex --precise=0.5.0 # Test workspace using MSRV. [group("test")] test-msrv: downgrade-for-msrv (test msrv_rustup) # Test workspace and generate Codecov coverage file [group("test")] test-coverage-codecov toolchain="": cargo {{ toolchain }} llvm-cov --workspace --all-features --codecov --output-path codecov.json # Test workspace and generate LCOV coverage file [group("test")] test-coverage-lcov toolchain="": cargo {{ toolchain }} llvm-cov --workspace --all-features --lcov --output-path lcov.info # Build crate for a no-std target. build-no-std: cargo build --target=thumbv6m-none-eabi --manifest-path=./ensure-no-std/Cargo.toml # Document crates in workspace. [group("docs")] doc *args: RUSTDOCFLAGS="--cfg=docsrs -Dwarnings" cargo +nightly doc --workspace --all-features {{ args }} bytesize-2.3.1/scripts/bump-changelogs000075500000000000000000000050431046102023000161570ustar 00000000000000#!/usr/bin/env bash # updates changelog version indicated by release-plz set -eEuo pipefail ### START HELPERS function bump_changelog_version() { local package_dir="$1" local version="$2" local cargo_manifest="${package_dir}/Cargo.toml" local current_version="$(sed -nE 's/^version ?= ?"([^"]+)"$/\1/ p' "$cargo_manifest" | head -n 1)" local changelog_file="${package_dir}/CHANGELOG.md" local change_chunk_file="$(mktemp)" local readme_file="${package_dir}/README.md" echo "${package_dir}/CHANGELOG.md | $current_version -> $version" # get changelog chunk and save to temp file cat "$changelog_file" | # skip up to unreleased heading sed '1,/Unreleased/ d' | # take up to previous version heading sed "/$current_version/ q" | # drop last line sed '$d' \ >"$change_chunk_file" # if word count of changelog chunk is 0 then insert filler changelog chunk if [[ "$(wc -w "$change_chunk_file" | awk '{ print $1 }')" == "0" ]]; then echo >"$change_chunk_file" echo "- No significant changes since \`$current_version\`." >>"$change_chunk_file" echo >>"$change_chunk_file" fi ( sed '/Unreleased/ q' "$changelog_file" # up to unreleased heading echo # blank line echo "## $version" # new version heading cat "$change_chunk_file" # previously unreleased changes sed "/$current_version/ q" "$changelog_file" | tail -n 1 # the previous version heading sed "1,/$current_version/ d" "$changelog_file" # everything after previous version heading ) >"$changelog_file.bak" mv "$changelog_file.bak" "$changelog_file" # update readme links if [ -f "$readme_file" ]; then sed -i.bak -E "s#([=/])$current_version([/)])#\1$version\2#g" "$readme_file" rm -f "${readme_file}.bak" fi } ### END HELPERS RELEASE_PLZ_PR_JSON="$1" specs="$(echo "$RELEASE_PLZ_PR_JSON" | jq -r '.releases[] | "\(.package_name):\(.version)"')" for spec in $specs; do name="$(echo "$spec" | cut -d: -f1)" version="$(echo "$spec" | cut -d: -f2)" bump_changelog_version "." "$version" done PR_NUMBER="$(echo "$RELEASE_PLZ_PR_JSON" | jq -r '.number')" # update release PR if one was created if [[ -n "$PR_NUMBER" ]]; then gh pr checkout "$PR_NUMBER" git add --all git commit -m "docs: update changelog versions" git push fi bytesize-2.3.1/scripts/update-release-notes000075500000000000000000000014611046102023000171320ustar 00000000000000#!/usr/bin/env bash # updates changelog version indicated by release-plz set -eEuo pipefail ### START HELPERS function update_release_notes() { local package_dir="$1" local version="$2" local tag="$3" local changelog_file="${package_dir}/CHANGELOG.md" echo "Updating $tag using $changelog_file" local notes="$(sed -n "/^## ${version}$/,/^## /p" "$changelog_file" | sed '1d;$d')" gh release edit "$tag" --notes="$notes" } ### END HELPERS RELEASE_PLZ_RELEASES_JSON="$1" specs="$(echo "$RELEASE_PLZ_RELEASES_JSON" | jq -r '.[] | "\(.package_name):\(.version):\(.tag)"')" for spec in $specs; do name="$(echo "$spec" | cut -d: -f1)" version="$(echo "$spec" | cut -d: -f2)" tag="$(echo "$spec" | cut -d: -f3)" update_release_notes "." "$version" "$tag" done bytesize-2.3.1/src/arbitrary.rs000064400000000000000000000004741046102023000146260ustar 00000000000000use arbitrary::{Arbitrary, Unstructured}; use crate::ByteSize; impl Arbitrary<'_> for ByteSize { fn arbitrary(u: &mut Unstructured<'_>) -> arbitrary::Result { Ok(ByteSize(u64::arbitrary(u)?)) } fn size_hint(depth: usize) -> (usize, Option) { u64::size_hint(depth) } } bytesize-2.3.1/src/display.rs000064400000000000000000000177661046102023000143100ustar 00000000000000use core::{fmt, write}; use crate::ByteSize; /// Format / style to use when displaying a [`ByteSize`]. #[derive(Debug, Clone, Copy)] pub(crate) enum Format { Iec, IecShort, Si, SiShort, } impl Format { fn unit(self) -> u64 { match self { Format::Iec | Format::IecShort => crate::KIB, Format::Si | Format::SiShort => crate::KB, } } fn unit_base(self) -> f64 { match self { Format::Iec | Format::IecShort => crate::LN_KIB, Format::Si | Format::SiShort => crate::LN_KB, } } fn unit_prefixes(self) -> &'static [u8] { match self { Format::Iec | Format::IecShort => crate::UNITS_IEC.as_bytes(), Format::Si | Format::SiShort => crate::UNITS_SI.as_bytes(), } } fn unit_separator(self) -> &'static str { match self { Format::Iec | Format::Si => " ", Format::IecShort | Format::SiShort => "", } } fn unit_suffix(self) -> &'static str { match self { Format::Iec => "iB", Format::Si => "B", Format::IecShort | Format::SiShort => "", } } } /// Formatting display wrapper for [`ByteSize`]. /// /// Supports various styles, see methods. By default, the [`iec()`](Self::iec()) style is used. /// /// # Examples /// /// ``` /// # use bytesize::ByteSize; /// assert_eq!( /// "1.0 MiB", /// ByteSize::mib(1).display().iec().to_string(), /// ); /// /// assert_eq!( /// "42.0k", /// ByteSize::kb(42).display().si_short().to_string(), /// ); /// ``` #[derive(Debug, Clone)] pub struct Display { pub(crate) byte_size: ByteSize, pub(crate) format: Format, } impl Display { /// Format using IEC (binary) units. /// /// E.g., `11.8 MiB`. #[must_use] #[doc(alias = "binary")] pub fn iec(mut self) -> Self { self.format = Format::Iec; self } /// Format using a short style and IEC (binary) units. /// /// E.g., `11.8M`. /// /// Designed to produce output compatible with `sort -h`. #[must_use] #[doc(alias = "binary")] pub fn iec_short(mut self) -> Self { self.format = Format::IecShort; self } /// Format using SI (decimal) units. /// /// E.g., `12.3 MB`. #[must_use] #[doc(alias = "decimal")] pub fn si(mut self) -> Self { self.format = Format::Si; self } /// Format using a short style and SI (decimal) units. /// /// E.g., `12.3M`. #[must_use] #[doc(alias = "decimal")] pub fn si_short(mut self) -> Self { self.format = Format::SiShort; self } } impl fmt::Display for Display { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { let bytes = self.byte_size.as_u64(); let unit = self.format.unit(); #[allow(unused_variables)] // used in std contexts let unit_base = self.format.unit_base(); let unit_prefixes = self.format.unit_prefixes(); let unit_separator = self.format.unit_separator(); let unit_suffix = self.format.unit_suffix(); let precision = f.precision().unwrap_or(1); if bytes < unit { write!(f, "{bytes}{unit_separator}B")?; } else { let size = bytes as f64; #[cfg(feature = "std")] let exp = ideal_unit_std(size, unit_base); #[cfg(not(feature = "std"))] let exp = ideal_unit_no_std(size, unit); let unit_prefix = unit_prefixes[exp - 1] as char; write!( f, "{:.precision$}{unit_separator}{unit_prefix}{unit_suffix}", (size / unit.pow(exp as u32) as f64), )?; } Ok(()) } } #[allow(dead_code)] // used in no-std contexts fn ideal_unit_no_std(size: f64, unit: u64) -> usize { assert!(size >= unit as f64, "only called when bytes >= unit"); let mut ideal_prefix = 0; let mut ideal_size = size; loop { ideal_prefix += 1; ideal_size /= unit as f64; if ideal_size < unit as f64 { break; } } ideal_prefix } #[cfg(feature = "std")] #[allow(dead_code)] // used in std contexts fn ideal_unit_std(size: f64, unit_base: f64) -> usize { assert!(size.ln() >= unit_base, "only called when bytes >= unit"); match (size.ln() / unit_base) as usize { 0 => unreachable!(), e => e, } } #[cfg(test)] mod tests { use alloc::{format, string::ToString as _}; use super::*; #[cfg(feature = "std")] quickcheck::quickcheck! { #[test] fn ideal_unit_selection_std_no_std_iec(bytes: ByteSize) -> bool { if bytes.0 < 1025 { return true; } let size = bytes.0 as f64; ideal_unit_std(size, crate::LN_KIB) == ideal_unit_no_std(size, crate::KIB) } #[test] fn ideal_unit_selection_std_no_std_si(bytes: ByteSize) -> bool { if bytes.0 < 1025 { return true; } let size = bytes.0 as f64; ideal_unit_std(size, crate::LN_KB) == ideal_unit_no_std(size, crate::KB) } } #[test] fn to_string_iec() { let display = Display { byte_size: ByteSize::gib(1), format: Format::Iec, }; assert_eq!("1.0 GiB", display.to_string()); let display = Display { byte_size: ByteSize::gb(1), format: Format::Iec, }; assert_eq!("953.7 MiB", display.to_string()); } #[test] fn to_string_si() { let display = Display { byte_size: ByteSize::gib(1), format: Format::Si, }; assert_eq!("1.1 GB", display.to_string()); let display = Display { byte_size: ByteSize::gb(1), format: Format::Si, }; assert_eq!("1.0 GB", display.to_string()); } #[test] fn to_string_short() { let display = Display { byte_size: ByteSize::gib(1), format: Format::IecShort, }; assert_eq!("1.0G", display.to_string()); let display = Display { byte_size: ByteSize::gb(1), format: Format::IecShort, }; assert_eq!("953.7M", display.to_string()); } #[track_caller] fn assert_to_string(expected: &str, byte_size: ByteSize, format: Format) { assert_eq!(expected, Display { byte_size, format }.to_string()); } #[test] fn test_to_string_as() { assert_to_string("215 B", ByteSize::b(215), Format::Iec); assert_to_string("215 B", ByteSize::b(215), Format::Si); assert_to_string("1.0 KiB", ByteSize::kib(1), Format::Iec); assert_to_string("1.0 kB", ByteSize::kib(1), Format::Si); assert_to_string("293.9 KiB", ByteSize::kb(301), Format::Iec); assert_to_string("301.0 kB", ByteSize::kb(301), Format::Si); assert_to_string("1.0 MiB", ByteSize::mib(1), Format::Iec); assert_to_string("1.0 MB", ByteSize::mib(1), Format::Si); assert_to_string("1.9 GiB", ByteSize::mib(1907), Format::Iec); assert_to_string("2.0 GB", ByteSize::mib(1908), Format::Si); assert_to_string("399.6 MiB", ByteSize::mb(419), Format::Iec); assert_to_string("419.0 MB", ByteSize::mb(419), Format::Si); assert_to_string("482.4 GiB", ByteSize::gb(518), Format::Iec); assert_to_string("518.0 GB", ByteSize::gb(518), Format::Si); assert_to_string("741.2 TiB", ByteSize::tb(815), Format::Iec); assert_to_string("815.0 TB", ByteSize::tb(815), Format::Si); assert_to_string("540.9 PiB", ByteSize::pb(609), Format::Iec); assert_to_string("609.0 PB", ByteSize::pb(609), Format::Si); } #[test] fn precision() { let size = ByteSize::mib(1908); assert_eq!("1.9 GiB".to_string(), format!("{size}")); assert_eq!("2 GiB".to_string(), format!("{size:.0}")); assert_eq!("1.86328 GiB".to_string(), format!("{size:.5}")); } } bytesize-2.3.1/src/lib.rs000064400000000000000000000362661046102023000134050ustar 00000000000000//! `ByteSize` is a semantic wrapper for byte count representations. //! //! Features: //! //! - Pre-defined constants for various size units (e.g., B, KB, KiB, MB, MiB, ... EB, EiB). //! - `ByteSize` type which presents size units convertible to different size units. //! - Arithmetic operations for `ByteSize`. //! - `FromStr` impl for `ByteSize`, allowing for parsing string size representations like "1.5KiB" //! and "521TiB". //! - Serde support for binary and human-readable deserializers like JSON. //! //! # Examples //! //! Construction using SI or IEC helpers. //! //! ``` //! use bytesize::ByteSize; //! //! assert!(ByteSize::kib(4) > ByteSize::kb(4)); //! ``` //! //! Display as human-readable string. //! //! ``` //! use bytesize::ByteSize; //! //! assert_eq!("518.0 GiB", ByteSize::gib(518).display().iec().to_string()); //! assert_eq!("556.2 GB", ByteSize::gib(518).display().si().to_string()); //! assert_eq!("518.0G", ByteSize::gib(518).display().iec_short().to_string()); //! ``` //! //! Arithmetic operations are supported. //! //! ``` //! use bytesize::ByteSize; //! //! let plus = ByteSize::mb(1) + ByteSize::kb(100); //! println!("{plus}"); //! //! let minus = ByteSize::tb(1) - ByteSize::gb(4); //! assert_eq!(ByteSize::gb(996), minus); //! ``` #![cfg_attr(not(feature = "std"), no_std)] extern crate alloc; use alloc::string::ToString as _; use core::{fmt, ops}; #[cfg(feature = "arbitrary")] mod arbitrary; mod display; mod parse; #[cfg(feature = "serde")] mod serde; pub use self::display::Display; use self::display::Format; pub use self::parse::{Unit, UnitParseError}; /// Number of bytes in 1 kilobyte. pub const KB: u64 = 1_000; /// Number of bytes in 1 megabyte. pub const MB: u64 = 1_000_000; /// Number of bytes in 1 gigabyte. pub const GB: u64 = 1_000_000_000; /// Number of bytes in 1 terabyte. pub const TB: u64 = 1_000_000_000_000; /// Number of bytes in 1 petabyte. pub const PB: u64 = 1_000_000_000_000_000; /// Number of bytes in 1 exabyte. pub const EB: u64 = 1_000_000_000_000_000_000; /// Number of bytes in 1 kibibyte. pub const KIB: u64 = 1_024; /// Number of bytes in 1 mebibyte. pub const MIB: u64 = 1_048_576; /// Number of bytes in 1 gibibyte. pub const GIB: u64 = 1_073_741_824; /// Number of bytes in 1 tebibyte. pub const TIB: u64 = 1_099_511_627_776; /// Number of bytes in 1 pebibyte. pub const PIB: u64 = 1_125_899_906_842_624; /// Number of bytes in 1 exbibyte. pub const EIB: u64 = 1_152_921_504_606_846_976; /// IEC (binary) units. /// /// See . const UNITS_IEC: &str = "KMGTPE"; /// SI (decimal) units. /// /// See . const UNITS_SI: &str = "kMGTPE"; /// `ln(1024) ~= 6.931` const LN_KIB: f64 = 6.931_471_805_599_453; /// `ln(1000) ~= 6.908` const LN_KB: f64 = 6.907_755_278_982_137; /// Converts a quantity of kilobytes to bytes. pub fn kb(size: impl Into) -> u64 { size.into() * KB } /// Converts a quantity of kibibytes to bytes. pub fn kib>(size: V) -> u64 { size.into() * KIB } /// Converts a quantity of megabytes to bytes. pub fn mb>(size: V) -> u64 { size.into() * MB } /// Converts a quantity of mebibytes to bytes. pub fn mib>(size: V) -> u64 { size.into() * MIB } /// Converts a quantity of gigabytes to bytes. pub fn gb>(size: V) -> u64 { size.into() * GB } /// Converts a quantity of gibibytes to bytes. pub fn gib>(size: V) -> u64 { size.into() * GIB } /// Converts a quantity of terabytes to bytes. pub fn tb>(size: V) -> u64 { size.into() * TB } /// Converts a quantity of tebibytes to bytes. pub fn tib>(size: V) -> u64 { size.into() * TIB } /// Converts a quantity of petabytes to bytes. pub fn pb>(size: V) -> u64 { size.into() * PB } /// Converts a quantity of pebibytes to bytes. pub fn pib>(size: V) -> u64 { size.into() * PIB } /// Converts a quantity of exabytes to bytes. pub fn eb>(size: V) -> u64 { size.into() * EB } /// Converts a quantity of exbibytes to bytes. pub fn eib>(size: V) -> u64 { size.into() * EIB } /// Byte size representation. #[derive(Copy, Clone, PartialEq, PartialOrd, Eq, Ord, Hash, Default)] pub struct ByteSize(pub u64); impl ByteSize { /// Constructs a byte size wrapper from a quantity of bytes. #[inline(always)] pub const fn b(size: u64) -> ByteSize { ByteSize(size) } /// Constructs a byte size wrapper from a quantity of kilobytes. #[inline(always)] pub const fn kb(size: u64) -> ByteSize { ByteSize(size * KB) } /// Constructs a byte size wrapper from a quantity of kibibytes. #[inline(always)] pub const fn kib(size: u64) -> ByteSize { ByteSize(size * KIB) } /// Constructs a byte size wrapper from a quantity of megabytes. #[inline(always)] pub const fn mb(size: u64) -> ByteSize { ByteSize(size * MB) } /// Constructs a byte size wrapper from a quantity of mebibytes. #[inline(always)] pub const fn mib(size: u64) -> ByteSize { ByteSize(size * MIB) } /// Constructs a byte size wrapper from a quantity of gigabytes. #[inline(always)] pub const fn gb(size: u64) -> ByteSize { ByteSize(size * GB) } /// Constructs a byte size wrapper from a quantity of gibibytes. #[inline(always)] pub const fn gib(size: u64) -> ByteSize { ByteSize(size * GIB) } /// Constructs a byte size wrapper from a quantity of terabytes. #[inline(always)] pub const fn tb(size: u64) -> ByteSize { ByteSize(size * TB) } /// Constructs a byte size wrapper from a quantity of tebibytes. #[inline(always)] pub const fn tib(size: u64) -> ByteSize { ByteSize(size * TIB) } /// Constructs a byte size wrapper from a quantity of petabytes. #[inline(always)] pub const fn pb(size: u64) -> ByteSize { ByteSize(size * PB) } /// Constructs a byte size wrapper from a quantity of pebibytes. #[inline(always)] pub const fn pib(size: u64) -> ByteSize { ByteSize(size * PIB) } /// Constructs a byte size wrapper from a quantity of exabytes. #[inline(always)] pub const fn eb(size: u64) -> ByteSize { ByteSize(size * EB) } /// Constructs a byte size wrapper from a quantity of exbibytes. #[inline(always)] pub const fn eib(size: u64) -> ByteSize { ByteSize(size * EIB) } /// Returns byte count. #[inline(always)] pub const fn as_u64(&self) -> u64 { self.0 } /// Returns byte count as kilobytes. #[inline(always)] pub fn as_kb(&self) -> f64 { self.0 as f64 / KB as f64 } /// Returns byte count as kibibytes. #[inline(always)] pub fn as_kib(&self) -> f64 { self.0 as f64 / KIB as f64 } /// Returns byte count as megabytes. #[inline(always)] pub fn as_mb(&self) -> f64 { self.0 as f64 / MB as f64 } /// Returns byte count as mebibytes. #[inline(always)] pub fn as_mib(&self) -> f64 { self.0 as f64 / MIB as f64 } /// Returns byte count as gigabytes. #[inline(always)] pub fn as_gb(&self) -> f64 { self.0 as f64 / GB as f64 } /// Returns byte count as gibibytes. #[inline(always)] pub fn as_gib(&self) -> f64 { self.0 as f64 / GIB as f64 } /// Returns byte count as terabytes. #[inline(always)] pub fn as_tb(&self) -> f64 { self.0 as f64 / TB as f64 } /// Returns byte count as tebibytes. #[inline(always)] pub fn as_tib(&self) -> f64 { self.0 as f64 / TIB as f64 } /// Returns byte count as petabytes. #[inline(always)] pub fn as_pb(&self) -> f64 { self.0 as f64 / PB as f64 } /// Returns byte count as pebibytes. #[inline(always)] pub fn as_pib(&self) -> f64 { self.0 as f64 / PIB as f64 } /// Returns byte count as exabytes. #[inline(always)] pub fn as_eb(&self) -> f64 { self.0 as f64 / EB as f64 } /// Returns byte count as exbibytes. #[inline(always)] pub fn as_eib(&self) -> f64 { self.0 as f64 / EIB as f64 } /// Returns a formatting display wrapper. pub fn display(&self) -> Display { Display { byte_size: *self, format: Format::Iec, } } } impl fmt::Display for ByteSize { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { let display = self.display(); if f.width().is_none() { // allocation-free fast path for when no formatting options are specified fmt::Display::fmt(&display, f) } else { f.pad(&display.to_string()) } } } impl fmt::Debug for ByteSize { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "{} ({} bytes)", self, self.0) } } macro_rules! commutative_op { ($t:ty) => { impl ops::Add for $t { type Output = ByteSize; #[inline(always)] fn add(self, rhs: ByteSize) -> ByteSize { ByteSize(rhs.0 + (self as u64)) } } impl ops::Mul for $t { type Output = ByteSize; #[inline(always)] fn mul(self, rhs: ByteSize) -> ByteSize { ByteSize(rhs.0 * (self as u64)) } } }; } commutative_op!(u64); commutative_op!(u32); commutative_op!(u16); commutative_op!(u8); impl ops::Add for ByteSize { type Output = ByteSize; #[inline(always)] fn add(self, rhs: ByteSize) -> ByteSize { ByteSize(self.0 + rhs.0) } } impl ops::AddAssign for ByteSize { #[inline(always)] fn add_assign(&mut self, rhs: ByteSize) { self.0 += rhs.0 } } impl ops::Add for ByteSize where T: Into, { type Output = ByteSize; #[inline(always)] fn add(self, rhs: T) -> ByteSize { ByteSize(self.0 + (rhs.into())) } } impl ops::AddAssign for ByteSize where T: Into, { #[inline(always)] fn add_assign(&mut self, rhs: T) { self.0 += rhs.into(); } } impl ops::Sub for ByteSize { type Output = ByteSize; #[inline(always)] fn sub(self, rhs: ByteSize) -> ByteSize { ByteSize(self.0 - rhs.0) } } impl ops::SubAssign for ByteSize { #[inline(always)] fn sub_assign(&mut self, rhs: ByteSize) { self.0 -= rhs.0 } } impl ops::Sub for ByteSize where T: Into, { type Output = ByteSize; #[inline(always)] fn sub(self, rhs: T) -> ByteSize { ByteSize(self.0 - (rhs.into())) } } impl ops::SubAssign for ByteSize where T: Into, { #[inline(always)] fn sub_assign(&mut self, rhs: T) { self.0 -= rhs.into(); } } impl ops::Mul for ByteSize where T: Into, { type Output = ByteSize; #[inline(always)] fn mul(self, rhs: T) -> ByteSize { ByteSize(self.0 * rhs.into()) } } impl ops::MulAssign for ByteSize where T: Into, { #[inline(always)] fn mul_assign(&mut self, rhs: T) { self.0 *= rhs.into(); } } #[cfg(test)] mod property_tests { use alloc::string::{String, ToString as _}; use super::*; impl quickcheck::Arbitrary for ByteSize { fn arbitrary(g: &mut quickcheck::Gen) -> Self { Self(u64::arbitrary(g)) } } quickcheck::quickcheck! { fn parsing_never_panics(size: String) -> bool { let _ = size.parse::(); true } fn to_string_never_blank(size: ByteSize) -> bool { !size.to_string().is_empty() } fn to_string_never_large(size: ByteSize) -> bool { size.to_string().len() < 11 } fn string_round_trip(size: ByteSize) -> bool { // currently fails on many inputs above the pebibyte level if size > ByteSize::pib(1) { return true; } size.to_string().parse::().unwrap() == size } } } #[cfg(test)] mod tests { use alloc::format; use super::*; #[test] fn test_arithmetic_op() { let mut x = ByteSize::mb(1); let y = ByteSize::kb(100); assert_eq!((x + y).as_u64(), 1_100_000u64); assert_eq!((x - y).as_u64(), 900_000u64); assert_eq!((x + (100 * 1000) as u64).as_u64(), 1_100_000); assert_eq!((x * 2u64).as_u64(), 2_000_000); x += y; assert_eq!(x.as_u64(), 1_100_000); x *= 2u64; assert_eq!(x.as_u64(), 2_200_000); } #[allow(clippy::unnecessary_cast)] #[test] fn test_arithmetic_primitives() { let mut x = ByteSize::mb(1); assert_eq!((x + MB as u64).as_u64(), 2_000_000); assert_eq!((x + MB as u32).as_u64(), 2_000_000); assert_eq!((x + KB as u16).as_u64(), 1_001_000); assert_eq!((x - MB as u64).as_u64(), 0); assert_eq!((x - MB as u32).as_u64(), 0); assert_eq!((x - KB as u32).as_u64(), 999_000); x += MB as u64; x += MB as u32; x += 10u16; x += 1u8; assert_eq!(x.as_u64(), 3_000_011); } #[test] fn test_comparison() { assert!(ByteSize::mb(1) == ByteSize::kb(1000)); assert!(ByteSize::mib(1) == ByteSize::kib(1024)); assert!(ByteSize::mb(1) != ByteSize::kib(1024)); assert!(ByteSize::mb(1) < ByteSize::kib(1024)); assert!(ByteSize::b(0) < ByteSize::tib(1)); assert!(ByteSize::pib(1) < ByteSize::eb(1)); } #[test] fn as_unit_conversions() { assert_eq!(41992187.5, ByteSize::gb(43).as_kib()); assert_eq!(0.028311552, ByteSize::mib(27).as_gb()); assert_eq!(0.0380859375, ByteSize::tib(39).as_pib()); assert_eq!(961.482752, ByteSize::kib(938948).as_mb()); assert_eq!(4.195428726649908, ByteSize::pb(4837).as_eib()); assert_eq!(2.613772153284117, ByteSize::b(2873872874893).as_tib()); } #[track_caller] fn assert_display(expected: &str, b: ByteSize) { assert_eq!(expected, format!("{b}")); } #[test] fn test_display() { assert_display("215 B", ByteSize::b(215)); assert_display("1.0 KiB", ByteSize::kib(1)); assert_display("301.0 KiB", ByteSize::kib(301)); assert_display("419.0 MiB", ByteSize::mib(419)); assert_display("518.0 GiB", ByteSize::gib(518)); assert_display("815.0 TiB", ByteSize::tib(815)); assert_display("609.0 PiB", ByteSize::pib(609)); assert_display("15.0 EiB", ByteSize::eib(15)); } #[test] fn test_display_alignment() { assert_eq!("|357 B |", format!("|{:10}|", ByteSize(357))); assert_eq!("| 357 B|", format!("|{:>10}|", ByteSize(357))); assert_eq!("|357 B |", format!("|{:<10}|", ByteSize(357))); assert_eq!("| 357 B |", format!("|{:^10}|", ByteSize(357))); assert_eq!("|-----357 B|", format!("|{:->10}|", ByteSize(357))); assert_eq!("|357 B-----|", format!("|{:-<10}|", ByteSize(357))); assert_eq!("|--357 B---|", format!("|{:-^10}|", ByteSize(357))); } #[test] fn test_default() { assert_eq!(ByteSize::b(0), ByteSize::default()); } } bytesize-2.3.1/src/parse.rs000064400000000000000000000231471046102023000137430ustar 00000000000000use alloc::{borrow::ToOwned as _, format, string::String}; use core::{fmt, str}; use super::ByteSize; impl str::FromStr for ByteSize { type Err = String; fn from_str(value: &str) -> Result { if let Ok(v) = value.parse::() { return Ok(Self(v)); } let number = take_while(value, |c| c.is_ascii_digit() || c == '.'); match number.parse::() { Ok(v) => { let suffix = skip_while(&value[number.len()..], char::is_whitespace); match suffix.parse::() { Ok(u) => Ok(Self((v * u) as u64)), Err(error) => Err(format!( "couldn't parse {suffix:?} into a known SI unit, {error}" )), } } Err(error) => Err(format!("couldn't parse {value:?} into a ByteSize, {error}")), } } } fn take_while

(s: &str, mut predicate: P) -> &str where P: FnMut(char) -> bool, { let offset = s .chars() .take_while(|ch| predicate(*ch)) .map(|ch| ch.len_utf8()) .sum(); &s[..offset] } fn skip_while

(s: &str, mut predicate: P) -> &str where P: FnMut(char) -> bool, { let offset: usize = s .chars() .skip_while(|ch| predicate(*ch)) .map(|ch| ch.len_utf8()) .sum(); &s[(s.len() - offset)..] } /// Scale unit. /// /// ``` /// use bytesize::Unit; /// /// assert_eq!( /// "GiB".parse::().unwrap(), /// Unit::GibiByte, /// ); /// /// "gibibyte".parse::().unwrap_err(); /// ``` #[non_exhaustive] #[derive(Debug, Clone, PartialEq)] pub enum Unit { /// Single byte. Byte, // power of tens /// Kilobyte (10^3 bytes). KiloByte, /// Megabyte (10^6 bytes) MegaByte, /// Gigabyte (10^9 bytes) GigaByte, /// Terabyte (10^12 bytes) TeraByte, /// Petabyte (10^15 bytes) PetaByte, /// Exabyte (10^18 bytes) ExaByte, // power of twos /// Kibibyte (2^10 bytes) KibiByte, /// Mebibyte (2^20 bytes) MebiByte, /// Gibibyte (2^30 bytes) GibiByte, /// Tebibyte (2^40 bytes) TebiByte, /// Pebibyte (2^50 bytes) PebiByte, /// Exbibyte (2^60 bytes) ExbiByte, } impl Unit { fn factor(&self) -> u64 { match self { Self::Byte => 1, // decimal units Self::KiloByte => crate::KB, Self::MegaByte => crate::MB, Self::GigaByte => crate::GB, Self::TeraByte => crate::TB, Self::PetaByte => crate::PB, Self::ExaByte => crate::EB, // binary units Self::KibiByte => crate::KIB, Self::MebiByte => crate::MIB, Self::GibiByte => crate::GIB, Self::TebiByte => crate::TIB, Self::PebiByte => crate::PIB, Self::ExbiByte => crate::EIB, } } } mod impl_ops { use super::Unit; use core::ops; impl ops::Add for Unit { type Output = u64; fn add(self, other: u64) -> Self::Output { self.factor() + other } } impl ops::Add for u64 { type Output = u64; fn add(self, other: Unit) -> Self::Output { self + other.factor() } } impl ops::Mul for Unit { type Output = u64; fn mul(self, other: u64) -> Self::Output { self.factor() * other } } impl ops::Mul for u64 { type Output = u64; fn mul(self, other: Unit) -> Self::Output { self * other.factor() } } impl ops::Add for Unit { type Output = f64; fn add(self, other: f64) -> Self::Output { self.factor() as f64 + other } } impl ops::Add for f64 { type Output = f64; fn add(self, other: Unit) -> Self::Output { other.factor() as f64 + self } } impl ops::Mul for Unit { type Output = f64; fn mul(self, other: f64) -> Self::Output { self.factor() as f64 * other } } impl ops::Mul for f64 { type Output = f64; fn mul(self, other: Unit) -> Self::Output { other.factor() as f64 * self } } } impl str::FromStr for Unit { type Err = UnitParseError; fn from_str(unit: &str) -> Result { match () { _ if unit.eq_ignore_ascii_case("b") => Ok(Self::Byte), _ if unit.eq_ignore_ascii_case("k") | unit.eq_ignore_ascii_case("kb") => { Ok(Self::KiloByte) } _ if unit.eq_ignore_ascii_case("m") | unit.eq_ignore_ascii_case("mb") => { Ok(Self::MegaByte) } _ if unit.eq_ignore_ascii_case("g") | unit.eq_ignore_ascii_case("gb") => { Ok(Self::GigaByte) } _ if unit.eq_ignore_ascii_case("t") | unit.eq_ignore_ascii_case("tb") => { Ok(Self::TeraByte) } _ if unit.eq_ignore_ascii_case("p") | unit.eq_ignore_ascii_case("pb") => { Ok(Self::PetaByte) } _ if unit.eq_ignore_ascii_case("e") | unit.eq_ignore_ascii_case("eb") => { Ok(Self::ExaByte) } _ if unit.eq_ignore_ascii_case("ki") | unit.eq_ignore_ascii_case("kib") => { Ok(Self::KibiByte) } _ if unit.eq_ignore_ascii_case("mi") | unit.eq_ignore_ascii_case("mib") => { Ok(Self::MebiByte) } _ if unit.eq_ignore_ascii_case("gi") | unit.eq_ignore_ascii_case("gib") => { Ok(Self::GibiByte) } _ if unit.eq_ignore_ascii_case("ti") | unit.eq_ignore_ascii_case("tib") => { Ok(Self::TebiByte) } _ if unit.eq_ignore_ascii_case("pi") | unit.eq_ignore_ascii_case("pib") => { Ok(Self::PebiByte) } _ if unit.eq_ignore_ascii_case("ei") | unit.eq_ignore_ascii_case("eib") => { Ok(Self::ExbiByte) } _ => Err(UnitParseError(to_string_truncate(unit))), } } } /// Safely truncates fn to_string_truncate(unit: &str) -> String { const MAX_UNIT_LEN: usize = 3; if unit.len() > MAX_UNIT_LEN { // TODO(MSRV 1.91): use ceil_char_boundary if unit.is_char_boundary(3) { format!("{}...", &unit[..3]) } else if unit.is_char_boundary(4) { format!("{}...", &unit[..4]) } else if unit.is_char_boundary(5) { format!("{}...", &unit[..5]) } else if unit.is_char_boundary(6) { format!("{}...", &unit[..6]) } else { unreachable!("char boundary will be within 4 bytes") } } else { unit.to_owned() } } /// Error returned when parsing a [`Unit`] fails. #[derive(Debug)] pub struct UnitParseError(String); impl fmt::Display for UnitParseError { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "Failed to parse unit \"{}\"", self.0) } } #[cfg(feature = "std")] impl std::error::Error for UnitParseError {} #[cfg(test)] mod tests { use alloc::string::ToString as _; use super::*; #[test] fn truncating_error_strings() { assert_eq!("", to_string_truncate("")); assert_eq!("b", to_string_truncate("b")); assert_eq!("ob", to_string_truncate("ob")); assert_eq!("foo", to_string_truncate("foo")); assert_eq!("foo...", to_string_truncate("foob")); assert_eq!("foo...", to_string_truncate("foobar")); } #[test] fn when_ok() { // shortcut for writing test cases fn parse(s: &str) -> u64 { s.parse::().unwrap().0 } assert_eq!("0".parse::().unwrap().0, 0); assert_eq!(parse("0"), 0); assert_eq!(parse("500"), 500); assert_eq!(parse("1K"), Unit::KiloByte * 1); assert_eq!(parse("1Ki"), Unit::KibiByte * 1); assert_eq!(parse("1.5Ki"), (1.5 * Unit::KibiByte) as u64); assert_eq!(parse("1KiB"), 1 * Unit::KibiByte); assert_eq!(parse("1.5KiB"), (1.5 * Unit::KibiByte) as u64); assert_eq!(parse("3 MB"), Unit::MegaByte * 3); assert_eq!(parse("4 MiB"), Unit::MebiByte * 4); assert_eq!(parse("6 GB"), 6 * Unit::GigaByte); assert_eq!(parse("4 GiB"), 4 * Unit::GibiByte); assert_eq!(parse("88TB"), 88 * Unit::TeraByte); assert_eq!(parse("521TiB"), 521 * Unit::TebiByte); assert_eq!(parse("8 PB"), 8 * Unit::PetaByte); assert_eq!(parse("8P"), 8 * Unit::PetaByte); assert_eq!(parse("12 PiB"), 12 * Unit::PebiByte); } #[test] fn when_err() { // shortcut for writing test cases fn parse(s: &str) -> Result { s.parse::() } assert!(parse("").is_err()); assert!(parse("a124GB").is_err()); assert!(parse("1.3 42.0 B").is_err()); assert!(parse("1.3 ... B").is_err()); // The original implementation did not account for the possibility that users may // use whitespace to visually separate digits, thus treat it as an error assert!(parse("1 000 B").is_err()); } #[test] fn to_and_from_str() { // shortcut for writing test cases fn parse(s: &str) -> u64 { s.parse::().unwrap().0 } assert_eq!(parse(&parse("128GB").to_string()), 128 * Unit::GigaByte); assert_eq!( parse(&ByteSize(parse("128.000 GiB")).to_string()), 128 * Unit::GibiByte, ); } } bytesize-2.3.1/src/serde.rs000064400000000000000000000057301046102023000137310ustar 00000000000000use alloc::string::{String, ToString as _}; use core::fmt; use serde_core::{de, Deserialize, Deserializer, Serialize, Serializer}; use crate::ByteSize; impl<'de> Deserialize<'de> for ByteSize { fn deserialize(de: D) -> Result where D: Deserializer<'de>, { struct ByteSizeVisitor; impl de::Visitor<'_> for ByteSizeVisitor { type Value = ByteSize; fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { formatter.write_str("an integer or string") } fn visit_i64(self, value: i64) -> Result { if let Ok(val) = u64::try_from(value) { Ok(ByteSize(val)) } else { Err(E::invalid_value( de::Unexpected::Signed(value), &"integer overflow", )) } } fn visit_u64(self, value: u64) -> Result { Ok(ByteSize(value)) } fn visit_str(self, value: &str) -> Result { if let Ok(val) = value.parse() { Ok(val) } else { Err(E::invalid_value( de::Unexpected::Str(value), &"parsable string", )) } } } if de.is_human_readable() { de.deserialize_any(ByteSizeVisitor) } else { de.deserialize_u64(ByteSizeVisitor) } } } impl Serialize for ByteSize { fn serialize(&self, ser: S) -> Result where S: Serializer, { if ser.is_human_readable() { ::serialize(&self.to_string(), ser) } else { self.0.serialize(ser) } } } #[cfg(test)] mod tests { use super::*; use serde::{Deserialize, Serialize}; #[test] fn test_serde() { #[derive(Serialize, Deserialize)] struct S { x: ByteSize, } let s = serde_json::from_str::(r#"{ "x": "5 B" }"#).unwrap(); assert_eq!(s.x, ByteSize(5)); let s = serde_json::from_str::(r#"{ "x": 1048576 }"#).unwrap(); assert_eq!(s.x, "1 MiB".parse::().unwrap()); let s = toml::from_str::(r#"x = "2.5 MiB""#).unwrap(); assert_eq!(s.x, "2.5 MiB".parse::().unwrap()); // i64 MAX let s = toml::from_str::(r#"x = "9223372036854775807""#).unwrap(); assert_eq!(s.x, "9223372036854775807".parse::().unwrap()); } #[test] fn test_serde_json() { let json = serde_json::to_string(&ByteSize::mib(1)).unwrap(); assert_eq!(json, "\"1.0 MiB\""); let deserialized = serde_json::from_str::(&json).unwrap(); assert_eq!(deserialized.0, 1048576); } }