Deduplicating vector filled with glib::Object

I have some source of data that is being converted into a vector of glib::Object. The insertion is done via a helper function that inserts the new object only if !data.contains(&new_object). This passes compilation just fine, suggesting that PartialEq is implemented for the glib::Object subclass but the result is clearly duplicated. The glib::Object is a structure with child enums whose value is stored in std::cell::Cell.

How can I achieve correct behaviour of .contains()?

glib::Objects and all their subclasses are compared (and hashed/etc) by pointer value. So if you have two distinct objects they’re different, even if they contain the same data otherwise.

Instead of contains() you could

  • use iter().any(|obj| do your comparison here). Note that this brings you quadratic behaviour on insert, just like your contains() version.
  • use a wrapper type around your objects that implements PartialEq/etc in the way you expect. Then you can also use a BTreeSet or similar instead, depending on what you’re planning to use this for.
1 Like

Ah, that does make sense, indeed. It’s difficult to get used to the glib::Object workflow in Rust :). In the end instead of iter().any() I used binary_search_by() to get deduplicated and sorted insert.

Thanks!

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.