2个稳定版本

使用旧版Rust 2015

1.0.2 2018年10月7日

#184值格式化

Download history · Rust 包仓库 3077/week @ 2024-03-14 · Rust 包仓库 3714/week @ 2024-03-21 · Rust 包仓库 3712/week @ 2024-03-28 · Rust 包仓库 3501/week @ 2024-04-04 · Rust 包仓库 2998/week @ 2024-04-11 · Rust 包仓库 3025/week @ 2024-04-18 · Rust 包仓库 2994/week @ 2024-04-25 · Rust 包仓库 3036/week @ 2024-05-02 · Rust 包仓库 3682/week @ 2024-05-09 · Rust 包仓库 3898/week @ 2024-05-16 · Rust 包仓库 2806/week @ 2024-05-23 · Rust 包仓库 4382/week @ 2024-05-30 · Rust 包仓库 3562/week @ 2024-06-06 · Rust 包仓库 2982/week @ 2024-06-13 · Rust 包仓库 3750/week @ 2024-06-20 · Rust 包仓库 2580/week @ 2024-06-27 · Rust 包仓库

13,733 每月下载量
用于 13 个crate (12直接使用)

MIT/Apache

20KB
354 代码行

size_format

这是一个使用前缀进行大小格式化的Rust crate。

例如,4000字节可以格式化为4.0kB。

主要目标是提供数据大小的简单格式化器。

默认提供二进制和SI单位前缀,尽管可以添加更多。

use size_format::{SizeFormatterBinary, SizeFormatterSI};

assert_eq!(
    format!("{}B", SizeFormatterBinary::new(42 * 1024 * 1024)),
    "42.0MiB".to_string()
);
assert_eq!(
    format!("{}B", SizeFormatterSI::new(42_000_000)),
    "42.0MB".to_string()
);

还可以指定精度。请注意,值始终向下舍入。

use size_format::SizeFormatterSI;

assert_eq!(
    format!("{:.4}B", SizeFormatterSI::new(1_999_999_999)),
    "1.9999GB".to_string()
);
assert_eq!(
    format!("{:.0}B", SizeFormatterSI::new(1_999_999_999)),
    "1GB".to_string()
);

显示的精度也永远不会超过可用精度。

use size_format::SizeFormatterSI;

assert_eq!(
    format!("{:.10}B", SizeFormatterSI::new(678)),
    "678B".to_string()
);
assert_eq!(
    format!("{:.10}B", SizeFormatterSI::new(1_999)),
    "1.999kB".to_string()
);

为了更多灵活性,直接使用具有正确类型参数的 SizeFormatter 类型。例如,以下代码使用二进制前缀格式化 u16 并使用逗号作为分隔符。

use size_format::{BinaryPrefixes, CommaSeparated, SizeFormatter};

assert_eq!(
    format!("{:.2}B", SizeFormatter::<u16, BinaryPrefixes, CommaSeparated>::from(65_535u16)),
    "63,99KiB".to_string()
);

虽然这个crate主要用于数据大小,但它也可以用于其他单位。

还可以实现 PrefixType trait 以创建自己的前缀系统。

use size_format::{PointSeparated, PrefixType, SizeFormatter};
use generic_array::{typenum::U3, GenericArray};

struct Millimeter;

impl PrefixType for Millimeter {
    type N = U3;

    const PREFIX_SIZE: u32 = 1000;

    fn prefixes() -> GenericArray<&'static str, Self::N> {
        ["m", "", "k"].into()
    }
}

assert_eq!(
    format!("{}m", SizeFormatter::<u32, Millimeter, PointSeparated>::new(1)),
    "1mm".to_string()
);
assert_eq!(
    format!("{}m", SizeFormatter::<u32, Millimeter, PointSeparated>::new(1_000)),
    "1.0m".to_string()
);
assert_eq!(
    format!("{}m", SizeFormatter::<u32, Millimeter, PointSeparated>::new(1_000_000)),
    "1.0km".to_string()
);
assert_eq!(
    format!("{}m", SizeFormatter::<u64, Millimeter, PointSeparated>::new(10_000_000_000)),
    "10000.0km".to_string()
);

依赖项

~730KB
~16K SLoC