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 解析器实现
11,812 个月下载量
在 9 个 crate 中使用(8 个直接使用)
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