Finding a [u8; N]/&[u8] in a Vec<u8>

I have a Vec<u8>, and I want to find the index of ['\n', '\n'] (two consecutive unix line endings). The current solution I have is unsafe { }. Is there a less get-yelled-at way to do it? I half-expected there to be a generic slice .find(), just like there is for &str.

2 Likes

I have no idea which part of this needs unsafe since you could just naïvely index into the Vec if you don't know about the appropriate standard library methods. However, for a likely faster (no bounds checking) std-only solution, you can use <[T]>::windows():

the_vec
    .windows(2)
    .position(|w| w == [b'\n', b'\n'])

Oh, I didn't say unsafe is needed, just that it currently is unsafe (and I don't remember why, and there's no comment to explain it either).

+1 for using plain ol' std

1 Like