Different ordering

Let's say I have a vector of nodes of some kind:

#[derive(...)]
struct Changes {
  pathname: PathBuf,
  timestamp: u64
  // .. blah ..
}

fn main() {
  let mut changes: Vec<Changes> = Vec::new();
}

In most situations I need the vector to be sorted on pathname (each of which happens to be unique). So I implement the appropriate traits on Changes to act as a proxy for comparing pathname for each node. This is all fine and dandy.

However, one day we realized that just as we're near the end of the lifetime of that vector we would greatly benefit from it being sorted by timestamp instead.

Is there some nifty way to accomplish this in Rust? ("nifty" being the operative word).

Is there some kind of "View" concept of structs in Rust? That would be pretty nifty. Something like:

changes::ViewAs<Defualt>.sort(); // Use the "Default" traits
changes::ViewAs<Timestamp>.sort(); // Use the "Timestamp" traits

I know that specifically can't be done, but it demonstrates the gist of what I'm looking for.

I've run into this quite a few times, so I imagine I'm not alone -- which makes me think there are some existing common pattern for it.

Sure, you can use sort_by_key.

Like changes.sort_by_key(|x| x.timestamp) [or if timestamp is not public but you have a getter e.g. changes.sort_by_key(|x| x.get_timestamp())]

The standard sorting functions for vector/slices are stable, which would mean in your example that things with the same timestamp stay in the same relative order as they were before. If you don’t need this property you can also use the slightly more efficient, especially more memory efficient sort_unstable* versions.

3 Likes

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.