how to enable comparison between Vec<_> and Vec<_,CustomAllocator>?

Viewed 253

I am trying to use a custom allocator, using the allocator API in Rust.

It seems Rust considers Vec<u8,CustomAllocator> and Vec<u8> as two distinct types.

    let a: Vec<u8,CustomAllocator> = Vec::new_in(CustomAllocator);
    for x in [1,2,3] { a.push(x) }

    let b:Vec<u8> = vec![1,2,3];
    assert_eq!(a,b);

It means that a simple comparison like the below won't compile:

error[E0277]: can't compare `Vec<u8, CustomAllocator>` with `Vec<u8>`
  --> src/main.rs:37:5
   |
37 |     assert_eq!(a,b);
   |     ^^^^^^^^^^^^^^^ no implementation for `Vec<u8, CustomAllocator> == Vec<u8>`
   |
   = help: the trait `PartialEq<Vec<u8>>` is not implemented for `Vec<u8, CustomAllocator>`
   = note: this error originates in the macro `assert_eq` (in Nightly builds, run with -Z macro-backtrace for more info)

I can't implement the trait, as I don't own either Vec or PartialEq.

In reality, and in the context of my implementation, I may compare both underlying slices. But I don't see how I can achieve this with the language...

Any clue appreciated!

1 Answers

Update: Since GitHub pull request #93755 has been merged, comparison between Vecs with different allocators is now possible.


Original answer:

Vec uses the std::alloc::Global allocator by default, so Vec<u8> is in fact Vec<u8, Global>. Since Vec<u8, CustomAllocator> and Vec<u8, Global> are indeed distinct types, they cannot directly be compared because the PartialEq implementation is not generic for the allocator type. As @PitaJ commented, you can compare the slices instead using assert_eq!(&a[..], &b[..]) (which is also what the author of the allocator API recommends).

Related