Skip to content

Instantly share code, notes, and snippets.

@maratik123
Created September 14, 2024 10:42
Show Gist options
  • Save maratik123/30e53d21dc13644b77aee4c92a64c375 to your computer and use it in GitHub Desktop.
Save maratik123/30e53d21dc13644b77aee4c92a64c375 to your computer and use it in GitHub Desktop.
Correct sorting for notify-rs
use rand::seq::SliceRandom;
use rand::thread_rng;
use std::collections::HashMap;
#[derive(Debug, Copy, Clone)]
struct A {
last: u32,
time: u32,
}
fn main() {
let mut events_expired = vec![
A { last: 1, time: 4 },
A { last: 1, time: 1 },
A { last: 2, time: 3 },
];
events_expired.extend(events_expired.clone());
events_expired.extend(events_expired.clone());
events_expired.extend(events_expired.clone());
events_expired.shuffle(&mut thread_rng());
println!("{events_expired:?}");
// group events by last
let events_expired_by_last: HashMap<_, Vec<_>> =
events_expired
.into_iter()
.fold(HashMap::new(), |mut acc, event| {
acc.entry(event.last)
.and_modify(|vec| vec.push(event))
.or_insert_with(|| vec![event]);
acc
});
// Extract groups and sort events in each group by time
let mut vecs_of_events: Vec<_> = events_expired_by_last
.into_values()
.map(|mut vec| {
vec.sort_by(|event_a, event_b| event_a.time.cmp(&event_b.time));
vec
})
.collect();
// Sort groups lexicographically
vecs_of_events.sort_by(|vec_a, vec_b| {
vec_a
.iter()
.map(|event_a| event_a.time)
.cmp(vec_b.iter().map(|event_b| event_b.time))
});
// Flatten vec of groups of events to vec of events
let events_expired: Vec<_> = vecs_of_events.into_iter().flatten().collect();
println!("{events_expired:?}");
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment