Efficient way to compare [u8] arrays and find index of the first not equal item

Viewed 261
1 Answers

A combination of zip and position with iterators would be O(n):

fn find_first_neq_index(a1: &[u8], a2: &[u8]) -> Option<usize> {
    a1.iter().zip(a2.iter()).position(|(a, b)| a != b)
}

Playground

Notice that this is valid just in the case of the arrays to be of equal length. If you consider one of them to be a sub-slice of the other this should be enough. If you want to consider that the point of difference then you can expand by checking the lengths. Another simple solution matching all cases with a simple loop:

fn find_first_neq_index_different_lengths(a1: &[u8], a2: &[u8]) -> Option<usize> {
    let mut itera = a1.iter();
    let mut iterb = a2.iter();
    let mut i = 0usize;
    loop {
        match (itera.next(), iterb.next()) {
            (None, None) => return None,
            (None, Some(_)) | (Some(_), None) => return Some(i),
            (Some(a), Some(b)) if a != b => return Some(i),
            _ => {
                i += 1;
            }
        }
    }
}

Playground

Related