1use std::sync::{Arc, Mutex, RwLock};
2use std::marker::PhantomData;
3use std::any::{Any, TypeId};
4use std::rc::Rc;
5use std::cell::RefCell;
6
7#[cfg(feature = "tagged")]
8use tagged_core::Tagged;
9
10#[macro_export]
32macro_rules! keypath {
33 ($closure:expr) => {
35 $crate::KeyPath::new($closure)
36 };
37}
38
39#[macro_export]
59macro_rules! opt_keypath {
60 ($closure:expr) => {
62 $crate::OptionalKeyPath::new($closure)
63 };
64}
65
66#[macro_export]
86macro_rules! writable_keypath {
87 ($closure:expr) => {
89 $crate::WritableKeyPath::new($closure)
90 };
91}
92
93#[macro_export]
113macro_rules! writable_opt_keypath {
114 ($closure:expr) => {
116 $crate::WritableOptionalKeyPath::new($closure)
117 };
118}
119
120#[derive(Clone)]
124pub struct KeyPath<Root, Value, F>
125where
126 F: for<'r> Fn(&'r Root) -> &'r Value,
127{
128 getter: F,
129 _phantom: PhantomData<(Root, Value)>,
130}
131
132impl<Root, Value, F> KeyPath<Root, Value, F>
133where
134 F: for<'r> Fn(&'r Root) -> &'r Value,
135{
136 pub fn new(getter: F) -> Self {
137 Self {
138 getter,
139 _phantom: PhantomData,
140 }
141 }
142
143 pub fn get<'r>(&self, root: &'r Root) -> &'r Value {
144 (self.getter)(root)
145}
146
147 pub fn for_box<Target>(self) -> KeyPath<Root, Target, impl for<'r> Fn(&'r Root) -> &'r Target + 'static>
150 where
151 Value: std::ops::Deref<Target = Target>,
152 F: 'static,
153 Value: 'static,
154 {
155 let getter = self.getter;
156
157 KeyPath {
158 getter: move |root: &Root| {
159 getter(root).deref()
160 },
161 _phantom: PhantomData,
162 }
163 }
164
165 pub fn for_arc<Target>(self) -> KeyPath<Root, Target, impl for<'r> Fn(&'r Root) -> &'r Target + 'static>
167 where
168 Value: std::ops::Deref<Target = Target>,
169 F: 'static,
170 Value: 'static,
171 {
172 let getter = self.getter;
173
174 KeyPath {
175 getter: move |root: &Root| {
176 getter(root).deref()
177 },
178 _phantom: PhantomData,
179 }
180 }
181
182 pub fn for_rc<Target>(self) -> KeyPath<Root, Target, impl for<'r> Fn(&'r Root) -> &'r Target + 'static>
184 where
185 Value: std::ops::Deref<Target = Target>,
186 F: 'static,
187 Value: 'static,
188 {
189 let getter = self.getter;
190
191 KeyPath {
192 getter: move |root: &Root| {
193 getter(root).deref()
194 },
195 _phantom: PhantomData,
196 }
197 }
198
199 pub fn for_arc_root(self) -> OptionalKeyPath<Arc<Root>, Value, impl for<'r> Fn(&'r Arc<Root>) -> Option<&'r Value> + 'static>
201 where
202 Value: Sized,
203 F: 'static,
204 Root: 'static,
205 Value: 'static,
206 {
207 let getter = self.getter;
208
209 OptionalKeyPath {
210 getter: move |arc: &Arc<Root>| {
211 Some(getter(arc.as_ref()))
212 },
213 _phantom: PhantomData,
214 }
215 }
216
217 pub fn for_box_root(self) -> OptionalKeyPath<Box<Root>, Value, impl for<'r> Fn(&'r Box<Root>) -> Option<&'r Value> + 'static>
219 where
220 Value: Sized,
221 F: 'static,
222 Root: 'static,
223 Value: 'static,
224 {
225 let getter = self.getter;
226
227 OptionalKeyPath {
228 getter: move |boxed: &Box<Root>| {
229 Some(getter(boxed.as_ref()))
230 },
231 _phantom: PhantomData,
232 }
233 }
234
235 pub fn for_rc_root(self) -> OptionalKeyPath<Rc<Root>, Value, impl for<'r> Fn(&'r Rc<Root>) -> Option<&'r Value> + 'static>
237 where
238 Value: Sized,
239 F: 'static,
240 Root: 'static,
241 Value: 'static,
242 {
243 let getter = self.getter;
244
245 OptionalKeyPath {
246 getter: move |rc: &Rc<Root>| {
247 Some(getter(rc.as_ref()))
248 },
249 _phantom: PhantomData,
250 }
251 }
252
253 pub fn for_result<E>(self) -> OptionalKeyPath<Result<Root, E>, Value, impl for<'r> Fn(&'r Result<Root, E>) -> Option<&'r Value> + 'static>
256 where
257 F: 'static,
258 Root: 'static,
259 Value: 'static,
260 E: 'static,
261 {
262 let getter = self.getter;
263
264 OptionalKeyPath {
265 getter: move |result: &Result<Root, E>| {
266 result.as_ref().ok().map(|root| getter(root))
267 },
268 _phantom: PhantomData,
269 }
270 }
271
272 pub fn to_optional(self) -> OptionalKeyPath<Root, Value, impl for<'r> Fn(&'r Root) -> Option<&'r Value> + 'static>
275 where
276 F: 'static,
277 {
278 let getter = self.getter;
279 OptionalKeyPath::new(move |root: &Root| Some(getter(root)))
280 }
281
282 pub fn with_option<Callback, R>(&self, option: &Option<Root>, f: Callback) -> Option<R>
284 where
285 F: Clone,
286 Callback: FnOnce(&Value) -> R,
287 {
288 option.as_ref().map(|root| {
289 let value = self.get(root);
290 f(value)
291 })
292 }
293
294 pub fn with_result<Callback, R, E>(&self, result: &Result<Root, E>, f: Callback) -> Option<R>
296 where
297 F: Clone,
298 Callback: FnOnce(&Value) -> R,
299 {
300 result.as_ref().ok().map(|root| {
301 let value = self.get(root);
302 f(value)
303 })
304 }
305
306 pub fn with_box<Callback, R>(&self, boxed: &Box<Root>, f: Callback) -> R
308 where
309 F: Clone,
310 Callback: FnOnce(&Value) -> R,
311 {
312 let value = self.get(boxed);
313 f(value)
314 }
315
316 pub fn with_arc<Callback, R>(&self, arc: &Arc<Root>, f: Callback) -> R
318 where
319 F: Clone,
320 Callback: FnOnce(&Value) -> R,
321 {
322 let value = self.get(arc);
323 f(value)
324 }
325
326 pub fn with_rc<Callback, R>(&self, rc: &Rc<Root>, f: Callback) -> R
328 where
329 F: Clone,
330 Callback: FnOnce(&Value) -> R,
331 {
332 let value = self.get(rc);
333 f(value)
334 }
335
336 pub fn with_refcell<Callback, R>(&self, refcell: &RefCell<Root>, f: Callback) -> Option<R>
338 where
339 F: Clone,
340 Callback: FnOnce(&Value) -> R,
341 {
342 refcell.try_borrow().ok().map(|borrow| {
343 let value = self.get(&*borrow);
344 f(value)
345 })
346 }
347
348 pub fn with_mutex<Callback, R>(&self, mutex: &Mutex<Root>, f: Callback) -> Option<R>
350 where
351 F: Clone,
352 Callback: FnOnce(&Value) -> R,
353 {
354 mutex.lock().ok().map(|guard| {
355 let value = self.get(&*guard);
356 f(value)
357 })
358 }
359
360 pub fn with_rwlock<Callback, R>(&self, rwlock: &RwLock<Root>, f: Callback) -> Option<R>
362 where
363 F: Clone,
364 Callback: FnOnce(&Value) -> R,
365 {
366 rwlock.read().ok().map(|guard| {
367 let value = self.get(&*guard);
368 f(value)
369 })
370 }
371
372 pub fn with_arc_rwlock<Callback, R>(&self, arc_rwlock: &Arc<RwLock<Root>>, f: Callback) -> Option<R>
374 where
375 F: Clone,
376 Callback: FnOnce(&Value) -> R,
377 {
378 arc_rwlock.read().ok().map(|guard| {
379 let value = self.get(&*guard);
380 f(value)
381 })
382 }
383
384 pub fn with_arc_mutex<Callback, R>(&self, arc_mutex: &Arc<Mutex<Root>>, f: Callback) -> Option<R>
386 where
387 F: Clone,
388 Callback: FnOnce(&Value) -> R,
389 {
390 arc_mutex.lock().ok().map(|guard| {
391 let value = self.get(&*guard);
392 f(value)
393 })
394 }
395
396 #[cfg(feature = "tagged")]
397 pub fn for_tagged<Tag>(self) -> KeyPath<Tagged<Root, Tag>, Value, impl for<'r> Fn(&'r Tagged<Root, Tag>) -> &'r Value + 'static>
400 where
401 Tagged<Root, Tag>: std::ops::Deref<Target = Root>,
402 F: 'static,
403 Root: 'static,
404 Value: 'static,
405 Tag: 'static,
406 {
407 use std::ops::Deref;
408 let getter = self.getter;
409
410 KeyPath {
411 getter: move |tagged: &Tagged<Root, Tag>| {
412 getter(tagged.deref())
413 },
414 _phantom: PhantomData,
415 }
416 }
417
418 #[cfg(feature = "tagged")]
419 pub fn with_tagged<Tag, Callback, R>(&self, tagged: &Tagged<Root, Tag>, f: Callback) -> R
422 where
423 Tagged<Root, Tag>: std::ops::Deref<Target = Root>,
424 Callback: FnOnce(&Value) -> R,
425 {
426 use std::ops::Deref;
427 let value = self.get(tagged.deref());
428 f(value)
429 }
430
431 pub fn for_option(self) -> OptionalKeyPath<Option<Root>, Value, impl for<'r> Fn(&'r Option<Root>) -> Option<&'r Value> + 'static>
434 where
435 F: 'static,
436 Root: 'static,
437 Value: 'static,
438 {
439 let getter = self.getter;
440
441 OptionalKeyPath {
442 getter: move |opt: &Option<Root>| {
443 opt.as_ref().map(|root| getter(root))
444 },
445 _phantom: PhantomData,
446 }
447 }
448
449 pub fn iter<'r, T>(&self, root: &'r Root) -> Option<std::slice::Iter<'r, T>>
452 where
453 Value: AsRef<[T]> + 'r,
454 {
455 let value_ref: &'r Value = self.get(root);
456 Some(value_ref.as_ref().iter())
457 }
458
459 pub fn extract_from_slice<'r>(&self, slice: &'r [Root]) -> Vec<&'r Value> {
462 slice.iter().map(|item| self.get(item)).collect()
463 }
464
465 pub fn extract_from_ref_slice<'r>(&self, slice: &'r [&Root]) -> Vec<&'r Value> {
468 slice.iter().map(|item| self.get(item)).collect()
469 }
470
471}
472
473impl<Root, Value, F> KeyPath<Root, Value, F>
475where
476 F: for<'r> Fn(&'r Root) -> &'r Value,
477{
478 pub fn with_arc_rwlock_direct<Callback, R>(&self, arc_rwlock: &Arc<RwLock<Root>>, f: Callback) -> Option<R>
481 where
482 Callback: FnOnce(&Value) -> R,
483 {
484 arc_rwlock.read().ok().map(|guard| {
485 let value = self.get(&*guard);
486 f(value)
487 })
488 }
489
490 pub fn with_arc_mutex_direct<Callback, R>(&self, arc_mutex: &Arc<Mutex<Root>>, f: Callback) -> Option<R>
493 where
494 Callback: FnOnce(&Value) -> R,
495 {
496 arc_mutex.lock().ok().map(|guard| {
497 let value = self.get(&*guard);
498 f(value)
499 })
500 }
501}
502
503pub fn for_slice<T>() -> impl for<'r> Fn(&'r [T], usize) -> Option<&'r T> {
505 |slice: &[T], index: usize| slice.get(index)
506}
507
508pub mod containers {
510 use super::{OptionalKeyPath, WritableOptionalKeyPath, KeyPath, WritableKeyPath};
511 use std::collections::{HashMap, BTreeMap, HashSet, BTreeSet, VecDeque, LinkedList, BinaryHeap};
512 use std::sync::{Mutex, RwLock, Weak as StdWeak, Arc};
513 use std::rc::{Weak as RcWeak, Rc};
514 use std::ops::{Deref, DerefMut};
515
516 #[cfg(feature = "parking_lot")]
517 use parking_lot::{Mutex as ParkingMutex, RwLock as ParkingRwLock};
518
519 #[cfg(feature = "tagged")]
520 use tagged_core::Tagged;
521
522 pub fn for_vec_index<T>(index: usize) -> OptionalKeyPath<Vec<T>, T, impl for<'r> Fn(&'r Vec<T>) -> Option<&'r T>> {
524 OptionalKeyPath::new(move |vec: &Vec<T>| vec.get(index))
525 }
526
527 pub fn for_vecdeque_index<T>(index: usize) -> OptionalKeyPath<VecDeque<T>, T, impl for<'r> Fn(&'r VecDeque<T>) -> Option<&'r T>> {
529 OptionalKeyPath::new(move |deque: &VecDeque<T>| deque.get(index))
530 }
531
532 pub fn for_linkedlist_index<T>(index: usize) -> OptionalKeyPath<LinkedList<T>, T, impl for<'r> Fn(&'r LinkedList<T>) -> Option<&'r T>> {
534 OptionalKeyPath::new(move |list: &LinkedList<T>| {
535 list.iter().nth(index)
536 })
537 }
538
539 pub fn for_hashmap_key<K, V>(key: K) -> OptionalKeyPath<HashMap<K, V>, V, impl for<'r> Fn(&'r HashMap<K, V>) -> Option<&'r V>>
541 where
542 K: std::hash::Hash + Eq + Clone + 'static,
543 V: 'static,
544 {
545 OptionalKeyPath::new(move |map: &HashMap<K, V>| map.get(&key))
546 }
547
548 pub fn for_btreemap_key<K, V>(key: K) -> OptionalKeyPath<BTreeMap<K, V>, V, impl for<'r> Fn(&'r BTreeMap<K, V>) -> Option<&'r V>>
550 where
551 K: Ord + Clone + 'static,
552 V: 'static,
553 {
554 OptionalKeyPath::new(move |map: &BTreeMap<K, V>| map.get(&key))
555 }
556
557 pub fn for_hashset_get<T>(value: T) -> OptionalKeyPath<HashSet<T>, T, impl for<'r> Fn(&'r HashSet<T>) -> Option<&'r T>>
559 where
560 T: std::hash::Hash + Eq + Clone + 'static,
561 {
562 OptionalKeyPath::new(move |set: &HashSet<T>| set.get(&value))
563 }
564
565 pub fn for_btreeset_get<T>(value: T) -> OptionalKeyPath<BTreeSet<T>, T, impl for<'r> Fn(&'r BTreeSet<T>) -> Option<&'r T>>
567 where
568 T: Ord + Clone + 'static,
569 {
570 OptionalKeyPath::new(move |set: &BTreeSet<T>| set.get(&value))
571 }
572
573 pub fn for_binaryheap_peek<T>() -> OptionalKeyPath<BinaryHeap<T>, T, impl for<'r> Fn(&'r BinaryHeap<T>) -> Option<&'r T>>
575 where
576 T: Ord + 'static,
577 {
578 OptionalKeyPath::new(|heap: &BinaryHeap<T>| heap.peek())
579 }
580
581 pub fn for_vec_index_mut<T>(index: usize) -> WritableOptionalKeyPath<Vec<T>, T, impl for<'r> Fn(&'r mut Vec<T>) -> Option<&'r mut T>> {
585 WritableOptionalKeyPath::new(move |vec: &mut Vec<T>| vec.get_mut(index))
586 }
587
588 pub fn for_vecdeque_index_mut<T>(index: usize) -> WritableOptionalKeyPath<VecDeque<T>, T, impl for<'r> Fn(&'r mut VecDeque<T>) -> Option<&'r mut T>> {
590 WritableOptionalKeyPath::new(move |deque: &mut VecDeque<T>| deque.get_mut(index))
591 }
592
593 pub fn for_linkedlist_index_mut<T>(index: usize) -> WritableOptionalKeyPath<LinkedList<T>, T, impl for<'r> Fn(&'r mut LinkedList<T>) -> Option<&'r mut T>> {
595 WritableOptionalKeyPath::new(move |list: &mut LinkedList<T>| {
596 let mut iter = list.iter_mut();
598 iter.nth(index)
599 })
600 }
601
602 pub fn for_hashmap_key_mut<K, V>(key: K) -> WritableOptionalKeyPath<HashMap<K, V>, V, impl for<'r> Fn(&'r mut HashMap<K, V>) -> Option<&'r mut V>>
604 where
605 K: std::hash::Hash + Eq + Clone + 'static,
606 V: 'static,
607 {
608 WritableOptionalKeyPath::new(move |map: &mut HashMap<K, V>| map.get_mut(&key))
609 }
610
611 pub fn for_btreemap_key_mut<K, V>(key: K) -> WritableOptionalKeyPath<BTreeMap<K, V>, V, impl for<'r> Fn(&'r mut BTreeMap<K, V>) -> Option<&'r mut V>>
613 where
614 K: Ord + Clone + 'static,
615 V: 'static,
616 {
617 WritableOptionalKeyPath::new(move |map: &mut BTreeMap<K, V>| map.get_mut(&key))
618 }
619
620 pub fn for_hashset_get_mut<T>(value: T) -> WritableOptionalKeyPath<HashSet<T>, T, impl for<'r> Fn(&'r mut HashSet<T>) -> Option<&'r mut T>>
623 where
624 T: std::hash::Hash + Eq + Clone + 'static,
625 {
626 WritableOptionalKeyPath::new(move |set: &mut HashSet<T>| {
627 if set.contains(&value) {
630 None
633 } else {
634 None
635 }
636 })
637 }
638
639 pub fn for_btreeset_get_mut<T>(value: T) -> WritableOptionalKeyPath<BTreeSet<T>, T, impl for<'r> Fn(&'r mut BTreeSet<T>) -> Option<&'r mut T>>
642 where
643 T: Ord + Clone + 'static,
644 {
645 WritableOptionalKeyPath::new(move |set: &mut BTreeSet<T>| {
646 if set.contains(&value) {
649 None
652 } else {
653 None
654 }
655 })
656 }
657
658 pub fn for_binaryheap_peek_mut<T>() -> WritableOptionalKeyPath<BinaryHeap<T>, T, impl for<'r> Fn(&'r mut BinaryHeap<T>) -> Option<&'r mut T>>
664 where
665 T: Ord + 'static,
666 {
667 WritableOptionalKeyPath::new(|_heap: &mut BinaryHeap<T>| {
671 None
672 })
673 }
674
675 pub fn lock_mutex<T>(mutex: &Mutex<T>) -> Option<std::sync::MutexGuard<'_, T>> {
684 mutex.lock().ok()
685 }
686
687 pub fn read_rwlock<T>(rwlock: &RwLock<T>) -> Option<std::sync::RwLockReadGuard<'_, T>> {
691 rwlock.read().ok()
692 }
693
694 pub fn write_rwlock<T>(rwlock: &RwLock<T>) -> Option<std::sync::RwLockWriteGuard<'_, T>> {
698 rwlock.write().ok()
699 }
700
701 pub fn lock_arc_mutex<T>(arc_mutex: &Arc<Mutex<T>>) -> Option<std::sync::MutexGuard<'_, T>> {
705 arc_mutex.lock().ok()
706 }
707
708 pub fn read_arc_rwlock<T>(arc_rwlock: &Arc<RwLock<T>>) -> Option<std::sync::RwLockReadGuard<'_, T>> {
712 arc_rwlock.read().ok()
713 }
714
715 pub fn write_arc_rwlock<T>(arc_rwlock: &Arc<RwLock<T>>) -> Option<std::sync::RwLockWriteGuard<'_, T>> {
719 arc_rwlock.write().ok()
720 }
721
722 pub fn upgrade_weak<T>(weak: &StdWeak<T>) -> Option<Arc<T>> {
726 weak.upgrade()
727 }
728
729 pub fn upgrade_rc_weak<T>(weak: &RcWeak<T>) -> Option<Rc<T>> {
733 weak.upgrade()
734 }
735
736 #[cfg(feature = "parking_lot")]
737 pub fn lock_parking_mutex<T>(mutex: &ParkingMutex<T>) -> parking_lot::MutexGuard<'_, T> {
740 mutex.lock()
741 }
742
743 #[cfg(feature = "parking_lot")]
744 pub fn read_parking_rwlock<T>(rwlock: &ParkingRwLock<T>) -> parking_lot::RwLockReadGuard<'_, T> {
747 rwlock.read()
748 }
749
750 #[cfg(feature = "parking_lot")]
751 pub fn write_parking_rwlock<T>(rwlock: &ParkingRwLock<T>) -> parking_lot::RwLockWriteGuard<'_, T> {
754 rwlock.write()
755 }
756
757 #[cfg(feature = "tagged")]
758 pub fn for_tagged<Tag, T>() -> KeyPath<Tagged<Tag, T>, T, impl for<'r> Fn(&'r Tagged<Tag, T>) -> &'r T>
761 where
762 Tagged<Tag, T>: std::ops::Deref<Target = T>,
763 Tag: 'static,
764 T: 'static,
765 {
766 KeyPath::new(|tagged: &Tagged<Tag, T>| tagged.deref())
767 }
768
769 #[cfg(feature = "tagged")]
770 pub fn for_tagged_mut<Tag, T>() -> WritableKeyPath<Tagged<Tag, T>, T, impl for<'r> Fn(&'r mut Tagged<Tag, T>) -> &'r mut T>
773 where
774 Tagged<Tag, T>: std::ops::DerefMut<Target = T>,
775 Tag: 'static,
776 T: 'static,
777 {
778 WritableKeyPath::new(|tagged: &mut Tagged<Tag, T>| tagged.deref_mut())
779 }
780}
781
782#[derive(Clone)]
784pub struct OptionalKeyPath<Root, Value, F>
785where
786 F: for<'r> Fn(&'r Root) -> Option<&'r Value>,
787{
788 getter: F,
789 _phantom: PhantomData<(Root, Value)>,
790}
791
792impl<Root, Value, F> OptionalKeyPath<Root, Value, F>
793where
794 F: for<'r> Fn(&'r Root) -> Option<&'r Value>,
795{
796 pub fn new(getter: F) -> Self {
797 Self {
798 getter,
799 _phantom: PhantomData,
800 }
801 }
802
803 pub fn get<'r>(&self, root: &'r Root) -> Option<&'r Value> {
804 (self.getter)(root)
805 }
806
807 pub fn then<SubValue, G>(
809 self,
810 next: OptionalKeyPath<Value, SubValue, G>,
811 ) -> OptionalKeyPath<Root, SubValue, impl for<'r> Fn(&'r Root) -> Option<&'r SubValue>>
812 where
813 G: for<'r> Fn(&'r Value) -> Option<&'r SubValue>,
814 F: 'static,
815 G: 'static,
816 Value: 'static,
817 {
818 let first = self.getter;
819 let second = next.getter;
820
821 OptionalKeyPath::new(move |root: &Root| {
822 first(root).and_then(|value| second(value))
823 })
824 }
825
826 pub fn for_box<Target>(self) -> OptionalKeyPath<Root, Target, impl for<'r> Fn(&'r Root) -> Option<&'r Target> + 'static>
829 where
830 Value: std::ops::Deref<Target = Target>,
831 F: 'static,
832 Value: 'static,
833 {
834 let getter = self.getter;
835
836 OptionalKeyPath {
837 getter: move |root: &Root| {
838 getter(root).map(|boxed| boxed.deref())
839 },
840 _phantom: PhantomData,
841 }
842 }
843
844 pub fn for_arc<Target>(self) -> OptionalKeyPath<Root, Target, impl for<'r> Fn(&'r Root) -> Option<&'r Target> + 'static>
846 where
847 Value: std::ops::Deref<Target = Target>,
848 F: 'static,
849 Value: 'static,
850 {
851 let getter = self.getter;
852
853 OptionalKeyPath {
854 getter: move |root: &Root| {
855 getter(root).map(|arc| arc.deref())
856 },
857 _phantom: PhantomData,
858 }
859 }
860
861 pub fn for_rc<Target>(self) -> OptionalKeyPath<Root, Target, impl for<'r> Fn(&'r Root) -> Option<&'r Target> + 'static>
863 where
864 Value: std::ops::Deref<Target = Target>,
865 F: 'static,
866 Value: 'static,
867 {
868 let getter = self.getter;
869
870 OptionalKeyPath {
871 getter: move |root: &Root| {
872 getter(root).map(|rc| rc.deref())
873 },
874 _phantom: PhantomData,
875 }
876 }
877
878 #[cfg(feature = "tagged")]
879 pub fn for_tagged<Tag>(self) -> OptionalKeyPath<Tagged<Root, Tag>, Value, impl for<'r> Fn(&'r Tagged<Root, Tag>) -> Option<&'r Value> + 'static>
882 where
883 Tagged<Root, Tag>: std::ops::Deref<Target = Root>,
884 F: 'static,
885 Root: 'static,
886 Value: 'static,
887 Tag: 'static,
888 {
889 use std::ops::Deref;
890 let getter = self.getter;
891
892 OptionalKeyPath {
893 getter: move |tagged: &Tagged<Root, Tag>| {
894 getter(tagged.deref())
895 },
896 _phantom: PhantomData,
897 }
898 }
899
900 #[cfg(feature = "tagged")]
901 pub fn with_tagged<Tag, Callback, R>(&self, tagged: &Tagged<Root, Tag>, f: Callback) -> Option<R>
904 where
905 Tagged<Root, Tag>: std::ops::Deref<Target = Root>,
906 F: Clone,
907 Callback: FnOnce(&Value) -> R,
908 {
909 use std::ops::Deref;
910 self.get(tagged.deref()).map(|value| f(value))
911 }
912
913 pub fn for_option(self) -> OptionalKeyPath<Option<Root>, Value, impl for<'r> Fn(&'r Option<Root>) -> Option<&'r Value> + 'static>
916 where
917 F: 'static,
918 Root: 'static,
919 Value: 'static,
920 {
921 let getter = self.getter;
922
923 OptionalKeyPath {
924 getter: move |opt: &Option<Root>| {
925 opt.as_ref().and_then(|root| getter(root))
926 },
927 _phantom: PhantomData,
928 }
929 }
930
931 pub fn for_result<E>(self) -> OptionalKeyPath<Result<Root, E>, Value, impl for<'r> Fn(&'r Result<Root, E>) -> Option<&'r Value> + 'static>
934 where
935 F: 'static,
936 Root: 'static,
937 Value: 'static,
938 E: 'static,
939 {
940 let getter = self.getter;
941
942 OptionalKeyPath {
943 getter: move |result: &Result<Root, E>| {
944 result.as_ref().ok().and_then(|root| getter(root))
945 },
946 _phantom: PhantomData,
947 }
948 }
949
950 pub fn for_arc_root(self) -> OptionalKeyPath<Arc<Root>, Value, impl for<'r> Fn(&'r Arc<Root>) -> Option<&'r Value> + 'static>
952 where
953 Value: Sized,
954 F: 'static,
955 Root: 'static,
956 Value: 'static,
957 {
958 let getter = self.getter;
959
960 OptionalKeyPath {
961 getter: move |arc: &Arc<Root>| {
962 getter(arc.as_ref())
963 },
964 _phantom: PhantomData,
965 }
966 }
967
968 pub fn for_rc_root(self) -> OptionalKeyPath<Rc<Root>, Value, impl for<'r> Fn(&'r Rc<Root>) -> Option<&'r Value> + 'static>
970 where
971 Value: Sized,
972 F: 'static,
973 Root: 'static,
974 Value: 'static,
975 {
976 let getter = self.getter;
977
978 OptionalKeyPath {
979 getter: move |rc: &Rc<Root>| {
980 getter(rc.as_ref())
981 },
982 _phantom: PhantomData,
983 }
984 }
985
986 pub fn with_option<Callback, R>(&self, option: &Option<Root>, f: Callback) -> Option<R>
988 where
989 F: Clone,
990 Callback: FnOnce(&Value) -> R,
991 {
992 option.as_ref().and_then(|root| {
993 self.get(root).map(|value| f(value))
994 })
995 }
996
997 pub fn with_mutex<Callback, R>(&self, mutex: &Mutex<Root>, f: Callback) -> Option<R>
999 where
1000 F: Clone,
1001 Callback: FnOnce(&Value) -> R,
1002 {
1003 mutex.lock().ok().and_then(|guard| {
1004 self.get(&*guard).map(|value| f(value))
1005 })
1006 }
1007
1008 pub fn with_rwlock<Callback, R>(&self, rwlock: &RwLock<Root>, f: Callback) -> Option<R>
1010 where
1011 F: Clone,
1012 Callback: FnOnce(&Value) -> R,
1013 {
1014 rwlock.read().ok().and_then(|guard| {
1015 self.get(&*guard).map(|value| f(value))
1016 })
1017 }
1018
1019 pub fn with_arc_rwlock<Callback, R>(&self, arc_rwlock: &Arc<RwLock<Root>>, f: Callback) -> Option<R>
1021 where
1022 F: Clone,
1023 Callback: FnOnce(&Value) -> R,
1024 {
1025 arc_rwlock.read().ok().and_then(|guard| {
1026 self.get(&*guard).map(|value| f(value))
1027 })
1028 }
1029
1030 pub fn with_arc_rwlock_direct<Callback, R>(&self, arc_rwlock: &Arc<RwLock<Root>>, f: Callback) -> Option<R>
1034 where
1035 Callback: FnOnce(&Value) -> R,
1036 {
1037 arc_rwlock.read().ok().and_then(|guard| {
1038 self.get(&*guard).map(|value| f(value))
1039 })
1040 }
1041
1042 pub fn with_arc_mutex<Callback, R>(&self, arc_mutex: &Arc<Mutex<Root>>, f: Callback) -> Option<R>
1044 where
1045 F: Clone,
1046 Callback: FnOnce(&Value) -> R,
1047 {
1048 arc_mutex.lock().ok().and_then(|guard| {
1049 self.get(&*guard).map(|value| f(value))
1050 })
1051 }
1052}
1053
1054
1055#[derive(Clone)]
1057pub struct WritableKeyPath<Root, Value, F>
1058where
1059 F: for<'r> Fn(&'r mut Root) -> &'r mut Value,
1060{
1061 getter: F,
1062 _phantom: PhantomData<(Root, Value)>,
1063}
1064
1065impl<Root, Value, F> WritableKeyPath<Root, Value, F>
1066where
1067 F: for<'r> Fn(&'r mut Root) -> &'r mut Value,
1068{
1069 pub fn new(getter: F) -> Self {
1070 Self {
1071 getter,
1072 _phantom: PhantomData,
1073 }
1074 }
1075
1076 pub fn get_mut<'r>(&self, root: &'r mut Root) -> &'r mut Value {
1077 (self.getter)(root)
1078 }
1079
1080 pub fn for_result<E>(self) -> WritableOptionalKeyPath<Result<Root, E>, Value, impl for<'r> Fn(&'r mut Result<Root, E>) -> Option<&'r mut Value> + 'static>
1083 where
1084 F: 'static,
1085 Root: 'static,
1086 Value: 'static,
1087 E: 'static,
1088 {
1089 let getter = self.getter;
1090
1091 WritableOptionalKeyPath {
1092 getter: move |result: &mut Result<Root, E>| {
1093 result.as_mut().ok().map(|root| getter(root))
1094 },
1095 _phantom: PhantomData,
1096 }
1097 }
1098
1099 pub fn for_box_root(self) -> WritableKeyPath<Box<Root>, Value, impl for<'r> Fn(&'r mut Box<Root>) -> &'r mut Value + 'static>
1101 where
1102 Value: Sized,
1103 F: 'static,
1104 Root: 'static,
1105 Value: 'static,
1106 {
1107 let getter = self.getter;
1108
1109 WritableKeyPath {
1110 getter: move |boxed: &mut Box<Root>| {
1111 getter(boxed.as_mut())
1112 },
1113 _phantom: PhantomData,
1114 }
1115 }
1116
1117 pub fn for_option(self) -> WritableOptionalKeyPath<Option<Root>, Value, impl for<'r> Fn(&'r mut Option<Root>) -> Option<&'r mut Value> + 'static>
1120 where
1121 F: 'static,
1122 Root: 'static,
1123 Value: 'static,
1124 {
1125 let getter = self.getter;
1126
1127 WritableOptionalKeyPath {
1128 getter: move |option: &mut Option<Root>| {
1129 option.as_mut().map(|root| getter(root))
1130 },
1131 _phantom: PhantomData,
1132 }
1133 }
1134
1135 pub fn to_optional(self) -> WritableOptionalKeyPath<Root, Value, impl for<'r> Fn(&'r mut Root) -> Option<&'r mut Value> + 'static>
1138 where
1139 F: 'static,
1140 {
1141 let getter = self.getter;
1142 WritableOptionalKeyPath::new(move |root: &mut Root| Some(getter(root)))
1143 }
1144
1145 pub fn for_box<Target>(self) -> WritableKeyPath<Root, Target, impl for<'r> Fn(&'r mut Root) -> &'r mut Target + 'static>
1148 where
1149 Value: std::ops::DerefMut<Target = Target>,
1150 F: 'static,
1151 Value: 'static,
1152 {
1153 let getter = self.getter;
1154
1155 WritableKeyPath {
1156 getter: move |root: &mut Root| {
1157 getter(root).deref_mut()
1158 },
1159 _phantom: PhantomData,
1160 }
1161 }
1162
1163 pub fn for_arc<Target>(self) -> WritableKeyPath<Root, Target, impl for<'r> Fn(&'r mut Root) -> &'r mut Target + 'static>
1166 where
1167 Value: std::ops::DerefMut<Target = Target>,
1168 F: 'static,
1169 Value: 'static,
1170 {
1171 let getter = self.getter;
1172
1173 WritableKeyPath {
1174 getter: move |root: &mut Root| {
1175 getter(root).deref_mut()
1176 },
1177 _phantom: PhantomData,
1178 }
1179 }
1180
1181 pub fn for_rc<Target>(self) -> WritableKeyPath<Root, Target, impl for<'r> Fn(&'r mut Root) -> &'r mut Target + 'static>
1184 where
1185 Value: std::ops::DerefMut<Target = Target>,
1186 F: 'static,
1187 Value: 'static,
1188 {
1189 let getter = self.getter;
1190
1191 WritableKeyPath {
1192 getter: move |root: &mut Root| {
1193 getter(root).deref_mut()
1194 },
1195 _phantom: PhantomData,
1196 }
1197 }
1198
1199 pub fn with_box_mut<Callback, R>(&self, boxed: &mut Box<Root>, f: Callback) -> R
1201 where
1202 F: Clone,
1203 Callback: FnOnce(&mut Value) -> R,
1204 {
1205 let value = self.get_mut(boxed);
1206 f(value)
1207 }
1208
1209 pub fn with_result_mut<Callback, R, E>(&self, result: &mut Result<Root, E>, f: Callback) -> Option<R>
1211 where
1212 F: Clone,
1213 Callback: FnOnce(&mut Value) -> R,
1214 {
1215 result.as_mut().ok().map(|root| {
1216 let value = self.get_mut(root);
1217 f(value)
1218 })
1219 }
1220
1221 pub fn with_option_mut<Callback, R>(&self, option: &mut Option<Root>, f: Callback) -> Option<R>
1223 where
1224 F: Clone,
1225 Callback: FnOnce(&mut Value) -> R,
1226 {
1227 option.as_mut().map(|root| {
1228 let value = self.get_mut(root);
1229 f(value)
1230 })
1231 }
1232
1233 pub fn with_refcell_mut<Callback, R>(&self, refcell: &RefCell<Root>, f: Callback) -> Option<R>
1235 where
1236 F: Clone,
1237 Callback: FnOnce(&mut Value) -> R,
1238 {
1239 refcell.try_borrow_mut().ok().map(|mut borrow| {
1240 let value = self.get_mut(&mut *borrow);
1241 f(value)
1242 })
1243 }
1244
1245 pub fn with_mutex_mut<Callback, R>(&self, mutex: &mut Mutex<Root>, f: Callback) -> Option<R>
1247 where
1248 F: Clone,
1249 Callback: FnOnce(&mut Value) -> R,
1250 {
1251 mutex.get_mut().ok().map(|root| {
1252 let value = self.get_mut(root);
1253 f(value)
1254 })
1255 }
1256
1257 pub fn with_rwlock_mut<Callback, R>(&self, rwlock: &mut RwLock<Root>, f: Callback) -> Option<R>
1259 where
1260 F: Clone,
1261 Callback: FnOnce(&mut Value) -> R,
1262 {
1263 rwlock.write().ok().map(|mut guard| {
1264 let value = self.get_mut(&mut *guard);
1265 f(value)
1266 })
1267 }
1268
1269 pub fn iter_mut<'r, T>(&self, root: &'r mut Root) -> Option<std::slice::IterMut<'r, T>>
1272 where
1273 Value: AsMut<[T]> + 'r,
1274 {
1275 let value_ref: &'r mut Value = self.get_mut(root);
1276 Some(value_ref.as_mut().iter_mut())
1277 }
1278
1279 pub fn extract_mut_from_slice<'r>(&self, slice: &'r mut [Root]) -> Vec<&'r mut Value> {
1282 slice.iter_mut().map(|item| self.get_mut(item)).collect()
1283 }
1284
1285 pub fn extract_mut_from_ref_slice<'r>(&self, slice: &'r mut [&'r mut Root]) -> Vec<&'r mut Value> {
1288 slice.iter_mut().map(|item| self.get_mut(*item)).collect()
1289 }
1290}
1291
1292#[derive(Clone)]
1294pub struct WritableOptionalKeyPath<Root, Value, F>
1295where
1296 F: for<'r> Fn(&'r mut Root) -> Option<&'r mut Value>,
1297{
1298 getter: F,
1299 _phantom: PhantomData<(Root, Value)>,
1300}
1301
1302impl<Root, Value, F> WritableOptionalKeyPath<Root, Value, F>
1303where
1304 F: for<'r> Fn(&'r mut Root) -> Option<&'r mut Value>,
1305{
1306 pub fn new(getter: F) -> Self {
1307 Self {
1308 getter,
1309 _phantom: PhantomData,
1310 }
1311 }
1312
1313 pub fn get_mut<'r>(&self, root: &'r mut Root) -> Option<&'r mut Value> {
1314 (self.getter)(root)
1315 }
1316
1317 pub fn for_option(self) -> WritableOptionalKeyPath<Option<Root>, Value, impl for<'r> Fn(&'r mut Option<Root>) -> Option<&'r mut Value> + 'static>
1320 where
1321 F: 'static,
1322 Root: 'static,
1323 Value: 'static,
1324 {
1325 let getter = self.getter;
1326
1327 WritableOptionalKeyPath {
1328 getter: move |option: &mut Option<Root>| {
1329 option.as_mut().and_then(|root| getter(root))
1330 },
1331 _phantom: PhantomData,
1332 }
1333 }
1334
1335 pub fn then<SubValue, G>(
1337 self,
1338 next: WritableOptionalKeyPath<Value, SubValue, G>,
1339 ) -> WritableOptionalKeyPath<Root, SubValue, impl for<'r> Fn(&'r mut Root) -> Option<&'r mut SubValue>>
1340 where
1341 G: for<'r> Fn(&'r mut Value) -> Option<&'r mut SubValue>,
1342 F: 'static,
1343 G: 'static,
1344 Value: 'static,
1345 {
1346 let first = self.getter;
1347 let second = next.getter;
1348
1349 WritableOptionalKeyPath::new(move |root: &mut Root| {
1350 first(root).and_then(|value| second(value))
1351 })
1352 }
1353
1354 pub fn for_box<Target>(self) -> WritableOptionalKeyPath<Root, Target, impl for<'r> Fn(&'r mut Root) -> Option<&'r mut Target> + 'static>
1357 where
1358 Value: std::ops::DerefMut<Target = Target>,
1359 F: 'static,
1360 Value: 'static,
1361 {
1362 let getter = self.getter;
1363
1364 WritableOptionalKeyPath {
1365 getter: move |root: &mut Root| {
1366 getter(root).map(|boxed| boxed.deref_mut())
1367 },
1368 _phantom: PhantomData,
1369 }
1370 }
1371
1372 pub fn for_arc<Target>(self) -> WritableOptionalKeyPath<Root, Target, impl for<'r> Fn(&'r mut Root) -> Option<&'r mut Target> + 'static>
1374 where
1375 Value: std::ops::DerefMut<Target = Target>,
1376 F: 'static,
1377 Value: 'static,
1378 {
1379 let getter = self.getter;
1380
1381 WritableOptionalKeyPath {
1382 getter: move |root: &mut Root| {
1383 getter(root).map(|arc| arc.deref_mut())
1384 },
1385 _phantom: PhantomData,
1386 }
1387 }
1388
1389 pub fn for_rc<Target>(self) -> WritableOptionalKeyPath<Root, Target, impl for<'r> Fn(&'r mut Root) -> Option<&'r mut Target> + 'static>
1391 where
1392 Value: std::ops::DerefMut<Target = Target>,
1393 F: 'static,
1394 Value: 'static,
1395 {
1396 let getter = self.getter;
1397
1398 WritableOptionalKeyPath {
1399 getter: move |root: &mut Root| {
1400 getter(root).map(|rc| rc.deref_mut())
1401 },
1402 _phantom: PhantomData,
1403 }
1404 }
1405
1406 pub fn for_result<E>(self) -> WritableOptionalKeyPath<Result<Root, E>, Value, impl for<'r> Fn(&'r mut Result<Root, E>) -> Option<&'r mut Value> + 'static>
1409 where
1410 F: 'static,
1411 Root: 'static,
1412 Value: 'static,
1413 E: 'static,
1414 {
1415 let getter = self.getter;
1416
1417 WritableOptionalKeyPath {
1418 getter: move |result: &mut Result<Root, E>| {
1419 result.as_mut().ok().and_then(|root| getter(root))
1420 },
1421 _phantom: PhantomData,
1422 }
1423 }
1424
1425 pub fn for_box_root(self) -> WritableOptionalKeyPath<Box<Root>, Value, impl for<'r> Fn(&'r mut Box<Root>) -> Option<&'r mut Value> + 'static>
1427 where
1428 Value: Sized,
1429 F: 'static,
1430 Root: 'static,
1431 Value: 'static,
1432 {
1433 let getter = self.getter;
1434
1435 WritableOptionalKeyPath {
1436 getter: move |boxed: &mut Box<Root>| {
1437 getter(boxed.as_mut())
1438 },
1439 _phantom: PhantomData,
1440 }
1441 }
1442
1443 pub fn for_arc_root(self) -> WritableOptionalKeyPath<Arc<Root>, Value, impl for<'r> Fn(&'r mut Arc<Root>) -> Option<&'r mut Value> + 'static>
1445 where
1446 Value: Sized,
1447 F: 'static,
1448 Root: 'static,
1449 Value: 'static,
1450 {
1451 let getter = self.getter;
1452
1453 WritableOptionalKeyPath {
1454 getter: move |arc: &mut Arc<Root>| {
1455 None
1458 },
1459 _phantom: PhantomData,
1460 }
1461 }
1462
1463 pub fn for_rc_root(self) -> WritableOptionalKeyPath<Rc<Root>, Value, impl for<'r> Fn(&'r mut Rc<Root>) -> Option<&'r mut Value> + 'static>
1465 where
1466 Value: Sized,
1467 F: 'static,
1468 Root: 'static,
1469 Value: 'static,
1470 {
1471 let getter = self.getter;
1472
1473 WritableOptionalKeyPath {
1474 getter: move |rc: &mut Rc<Root>| {
1475 None
1478 },
1479 _phantom: PhantomData,
1480 }
1481 }
1482}
1483
1484impl WritableOptionalKeyPath<(), (), fn(&mut ()) -> Option<&mut ()>> {
1486 pub fn for_option_static<T>() -> WritableOptionalKeyPath<Option<T>, T, impl for<'r> Fn(&'r mut Option<T>) -> Option<&'r mut T>> {
1489 WritableOptionalKeyPath::new(|opt: &mut Option<T>| opt.as_mut())
1490 }
1491
1492 pub fn writable_enum<Enum, Variant, EmbedFn, ReadExtractFn, WriteExtractFn>(
1513 _embedder: EmbedFn,
1514 _read_extractor: ReadExtractFn,
1515 write_extractor: WriteExtractFn,
1516 ) -> WritableOptionalKeyPath<Enum, Variant, impl for<'r> Fn(&'r mut Enum) -> Option<&'r mut Variant> + 'static>
1517 where
1518 EmbedFn: Fn(Variant) -> Enum + 'static,
1519 ReadExtractFn: for<'r> Fn(&'r Enum) -> Option<&'r Variant> + 'static,
1520 WriteExtractFn: for<'r> Fn(&'r mut Enum) -> Option<&'r mut Variant> + 'static,
1521 {
1522 WritableOptionalKeyPath::new(write_extractor)
1523 }
1524}
1525
1526pub struct EnumKeyPath<Enum = (), Variant = (), ExtractFn = fn(&()) -> Option<&()>, EmbedFn = fn(()) -> ()>
1534where
1535 ExtractFn: for<'r> Fn(&'r Enum) -> Option<&'r Variant> + 'static,
1536 EmbedFn: Fn(Variant) -> Enum + 'static,
1537{
1538 extractor: OptionalKeyPath<Enum, Variant, ExtractFn>,
1539 embedder: EmbedFn,
1540}
1541
1542impl<Enum, Variant, ExtractFn, EmbedFn> EnumKeyPath<Enum, Variant, ExtractFn, EmbedFn>
1543where
1544 ExtractFn: for<'r> Fn(&'r Enum) -> Option<&'r Variant> + 'static,
1545 EmbedFn: Fn(Variant) -> Enum + 'static,
1546{
1547 pub fn new(
1549 extractor: ExtractFn,
1550 embedder: EmbedFn,
1551 ) -> Self {
1552 Self {
1553 extractor: OptionalKeyPath::new(extractor),
1554 embedder,
1555 }
1556 }
1557
1558 pub fn get<'r>(&self, enum_value: &'r Enum) -> Option<&'r Variant> {
1560 self.extractor.get(enum_value)
1561 }
1562
1563 pub fn embed(&self, value: Variant) -> Enum {
1565 (self.embedder)(value)
1566 }
1567
1568 pub fn as_optional(&self) -> &OptionalKeyPath<Enum, Variant, ExtractFn> {
1570 &self.extractor
1571 }
1572
1573 pub fn to_optional(self) -> OptionalKeyPath<Enum, Variant, ExtractFn> {
1575 self.extractor
1576 }
1577}
1578
1579impl EnumKeyPath {
1581 pub fn readable_enum<Enum, Variant, ExtractFn, EmbedFn>(
1584 embedder: EmbedFn,
1585 extractor: ExtractFn,
1586 ) -> EnumKeyPath<Enum, Variant, ExtractFn, EmbedFn>
1587 where
1588 ExtractFn: for<'r> Fn(&'r Enum) -> Option<&'r Variant> + 'static,
1589 EmbedFn: Fn(Variant) -> Enum + 'static,
1590 {
1591 EnumKeyPath::new(extractor, embedder)
1592 }
1593
1594 pub fn for_variant<Enum, Variant, ExtractFn>(
1596 extractor: ExtractFn
1597 ) -> OptionalKeyPath<Enum, Variant, impl for<'r> Fn(&'r Enum) -> Option<&'r Variant>>
1598 where
1599 ExtractFn: Fn(&Enum) -> Option<&Variant>,
1600 {
1601 OptionalKeyPath::new(extractor)
1602 }
1603
1604 pub fn for_match<Enum, Output, MatchFn>(
1606 matcher: MatchFn
1607 ) -> KeyPath<Enum, Output, impl for<'r> Fn(&'r Enum) -> &'r Output>
1608 where
1609 MatchFn: Fn(&Enum) -> &Output,
1610 {
1611 KeyPath::new(matcher)
1612 }
1613
1614 pub fn for_ok<T, E>() -> OptionalKeyPath<Result<T, E>, T, impl for<'r> Fn(&'r Result<T, E>) -> Option<&'r T>> {
1616 OptionalKeyPath::new(|result: &Result<T, E>| result.as_ref().ok())
1617 }
1618
1619 pub fn for_err<T, E>() -> OptionalKeyPath<Result<T, E>, E, impl for<'r> Fn(&'r Result<T, E>) -> Option<&'r E>> {
1621 OptionalKeyPath::new(|result: &Result<T, E>| result.as_ref().err())
1622 }
1623
1624 pub fn for_some<T>() -> OptionalKeyPath<Option<T>, T, impl for<'r> Fn(&'r Option<T>) -> Option<&'r T>> {
1626 OptionalKeyPath::new(|opt: &Option<T>| opt.as_ref())
1627 }
1628
1629 pub fn for_option<T>() -> OptionalKeyPath<Option<T>, T, impl for<'r> Fn(&'r Option<T>) -> Option<&'r T>> {
1631 OptionalKeyPath::new(|opt: &Option<T>| opt.as_ref())
1632 }
1633
1634 pub fn for_box<T>() -> KeyPath<Box<T>, T, impl for<'r> Fn(&'r Box<T>) -> &'r T> {
1636 KeyPath::new(|b: &Box<T>| b.as_ref())
1637 }
1638
1639 pub fn for_arc<T>() -> KeyPath<Arc<T>, T, impl for<'r> Fn(&'r Arc<T>) -> &'r T> {
1641 KeyPath::new(|arc: &Arc<T>| arc.as_ref())
1642 }
1643
1644 pub fn for_rc<T>() -> KeyPath<std::rc::Rc<T>, T, impl for<'r> Fn(&'r std::rc::Rc<T>) -> &'r T> {
1646 KeyPath::new(|rc: &std::rc::Rc<T>| rc.as_ref())
1647 }
1648
1649 pub fn for_box_mut<T>() -> WritableKeyPath<Box<T>, T, impl for<'r> Fn(&'r mut Box<T>) -> &'r mut T> {
1651 WritableKeyPath::new(|b: &mut Box<T>| b.as_mut())
1652 }
1653
1654 }
1658
1659pub fn variant_of<Enum, Variant, F>(extractor: F) -> OptionalKeyPath<Enum, Variant, F>
1661where
1662 F: for<'r> Fn(&'r Enum) -> Option<&'r Variant>,
1663{
1664 OptionalKeyPath::new(extractor)
1665}
1666
1667#[derive(Clone)]
1683pub struct PartialKeyPath<Root> {
1684 getter: Rc<dyn for<'r> Fn(&'r Root) -> &'r dyn Any>,
1685 value_type_id: TypeId,
1686 _phantom: PhantomData<Root>,
1687}
1688
1689impl<Root> PartialKeyPath<Root> {
1690 pub fn new<Value>(keypath: KeyPath<Root, Value, impl for<'r> Fn(&'r Root) -> &'r Value + 'static>) -> Self
1691 where
1692 Value: Any + 'static,
1693 Root: 'static,
1694 {
1695 let value_type_id = TypeId::of::<Value>();
1696 let getter = Rc::new(keypath.getter);
1697
1698 Self {
1699 getter: Rc::new(move |root: &Root| {
1700 let value: &Value = getter(root);
1701 value as &dyn Any
1702 }),
1703 value_type_id,
1704 _phantom: PhantomData,
1705 }
1706 }
1707
1708 pub fn from<Value>(keypath: KeyPath<Root, Value, impl for<'r> Fn(&'r Root) -> &'r Value + 'static>) -> Self
1711 where
1712 Value: Any + 'static,
1713 Root: 'static,
1714 {
1715 Self::new(keypath)
1716 }
1717
1718 pub fn get<'r>(&self, root: &'r Root) -> &'r dyn Any {
1719 (self.getter)(root)
1720 }
1721
1722 pub fn value_type_id(&self) -> TypeId {
1724 self.value_type_id
1725 }
1726
1727 pub fn get_as<'a, Value: Any>(&self, root: &'a Root) -> Option<&'a Value> {
1729 if self.value_type_id == TypeId::of::<Value>() {
1730 self.get(root).downcast_ref::<Value>()
1731 } else {
1732 None
1733 }
1734 }
1735
1736 pub fn kind_name(&self) -> String {
1739 format!("{:?}", self.value_type_id)
1740 }
1741
1742 pub fn for_arc(&self) -> PartialOptionalKeyPath<Arc<Root>>
1744 where
1745 Root: 'static,
1746 {
1747 let getter = self.getter.clone();
1748 let value_type_id = self.value_type_id;
1749
1750 PartialOptionalKeyPath {
1751 getter: Rc::new(move |arc: &Arc<Root>| {
1752 Some(getter(arc.as_ref()))
1753 }),
1754 value_type_id,
1755 _phantom: PhantomData,
1756 }
1757 }
1758
1759 pub fn for_box(&self) -> PartialOptionalKeyPath<Box<Root>>
1761 where
1762 Root: 'static,
1763 {
1764 let getter = self.getter.clone();
1765 let value_type_id = self.value_type_id;
1766
1767 PartialOptionalKeyPath {
1768 getter: Rc::new(move |boxed: &Box<Root>| {
1769 Some(getter(boxed.as_ref()))
1770 }),
1771 value_type_id,
1772 _phantom: PhantomData,
1773 }
1774 }
1775
1776 pub fn for_rc(&self) -> PartialOptionalKeyPath<Rc<Root>>
1778 where
1779 Root: 'static,
1780 {
1781 let getter = self.getter.clone();
1782 let value_type_id = self.value_type_id;
1783
1784 PartialOptionalKeyPath {
1785 getter: Rc::new(move |rc: &Rc<Root>| {
1786 Some(getter(rc.as_ref()))
1787 }),
1788 value_type_id,
1789 _phantom: PhantomData,
1790 }
1791 }
1792
1793 pub fn for_option(&self) -> PartialOptionalKeyPath<Option<Root>>
1795 where
1796 Root: 'static,
1797 {
1798 let getter = self.getter.clone();
1799 let value_type_id = self.value_type_id;
1800
1801 PartialOptionalKeyPath {
1802 getter: Rc::new(move |opt: &Option<Root>| {
1803 opt.as_ref().map(|root| getter(root))
1804 }),
1805 value_type_id,
1806 _phantom: PhantomData,
1807 }
1808 }
1809
1810 pub fn for_result<E>(&self) -> PartialOptionalKeyPath<Result<Root, E>>
1812 where
1813 Root: 'static,
1814 E: 'static,
1815 {
1816 let getter = self.getter.clone();
1817 let value_type_id = self.value_type_id;
1818
1819 PartialOptionalKeyPath {
1820 getter: Rc::new(move |result: &Result<Root, E>| {
1821 result.as_ref().ok().map(|root| getter(root))
1822 }),
1823 value_type_id,
1824 _phantom: PhantomData,
1825 }
1826 }
1827
1828 pub fn for_arc_rwlock(&self) -> PartialOptionalKeyPath<Arc<RwLock<Root>>>
1832 where
1833 Root: Clone + 'static,
1834 {
1835 PartialOptionalKeyPath {
1838 getter: Rc::new(move |_arc_rwlock: &Arc<RwLock<Root>>| {
1839 None
1842 }),
1843 value_type_id: self.value_type_id,
1844 _phantom: PhantomData,
1845 }
1846 }
1847
1848 pub fn for_arc_mutex(&self) -> PartialOptionalKeyPath<Arc<Mutex<Root>>>
1852 where
1853 Root: Clone + 'static,
1854 {
1855 PartialOptionalKeyPath {
1858 getter: Rc::new(move |_arc_mutex: &Arc<Mutex<Root>>| {
1859 None
1862 }),
1863 value_type_id: self.value_type_id,
1864 _phantom: PhantomData,
1865 }
1866 }
1867}
1868
1869#[derive(Clone)]
1876pub struct PartialOptionalKeyPath<Root> {
1877 getter: Rc<dyn for<'r> Fn(&'r Root) -> Option<&'r dyn Any>>,
1878 value_type_id: TypeId,
1879 _phantom: PhantomData<Root>,
1880}
1881
1882impl<Root> PartialOptionalKeyPath<Root> {
1883 pub fn new<Value>(keypath: OptionalKeyPath<Root, Value, impl for<'r> Fn(&'r Root) -> Option<&'r Value> + 'static>) -> Self
1884 where
1885 Value: Any + 'static,
1886 Root: 'static,
1887 {
1888 let value_type_id = TypeId::of::<Value>();
1889 let getter = Rc::new(keypath.getter);
1890
1891 Self {
1892 getter: Rc::new(move |root: &Root| {
1893 getter(root).map(|value: &Value| value as &dyn Any)
1894 }),
1895 value_type_id,
1896 _phantom: PhantomData,
1897 }
1898 }
1899
1900 pub fn get<'r>(&self, root: &'r Root) -> Option<&'r dyn Any> {
1901 (self.getter)(root)
1902 }
1903
1904 pub fn value_type_id(&self) -> TypeId {
1906 self.value_type_id
1907 }
1908
1909 pub fn get_as<'a, Value: Any>(&self, root: &'a Root) -> Option<Option<&'a Value>> {
1911 if self.value_type_id == TypeId::of::<Value>() {
1912 self.get(root).map(|any| any.downcast_ref::<Value>())
1913 } else {
1914 None
1915 }
1916 }
1917
1918 pub fn then<MidValue>(
1922 self,
1923 next: PartialOptionalKeyPath<MidValue>,
1924 ) -> PartialOptionalKeyPath<Root>
1925 where
1926 MidValue: Any + 'static,
1927 Root: 'static,
1928 {
1929 let first = self.getter;
1930 let second = next.getter;
1931 let value_type_id = next.value_type_id;
1932
1933 PartialOptionalKeyPath {
1934 getter: Rc::new(move |root: &Root| {
1935 first(root).and_then(|any| {
1936 if let Some(mid_value) = any.downcast_ref::<MidValue>() {
1937 second(mid_value)
1938 } else {
1939 None
1940 }
1941 })
1942 }),
1943 value_type_id,
1944 _phantom: PhantomData,
1945 }
1946 }
1947}
1948
1949#[derive(Clone)]
1955pub struct PartialWritableKeyPath<Root> {
1956 getter: Rc<dyn for<'r> Fn(&'r mut Root) -> &'r mut dyn Any>,
1957 value_type_id: TypeId,
1958 _phantom: PhantomData<Root>,
1959}
1960
1961impl<Root> PartialWritableKeyPath<Root> {
1962 pub fn new<Value>(keypath: WritableKeyPath<Root, Value, impl for<'r> Fn(&'r mut Root) -> &'r mut Value + 'static>) -> Self
1963 where
1964 Value: Any + 'static,
1965 Root: 'static,
1966 {
1967 let value_type_id = TypeId::of::<Value>();
1968 let getter = Rc::new(keypath.getter);
1969
1970 Self {
1971 getter: Rc::new(move |root: &mut Root| {
1972 let value: &mut Value = getter(root);
1973 value as &mut dyn Any
1974 }),
1975 value_type_id,
1976 _phantom: PhantomData,
1977 }
1978 }
1979
1980 pub fn from<Value>(keypath: WritableKeyPath<Root, Value, impl for<'r> Fn(&'r mut Root) -> &'r mut Value + 'static>) -> Self
1983 where
1984 Value: Any + 'static,
1985 Root: 'static,
1986 {
1987 Self::new(keypath)
1988 }
1989
1990 pub fn get_mut<'r>(&self, root: &'r mut Root) -> &'r mut dyn Any {
1991 (self.getter)(root)
1992 }
1993
1994 pub fn value_type_id(&self) -> TypeId {
1996 self.value_type_id
1997 }
1998
1999 pub fn get_mut_as<'a, Value: Any>(&self, root: &'a mut Root) -> Option<&'a mut Value> {
2001 if self.value_type_id == TypeId::of::<Value>() {
2002 self.get_mut(root).downcast_mut::<Value>()
2003 } else {
2004 None
2005 }
2006 }
2007}
2008
2009#[derive(Clone)]
2015pub struct PartialWritableOptionalKeyPath<Root> {
2016 getter: Rc<dyn for<'r> Fn(&'r mut Root) -> Option<&'r mut dyn Any>>,
2017 value_type_id: TypeId,
2018 _phantom: PhantomData<Root>,
2019}
2020
2021impl<Root> PartialWritableOptionalKeyPath<Root> {
2022 pub fn new<Value>(keypath: WritableOptionalKeyPath<Root, Value, impl for<'r> Fn(&'r mut Root) -> Option<&'r mut Value> + 'static>) -> Self
2023 where
2024 Value: Any + 'static,
2025 Root: 'static,
2026 {
2027 let value_type_id = TypeId::of::<Value>();
2028 let getter = Rc::new(keypath.getter);
2029
2030 Self {
2031 getter: Rc::new(move |root: &mut Root| {
2032 getter(root).map(|value: &mut Value| value as &mut dyn Any)
2033 }),
2034 value_type_id,
2035 _phantom: PhantomData,
2036 }
2037 }
2038
2039 pub fn get_mut<'r>(&self, root: &'r mut Root) -> Option<&'r mut dyn Any> {
2040 (self.getter)(root)
2041 }
2042
2043 pub fn value_type_id(&self) -> TypeId {
2045 self.value_type_id
2046 }
2047
2048 pub fn get_mut_as<'a, Value: Any>(&self, root: &'a mut Root) -> Option<Option<&'a mut Value>> {
2050 if self.value_type_id == TypeId::of::<Value>() {
2051 self.get_mut(root).map(|any| any.downcast_mut::<Value>())
2052 } else {
2053 None
2054 }
2055 }
2056}
2057
2058#[derive(Clone)]
2072pub struct AnyKeyPath {
2073 getter: Rc<dyn for<'r> Fn(&'r dyn Any) -> Option<&'r dyn Any>>,
2074 root_type_id: TypeId,
2075 value_type_id: TypeId,
2076}
2077
2078impl AnyKeyPath {
2079 pub fn new<Root, Value>(keypath: OptionalKeyPath<Root, Value, impl for<'r> Fn(&'r Root) -> Option<&'r Value> + 'static>) -> Self
2080 where
2081 Root: Any + 'static,
2082 Value: Any + 'static,
2083 {
2084 let root_type_id = TypeId::of::<Root>();
2085 let value_type_id = TypeId::of::<Value>();
2086 let getter = keypath.getter;
2087
2088 Self {
2089 getter: Rc::new(move |any: &dyn Any| {
2090 if let Some(root) = any.downcast_ref::<Root>() {
2091 getter(root).map(|value: &Value| value as &dyn Any)
2092 } else {
2093 None
2094 }
2095 }),
2096 root_type_id,
2097 value_type_id,
2098 }
2099 }
2100
2101 pub fn from<Root, Value>(keypath: OptionalKeyPath<Root, Value, impl for<'r> Fn(&'r Root) -> Option<&'r Value> + 'static>) -> Self
2104 where
2105 Root: Any + 'static,
2106 Value: Any + 'static,
2107 {
2108 Self::new(keypath)
2109 }
2110
2111 pub fn get<'r>(&self, root: &'r dyn Any) -> Option<&'r dyn Any> {
2112 (self.getter)(root)
2113 }
2114
2115 pub fn root_type_id(&self) -> TypeId {
2117 self.root_type_id
2118 }
2119
2120 pub fn value_type_id(&self) -> TypeId {
2122 self.value_type_id
2123 }
2124
2125 pub fn get_as<'a, Root: Any, Value: Any>(&self, root: &'a Root) -> Option<Option<&'a Value>> {
2127 if self.root_type_id == TypeId::of::<Root>() && self.value_type_id == TypeId::of::<Value>() {
2128 self.get(root as &dyn Any).map(|any| any.downcast_ref::<Value>())
2129 } else {
2130 None
2131 }
2132 }
2133
2134 pub fn kind_name(&self) -> String {
2137 format!("{:?}", self.value_type_id)
2138 }
2139
2140 pub fn for_arc<Root>(&self) -> AnyKeyPath
2142 where
2143 Root: Any + 'static,
2144 {
2145 let root_type_id = self.root_type_id;
2146 let value_type_id = self.value_type_id;
2147 let getter = self.getter.clone();
2148
2149 AnyKeyPath {
2150 getter: Rc::new(move |any: &dyn Any| {
2151 if let Some(arc) = any.downcast_ref::<Arc<Root>>() {
2152 getter(arc.as_ref() as &dyn Any)
2153 } else {
2154 None
2155 }
2156 }),
2157 root_type_id: TypeId::of::<Arc<Root>>(),
2158 value_type_id,
2159 }
2160 }
2161
2162 pub fn for_box<Root>(&self) -> AnyKeyPath
2164 where
2165 Root: Any + 'static,
2166 {
2167 let root_type_id = self.root_type_id;
2168 let value_type_id = self.value_type_id;
2169 let getter = self.getter.clone();
2170
2171 AnyKeyPath {
2172 getter: Rc::new(move |any: &dyn Any| {
2173 if let Some(boxed) = any.downcast_ref::<Box<Root>>() {
2174 getter(boxed.as_ref() as &dyn Any)
2175 } else {
2176 None
2177 }
2178 }),
2179 root_type_id: TypeId::of::<Box<Root>>(),
2180 value_type_id,
2181 }
2182 }
2183
2184 pub fn for_rc<Root>(&self) -> AnyKeyPath
2186 where
2187 Root: Any + 'static,
2188 {
2189 let root_type_id = self.root_type_id;
2190 let value_type_id = self.value_type_id;
2191 let getter = self.getter.clone();
2192
2193 AnyKeyPath {
2194 getter: Rc::new(move |any: &dyn Any| {
2195 if let Some(rc) = any.downcast_ref::<Rc<Root>>() {
2196 getter(rc.as_ref() as &dyn Any)
2197 } else {
2198 None
2199 }
2200 }),
2201 root_type_id: TypeId::of::<Rc<Root>>(),
2202 value_type_id,
2203 }
2204 }
2205
2206 pub fn for_option<Root>(&self) -> AnyKeyPath
2208 where
2209 Root: Any + 'static,
2210 {
2211 let root_type_id = self.root_type_id;
2212 let value_type_id = self.value_type_id;
2213 let getter = self.getter.clone();
2214
2215 AnyKeyPath {
2216 getter: Rc::new(move |any: &dyn Any| {
2217 if let Some(opt) = any.downcast_ref::<Option<Root>>() {
2218 opt.as_ref().and_then(|root| getter(root as &dyn Any))
2219 } else {
2220 None
2221 }
2222 }),
2223 root_type_id: TypeId::of::<Option<Root>>(),
2224 value_type_id,
2225 }
2226 }
2227
2228 pub fn for_result<Root, E>(&self) -> AnyKeyPath
2230 where
2231 Root: Any + 'static,
2232 E: Any + 'static,
2233 {
2234 let root_type_id = self.root_type_id;
2235 let value_type_id = self.value_type_id;
2236 let getter = self.getter.clone();
2237
2238 AnyKeyPath {
2239 getter: Rc::new(move |any: &dyn Any| {
2240 if let Some(result) = any.downcast_ref::<Result<Root, E>>() {
2241 result.as_ref().ok().and_then(|root| getter(root as &dyn Any))
2242 } else {
2243 None
2244 }
2245 }),
2246 root_type_id: TypeId::of::<Result<Root, E>>(),
2247 value_type_id,
2248 }
2249 }
2250
2251 pub fn for_arc_rwlock<Root>(&self) -> AnyKeyPath
2254 where
2255 Root: Any + Clone + 'static,
2256 {
2257 AnyKeyPath {
2260 getter: Rc::new(move |_any: &dyn Any| {
2261 None
2264 }),
2265 root_type_id: TypeId::of::<Arc<RwLock<Root>>>(),
2266 value_type_id: self.value_type_id,
2267 }
2268 }
2269
2270 pub fn for_arc_mutex<Root>(&self) -> AnyKeyPath
2273 where
2274 Root: Any + Clone + 'static,
2275 {
2276 AnyKeyPath {
2279 getter: Rc::new(move |_any: &dyn Any| {
2280 None
2283 }),
2284 root_type_id: TypeId::of::<Arc<Mutex<Root>>>(),
2285 value_type_id: self.value_type_id,
2286 }
2287 }
2288}
2289
2290#[derive(Clone)]
2292pub struct AnyWritableKeyPath {
2293 getter: Rc<dyn for<'r> Fn(&'r mut dyn Any) -> Option<&'r mut dyn Any>>,
2294 root_type_id: TypeId,
2295 value_type_id: TypeId,
2296}
2297
2298#[derive(Clone)]
2303pub struct FailableCombinedKeyPath<Root, Value, ReadFn, WriteFn, OwnedFn>
2304where
2305 ReadFn: for<'r> Fn(&'r Root) -> Option<&'r Value> + 'static,
2306 WriteFn: for<'r> Fn(&'r mut Root) -> Option<&'r mut Value> + 'static,
2307 OwnedFn: Fn(Root) -> Option<Value> + 'static,
2308{
2309 readable: ReadFn,
2310 writable: WriteFn,
2311 owned: OwnedFn,
2312 _phantom: PhantomData<(Root, Value)>,
2313}
2314
2315impl<Root, Value, ReadFn, WriteFn, OwnedFn> FailableCombinedKeyPath<Root, Value, ReadFn, WriteFn, OwnedFn>
2316where
2317 ReadFn: for<'r> Fn(&'r Root) -> Option<&'r Value> + 'static,
2318 WriteFn: for<'r> Fn(&'r mut Root) -> Option<&'r mut Value> + 'static,
2319 OwnedFn: Fn(Root) -> Option<Value> + 'static,
2320{
2321 pub fn new(readable: ReadFn, writable: WriteFn, owned: OwnedFn) -> Self {
2323 Self {
2324 readable,
2325 writable,
2326 owned,
2327 _phantom: PhantomData,
2328 }
2329 }
2330
2331 pub fn get<'r>(&self, root: &'r Root) -> Option<&'r Value> {
2333 (self.readable)(root)
2334 }
2335
2336 pub fn get_mut<'r>(&self, root: &'r mut Root) -> Option<&'r mut Value> {
2338 (self.writable)(root)
2339 }
2340
2341 pub fn get_failable_owned(&self, root: Root) -> Option<Value> {
2343 (self.owned)(root)
2344 }
2345
2346 pub fn to_optional(self) -> OptionalKeyPath<Root, Value, ReadFn> {
2348 OptionalKeyPath::new(self.readable)
2349 }
2350
2351 pub fn to_writable_optional(self) -> WritableOptionalKeyPath<Root, Value, WriteFn> {
2353 WritableOptionalKeyPath::new(self.writable)
2354 }
2355
2356 pub fn then<SubValue, SubReadFn, SubWriteFn, SubOwnedFn>(
2359 self,
2360 next: FailableCombinedKeyPath<Value, SubValue, SubReadFn, SubWriteFn, SubOwnedFn>,
2361 ) -> FailableCombinedKeyPath<Root, SubValue, impl for<'r> Fn(&'r Root) -> Option<&'r SubValue> + 'static, impl for<'r> Fn(&'r mut Root) -> Option<&'r mut SubValue> + 'static, impl Fn(Root) -> Option<SubValue> + 'static>
2362 where
2363 SubReadFn: for<'r> Fn(&'r Value) -> Option<&'r SubValue> + 'static,
2364 SubWriteFn: for<'r> Fn(&'r mut Value) -> Option<&'r mut SubValue> + 'static,
2365 SubOwnedFn: Fn(Value) -> Option<SubValue> + 'static,
2366 ReadFn: 'static,
2367 WriteFn: 'static,
2368 OwnedFn: 'static,
2369 Value: 'static,
2370 Root: 'static,
2371 SubValue: 'static,
2372 {
2373 let first_read = self.readable;
2374 let first_write = self.writable;
2375 let first_owned = self.owned;
2376 let second_read = next.readable;
2377 let second_write = next.writable;
2378 let second_owned = next.owned;
2379
2380 FailableCombinedKeyPath::new(
2381 move |root: &Root| {
2382 first_read(root).and_then(|value| second_read(value))
2383 },
2384 move |root: &mut Root| {
2385 first_write(root).and_then(|value| second_write(value))
2386 },
2387 move |root: Root| {
2388 first_owned(root).and_then(|value| second_owned(value))
2389 },
2390 )
2391 }
2392
2393 pub fn then_optional<SubValue, SubReadFn>(
2397 self,
2398 next: OptionalKeyPath<Value, SubValue, SubReadFn>,
2399 ) -> FailableCombinedKeyPath<Root, SubValue, impl for<'r> Fn(&'r Root) -> Option<&'r SubValue> + 'static, impl for<'r> Fn(&'r mut Root) -> Option<&'r mut SubValue> + 'static, impl Fn(Root) -> Option<SubValue> + 'static>
2400 where
2401 SubReadFn: for<'r> Fn(&'r Value) -> Option<&'r SubValue> + 'static,
2402 ReadFn: 'static,
2403 WriteFn: 'static,
2404 OwnedFn: 'static,
2405 Value: 'static,
2406 Root: 'static,
2407 SubValue: 'static,
2408 {
2409 let first_read = self.readable;
2410 let first_write = self.writable;
2411 let first_owned = self.owned;
2412 let second_read = next.getter;
2413
2414 FailableCombinedKeyPath::new(
2415 move |root: &Root| {
2416 first_read(root).and_then(|value| second_read(value))
2417 },
2418 move |_root: &mut Root| {
2419 None },
2421 move |root: Root| {
2422 first_owned(root).and_then(|value| {
2423 None
2425 })
2426 },
2427 )
2428 }
2429}
2430
2431impl FailableCombinedKeyPath<(), (), fn(&()) -> Option<&()>, fn(&mut ()) -> Option<&mut ()>, fn(()) -> Option<()>> {
2433 pub fn failable_combined<Root, Value, ReadFn, WriteFn, OwnedFn>(
2435 readable: ReadFn,
2436 writable: WriteFn,
2437 owned: OwnedFn,
2438 ) -> FailableCombinedKeyPath<Root, Value, ReadFn, WriteFn, OwnedFn>
2439 where
2440 ReadFn: for<'r> Fn(&'r Root) -> Option<&'r Value> + 'static,
2441 WriteFn: for<'r> Fn(&'r mut Root) -> Option<&'r mut Value> + 'static,
2442 OwnedFn: Fn(Root) -> Option<Value> + 'static,
2443 {
2444 FailableCombinedKeyPath::new(readable, writable, owned)
2445 }
2446}
2447
2448impl AnyWritableKeyPath {
2449 pub fn new<Root, Value>(keypath: WritableOptionalKeyPath<Root, Value, impl for<'r> Fn(&'r mut Root) -> Option<&'r mut Value> + 'static>) -> Self
2450 where
2451 Root: Any + 'static,
2452 Value: Any + 'static,
2453 {
2454 let root_type_id = TypeId::of::<Root>();
2455 let value_type_id = TypeId::of::<Value>();
2456 let getter = keypath.getter;
2457
2458 Self {
2459 getter: Rc::new(move |any: &mut dyn Any| {
2460 if let Some(root) = any.downcast_mut::<Root>() {
2461 getter(root).map(|value: &mut Value| value as &mut dyn Any)
2462 } else {
2463 None
2464 }
2465 }),
2466 root_type_id,
2467 value_type_id,
2468 }
2469 }
2470
2471 pub fn get_mut<'r>(&self, root: &'r mut dyn Any) -> Option<&'r mut dyn Any> {
2472 (self.getter)(root)
2473 }
2474
2475 pub fn root_type_id(&self) -> TypeId {
2477 self.root_type_id
2478 }
2479
2480 pub fn value_type_id(&self) -> TypeId {
2482 self.value_type_id
2483 }
2484
2485 pub fn get_mut_as<'a, Root: Any, Value: Any>(&self, root: &'a mut Root) -> Option<Option<&'a mut Value>> {
2487 if self.root_type_id == TypeId::of::<Root>() && self.value_type_id == TypeId::of::<Value>() {
2488 self.get_mut(root as &mut dyn Any).map(|any| any.downcast_mut::<Value>())
2489 } else {
2490 None
2491 }
2492 }
2493}
2494
2495impl<Root, Value, F> KeyPath<Root, Value, F>
2497where
2498 F: for<'r> Fn(&'r Root) -> &'r Value + 'static,
2499 Root: 'static,
2500 Value: Any + 'static,
2501{
2502 pub fn to_partial(self) -> PartialKeyPath<Root> {
2504 PartialKeyPath::new(self)
2505 }
2506
2507 pub fn to(self) -> PartialKeyPath<Root> {
2509 self.to_partial()
2510 }
2511}
2512
2513impl<Root, Value, F> OptionalKeyPath<Root, Value, F>
2514where
2515 F: for<'r> Fn(&'r Root) -> Option<&'r Value> + 'static,
2516 Root: Any + 'static,
2517 Value: Any + 'static,
2518{
2519 pub fn to_partial(self) -> PartialOptionalKeyPath<Root> {
2521 PartialOptionalKeyPath::new(self)
2522 }
2523
2524 pub fn to_any(self) -> AnyKeyPath {
2526 AnyKeyPath::new(self)
2527 }
2528
2529 pub fn to(self) -> PartialOptionalKeyPath<Root> {
2531 self.to_partial()
2532 }
2533}
2534
2535impl<Root, Value, F> WritableKeyPath<Root, Value, F>
2536where
2537 F: for<'r> Fn(&'r mut Root) -> &'r mut Value + 'static,
2538 Root: 'static,
2539 Value: Any + 'static,
2540{
2541 pub fn to_partial(self) -> PartialWritableKeyPath<Root> {
2543 PartialWritableKeyPath::new(self)
2544 }
2545
2546 pub fn to(self) -> PartialWritableKeyPath<Root> {
2548 self.to_partial()
2549 }
2550}
2551
2552impl<Root, Value, F> WritableOptionalKeyPath<Root, Value, F>
2553where
2554 F: for<'r> Fn(&'r mut Root) -> Option<&'r mut Value> + 'static,
2555 Root: Any + 'static,
2556 Value: Any + 'static,
2557{
2558 pub fn to_partial(self) -> PartialWritableOptionalKeyPath<Root> {
2560 PartialWritableOptionalKeyPath::new(self)
2561 }
2562
2563 pub fn to_any(self) -> AnyWritableKeyPath {
2565 AnyWritableKeyPath::new(self)
2566 }
2567
2568 pub fn to(self) -> PartialWritableOptionalKeyPath<Root> {
2570 self.to_partial()
2571 }
2572}
2573
2574#[cfg(test)]
2575mod tests {
2576 use super::*;
2577 use std::sync::atomic::{AtomicUsize, Ordering};
2578 use std::rc::Rc;
2579
2580 static ALLOC_COUNT: AtomicUsize = AtomicUsize::new(0);
2582 static DEALLOC_COUNT: AtomicUsize = AtomicUsize::new(0);
2583
2584 #[derive(Debug)]
2586 struct NoCloneType {
2587 id: usize,
2588 data: String,
2589 }
2590
2591 impl NoCloneType {
2592 fn new(data: String) -> Self {
2593 ALLOC_COUNT.fetch_add(1, Ordering::SeqCst);
2594 Self {
2595 id: ALLOC_COUNT.load(Ordering::SeqCst),
2596 data,
2597 }
2598 }
2599 }
2600
2601 impl Clone for NoCloneType {
2602 fn clone(&self) -> Self {
2603 eprintln!("[DEBUG] NoCloneType should not be cloned! ID: {}", self.id);
2604 unreachable!("NoCloneType should not be cloned! ID: {}", self.id);
2605 }
2606 }
2607
2608 impl Drop for NoCloneType {
2609 fn drop(&mut self) {
2610 DEALLOC_COUNT.fetch_add(1, Ordering::SeqCst);
2611 }
2612 }
2613
2614 fn reset_memory_counters() {
2616 ALLOC_COUNT.store(0, Ordering::SeqCst);
2617 DEALLOC_COUNT.store(0, Ordering::SeqCst);
2618 }
2619
2620 fn get_alloc_count() -> usize {
2621 ALLOC_COUNT.load(Ordering::SeqCst)
2622 }
2623
2624 fn get_dealloc_count() -> usize {
2625 DEALLOC_COUNT.load(Ordering::SeqCst)
2626 }
2627
2628#[derive(Debug)]
2630struct User {
2631 name: String,
2632 metadata: Option<Box<UserMetadata>>,
2633 friends: Vec<Arc<User>>,
2634}
2635
2636#[derive(Debug)]
2637struct UserMetadata {
2638 created_at: String,
2639}
2640
2641fn some_fn() {
2642 let akash = User {
2643 name: "Alice".to_string(),
2644 metadata: Some(Box::new(UserMetadata {
2645 created_at: "2024-01-01".to_string(),
2646 })),
2647 friends: vec![
2648 Arc::new(User {
2649 name: "Bob".to_string(),
2650 metadata: None,
2651 friends: vec![],
2652 }),
2653 ],
2654 };
2655
2656 let name_kp = KeyPath::new(|u: &User| &u.name);
2658 let metadata_kp = OptionalKeyPath::new(|u: &User| u.metadata.as_ref());
2659 let friends_kp = KeyPath::new(|u: &User| &u.friends);
2660
2661 println!("Name: {}", name_kp.get(&akash));
2663
2664 if let Some(metadata) = metadata_kp.get(&akash) {
2665 println!("Has metadata: {:?}", metadata);
2666 }
2667
2668 if let Some(first_friend) = akash.friends.get(0) {
2670 println!("First friend: {}", name_kp.get(first_friend));
2671 }
2672
2673 let created_at_kp = KeyPath::new(|m: &UserMetadata| &m.created_at);
2675
2676 if let Some(metadata) = akash.metadata.as_ref() {
2677 let boxed_metadata: &Box<UserMetadata> = metadata;
2679 let unwrapped = boxed_metadata.as_ref();
2680 println!("Created at: {:?}", created_at_kp.get(unwrapped));
2681 }
2682 }
2683
2684 #[test]
2685 fn test_name() {
2686 some_fn();
2687 }
2688
2689 #[test]
2690 fn test_no_cloning_on_keypath_operations() {
2691 reset_memory_counters();
2692
2693 let value = NoCloneType::new("test".to_string());
2695 let boxed = Box::new(value);
2696
2697 let kp = KeyPath::new(|b: &Box<NoCloneType>| b.as_ref());
2699
2700 let _ref = kp.get(&boxed);
2702
2703 let _kp_clone = kp.clone();
2705
2706 let _ref2 = _kp_clone.get(&boxed);
2708
2709 assert_eq!(get_alloc_count(), 1);
2711 }
2712
2713 #[test]
2714 fn test_no_cloning_on_optional_keypath_operations() {
2715 reset_memory_counters();
2716
2717 let value = NoCloneType::new("test".to_string());
2718 let opt = Some(Box::new(value));
2719
2720 let okp = OptionalKeyPath::new(|o: &Option<Box<NoCloneType>>| o.as_ref());
2722
2723 let _ref = okp.get(&opt);
2725
2726 let _okp_clone = okp.clone();
2728
2729 let chained = okp.then(OptionalKeyPath::new(|b: &Box<NoCloneType>| Some(b.as_ref())));
2731 let _ref2 = chained.get(&opt);
2732
2733 assert_eq!(get_alloc_count(), 1);
2734 }
2735
2736 #[test]
2737 fn test_memory_release() {
2738 reset_memory_counters();
2739
2740 {
2741 let value = NoCloneType::new("test".to_string());
2742 let boxed = Box::new(value);
2743 let kp = KeyPath::new(|b: &Box<NoCloneType>| b.as_ref());
2744
2745 let _ref = kp.get(&boxed);
2747
2748 }
2750
2751 assert_eq!(get_alloc_count(), 1);
2754 }
2757
2758 #[test]
2759 fn test_keypath_clone_does_not_clone_underlying_data() {
2760 reset_memory_counters();
2761
2762 let value = NoCloneType::new("data".to_string());
2763 let rc_value = Rc::new(value);
2764
2765 let kp = KeyPath::new(|r: &Rc<NoCloneType>| r.as_ref());
2767
2768 let kp1 = kp.clone();
2770 let kp2 = kp.clone();
2771 let kp3 = kp1.clone();
2772
2773 let _ref1 = kp.get(&rc_value);
2775 let _ref2 = kp1.get(&rc_value);
2776 let _ref3 = kp2.get(&rc_value);
2777 let _ref4 = kp3.get(&rc_value);
2778
2779 assert_eq!(get_alloc_count(), 1);
2781 }
2782
2783 #[test]
2784 fn test_optional_keypath_chaining_no_clone() {
2785 reset_memory_counters();
2786
2787 let value = NoCloneType::new("value1".to_string());
2788
2789 struct Container {
2790 inner: Option<Box<NoCloneType>>,
2791 }
2792
2793 let container = Container {
2794 inner: Some(Box::new(value)),
2795 };
2796
2797 let kp1 = OptionalKeyPath::new(|c: &Container| c.inner.as_ref());
2799 let kp2 = OptionalKeyPath::new(|b: &Box<NoCloneType>| Some(b.as_ref()));
2800
2801 let chained = kp1.then(kp2);
2803
2804 let _result = chained.get(&container);
2806
2807 assert_eq!(get_alloc_count(), 1);
2809 }
2810
2811 #[test]
2812 fn test_for_box_no_clone() {
2813 reset_memory_counters();
2814
2815 let value = NoCloneType::new("test".to_string());
2816 let boxed = Box::new(value);
2817 let opt_boxed = Some(boxed);
2818
2819 let kp = OptionalKeyPath::new(|o: &Option<Box<NoCloneType>>| o.as_ref());
2821 let unwrapped = kp.for_box();
2822
2823 let _ref = unwrapped.get(&opt_boxed);
2825
2826 assert_eq!(get_alloc_count(), 1);
2827 }
2828
2829 #[derive(Debug, PartialEq)]
2832 struct TestUser {
2833 name: String,
2834 age: u32,
2835 metadata: Option<String>,
2836 address: Option<TestAddress>,
2837 }
2838
2839 #[derive(Debug, PartialEq)]
2840 struct TestAddress {
2841 street: String,
2842 city: String,
2843 country: Option<TestCountry>,
2844 }
2845
2846 #[derive(Debug, PartialEq)]
2847 struct TestCountry {
2848 name: String,
2849 }
2850
2851 #[test]
2852 fn test_keypath_macro() {
2853 let user = TestUser {
2854 name: "Alice".to_string(),
2855 age: 30,
2856 metadata: None,
2857 address: None,
2858 };
2859
2860 let name_kp = keypath!(|u: &TestUser| &u.name);
2862 assert_eq!(name_kp.get(&user), "Alice");
2863
2864 let user_with_address = TestUser {
2866 name: "Bob".to_string(),
2867 age: 25,
2868 metadata: None,
2869 address: Some(TestAddress {
2870 street: "123 Main St".to_string(),
2871 city: "New York".to_string(),
2872 country: None,
2873 }),
2874 };
2875
2876 let street_kp = keypath!(|u: &TestUser| &u.address.as_ref().unwrap().street);
2877 assert_eq!(street_kp.get(&user_with_address), "123 Main St");
2878
2879 let user_with_country = TestUser {
2881 name: "Charlie".to_string(),
2882 age: 35,
2883 metadata: None,
2884 address: Some(TestAddress {
2885 street: "456 Oak Ave".to_string(),
2886 city: "London".to_string(),
2887 country: Some(TestCountry {
2888 name: "UK".to_string(),
2889 }),
2890 }),
2891 };
2892
2893 let country_name_kp = keypath!(|u: &TestUser| &u.address.as_ref().unwrap().country.as_ref().unwrap().name);
2894 assert_eq!(country_name_kp.get(&user_with_country), "UK");
2895
2896 let age_kp = keypath!(|u: &TestUser| &u.age);
2898 assert_eq!(age_kp.get(&user), &30);
2899 }
2900
2901 #[test]
2902 fn test_opt_keypath_macro() {
2903 let user = TestUser {
2904 name: "Alice".to_string(),
2905 age: 30,
2906 metadata: Some("admin".to_string()),
2907 address: None,
2908 };
2909
2910 let metadata_kp = opt_keypath!(|u: &TestUser| u.metadata.as_ref());
2912 assert_eq!(metadata_kp.get(&user), Some(&"admin".to_string()));
2913
2914 let user_no_metadata = TestUser {
2916 name: "Bob".to_string(),
2917 age: 25,
2918 metadata: None,
2919 address: None,
2920 };
2921 assert_eq!(metadata_kp.get(&user_no_metadata), None);
2922
2923 let user_with_address = TestUser {
2925 name: "Charlie".to_string(),
2926 age: 35,
2927 metadata: None,
2928 address: Some(TestAddress {
2929 street: "789 Pine Rd".to_string(),
2930 city: "Paris".to_string(),
2931 country: None,
2932 }),
2933 };
2934
2935 let street_kp = opt_keypath!(|u: &TestUser| u.address.as_ref().map(|a| &a.street));
2936 assert_eq!(street_kp.get(&user_with_address), Some(&"789 Pine Rd".to_string()));
2937
2938 let user_with_country = TestUser {
2940 name: "David".to_string(),
2941 age: 40,
2942 metadata: None,
2943 address: Some(TestAddress {
2944 street: "321 Elm St".to_string(),
2945 city: "Tokyo".to_string(),
2946 country: Some(TestCountry {
2947 name: "Japan".to_string(),
2948 }),
2949 }),
2950 };
2951
2952 let country_name_kp = opt_keypath!(|u: &TestUser| u.address.as_ref().and_then(|a| a.country.as_ref().map(|c| &c.name)));
2953 assert_eq!(country_name_kp.get(&user_with_country), Some(&"Japan".to_string()));
2954
2955 let metadata_kp2 = opt_keypath!(|u: &TestUser| u.metadata.as_ref());
2957 assert_eq!(metadata_kp2.get(&user), Some(&"admin".to_string()));
2958 }
2959
2960 #[test]
2961 fn test_writable_keypath_macro() {
2962 let mut user = TestUser {
2963 name: "Alice".to_string(),
2964 age: 30,
2965 metadata: None,
2966 address: None,
2967 };
2968
2969 let name_kp = writable_keypath!(|u: &mut TestUser| &mut u.name);
2971 *name_kp.get_mut(&mut user) = "Bob".to_string();
2972 assert_eq!(user.name, "Bob");
2973
2974 let mut user_with_address = TestUser {
2976 name: "Charlie".to_string(),
2977 age: 25,
2978 metadata: None,
2979 address: Some(TestAddress {
2980 street: "123 Main St".to_string(),
2981 city: "New York".to_string(),
2982 country: None,
2983 }),
2984 };
2985
2986 let street_kp = writable_keypath!(|u: &mut TestUser| &mut u.address.as_mut().unwrap().street);
2987 *street_kp.get_mut(&mut user_with_address) = "456 Oak Ave".to_string();
2988 assert_eq!(user_with_address.address.as_ref().unwrap().street, "456 Oak Ave");
2989
2990 let mut user_with_country = TestUser {
2992 name: "David".to_string(),
2993 age: 35,
2994 metadata: None,
2995 address: Some(TestAddress {
2996 street: "789 Pine Rd".to_string(),
2997 city: "London".to_string(),
2998 country: Some(TestCountry {
2999 name: "UK".to_string(),
3000 }),
3001 }),
3002 };
3003
3004 let country_name_kp = writable_keypath!(|u: &mut TestUser| &mut u.address.as_mut().unwrap().country.as_mut().unwrap().name);
3005 *country_name_kp.get_mut(&mut user_with_country) = "United Kingdom".to_string();
3006 assert_eq!(user_with_country.address.as_ref().unwrap().country.as_ref().unwrap().name, "United Kingdom");
3007
3008 let age_kp = writable_keypath!(|u: &mut TestUser| &mut u.age);
3010 *age_kp.get_mut(&mut user) = 31;
3011 assert_eq!(user.age, 31);
3012 }
3013
3014 #[test]
3015 fn test_writable_opt_keypath_macro() {
3016 let mut user = TestUser {
3017 name: "Alice".to_string(),
3018 age: 30,
3019 metadata: Some("user".to_string()),
3020 address: None,
3021 };
3022
3023 let metadata_kp = writable_opt_keypath!(|u: &mut TestUser| u.metadata.as_mut());
3025 if let Some(metadata) = metadata_kp.get_mut(&mut user) {
3026 *metadata = "admin".to_string();
3027 }
3028 assert_eq!(user.metadata, Some("admin".to_string()));
3029
3030 let mut user_no_metadata = TestUser {
3032 name: "Bob".to_string(),
3033 age: 25,
3034 metadata: None,
3035 address: None,
3036 };
3037 assert_eq!(metadata_kp.get_mut(&mut user_no_metadata), None);
3038
3039 let mut user_with_address = TestUser {
3041 name: "Charlie".to_string(),
3042 age: 35,
3043 metadata: None,
3044 address: Some(TestAddress {
3045 street: "123 Main St".to_string(),
3046 city: "New York".to_string(),
3047 country: None,
3048 }),
3049 };
3050
3051 let street_kp = writable_opt_keypath!(|u: &mut TestUser| u.address.as_mut().map(|a| &mut a.street));
3052 if let Some(street) = street_kp.get_mut(&mut user_with_address) {
3053 *street = "456 Oak Ave".to_string();
3054 }
3055 assert_eq!(user_with_address.address.as_ref().unwrap().street, "456 Oak Ave");
3056
3057 let mut user_with_country = TestUser {
3059 name: "David".to_string(),
3060 age: 40,
3061 metadata: None,
3062 address: Some(TestAddress {
3063 street: "789 Pine Rd".to_string(),
3064 city: "Tokyo".to_string(),
3065 country: Some(TestCountry {
3066 name: "Japan".to_string(),
3067 }),
3068 }),
3069 };
3070
3071 let country_name_kp = writable_opt_keypath!(|u: &mut TestUser| u.address.as_mut().and_then(|a| a.country.as_mut().map(|c| &mut c.name)));
3072 if let Some(country_name) = country_name_kp.get_mut(&mut user_with_country) {
3073 *country_name = "Nippon".to_string();
3074 }
3075 assert_eq!(user_with_country.address.as_ref().unwrap().country.as_ref().unwrap().name, "Nippon");
3076
3077 let metadata_kp2 = writable_opt_keypath!(|u: &mut TestUser| u.metadata.as_mut());
3079 if let Some(metadata) = metadata_kp2.get_mut(&mut user) {
3080 *metadata = "super_admin".to_string();
3081 }
3082 assert_eq!(user.metadata, Some("super_admin".to_string()));
3083 }
3084}
3085
3086pub trait WithContainer<Root, Value> {
3092 fn with_arc<F, R>(&self, arc: &Arc<Root>, f: F) -> R
3094 where
3095 F: FnOnce(&Value) -> R;
3096
3097 fn with_box<F, R>(&self, boxed: &Box<Root>, f: F) -> R
3099 where
3100 F: FnOnce(&Value) -> R;
3101
3102 fn with_box_mut<F, R>(&self, boxed: &mut Box<Root>, f: F) -> R
3104 where
3105 F: FnOnce(&mut Value) -> R;
3106
3107 fn with_rc<F, R>(&self, rc: &Rc<Root>, f: F) -> R
3109 where
3110 F: FnOnce(&Value) -> R;
3111
3112 fn with_result<F, R, E>(&self, result: &Result<Root, E>, f: F) -> Option<R>
3114 where
3115 F: FnOnce(&Value) -> R;
3116
3117 fn with_result_mut<F, R, E>(&self, result: &mut Result<Root, E>, f: F) -> Option<R>
3119 where
3120 F: FnOnce(&mut Value) -> R;
3121
3122 fn with_option<F, R>(&self, option: &Option<Root>, f: F) -> Option<R>
3124 where
3125 F: FnOnce(&Value) -> R;
3126
3127 fn with_option_mut<F, R>(&self, option: &mut Option<Root>, f: F) -> Option<R>
3129 where
3130 F: FnOnce(&mut Value) -> R;
3131
3132 fn with_refcell<F, R>(&self, refcell: &RefCell<Root>, f: F) -> Option<R>
3134 where
3135 F: FnOnce(&Value) -> R;
3136
3137 fn with_refcell_mut<F, R>(&self, refcell: &RefCell<Root>, f: F) -> Option<R>
3139 where
3140 F: FnOnce(&mut Value) -> R;
3141
3142 #[cfg(feature = "tagged")]
3143 fn with_tagged<F, R, Tag>(&self, tagged: &Tagged<Root, Tag>, f: F) -> R
3145 where
3146 Tagged<Root, Tag>: std::ops::Deref<Target = Root>,
3147 F: FnOnce(&Value) -> R;
3148
3149 fn with_mutex<F, R>(&self, mutex: &Mutex<Root>, f: F) -> Option<R>
3151 where
3152 F: FnOnce(&Value) -> R;
3153
3154 fn with_mutex_mut<F, R>(&self, mutex: &mut Mutex<Root>, f: F) -> Option<R>
3156 where
3157 F: FnOnce(&mut Value) -> R;
3158
3159 fn with_rwlock<F, R>(&self, rwlock: &RwLock<Root>, f: F) -> Option<R>
3161 where
3162 F: FnOnce(&Value) -> R;
3163
3164 fn with_rwlock_mut<F, R>(&self, rwlock: &mut RwLock<Root>, f: F) -> Option<R>
3166 where
3167 F: FnOnce(&mut Value) -> R;
3168
3169 fn with_arc_rwlock<F, R>(&self, arc_rwlock: &Arc<RwLock<Root>>, f: F) -> Option<R>
3171 where
3172 F: FnOnce(&Value) -> R;
3173
3174 fn with_arc_rwlock_mut<F, R>(&self, arc_rwlock: &Arc<RwLock<Root>>, f: F) -> Option<R>
3176 where
3177 F: FnOnce(&mut Value) -> R;
3178}
3179
3180impl<Root, Value, F> WithContainer<Root, Value> for KeyPath<Root, Value, F>
3182where
3183 F: for<'r> Fn(&'r Root) -> &'r Value + Clone,
3184{
3185 fn with_arc<Callback, R>(&self, arc: &Arc<Root>, f: Callback) -> R
3186 where
3187 Callback: FnOnce(&Value) -> R,
3188 {
3189 self.with_arc(arc, f)
3190 }
3191
3192 fn with_box<Callback, R>(&self, boxed: &Box<Root>, f: Callback) -> R
3193 where
3194 Callback: FnOnce(&Value) -> R,
3195 {
3196 self.with_box(boxed, f)
3197 }
3198
3199 fn with_box_mut<Callback, R>(&self, _boxed: &mut Box<Root>, _f: Callback) -> R
3200 where
3201 Callback: FnOnce(&mut Value) -> R,
3202 {
3203 eprintln!("[DEBUG] KeyPath does not support mutable access - use WritableKeyPath instead");
3204 unreachable!("KeyPath does not support mutable access - use WritableKeyPath instead")
3205 }
3206
3207 fn with_rc<Callback, R>(&self, rc: &Rc<Root>, f: Callback) -> R
3208 where
3209 Callback: FnOnce(&Value) -> R,
3210 {
3211 self.with_rc(rc, f)
3212 }
3213
3214 fn with_result<Callback, R, E>(&self, result: &Result<Root, E>, f: Callback) -> Option<R>
3215 where
3216 Callback: FnOnce(&Value) -> R,
3217 {
3218 self.with_result(result, f)
3219 }
3220
3221 fn with_result_mut<Callback, R, E>(&self, _result: &mut Result<Root, E>, _f: Callback) -> Option<R>
3222 where
3223 Callback: FnOnce(&mut Value) -> R,
3224 {
3225 None
3226 }
3227
3228 fn with_option<Callback, R>(&self, option: &Option<Root>, f: Callback) -> Option<R>
3229 where
3230 Callback: FnOnce(&Value) -> R,
3231 {
3232 self.with_option(option, f)
3233 }
3234
3235 fn with_option_mut<Callback, R>(&self, _option: &mut Option<Root>, _f: Callback) -> Option<R>
3236 where
3237 Callback: FnOnce(&mut Value) -> R,
3238 {
3239 None
3240 }
3241
3242 fn with_refcell<Callback, R>(&self, refcell: &RefCell<Root>, f: Callback) -> Option<R>
3243 where
3244 Callback: FnOnce(&Value) -> R,
3245 {
3246 self.with_refcell(refcell, f)
3247 }
3248
3249 fn with_refcell_mut<Callback, R>(&self, _refcell: &RefCell<Root>, _f: Callback) -> Option<R>
3250 where
3251 Callback: FnOnce(&mut Value) -> R,
3252 {
3253 None
3254 }
3255
3256 #[cfg(feature = "tagged")]
3257 fn with_tagged<Tag, Callback, R>(&self, tagged: &Tagged<Root, Tag>, f: Callback) -> R
3258 where
3259 Tagged<Root, Tag>: std::ops::Deref<Target = Root>,
3260 Callback: FnOnce(&Value) -> R,
3261 {
3262 self.with_tagged(tagged, f)
3263 }
3264
3265 fn with_mutex<Callback, R>(&self, mutex: &Mutex<Root>, f: Callback) -> Option<R>
3266 where
3267 Callback: FnOnce(&Value) -> R,
3268 {
3269 self.with_mutex(mutex, f)
3270 }
3271
3272 fn with_mutex_mut<Callback, R>(&self, _mutex: &mut Mutex<Root>, _f: Callback) -> Option<R>
3273 where
3274 Callback: FnOnce(&mut Value) -> R,
3275 {
3276 None
3277 }
3278
3279 fn with_rwlock<Callback, R>(&self, rwlock: &RwLock<Root>, f: Callback) -> Option<R>
3280 where
3281 Callback: FnOnce(&Value) -> R,
3282 {
3283 self.with_rwlock(rwlock, f)
3284 }
3285
3286 fn with_rwlock_mut<Callback, R>(&self, _rwlock: &mut RwLock<Root>, _f: Callback) -> Option<R>
3287 where
3288 Callback: FnOnce(&mut Value) -> R,
3289 {
3290 None
3291 }
3292
3293 fn with_arc_rwlock<Callback, R>(&self, arc_rwlock: &Arc<RwLock<Root>>, f: Callback) -> Option<R>
3294 where
3295 Callback: FnOnce(&Value) -> R,
3296 {
3297 self.with_arc_rwlock(arc_rwlock, f)
3298 }
3299
3300 fn with_arc_rwlock_mut<Callback, R>(&self, _arc_rwlock: &Arc<RwLock<Root>>, _f: Callback) -> Option<R>
3301 where
3302 Callback: FnOnce(&mut Value) -> R,
3303 {
3304 None
3305 }
3306}
3307
3308impl<Root, Value, F> WithContainer<Root, Value> for OptionalKeyPath<Root, Value, F>
3310where
3311 F: for<'r> Fn(&'r Root) -> Option<&'r Value> + Clone,
3312{
3313 fn with_arc<Callback, R>(&self, arc: &Arc<Root>, f: Callback) -> R
3314 where
3315 Callback: FnOnce(&Value) -> R,
3316 {
3317 self.with_arc(arc, f)
3318 }
3319
3320 fn with_box<Callback, R>(&self, boxed: &Box<Root>, f: Callback) -> R
3321 where
3322 Callback: FnOnce(&Value) -> R,
3323 {
3324 self.with_box(boxed, f)
3325 }
3326
3327 fn with_box_mut<Callback, R>(&self, _boxed: &mut Box<Root>, _f: Callback) -> R
3328 where
3329 Callback: FnOnce(&mut Value) -> R,
3330 {
3331 eprintln!("[DEBUG] OptionalKeyPath does not support mutable access - use WritableOptionalKeyPath instead");
3332 unreachable!("OptionalKeyPath does not support mutable access - use WritableOptionalKeyPath instead")
3333 }
3334
3335 fn with_rc<Callback, R>(&self, rc: &Rc<Root>, f: Callback) -> R
3336 where
3337 Callback: FnOnce(&Value) -> R,
3338 {
3339 self.with_rc(rc, f)
3340 }
3341
3342 fn with_result<Callback, R, E>(&self, result: &Result<Root, E>, f: Callback) -> Option<R>
3343 where
3344 Callback: FnOnce(&Value) -> R,
3345 {
3346 self.with_result(result, f)
3347 }
3348
3349 fn with_result_mut<Callback, R, E>(&self, _result: &mut Result<Root, E>, _f: Callback) -> Option<R>
3350 where
3351 Callback: FnOnce(&mut Value) -> R,
3352 {
3353 None }
3355
3356 fn with_option<Callback, R>(&self, option: &Option<Root>, f: Callback) -> Option<R>
3357 where
3358 Callback: FnOnce(&Value) -> R,
3359 {
3360 self.with_option(option, f)
3361 }
3362
3363 fn with_option_mut<Callback, R>(&self, _option: &mut Option<Root>, _f: Callback) -> Option<R>
3364 where
3365 Callback: FnOnce(&mut Value) -> R,
3366 {
3367 None }
3369
3370 fn with_refcell<Callback, R>(&self, refcell: &RefCell<Root>, f: Callback) -> Option<R>
3371 where
3372 Callback: FnOnce(&Value) -> R,
3373 {
3374 self.with_refcell(refcell, f)
3375 }
3376
3377 fn with_refcell_mut<Callback, R>(&self, _refcell: &RefCell<Root>, _f: Callback) -> Option<R>
3378 where
3379 Callback: FnOnce(&mut Value) -> R,
3380 {
3381 None }
3383
3384 #[cfg(feature = "tagged")]
3385 fn with_tagged<Tag, Callback, R>(&self, tagged: &Tagged<Root, Tag>, f: Callback) -> R
3386 where
3387 Tagged<Root, Tag>: std::ops::Deref<Target = Root>,
3388 Callback: FnOnce(&Value) -> R,
3389 {
3390 self.with_tagged(tagged, f)
3391 }
3392
3393 fn with_mutex<Callback, R>(&self, mutex: &Mutex<Root>, f: Callback) -> Option<R>
3394 where
3395 Callback: FnOnce(&Value) -> R,
3396 {
3397 self.with_mutex(mutex, f)
3398 }
3399
3400 fn with_mutex_mut<Callback, R>(&self, _mutex: &mut Mutex<Root>, _f: Callback) -> Option<R>
3401 where
3402 Callback: FnOnce(&mut Value) -> R,
3403 {
3404 None }
3406
3407 fn with_rwlock<Callback, R>(&self, rwlock: &RwLock<Root>, f: Callback) -> Option<R>
3408 where
3409 Callback: FnOnce(&Value) -> R,
3410 {
3411 self.with_rwlock(rwlock, f)
3412 }
3413
3414 fn with_rwlock_mut<Callback, R>(&self, _rwlock: &mut RwLock<Root>, _f: Callback) -> Option<R>
3415 where
3416 Callback: FnOnce(&mut Value) -> R,
3417 {
3418 None }
3420
3421 fn with_arc_rwlock<Callback, R>(&self, arc_rwlock: &Arc<RwLock<Root>>, f: Callback) -> Option<R>
3422 where
3423 Callback: FnOnce(&Value) -> R,
3424 {
3425 self.with_arc_rwlock(arc_rwlock, f)
3426 }
3427
3428 fn with_arc_rwlock_mut<Callback, R>(&self, _arc_rwlock: &Arc<RwLock<Root>>, _f: Callback) -> Option<R>
3429 where
3430 Callback: FnOnce(&mut Value) -> R,
3431 {
3432 None }
3434}
3435
3436impl<Root, Value, F> WithContainer<Root, Value> for WritableKeyPath<Root, Value, F>
3438where
3439 F: for<'r> Fn(&'r mut Root) -> &'r mut Value,
3440{
3441 fn with_arc<Callback, R>(&self, _arc: &Arc<Root>, _f: Callback) -> R
3442 where
3443 Callback: FnOnce(&Value) -> R,
3444 {
3445 eprintln!("[DEBUG] WritableKeyPath::with_arc requires &mut Arc<Root> or interior mutability");
3448 unreachable!("WritableKeyPath::with_arc requires &mut Arc<Root> or interior mutability")
3449 }
3450
3451 fn with_box<Callback, R>(&self, boxed: &Box<Root>, f: Callback) -> R
3452 where
3453 Callback: FnOnce(&Value) -> R,
3454 {
3455 eprintln!("[DEBUG] WritableKeyPath::with_box requires &mut Box<Root> - use with_box_mut instead");
3458 unreachable!("WritableKeyPath::with_box requires &mut Box<Root> - use with_box_mut instead")
3459 }
3460
3461 fn with_box_mut<Callback, R>(&self, boxed: &mut Box<Root>, f: Callback) -> R
3462 where
3463 Callback: FnOnce(&mut Value) -> R,
3464 {
3465 let value = self.get_mut(boxed.as_mut());
3466 f(value)
3467 }
3468
3469 fn with_rc<Callback, R>(&self, _rc: &Rc<Root>, _f: Callback) -> R
3470 where
3471 Callback: FnOnce(&Value) -> R,
3472 {
3473 eprintln!("[DEBUG] WritableKeyPath::with_rc requires &mut Rc<Root> or interior mutability");
3476 unreachable!("WritableKeyPath::with_rc requires &mut Rc<Root> or interior mutability")
3477 }
3478
3479 fn with_result<Callback, R, E>(&self, _result: &Result<Root, E>, _f: Callback) -> Option<R>
3480 where
3481 Callback: FnOnce(&Value) -> R,
3482 {
3483 None
3486 }
3487
3488 fn with_result_mut<Callback, R, E>(&self, result: &mut Result<Root, E>, f: Callback) -> Option<R>
3489 where
3490 Callback: FnOnce(&mut Value) -> R,
3491 {
3492 result.as_mut().ok().map(|root| {
3493 let value = self.get_mut(root);
3494 f(value)
3495 })
3496 }
3497
3498 fn with_option<Callback, R>(&self, _option: &Option<Root>, _f: Callback) -> Option<R>
3499 where
3500 Callback: FnOnce(&Value) -> R,
3501 {
3502 None
3505 }
3506
3507 fn with_option_mut<Callback, R>(&self, option: &mut Option<Root>, f: Callback) -> Option<R>
3508 where
3509 Callback: FnOnce(&mut Value) -> R,
3510 {
3511 option.as_mut().map(|root| {
3512 let value = self.get_mut(root);
3513 f(value)
3514 })
3515 }
3516
3517 fn with_refcell<Callback, R>(&self, refcell: &RefCell<Root>, f: Callback) -> Option<R>
3518 where
3519 Callback: FnOnce(&Value) -> R,
3520 {
3521 None
3524 }
3525
3526 fn with_refcell_mut<Callback, R>(&self, refcell: &RefCell<Root>, f: Callback) -> Option<R>
3527 where
3528 Callback: FnOnce(&mut Value) -> R,
3529 {
3530 refcell.try_borrow_mut().ok().map(|mut borrow| {
3531 let value = self.get_mut(&mut *borrow);
3532 f(value)
3533 })
3534 }
3535
3536 #[cfg(feature = "tagged")]
3537 fn with_tagged<Tag, Callback, R>(&self, _tagged: &Tagged<Root, Tag>, _f: Callback) -> R
3538 where
3539 Tagged<Root, Tag>: std::ops::Deref<Target = Root>,
3540 Callback: FnOnce(&Value) -> R,
3541 {
3542 eprintln!("[DEBUG] WritableKeyPath::with_tagged requires &mut Tagged<Root, Tag> or interior mutability");
3545 unreachable!("WritableKeyPath::with_tagged requires &mut Tagged<Root, Tag> or interior mutability")
3546 }
3547
3548 fn with_mutex<Callback, R>(&self, mutex: &Mutex<Root>, f: Callback) -> Option<R>
3549 where
3550 Callback: FnOnce(&Value) -> R,
3551 {
3552 mutex.lock().ok().map(|mut guard| {
3553 let value = self.get_mut(&mut *guard);
3554 f(value)
3555 })
3556 }
3557
3558 fn with_mutex_mut<Callback, R>(&self, mutex: &mut Mutex<Root>, f: Callback) -> Option<R>
3559 where
3560 Callback: FnOnce(&mut Value) -> R,
3561 {
3562 mutex.get_mut().ok().map(|root| {
3564 let value = self.get_mut(root);
3565 f(value)
3566 })
3567 }
3568
3569 fn with_rwlock<Callback, R>(&self, rwlock: &RwLock<Root>, f: Callback) -> Option<R>
3570 where
3571 Callback: FnOnce(&Value) -> R,
3572 {
3573 None
3576 }
3577
3578 fn with_rwlock_mut<Callback, R>(&self, rwlock: &mut RwLock<Root>, f: Callback) -> Option<R>
3579 where
3580 Callback: FnOnce(&mut Value) -> R,
3581 {
3582 rwlock.get_mut().ok().map(|root| {
3584 let value = self.get_mut(root);
3585 f(value)
3586 })
3587 }
3588
3589 fn with_arc_rwlock<Callback, R>(&self, arc_rwlock: &Arc<RwLock<Root>>, f: Callback) -> Option<R>
3590 where
3591 Callback: FnOnce(&Value) -> R,
3592 {
3593 None
3596 }
3597
3598 fn with_arc_rwlock_mut<Callback, R>(&self, arc_rwlock: &Arc<RwLock<Root>>, f: Callback) -> Option<R>
3599 where
3600 Callback: FnOnce(&mut Value) -> R,
3601 {
3602 arc_rwlock.write().ok().map(|mut guard| {
3603 let value = self.get_mut(&mut *guard);
3604 f(value)
3605 })
3606 }
3607}
3608
3609impl<Root, Value, F> WithContainer<Root, Value> for WritableOptionalKeyPath<Root, Value, F>
3611where
3612 F: for<'r> Fn(&'r mut Root) -> Option<&'r mut Value>,
3613{
3614 fn with_arc<Callback, R>(&self, _arc: &Arc<Root>, _f: Callback) -> R
3615 where
3616 Callback: FnOnce(&Value) -> R,
3617 {
3618 eprintln!("[DEBUG] WritableOptionalKeyPath::with_arc requires &mut Arc<Root> or interior mutability");
3621 unreachable!("WritableOptionalKeyPath::with_arc requires &mut Arc<Root> or interior mutability")
3622 }
3623
3624 fn with_box<Callback, R>(&self, _boxed: &Box<Root>, _f: Callback) -> R
3625 where
3626 Callback: FnOnce(&Value) -> R,
3627 {
3628 eprintln!("[DEBUG] WritableOptionalKeyPath::with_box requires &mut Box<Root> - use with_box_mut instead");
3631 unreachable!("WritableOptionalKeyPath::with_box requires &mut Box<Root> - use with_box_mut instead")
3632 }
3633
3634 fn with_box_mut<Callback, R>(&self, boxed: &mut Box<Root>, f: Callback) -> R
3635 where
3636 Callback: FnOnce(&mut Value) -> R,
3637 {
3638 if let Some(value) = self.get_mut(boxed.as_mut()) {
3639 f(value)
3640 } else {
3641 eprintln!("[DEBUG] WritableOptionalKeyPath failed to get value from Box");
3642 unreachable!("WritableOptionalKeyPath failed to get value from Box")
3643 }
3644 }
3645
3646 fn with_rc<Callback, R>(&self, _rc: &Rc<Root>, _f: Callback) -> R
3647 where
3648 Callback: FnOnce(&Value) -> R,
3649 {
3650 eprintln!("[DEBUG] WritableOptionalKeyPath::with_rc requires &mut Rc<Root> or interior mutability");
3653 unreachable!("WritableOptionalKeyPath::with_rc requires &mut Rc<Root> or interior mutability")
3654 }
3655
3656 fn with_result<Callback, R, E>(&self, _result: &Result<Root, E>, _f: Callback) -> Option<R>
3657 where
3658 Callback: FnOnce(&Value) -> R,
3659 {
3660 None
3663 }
3664
3665 fn with_result_mut<Callback, R, E>(&self, result: &mut Result<Root, E>, f: Callback) -> Option<R>
3666 where
3667 Callback: FnOnce(&mut Value) -> R,
3668 {
3669 result.as_mut().ok().and_then(|root| {
3670 self.get_mut(root).map(|value| f(value))
3671 })
3672 }
3673
3674 fn with_option<Callback, R>(&self, _option: &Option<Root>, _f: Callback) -> Option<R>
3675 where
3676 Callback: FnOnce(&Value) -> R,
3677 {
3678 None
3681 }
3682
3683 fn with_option_mut<Callback, R>(&self, option: &mut Option<Root>, f: Callback) -> Option<R>
3684 where
3685 Callback: FnOnce(&mut Value) -> R,
3686 {
3687 option.as_mut().and_then(|root| {
3688 self.get_mut(root).map(|value| f(value))
3689 })
3690 }
3691
3692 fn with_refcell<Callback, R>(&self, _refcell: &RefCell<Root>, _f: Callback) -> Option<R>
3693 where
3694 Callback: FnOnce(&Value) -> R,
3695 {
3696 None
3699 }
3700
3701 fn with_refcell_mut<Callback, R>(&self, refcell: &RefCell<Root>, f: Callback) -> Option<R>
3702 where
3703 Callback: FnOnce(&mut Value) -> R,
3704 {
3705 refcell.try_borrow_mut().ok().and_then(|mut borrow| {
3706 self.get_mut(&mut *borrow).map(|value| f(value))
3707 })
3708 }
3709
3710 #[cfg(feature = "tagged")]
3711 fn with_tagged<Tag, Callback, R>(&self, _tagged: &Tagged<Root, Tag>, _f: Callback) -> R
3712 where
3713 Tagged<Root, Tag>: std::ops::Deref<Target = Root>,
3714 Callback: FnOnce(&Value) -> R,
3715 {
3716 eprintln!("[DEBUG] WritableOptionalKeyPath::with_tagged requires &mut Tagged<Root, Tag> or interior mutability");
3719 unreachable!("WritableOptionalKeyPath::with_tagged requires &mut Tagged<Root, Tag> or interior mutability")
3720 }
3721
3722 fn with_mutex<Callback, R>(&self, mutex: &Mutex<Root>, f: Callback) -> Option<R>
3723 where
3724 Callback: FnOnce(&Value) -> R,
3725 {
3726 mutex.lock().ok().and_then(|mut guard| {
3727 self.get_mut(&mut *guard).map(|value| f(value))
3728 })
3729 }
3730
3731 fn with_mutex_mut<Callback, R>(&self, mutex: &mut Mutex<Root>, f: Callback) -> Option<R>
3732 where
3733 Callback: FnOnce(&mut Value) -> R,
3734 {
3735 mutex.get_mut().ok().and_then(|root| {
3737 self.get_mut(root).map(|value| f(value))
3738 })
3739 }
3740
3741 fn with_rwlock<Callback, R>(&self, _rwlock: &RwLock<Root>, _f: Callback) -> Option<R>
3742 where
3743 Callback: FnOnce(&Value) -> R,
3744 {
3745 None
3748 }
3749
3750 fn with_rwlock_mut<Callback, R>(&self, rwlock: &mut RwLock<Root>, f: Callback) -> Option<R>
3751 where
3752 Callback: FnOnce(&mut Value) -> R,
3753 {
3754 rwlock.get_mut().ok().and_then(|root| {
3756 self.get_mut(root).map(|value| f(value))
3757 })
3758 }
3759
3760 fn with_arc_rwlock<Callback, R>(&self, _arc_rwlock: &Arc<RwLock<Root>>, _f: Callback) -> Option<R>
3761 where
3762 Callback: FnOnce(&Value) -> R,
3763 {
3764 None
3767 }
3768
3769 fn with_arc_rwlock_mut<Callback, R>(&self, arc_rwlock: &Arc<RwLock<Root>>, f: Callback) -> Option<R>
3770 where
3771 Callback: FnOnce(&mut Value) -> R,
3772 {
3773 arc_rwlock.write().ok().and_then(|mut guard| {
3774 self.get_mut(&mut *guard).map(|value| f(value))
3775 })
3776 }
3777}