difference

Function difference 

Source
pub fn difference<T: Eq + Hash + Clone>(
    to_compare: &Vec<T>,
    others: &Vec<&Vec<T>>,
) -> Vec<T>
Expand description

Computes the difference between a primary list and multiple exclusion lists using std::collections::HashSet.

§Type Parameters

  • T: The element type. Must implement Clone, Eq, and Hash.

§Arguments

  • to_compare: A vector of values to retain if not found in others.
  • others: A reference to a list of reference vectors containing values to exclude.

§Returns

A new Vec<T> containing only the values from to_compare that are not found in any of the others.

§Behavior

  • Returns all items from to_compare that are not present in any exclusion list in others.
  • Performs equality comparison using ==, backed by Eq + Hash.

§Performance

  • Uses HashSet (SipHash): secure and collision-resistant, suitable for untrusted input.
  • Preallocates capacity for efficiency and avoids unnecessary allocations.
  • Performs at most one clone() per included or excluded item.
  • For large datasets where security is not a concern, see difference_performant.

§Examples

§✂️ Filter out excluded values

use pencil_box::array::difference::difference;

let a = vec![1, 2, 3, 4, 5];
let b = vec![2, 4];
let c = vec![5];

let result = difference(&a, &vec![&b, &c]);
assert_eq!(result, vec![1, 3]);

§🔤 Works with strings

let a = vec!["apple", "banana", "cherry"];
let b = vec!["banana"];
let result = difference(&a, &vec![&b]);
assert_eq!(result, vec!["apple", "cherry"]);

§📭 Handles empty inputs

let a: Vec<i32> = vec![];
let b = vec![1, 2, 3];
let result = difference(&a, &vec![&b]);
assert!(result.is_empty());