gpt4 book ai didi

rust - 如何匹配任意位置的多个字节?

转载 作者:行者123 更新时间:2023-11-29 08:02:28 26 4
gpt4 key购买 nike

我必须匹配 &[u8] 中的字节并希望简化我的代码。现在它看起来像这样:

fn f(s: &[u8]) {
if Some(&b'A') == s.get(5) && Some(&b'X') == s.get(16) &&
(Some(&b'B') == s.get(17) || Some(&b'C') == s.get(18)) {
} else if Some(&b'1') == s.get(4) && Some(&b'2') == s.get(7) && Some(&b'D') == s.get(10) {
}
}

我知道 nom , 但它并没有使这种特殊情况更简单,尽管我使用的是 nom之后提取比赛后的数据。

所以我第一次尝试简化代码是编写这些宏:

macro_rules! m {
($ch:expr, $pos:expr) => {{
Some(&$ch) == line.get($pos)
}};
($ch1:expr, $ch2:expr, $pos:expr) => {{
Some(&$ch1) == line.get($pos) || Some(&$ch2) == line.get($pos)
}}
}

它减少了代码大小,并减少了出错的可能性,但我想要更多:

macro_rules! match_several {
($($ch:expr, $pos:expr),*, $last_ch:expr, $last_pos:expr) => {{
(Some(&$ch) == line.get($pos) &&)* Some(&$last_ch) == line.get($last_pos)
}}
}

但是编译器给出了这个错误:

 error: local ambiguity: multiple parsing options: built-in NTs expr ('last_ch') or expr ('ch').
--> lib.rs:45:32
|
45 | if match_several!(b'P', 4, b' ', 5, b'A', 12) {
| ------------------------^^^^-------------- in this macro invocation

测试代码:

let line: &'static [u8] = b"0123P 6789ABA";
println!("match result {:?}", match_several!(b'P', 4, b' ', 5, b'A', 12));

最佳答案

将宏更改为:

macro_rules! match_several {
($($ch:expr, $pos:expr),*) => {{
$(Some(&$ch) == line.get($pos))&&*
}}
}

请注意,我使用 && 作为分隔符,并且去掉了 $last_ch$last_pos。这是可行的,因为您可以使用+* 以外的任何 标记作为分隔符,而&& 是单个 token 。

关于rust - 如何匹配任意位置的多个字节?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44821866/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com