2 个版本
| 0.1.1 | 2022 年 7 月 24 日 |
|---|---|
| 0.1.0 | 2022 年 7 月 23 日 |
1462 在 解析器实现 中
每月 242 次下载
在 3 个 crate 中使用(通过 samsa)
26KB
457 行
NomBytes
nombytes 是一个提供用于与 nom 一起使用的 bytes::Bytes 字节容器的包装器的库。
我最初创建这个库是为了让一个函数能够接收文件名路径并返回解析值,同时仍然保留对已加载文件的引用,而不会遇到与 &[u8] 和 &str 相关的生命周期问题。我决定将其作为一个 crate 发布,以便其他人也能利用我的努力。
这个库经过测试,可以与 bytes 版本 v5.3.0 及以下和 nom 版本 v6.0.0 及以下一起使用,并在其 Cargo.toml 文件中进行了标记。
用法
在您的 Cargo.toml 中添加以下内容
[dependencies]
nombytes = "0.1.1"
特性
miette
启用 miette 特性后,NomBytes 实现 SourceCode 特性,因此可以直接与 miette 的 #[source_code] 错误属性一起使用。此特性还启用了 std 特性。
这个库经过测试,可以与 miette 版本 v3.0.0 及以下一起使用,并在其 Cargo.toml 文件中进行了标记。
serde
为此库中的类型添加了 serde::Serialize 和 serde::Deserialize 实现以允许与 serde 一起使用。
std
默认启用;允许通过 From<String> 实现直接从 String 创建 NomBytes。关闭此特性后,此 crate 与 #![no_std] 兼容。
示例
从 nom 套件借用,使用 NomBytes 代替 &str。因为 NomBytes 作用相当于 &[u8],而不是作为 &str。
use nom::{
IResult,
bytes::complete::{tag, take_while_m_n},
combinator::map_res,
sequence::tuple};
use nombytes::NomBytes;
#[derive(Debug,PartialEq)]
pub struct Color {
pub red: u8,
pub green: u8,
pub blue: u8,
}
fn from_hex(input: NomBytes) -> Result<u8, std::num::ParseIntError> {
u8::from_str_radix(input.to_str(), 16)
}
fn is_hex_digit(c: u8) -> bool {
(c as char).is_digit(16)
}
fn hex_primary(input: NomBytes) -> IResult<NomBytes, u8> {
map_res(
take_while_m_n(2, 2, is_hex_digit),
from_hex
)(input)
}
fn hex_color(input: NomBytes) -> IResult<NomBytes, Color> {
let (input, output) = tag("#")(input)?;
let (input, (red, green, blue)) = tuple((hex_primary, hex_primary, hex_primary))(input)?;
Ok((input, Color { red, green, blue }))
}
fn main() {
assert!(matches!(hex_color(NomBytes::from("#2F14DF")),
Ok((r, Color {
red: 47,
green: 20,
blue: 223,
})) if r.to_str() == ""));
}
许可证
根据以下许可证之一
- Apache License, Version 2.0, (LICENSE-APACHE 或 https://apache.ac.cn/licenses/LICENSE-2.0)
- MIT 许可证 (LICENSE-MIT 或 https://open-source.org.cn/licenses/MIT)
任选其一。
贡献
除非您明确表示,否则您根据 Apache-2.0 许可证定义的,有意提交以包含在作品中的任何贡献,都将按照上述方式双许可,不附加任何额外条款或条件。
依赖项
~1.5MB
~30K SLoC