1#![no_std]
10
11use core::any::TypeId;
12
13pub trait KeyPathValueTarget {
16 type Target: Sized;
18}
19
20impl<T: Sized> KeyPathValueTarget for &T {
21 type Target = T;
22}
23
24impl<T: Sized> KeyPathValueTarget for &mut T {
25 type Target = T;
26}
27
28pub trait Readable<Root, Value> {
30 fn get(&self, root: Root) -> Option<Value>;
32}
33
34pub trait Writable<MutRoot, MutValue> {
36 fn set(&self, root: MutRoot) -> Option<MutValue>;
38}
39
40pub trait KeyPath<Root, Value, MutRoot, MutValue>:
42 Readable<Root, Value> + Writable<MutRoot, MutValue>
43{
44}
45
46impl<T, Root, Value, MutRoot, MutValue> KeyPath<Root, Value, MutRoot, MutValue> for T where
47 T: Readable<Root, Value> + Writable<MutRoot, MutValue>
48{
49}
50
51pub trait KpTrait<R, V, Root, Value, MutRoot, MutValue>:
53 Readable<Root, Value> + Writable<MutRoot, MutValue>
54{
55 fn type_id_of_root() -> TypeId
57 where
58 R: 'static,
59 {
60 TypeId::of::<R>()
61 }
62
63 fn type_id_of_value() -> TypeId
65 where
66 V: 'static,
67 {
68 TypeId::of::<V>()
69 }
70
71 fn then<SV, SubValue, MutSubValue, Next>(
76 self,
77 next: Next,
78 ) -> impl KeyPath<Root, SubValue, MutRoot, MutSubValue>
79 where
80 Self: Sized,
81 SubValue: core::borrow::Borrow<SV>,
82 MutSubValue: core::borrow::BorrowMut<SV>,
83 Next: Readable<Value, SubValue> + Writable<MutValue, MutSubValue> + Clone;
84}
85
86pub trait AccessorTrait<Root, Value, MutRoot, MutValue>:
88 Readable<Root, Value> + Writable<MutRoot, MutValue>
89{
90 fn get_optional(&self, root: Option<Root>) -> Option<Value> {
92 root.and_then(|r| Readable::get(self, r))
93 }
94
95 fn get_mut_optional(&self, root: Option<MutRoot>) -> Option<MutValue> {
97 root.and_then(|r| Writable::set(self, r))
98 }
99
100 fn get_or_else<F>(&self, root: Root, f: F) -> Value
102 where
103 F: FnOnce() -> Value,
104 {
105 Readable::get(self, root).unwrap_or_else(f)
106 }
107
108 fn get_mut_or_else<F>(&self, root: MutRoot, f: F) -> MutValue
110 where
111 F: FnOnce() -> MutValue,
112 {
113 Writable::set(self, root).unwrap_or_else(f)
114 }
115}