切片中找到子序列

切片中找到子序列

本文介绍了如何在 &[u8] 切片中找到子序列?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在二进制缓冲区上有一个 &[u8] 切片.我需要解析它,但是我想使用的很多方法(例如 str::find)似乎在切片上不可用.

I have a &[u8] slice over a binary buffer. I need to parse it, but a lot of the methods that I would like to use (such as str::find) don't seem to be available on slices.

我已经看到我可以通过使用 from_utf8_unchecked() 通过缓冲区切片和我的模式将我的模式转换为 str 但这似乎有点危险(而且真的很hacky).

I've seen that I can covert both by buffer slice and my pattern to str by using from_utf8_unchecked() but that seems a little dangerous (and also really hacky).

我怎样才能在这个切片中找到一个子序列?我实际上需要模式的索引,而不仅仅是部分的切片视图,所以我认为 split 行不通.

How can I find a subsequence in this slice? I actually need the index of the pattern, not just a slice view of the parts, so I don't think split will work.

推荐答案

这里是一个基于 windows 迭代器.

Here's a simple implementation based on the windows iterator.

fn find_subsequence(haystack: &[u8], needle: &[u8]) -> Option<usize> {
    haystack.windows(needle.len()).position(|window| window == needle)
}

fn main() {
    assert_eq!(find_subsequence(b"qwertyuiop", b"tyu"), Some(4));
    assert_eq!(find_subsequence(b"qwertyuiop", b"asd"), None);
}

find_subsequence 函数也可以通用:

fn find_subsequence<T>(haystack: &[T], needle: &[T]) -> Option<usize>
    where for<'a> &'a [T]: PartialEq
{
    haystack.windows(needle.len()).position(|window| window == needle)
}

这篇关于如何在 &amp;[u8] 切片中找到子序列?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-20 08:59