Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to compare contents an owned vector to a static vector in Rust?

As a part of a test, I want to assert that a function returns a vector with proper contents. I therefore made the expected data available as a static variable. However, I can't find a proper way to compare the contents of a managed vector to the static vector variable.

#[test]
fn test_my_data_matches_expected_data () {
  static expected_data: [u8, ..3] = [1, 2, 3];
  let my_data: ~[u8] = ~[1, 2, 3];  // actually returned by the function to test

  // This would be obvious, but fails:
  // -> mismatched types: expected `~[u8]` but found `[u8 * 3]`
  assert_eq!(my_data, expected_data);

  // Static vectors are told to be available as a borrowed pointer,
  // so I tried to borrow a pointer from my_data and compare it:
  // -> mismatched types: expected `&const ~[u8]` but found `[u8 * 3]`
  assert_eq!(&my_data, expected_data);

  // Dereferencing also doesn't work:
  // -> type ~[u8] cannot be dereferenced
  assert_eq!(*my_data, expected_data);

  // Copying the static vector to a managed one works, but this
  // involves creating a copy of the data and actually defeats
  // the reason to declare it statically:
  assert_eq!(my_data, expected_data.to_owned());
}

Update: Assigning a reference to the static vector before comparing it works around the problem, so I ended up with a small macro to assert equality of vectors:

macro_rules! assert_typed_eq (($T: ty, $given: expr, $expected: expr) => ({
  let given_val: &$T = $given;
  let expected_val: &$T = $expected;
  assert_eq!(given_val, expected_val);
}))

Usage: assert_typed_eq([u8], my_data, expected_data);

like image 931
Zargony Avatar asked May 07 '13 19:05

Zargony


1 Answers

There's actually two sorts of static vectors: fixed length ones ([u8, .. 3]) and static slices (&'static [u8]). The former doesn't interact very well with other types of vectors. The latter is most useful here:

fn main() {
    static x: &'static [u8] = &[1,2,3];

    let y = ~[1u8,2,3];
    assert_eq!(y.as_slice(), x);
}
like image 79
huon Avatar answered Oct 21 '22 16:10

huon