1use std::{borrow::Borrow, cmp::Eq, fmt::Debug, hash::Hash};
19
20pub trait Key: Hash + Eq + Send + Sync + Debug + 'static {}
25impl<T: Hash + Eq + Send + Sync + Debug + 'static> Key for T {}
26
27pub trait Keyed {
29 type Key: Key;
30}
31
32impl<T: Key + Clone> Keyed for T {
33 type Key = T;
34}
35
36pub trait PartialKeyed {
37 type PartialKey: Key;
38}
39
40pub trait Keyring<State>: Keyed {
43 type KeyRef<'a>: Borrow<Self::Key> + 'a
44 where
45 Self: 'a,
46 State: 'a;
47
48 fn key_for<'a>(&'a self, state: &'a State) -> Self::KeyRef<'a>
49 where
50 Self: 'a,
51 State: 'a;
52}
53
54pub trait SelfKey: Keyed {
57 type KeyRef<'a>: Borrow<Self::Key> + 'a
58 where
59 Self: 'a;
60 fn key<'a>(&'a self) -> Self::KeyRef<'a>
61 where
62 Self: 'a;
63}
64
65impl<T: Key + Clone> SelfKey for T {
66 type KeyRef<'a>
67 = &'a Self::Key
68 where
69 Self: 'a;
70 fn key<'a>(&'a self) -> &'a Self::Key
71 where
72 Self: 'a,
73 {
74 self
75 }
76}
77
78pub struct SelfKeyring<K>(std::marker::PhantomData<K>);
80
81impl<K> SelfKeyring<K> {
82 pub fn new() -> Self {
83 Self(Default::default())
84 }
85}
86
87impl<K> Default for SelfKeyring<K> {
88 fn default() -> Self {
89 Self::new()
90 }
91}
92
93impl<K: Key> Keyed for SelfKeyring<K> {
94 type Key = K;
95}
96
97impl<State: SelfKey> Keyring<State> for SelfKeyring<State::Key> {
98 type KeyRef<'a>
99 = State::KeyRef<'a>
100 where
101 State: 'a;
102 fn key_for<'a>(&'a self, state: &'a State) -> State::KeyRef<'a>
103 where
104 State: 'a,
105 {
106 state.key()
107 }
108}
109
110pub struct SelfPartialKeyring<K>(std::marker::PhantomData<K>);
111
112impl<K> SelfPartialKeyring<K> {
113 pub fn new() -> Self {
114 Self(Default::default())
115 }
116}
117
118impl<K> Default for SelfPartialKeyring<K> {
119 fn default() -> Self {
120 Self::new()
121 }
122}
123
124impl<K: Key> PartialKeyed for SelfPartialKeyring<K> {
125 type PartialKey = K;
126}
127
128impl<K: Key> Keyed for SelfPartialKeyring<K> {
129 type Key = Option<K>;
130}
131
132impl<K: Key, State: SelfKey<Key = Option<K>>> Keyring<State> for SelfPartialKeyring<K> {
133 type KeyRef<'a>
134 = State::KeyRef<'a>
135 where
136 Self: 'a,
137 State: 'a,
138 K: 'a;
139
140 fn key_for<'a>(&'a self, state: &'a State) -> State::KeyRef<'a>
141 where
142 Self: 'a,
143 State: 'a,
144 K: 'a,
145 {
146 state.key()
147 }
148}