我有一个Vec<u8>
,我想在n
上拆分并逐行处理它。在某些时候有一个空行,我想在一个块中处理整个向量的其余部分(而不是逐行处理)。这种事情在HTTP或Git提交对象中很常见。
例如:
key: value
otherkey: othervalue
This is the content
that is now just a big
block. I don't care about
newlines here.
有没有一种优雅的方法可以用 Rust 解析它?我可以这样拆分它:
pub fn main() {
let data: Vec<u8> = "key: valuenotherkey: othervaluennThis is the contentnthat is now just a bignblock. I don't care aboutnnewlines here.".as_bytes().to_owned();
for line in data.split(|&c| c == 'n' as u8) {
println!("Line: {:?}", line);
if line.len() == 0 {
// Start of message...
} else {
// Header
}
}
}
然而,当我到达nn
时,我找不到一种方法说"从这里给我剩下的Vec
"。如果有一种split()
形式返回带有索引的切片而不是实际内容,那会很容易,但我似乎找不到。
有没有一种优雅的方法可以做到这一点,而不仅仅是拆分消息,然后将其重新连接在一起?
您可以轻松获取每个切片的长度,跟踪当前偏移量并自己执行最终切片:
static DATA: &[u8] = br#"key: value
otherkey: othervalue
This is the content
that is now just a big
block. I don't care about
newlines here.
"#;
pub fn main() {
let mut offset = 0;
for line in DATA.split(|&c| c == 'n' as u8) {
offset += line.len() + 1; // Include the newline.
if line.len() == 0 {
break;
} else {
// Header
println!("{:?}", line);
}
}
let body = &DATA[offset..];
println!("{:?}", body);
}
另请参阅:
- 如何获取"&str"之间的字节偏移量