Skip to main content

async_selector/selector/
id.rs

1use std::{
2    cmp::Ordering,
3    fmt,
4    hash::{Hash, Hasher},
5    sync::Weak,
6};
7
8use crate::task::Task;
9
10/// A unique id of a task stored in a [`Selector`](crate::selector::Selector).
11///
12/// See [example](https://github.com/Razz4780/async-selector/blob/main/examples/map.rs)
13/// of how it can be leverage to use the selector like a map.
14///
15/// Mind that this keeping this id alive prevents the selector
16/// from deallocating memory used to store the task.
17pub struct Id<P>(pub(super) Weak<Task<P>>);
18
19impl<P> Clone for Id<P> {
20    fn clone(&self) -> Self {
21        Self(self.0.clone())
22    }
23}
24
25impl<P> fmt::Debug for Id<P> {
26    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
27        Weak::as_ptr(&self.0).fmt(f)
28    }
29}
30
31impl<P> PartialEq for Id<P> {
32    fn eq(&self, other: &Self) -> bool {
33        self.0.ptr_eq(&other.0)
34    }
35}
36
37impl<P> Eq for Id<P> {}
38
39impl<P> Hash for Id<P> {
40    fn hash<H: Hasher>(&self, state: &mut H) {
41        std::ptr::hash(self.0.as_ptr(), state);
42    }
43}
44
45impl<P> PartialOrd for Id<P> {
46    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
47        Some(self.cmp(other))
48    }
49}
50
51impl<P> Ord for Id<P> {
52    fn cmp(&self, other: &Self) -> Ordering {
53        self.0.as_ptr().cmp(&other.0.as_ptr())
54    }
55}
56
57unsafe impl<P> Send for Id<P> {}
58unsafe impl<P> Sync for Id<P> {}