Note: This site is currently "Under construction". I'm migrating to a new version of my site building software. Lots of things are in a state of disrepair as a result (for example, footnote links aren't working). It's all part of the process of building in public. Most things should still be readable though.

Find Where Two Vecs Diverge In Rust

This isn't a full diff, it gets the place where things diverge and follows the second vec from that point

Code

use std::collections::VecDeque;
use std::cmp::min;

fn main() {
  let primary = vec!["alfa".to_string(), "bravo".to_string()];
  let diff1 = vec![];
  let diff2 = vec!["alfa".to_string()];
  let diff3 = vec!["alfa".to_string(), "bravo".to_string()];
  let diff4 = vec!["alfa".to_string(), "bravo".to_string(), "charlie".to_string()];
  let diff5 = vec!["alfa".to_string(), "echo".to_string(), "charlie".to_string()];
  let diff6 = vec!["echo".to_string()];
  let diff7 = vec!["echo".to_string(), "alfa".to_string()];

  assert_eq!(walk_vecs(&primary, &diff1), vec!["alfa".to_string(), "bravo".to_string()]);
  assert_eq!(walk_vecs(&primary, &diff2), vec!["bravo".to_string()]);
  assert_eq!(walk_vecs(&primary, &diff3), Vec::<String>::from([]));
  assert_eq!(walk_vecs(&primary, &diff4), vec!["charlie".to_string()]);
  assert_eq!(walk_vecs(&primary, &diff5), vec!["echo".to_string(), "charlie".to_string()]);
  assert_eq!(walk_vecs(&primary, &diff6), vec!["echo".to_string()]);
  assert_eq!(walk_vecs(&primary, &diff7), vec!["echo".to_string(), "alfa".to_string()]);

  println!("testing complete");
}

fn walk_vecs(v1: &Vec<String>, v2: &Vec<String>) -> Vec<String> {
  let mut d1: VecDeque<String> = VecDeque::from(v1.clone());
  let mut d2: VecDeque<String> = VecDeque::from(v2.clone());
  let min_length = min(d1.len(), d2.len());
  for _ in 0..min_length {
    if d1[0] == d2[0] {
      d1.pop_front();
      d2.pop_front();
    }
  }
  if d2.len() == 0 && d1.len() != 0 {
    d1.into()
  } else {
    d2.into()
  }
}

Results

testing complete