6 个版本

0.1.5 2021 年 3 月 17 日
0.1.4 2020 年 6 月 18 日
0.1.3 2020 年 5 月 28 日
0.1.2 2019 年 8 月 23 日
0.1.1 2019 年 1 月 18 日

#565 in 解析器实现

Download history 5234/week @ 2024-03-14 8068/week @ 2024-03-21 5249/week @ 2024-03-28 7341/week @ 2024-04-04 5940/week @ 2024-04-11 6314/week @ 2024-04-18 6530/week @ 2024-04-25 3144/week @ 2024-05-02 2588/week @ 2024-05-09 2897/week @ 2024-05-16 2470/week @ 2024-05-23 2787/week @ 2024-05-30 2788/week @ 2024-06-06 3166/week @ 2024-06-13 3102/week @ 2024-06-20 2313/week @ 2024-06-27

11,812 个月下载量
9 crate 中使用(8 个直接使用)

MIT 许可证

67KB
1.5K SLoC

dynfmt - Rust 中的动态格式化

动态字符串格式化程序库。

dynfmt 为实现 std::fmt 部分功能的格式提供了一些实现。格式字符串和参数的解析检查是在运行时进行的。也可以选择实现新的格式。

通过 Format trait 公开公共 API,其中包含格式化辅助函数和用于与格式字符串接口的底层工具。有关提供的实现列表,请参阅功能部分。

用法

use dynfmt::{Format, NoopFormat};

let formatted = NoopFormat.format("hello, world", &["unused"]);
assert_eq!("hello, world", formatted.expect("formatting failed"));

有关更多信息,请参阅 Format trait。

功能

此程序库附带了一组功能,这些功能可以激活格式化能力或新的格式实现

  • json (默认):通过 JSON 实现复杂结构的序列化。某些格式(如 Python)也具有使用此功能的 表示 格式(%r),如果启用此功能,则可以使用该格式。如果没有此功能,此类值将导致错误。
  • python:实现类似于 python 2 的 printf 格式。有关更多信息,请参阅 PythonFormat
  • curly:使用大括号作为参数的简单格式字符串语法。类似于 .NET 和 Rust,但功能较少。有关更多信息,请参阅 SimpleCurlyFormat

可扩展性

通过实现 Format trait 创建一个新的格式。唯一必需的方法是 iter_args,它必须返回一个遍历 ArgumentSpec 结构的迭代器。根据格式的功能,规格可以与格式化参数进行参数化。

use std::str::MatchIndices;
use dynfmt::{ArgumentSpec, Format, Error};

struct HashFormat;

impl<'f> Format<'f> for HashFormat {
    type Iter = HashIter<'f>;

    fn iter_args(&self, format: &'f str) -> Result<Self::Iter, Error<'f>> {
        Ok(HashIter(format.match_indices('#')))
    }
}

struct HashIter<'f>(MatchIndices<'f, char>);

impl<'f> Iterator for HashIter<'f> {
    type Item = Result<ArgumentSpec<'f>, Error<'f>>;

    fn next(&mut self) -> Option<Self::Item> {
        self.0.next().map(|(index, _)| Ok(ArgumentSpec::new(index, index + 1)))
    }
}

let formatted = HashFormat.format("hello, #", &["world"]);
assert_eq!("hello, world", formatted.expect("formatting failed"));

许可证:MIT

依赖关系

~0.5–1.7MB
~36K SLoC