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}
460
461impl<Root, Value, F> KeyPath<Root, Value, F>
463where
464 F: for<'r> Fn(&'r Root) -> &'r Value,
465{
466 pub fn with_arc_rwlock_direct<Callback, R>(&self, arc_rwlock: &Arc<RwLock<Root>>, f: Callback) -> Option<R>
469 where
470 Callback: FnOnce(&Value) -> R,
471 {
472 arc_rwlock.read().ok().map(|guard| {
473 let value = self.get(&*guard);
474 f(value)
475 })
476 }
477
478 pub fn with_arc_mutex_direct<Callback, R>(&self, arc_mutex: &Arc<Mutex<Root>>, f: Callback) -> Option<R>
481 where
482 Callback: FnOnce(&Value) -> R,
483 {
484 arc_mutex.lock().ok().map(|guard| {
485 let value = self.get(&*guard);
486 f(value)
487 })
488 }
489}
490
491pub fn for_slice<T>() -> impl for<'r> Fn(&'r [T], usize) -> Option<&'r T> {
493 |slice: &[T], index: usize| slice.get(index)
494}
495
496pub mod containers {
498 use super::{OptionalKeyPath, WritableOptionalKeyPath, KeyPath, WritableKeyPath};
499 use std::collections::{HashMap, BTreeMap, HashSet, BTreeSet, VecDeque, LinkedList, BinaryHeap};
500 use std::sync::{Mutex, RwLock, Weak as StdWeak, Arc};
501 use std::rc::{Weak as RcWeak, Rc};
502 use std::ops::{Deref, DerefMut};
503
504 #[cfg(feature = "parking_lot")]
505 use parking_lot::{Mutex as ParkingMutex, RwLock as ParkingRwLock};
506
507 #[cfg(feature = "tagged")]
508 use tagged_core::Tagged;
509
510 pub fn for_vec_index<T>(index: usize) -> OptionalKeyPath<Vec<T>, T, impl for<'r> Fn(&'r Vec<T>) -> Option<&'r T>> {
512 OptionalKeyPath::new(move |vec: &Vec<T>| vec.get(index))
513 }
514
515 pub fn for_vecdeque_index<T>(index: usize) -> OptionalKeyPath<VecDeque<T>, T, impl for<'r> Fn(&'r VecDeque<T>) -> Option<&'r T>> {
517 OptionalKeyPath::new(move |deque: &VecDeque<T>| deque.get(index))
518 }
519
520 pub fn for_linkedlist_index<T>(index: usize) -> OptionalKeyPath<LinkedList<T>, T, impl for<'r> Fn(&'r LinkedList<T>) -> Option<&'r T>> {
522 OptionalKeyPath::new(move |list: &LinkedList<T>| {
523 list.iter().nth(index)
524 })
525 }
526
527 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>>
529 where
530 K: std::hash::Hash + Eq + Clone + 'static,
531 V: 'static,
532 {
533 OptionalKeyPath::new(move |map: &HashMap<K, V>| map.get(&key))
534 }
535
536 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>>
538 where
539 K: Ord + Clone + 'static,
540 V: 'static,
541 {
542 OptionalKeyPath::new(move |map: &BTreeMap<K, V>| map.get(&key))
543 }
544
545 pub fn for_hashset_get<T>(value: T) -> OptionalKeyPath<HashSet<T>, T, impl for<'r> Fn(&'r HashSet<T>) -> Option<&'r T>>
547 where
548 T: std::hash::Hash + Eq + Clone + 'static,
549 {
550 OptionalKeyPath::new(move |set: &HashSet<T>| set.get(&value))
551 }
552
553 pub fn for_btreeset_get<T>(value: T) -> OptionalKeyPath<BTreeSet<T>, T, impl for<'r> Fn(&'r BTreeSet<T>) -> Option<&'r T>>
555 where
556 T: Ord + Clone + 'static,
557 {
558 OptionalKeyPath::new(move |set: &BTreeSet<T>| set.get(&value))
559 }
560
561 pub fn for_binaryheap_peek<T>() -> OptionalKeyPath<BinaryHeap<T>, T, impl for<'r> Fn(&'r BinaryHeap<T>) -> Option<&'r T>>
563 where
564 T: Ord + 'static,
565 {
566 OptionalKeyPath::new(|heap: &BinaryHeap<T>| heap.peek())
567 }
568
569 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>> {
573 WritableOptionalKeyPath::new(move |vec: &mut Vec<T>| vec.get_mut(index))
574 }
575
576 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>> {
578 WritableOptionalKeyPath::new(move |deque: &mut VecDeque<T>| deque.get_mut(index))
579 }
580
581 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>> {
583 WritableOptionalKeyPath::new(move |list: &mut LinkedList<T>| {
584 let mut iter = list.iter_mut();
586 iter.nth(index)
587 })
588 }
589
590 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>>
592 where
593 K: std::hash::Hash + Eq + Clone + 'static,
594 V: 'static,
595 {
596 WritableOptionalKeyPath::new(move |map: &mut HashMap<K, V>| map.get_mut(&key))
597 }
598
599 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>>
601 where
602 K: Ord + Clone + 'static,
603 V: 'static,
604 {
605 WritableOptionalKeyPath::new(move |map: &mut BTreeMap<K, V>| map.get_mut(&key))
606 }
607
608 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>>
611 where
612 T: std::hash::Hash + Eq + Clone + 'static,
613 {
614 WritableOptionalKeyPath::new(move |set: &mut HashSet<T>| {
615 if set.contains(&value) {
618 None
621 } else {
622 None
623 }
624 })
625 }
626
627 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>>
630 where
631 T: Ord + Clone + 'static,
632 {
633 WritableOptionalKeyPath::new(move |set: &mut BTreeSet<T>| {
634 if set.contains(&value) {
637 None
640 } else {
641 None
642 }
643 })
644 }
645
646 pub fn for_binaryheap_peek_mut<T>() -> WritableOptionalKeyPath<BinaryHeap<T>, T, impl for<'r> Fn(&'r mut BinaryHeap<T>) -> Option<&'r mut T>>
652 where
653 T: Ord + 'static,
654 {
655 WritableOptionalKeyPath::new(|_heap: &mut BinaryHeap<T>| {
659 None
660 })
661 }
662
663 pub fn lock_mutex<T>(mutex: &Mutex<T>) -> Option<std::sync::MutexGuard<'_, T>> {
672 mutex.lock().ok()
673 }
674
675 pub fn read_rwlock<T>(rwlock: &RwLock<T>) -> Option<std::sync::RwLockReadGuard<'_, T>> {
679 rwlock.read().ok()
680 }
681
682 pub fn write_rwlock<T>(rwlock: &RwLock<T>) -> Option<std::sync::RwLockWriteGuard<'_, T>> {
686 rwlock.write().ok()
687 }
688
689 pub fn lock_arc_mutex<T>(arc_mutex: &Arc<Mutex<T>>) -> Option<std::sync::MutexGuard<'_, T>> {
693 arc_mutex.lock().ok()
694 }
695
696 pub fn read_arc_rwlock<T>(arc_rwlock: &Arc<RwLock<T>>) -> Option<std::sync::RwLockReadGuard<'_, T>> {
700 arc_rwlock.read().ok()
701 }
702
703 pub fn write_arc_rwlock<T>(arc_rwlock: &Arc<RwLock<T>>) -> Option<std::sync::RwLockWriteGuard<'_, T>> {
707 arc_rwlock.write().ok()
708 }
709
710 pub fn upgrade_weak<T>(weak: &StdWeak<T>) -> Option<Arc<T>> {
714 weak.upgrade()
715 }
716
717 pub fn upgrade_rc_weak<T>(weak: &RcWeak<T>) -> Option<Rc<T>> {
721 weak.upgrade()
722 }
723
724 #[cfg(feature = "parking_lot")]
725 pub fn lock_parking_mutex<T>(mutex: &ParkingMutex<T>) -> parking_lot::MutexGuard<'_, T> {
728 mutex.lock()
729 }
730
731 #[cfg(feature = "parking_lot")]
732 pub fn read_parking_rwlock<T>(rwlock: &ParkingRwLock<T>) -> parking_lot::RwLockReadGuard<'_, T> {
735 rwlock.read()
736 }
737
738 #[cfg(feature = "parking_lot")]
739 pub fn write_parking_rwlock<T>(rwlock: &ParkingRwLock<T>) -> parking_lot::RwLockWriteGuard<'_, T> {
742 rwlock.write()
743 }
744
745 #[cfg(feature = "tagged")]
746 pub fn for_tagged<Tag, T>() -> KeyPath<Tagged<Tag, T>, T, impl for<'r> Fn(&'r Tagged<Tag, T>) -> &'r T>
749 where
750 Tagged<Tag, T>: std::ops::Deref<Target = T>,
751 Tag: 'static,
752 T: 'static,
753 {
754 KeyPath::new(|tagged: &Tagged<Tag, T>| tagged.deref())
755 }
756
757 #[cfg(feature = "tagged")]
758 pub fn for_tagged_mut<Tag, T>() -> WritableKeyPath<Tagged<Tag, T>, T, impl for<'r> Fn(&'r mut Tagged<Tag, T>) -> &'r mut T>
761 where
762 Tagged<Tag, T>: std::ops::DerefMut<Target = T>,
763 Tag: 'static,
764 T: 'static,
765 {
766 WritableKeyPath::new(|tagged: &mut Tagged<Tag, T>| tagged.deref_mut())
767 }
768}
769
770#[derive(Clone)]
772pub struct OptionalKeyPath<Root, Value, F>
773where
774 F: for<'r> Fn(&'r Root) -> Option<&'r Value>,
775{
776 getter: F,
777 _phantom: PhantomData<(Root, Value)>,
778}
779
780impl<Root, Value, F> OptionalKeyPath<Root, Value, F>
781where
782 F: for<'r> Fn(&'r Root) -> Option<&'r Value>,
783{
784 pub fn new(getter: F) -> Self {
785 Self {
786 getter,
787 _phantom: PhantomData,
788 }
789 }
790
791 pub fn get<'r>(&self, root: &'r Root) -> Option<&'r Value> {
792 (self.getter)(root)
793 }
794
795 pub fn then<SubValue, G>(
797 self,
798 next: OptionalKeyPath<Value, SubValue, G>,
799 ) -> OptionalKeyPath<Root, SubValue, impl for<'r> Fn(&'r Root) -> Option<&'r SubValue>>
800 where
801 G: for<'r> Fn(&'r Value) -> Option<&'r SubValue>,
802 F: 'static,
803 G: 'static,
804 Value: 'static,
805 {
806 let first = self.getter;
807 let second = next.getter;
808
809 OptionalKeyPath::new(move |root: &Root| {
810 first(root).and_then(|value| second(value))
811 })
812 }
813
814 pub fn for_box<Target>(self) -> OptionalKeyPath<Root, Target, impl for<'r> Fn(&'r Root) -> Option<&'r Target> + 'static>
817 where
818 Value: std::ops::Deref<Target = Target>,
819 F: 'static,
820 Value: 'static,
821 {
822 let getter = self.getter;
823
824 OptionalKeyPath {
825 getter: move |root: &Root| {
826 getter(root).map(|boxed| boxed.deref())
827 },
828 _phantom: PhantomData,
829 }
830 }
831
832 pub fn for_arc<Target>(self) -> OptionalKeyPath<Root, Target, impl for<'r> Fn(&'r Root) -> Option<&'r Target> + 'static>
834 where
835 Value: std::ops::Deref<Target = Target>,
836 F: 'static,
837 Value: 'static,
838 {
839 let getter = self.getter;
840
841 OptionalKeyPath {
842 getter: move |root: &Root| {
843 getter(root).map(|arc| arc.deref())
844 },
845 _phantom: PhantomData,
846 }
847 }
848
849 pub fn for_rc<Target>(self) -> OptionalKeyPath<Root, Target, impl for<'r> Fn(&'r Root) -> Option<&'r Target> + 'static>
851 where
852 Value: std::ops::Deref<Target = Target>,
853 F: 'static,
854 Value: 'static,
855 {
856 let getter = self.getter;
857
858 OptionalKeyPath {
859 getter: move |root: &Root| {
860 getter(root).map(|rc| rc.deref())
861 },
862 _phantom: PhantomData,
863 }
864 }
865
866 #[cfg(feature = "tagged")]
867 pub fn for_tagged<Tag>(self) -> OptionalKeyPath<Tagged<Root, Tag>, Value, impl for<'r> Fn(&'r Tagged<Root, Tag>) -> Option<&'r Value> + 'static>
870 where
871 Tagged<Root, Tag>: std::ops::Deref<Target = Root>,
872 F: 'static,
873 Root: 'static,
874 Value: 'static,
875 Tag: 'static,
876 {
877 use std::ops::Deref;
878 let getter = self.getter;
879
880 OptionalKeyPath {
881 getter: move |tagged: &Tagged<Root, Tag>| {
882 getter(tagged.deref())
883 },
884 _phantom: PhantomData,
885 }
886 }
887
888 #[cfg(feature = "tagged")]
889 pub fn with_tagged<Tag, Callback, R>(&self, tagged: &Tagged<Root, Tag>, f: Callback) -> Option<R>
892 where
893 Tagged<Root, Tag>: std::ops::Deref<Target = Root>,
894 F: Clone,
895 Callback: FnOnce(&Value) -> R,
896 {
897 use std::ops::Deref;
898 self.get(tagged.deref()).map(|value| f(value))
899 }
900
901 pub fn for_option(self) -> OptionalKeyPath<Option<Root>, Value, impl for<'r> Fn(&'r Option<Root>) -> Option<&'r Value> + 'static>
904 where
905 F: 'static,
906 Root: 'static,
907 Value: 'static,
908 {
909 let getter = self.getter;
910
911 OptionalKeyPath {
912 getter: move |opt: &Option<Root>| {
913 opt.as_ref().and_then(|root| getter(root))
914 },
915 _phantom: PhantomData,
916 }
917 }
918
919 pub fn for_result<E>(self) -> OptionalKeyPath<Result<Root, E>, Value, impl for<'r> Fn(&'r Result<Root, E>) -> Option<&'r Value> + 'static>
922 where
923 F: 'static,
924 Root: 'static,
925 Value: 'static,
926 E: 'static,
927 {
928 let getter = self.getter;
929
930 OptionalKeyPath {
931 getter: move |result: &Result<Root, E>| {
932 result.as_ref().ok().and_then(|root| getter(root))
933 },
934 _phantom: PhantomData,
935 }
936 }
937
938 pub fn for_arc_root(self) -> OptionalKeyPath<Arc<Root>, Value, impl for<'r> Fn(&'r Arc<Root>) -> Option<&'r Value> + 'static>
940 where
941 Value: Sized,
942 F: 'static,
943 Root: 'static,
944 Value: 'static,
945 {
946 let getter = self.getter;
947
948 OptionalKeyPath {
949 getter: move |arc: &Arc<Root>| {
950 getter(arc.as_ref())
951 },
952 _phantom: PhantomData,
953 }
954 }
955
956 pub fn for_rc_root(self) -> OptionalKeyPath<Rc<Root>, Value, impl for<'r> Fn(&'r Rc<Root>) -> Option<&'r Value> + 'static>
958 where
959 Value: Sized,
960 F: 'static,
961 Root: 'static,
962 Value: 'static,
963 {
964 let getter = self.getter;
965
966 OptionalKeyPath {
967 getter: move |rc: &Rc<Root>| {
968 getter(rc.as_ref())
969 },
970 _phantom: PhantomData,
971 }
972 }
973
974 pub fn with_option<Callback, R>(&self, option: &Option<Root>, f: Callback) -> Option<R>
976 where
977 F: Clone,
978 Callback: FnOnce(&Value) -> R,
979 {
980 option.as_ref().and_then(|root| {
981 self.get(root).map(|value| f(value))
982 })
983 }
984
985 pub fn with_mutex<Callback, R>(&self, mutex: &Mutex<Root>, f: Callback) -> Option<R>
987 where
988 F: Clone,
989 Callback: FnOnce(&Value) -> R,
990 {
991 mutex.lock().ok().and_then(|guard| {
992 self.get(&*guard).map(|value| f(value))
993 })
994 }
995
996 pub fn with_rwlock<Callback, R>(&self, rwlock: &RwLock<Root>, f: Callback) -> Option<R>
998 where
999 F: Clone,
1000 Callback: FnOnce(&Value) -> R,
1001 {
1002 rwlock.read().ok().and_then(|guard| {
1003 self.get(&*guard).map(|value| f(value))
1004 })
1005 }
1006
1007 pub fn with_arc_rwlock<Callback, R>(&self, arc_rwlock: &Arc<RwLock<Root>>, f: Callback) -> Option<R>
1009 where
1010 F: Clone,
1011 Callback: FnOnce(&Value) -> R,
1012 {
1013 arc_rwlock.read().ok().and_then(|guard| {
1014 self.get(&*guard).map(|value| f(value))
1015 })
1016 }
1017
1018 pub fn with_arc_rwlock_direct<Callback, R>(&self, arc_rwlock: &Arc<RwLock<Root>>, f: Callback) -> Option<R>
1022 where
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_mutex<Callback, R>(&self, arc_mutex: &Arc<Mutex<Root>>, f: Callback) -> Option<R>
1032 where
1033 F: Clone,
1034 Callback: FnOnce(&Value) -> R,
1035 {
1036 arc_mutex.lock().ok().and_then(|guard| {
1037 self.get(&*guard).map(|value| f(value))
1038 })
1039 }
1040}
1041
1042
1043#[derive(Clone)]
1045pub struct WritableKeyPath<Root, Value, F>
1046where
1047 F: for<'r> Fn(&'r mut Root) -> &'r mut Value,
1048{
1049 getter: F,
1050 _phantom: PhantomData<(Root, Value)>,
1051}
1052
1053impl<Root, Value, F> WritableKeyPath<Root, Value, F>
1054where
1055 F: for<'r> Fn(&'r mut Root) -> &'r mut Value,
1056{
1057 pub fn new(getter: F) -> Self {
1058 Self {
1059 getter,
1060 _phantom: PhantomData,
1061 }
1062 }
1063
1064 pub fn get_mut<'r>(&self, root: &'r mut Root) -> &'r mut Value {
1065 (self.getter)(root)
1066 }
1067
1068 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>
1071 where
1072 F: 'static,
1073 Root: 'static,
1074 Value: 'static,
1075 E: 'static,
1076 {
1077 let getter = self.getter;
1078
1079 WritableOptionalKeyPath {
1080 getter: move |result: &mut Result<Root, E>| {
1081 result.as_mut().ok().map(|root| getter(root))
1082 },
1083 _phantom: PhantomData,
1084 }
1085 }
1086
1087 pub fn for_box_root(self) -> WritableKeyPath<Box<Root>, Value, impl for<'r> Fn(&'r mut Box<Root>) -> &'r mut Value + 'static>
1089 where
1090 Value: Sized,
1091 F: 'static,
1092 Root: 'static,
1093 Value: 'static,
1094 {
1095 let getter = self.getter;
1096
1097 WritableKeyPath {
1098 getter: move |boxed: &mut Box<Root>| {
1099 getter(boxed.as_mut())
1100 },
1101 _phantom: PhantomData,
1102 }
1103 }
1104
1105 pub fn to_optional(self) -> WritableOptionalKeyPath<Root, Value, impl for<'r> Fn(&'r mut Root) -> Option<&'r mut Value> + 'static>
1108 where
1109 F: 'static,
1110 {
1111 let getter = self.getter;
1112 WritableOptionalKeyPath::new(move |root: &mut Root| Some(getter(root)))
1113 }
1114
1115 pub fn for_box<Target>(self) -> WritableKeyPath<Root, Target, impl for<'r> Fn(&'r mut Root) -> &'r mut Target + 'static>
1118 where
1119 Value: std::ops::DerefMut<Target = Target>,
1120 F: 'static,
1121 Value: 'static,
1122 {
1123 let getter = self.getter;
1124
1125 WritableKeyPath {
1126 getter: move |root: &mut Root| {
1127 getter(root).deref_mut()
1128 },
1129 _phantom: PhantomData,
1130 }
1131 }
1132
1133 pub fn for_arc<Target>(self) -> WritableKeyPath<Root, Target, impl for<'r> Fn(&'r mut Root) -> &'r mut Target + 'static>
1136 where
1137 Value: std::ops::DerefMut<Target = Target>,
1138 F: 'static,
1139 Value: 'static,
1140 {
1141 let getter = self.getter;
1142
1143 WritableKeyPath {
1144 getter: move |root: &mut Root| {
1145 getter(root).deref_mut()
1146 },
1147 _phantom: PhantomData,
1148 }
1149 }
1150
1151 pub fn for_rc<Target>(self) -> WritableKeyPath<Root, Target, impl for<'r> Fn(&'r mut Root) -> &'r mut Target + 'static>
1154 where
1155 Value: std::ops::DerefMut<Target = Target>,
1156 F: 'static,
1157 Value: 'static,
1158 {
1159 let getter = self.getter;
1160
1161 WritableKeyPath {
1162 getter: move |root: &mut Root| {
1163 getter(root).deref_mut()
1164 },
1165 _phantom: PhantomData,
1166 }
1167 }
1168
1169 pub fn with_box_mut<Callback, R>(&self, boxed: &mut Box<Root>, f: Callback) -> R
1171 where
1172 F: Clone,
1173 Callback: FnOnce(&mut Value) -> R,
1174 {
1175 let value = self.get_mut(boxed);
1176 f(value)
1177 }
1178
1179 pub fn with_result_mut<Callback, R, E>(&self, result: &mut Result<Root, E>, f: Callback) -> Option<R>
1181 where
1182 F: Clone,
1183 Callback: FnOnce(&mut Value) -> R,
1184 {
1185 result.as_mut().ok().map(|root| {
1186 let value = self.get_mut(root);
1187 f(value)
1188 })
1189 }
1190
1191 pub fn with_option_mut<Callback, R>(&self, option: &mut Option<Root>, f: Callback) -> Option<R>
1193 where
1194 F: Clone,
1195 Callback: FnOnce(&mut Value) -> R,
1196 {
1197 option.as_mut().map(|root| {
1198 let value = self.get_mut(root);
1199 f(value)
1200 })
1201 }
1202
1203 pub fn with_refcell_mut<Callback, R>(&self, refcell: &RefCell<Root>, f: Callback) -> Option<R>
1205 where
1206 F: Clone,
1207 Callback: FnOnce(&mut Value) -> R,
1208 {
1209 refcell.try_borrow_mut().ok().map(|mut borrow| {
1210 let value = self.get_mut(&mut *borrow);
1211 f(value)
1212 })
1213 }
1214
1215 pub fn with_mutex_mut<Callback, R>(&self, mutex: &mut Mutex<Root>, f: Callback) -> Option<R>
1217 where
1218 F: Clone,
1219 Callback: FnOnce(&mut Value) -> R,
1220 {
1221 mutex.get_mut().ok().map(|root| {
1222 let value = self.get_mut(root);
1223 f(value)
1224 })
1225 }
1226
1227 pub fn with_rwlock_mut<Callback, R>(&self, rwlock: &mut RwLock<Root>, f: Callback) -> Option<R>
1229 where
1230 F: Clone,
1231 Callback: FnOnce(&mut Value) -> R,
1232 {
1233 rwlock.write().ok().map(|mut guard| {
1234 let value = self.get_mut(&mut *guard);
1235 f(value)
1236 })
1237 }
1238
1239 pub fn iter_mut<'r, T>(&self, root: &'r mut Root) -> Option<std::slice::IterMut<'r, T>>
1242 where
1243 Value: AsMut<[T]> + 'r,
1244 {
1245 let value_ref: &'r mut Value = self.get_mut(root);
1246 Some(value_ref.as_mut().iter_mut())
1247 }
1248}
1249
1250#[derive(Clone)]
1252pub struct WritableOptionalKeyPath<Root, Value, F>
1253where
1254 F: for<'r> Fn(&'r mut Root) -> Option<&'r mut Value>,
1255{
1256 getter: F,
1257 _phantom: PhantomData<(Root, Value)>,
1258}
1259
1260impl<Root, Value, F> WritableOptionalKeyPath<Root, Value, F>
1261where
1262 F: for<'r> Fn(&'r mut Root) -> Option<&'r mut Value>,
1263{
1264 pub fn new(getter: F) -> Self {
1265 Self {
1266 getter,
1267 _phantom: PhantomData,
1268 }
1269 }
1270
1271 pub fn get_mut<'r>(&self, root: &'r mut Root) -> Option<&'r mut Value> {
1272 (self.getter)(root)
1273 }
1274
1275 pub fn then<SubValue, G>(
1277 self,
1278 next: WritableOptionalKeyPath<Value, SubValue, G>,
1279 ) -> WritableOptionalKeyPath<Root, SubValue, impl for<'r> Fn(&'r mut Root) -> Option<&'r mut SubValue>>
1280 where
1281 G: for<'r> Fn(&'r mut Value) -> Option<&'r mut SubValue>,
1282 F: 'static,
1283 G: 'static,
1284 Value: 'static,
1285 {
1286 let first = self.getter;
1287 let second = next.getter;
1288
1289 WritableOptionalKeyPath::new(move |root: &mut Root| {
1290 first(root).and_then(|value| second(value))
1291 })
1292 }
1293
1294 pub fn for_box<Target>(self) -> WritableOptionalKeyPath<Root, Target, impl for<'r> Fn(&'r mut Root) -> Option<&'r mut Target> + 'static>
1297 where
1298 Value: std::ops::DerefMut<Target = Target>,
1299 F: 'static,
1300 Value: 'static,
1301 {
1302 let getter = self.getter;
1303
1304 WritableOptionalKeyPath {
1305 getter: move |root: &mut Root| {
1306 getter(root).map(|boxed| boxed.deref_mut())
1307 },
1308 _phantom: PhantomData,
1309 }
1310 }
1311
1312 pub fn for_arc<Target>(self) -> WritableOptionalKeyPath<Root, Target, impl for<'r> Fn(&'r mut Root) -> Option<&'r mut Target> + 'static>
1314 where
1315 Value: std::ops::DerefMut<Target = Target>,
1316 F: 'static,
1317 Value: 'static,
1318 {
1319 let getter = self.getter;
1320
1321 WritableOptionalKeyPath {
1322 getter: move |root: &mut Root| {
1323 getter(root).map(|arc| arc.deref_mut())
1324 },
1325 _phantom: PhantomData,
1326 }
1327 }
1328
1329 pub fn for_rc<Target>(self) -> WritableOptionalKeyPath<Root, Target, impl for<'r> Fn(&'r mut Root) -> Option<&'r mut Target> + 'static>
1331 where
1332 Value: std::ops::DerefMut<Target = Target>,
1333 F: 'static,
1334 Value: 'static,
1335 {
1336 let getter = self.getter;
1337
1338 WritableOptionalKeyPath {
1339 getter: move |root: &mut Root| {
1340 getter(root).map(|rc| rc.deref_mut())
1341 },
1342 _phantom: PhantomData,
1343 }
1344 }
1345
1346 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>
1349 where
1350 F: 'static,
1351 Root: 'static,
1352 Value: 'static,
1353 E: 'static,
1354 {
1355 let getter = self.getter;
1356
1357 WritableOptionalKeyPath {
1358 getter: move |result: &mut Result<Root, E>| {
1359 result.as_mut().ok().and_then(|root| getter(root))
1360 },
1361 _phantom: PhantomData,
1362 }
1363 }
1364
1365 pub fn for_box_root(self) -> WritableOptionalKeyPath<Box<Root>, Value, impl for<'r> Fn(&'r mut Box<Root>) -> Option<&'r mut Value> + 'static>
1367 where
1368 Value: Sized,
1369 F: 'static,
1370 Root: 'static,
1371 Value: 'static,
1372 {
1373 let getter = self.getter;
1374
1375 WritableOptionalKeyPath {
1376 getter: move |boxed: &mut Box<Root>| {
1377 getter(boxed.as_mut())
1378 },
1379 _phantom: PhantomData,
1380 }
1381 }
1382
1383 pub fn for_arc_root(self) -> WritableOptionalKeyPath<Arc<Root>, Value, impl for<'r> Fn(&'r mut Arc<Root>) -> Option<&'r mut Value> + 'static>
1385 where
1386 Value: Sized,
1387 F: 'static,
1388 Root: 'static,
1389 Value: 'static,
1390 {
1391 let getter = self.getter;
1392
1393 WritableOptionalKeyPath {
1394 getter: move |arc: &mut Arc<Root>| {
1395 None
1398 },
1399 _phantom: PhantomData,
1400 }
1401 }
1402
1403 pub fn for_rc_root(self) -> WritableOptionalKeyPath<Rc<Root>, Value, impl for<'r> Fn(&'r mut Rc<Root>) -> Option<&'r mut Value> + 'static>
1405 where
1406 Value: Sized,
1407 F: 'static,
1408 Root: 'static,
1409 Value: 'static,
1410 {
1411 let getter = self.getter;
1412
1413 WritableOptionalKeyPath {
1414 getter: move |rc: &mut Rc<Root>| {
1415 None
1418 },
1419 _phantom: PhantomData,
1420 }
1421 }
1422
1423 pub fn for_option<T>() -> WritableOptionalKeyPath<Option<T>, T, impl for<'r> Fn(&'r mut Option<T>) -> Option<&'r mut T>> {
1425 WritableOptionalKeyPath::new(|opt: &mut Option<T>| opt.as_mut())
1426 }
1427}
1428
1429pub struct EnumKeyPath<Enum = (), Variant = (), ExtractFn = fn(&()) -> Option<&()>, EmbedFn = fn(()) -> ()>
1437where
1438 ExtractFn: for<'r> Fn(&'r Enum) -> Option<&'r Variant> + 'static,
1439 EmbedFn: Fn(Variant) -> Enum + 'static,
1440{
1441 extractor: OptionalKeyPath<Enum, Variant, ExtractFn>,
1442 embedder: EmbedFn,
1443}
1444
1445impl<Enum, Variant, ExtractFn, EmbedFn> EnumKeyPath<Enum, Variant, ExtractFn, EmbedFn>
1446where
1447 ExtractFn: for<'r> Fn(&'r Enum) -> Option<&'r Variant> + 'static,
1448 EmbedFn: Fn(Variant) -> Enum + 'static,
1449{
1450 pub fn new(
1452 extractor: ExtractFn,
1453 embedder: EmbedFn,
1454 ) -> Self {
1455 Self {
1456 extractor: OptionalKeyPath::new(extractor),
1457 embedder,
1458 }
1459 }
1460
1461 pub fn get<'r>(&self, enum_value: &'r Enum) -> Option<&'r Variant> {
1463 self.extractor.get(enum_value)
1464 }
1465
1466 pub fn embed(&self, value: Variant) -> Enum {
1468 (self.embedder)(value)
1469 }
1470
1471 pub fn as_optional(&self) -> &OptionalKeyPath<Enum, Variant, ExtractFn> {
1473 &self.extractor
1474 }
1475
1476 pub fn to_optional(self) -> OptionalKeyPath<Enum, Variant, ExtractFn> {
1478 self.extractor
1479 }
1480}
1481
1482impl EnumKeyPath {
1484 pub fn readable_enum<Enum, Variant, ExtractFn, EmbedFn>(
1487 embedder: EmbedFn,
1488 extractor: ExtractFn,
1489 ) -> EnumKeyPath<Enum, Variant, ExtractFn, EmbedFn>
1490 where
1491 ExtractFn: for<'r> Fn(&'r Enum) -> Option<&'r Variant> + 'static,
1492 EmbedFn: Fn(Variant) -> Enum + 'static,
1493 {
1494 EnumKeyPath::new(extractor, embedder)
1495 }
1496
1497 pub fn for_variant<Enum, Variant, ExtractFn>(
1499 extractor: ExtractFn
1500 ) -> OptionalKeyPath<Enum, Variant, impl for<'r> Fn(&'r Enum) -> Option<&'r Variant>>
1501 where
1502 ExtractFn: Fn(&Enum) -> Option<&Variant>,
1503 {
1504 OptionalKeyPath::new(extractor)
1505 }
1506
1507 pub fn for_match<Enum, Output, MatchFn>(
1509 matcher: MatchFn
1510 ) -> KeyPath<Enum, Output, impl for<'r> Fn(&'r Enum) -> &'r Output>
1511 where
1512 MatchFn: Fn(&Enum) -> &Output,
1513 {
1514 KeyPath::new(matcher)
1515 }
1516
1517 pub fn for_ok<T, E>() -> OptionalKeyPath<Result<T, E>, T, impl for<'r> Fn(&'r Result<T, E>) -> Option<&'r T>> {
1519 OptionalKeyPath::new(|result: &Result<T, E>| result.as_ref().ok())
1520 }
1521
1522 pub fn for_err<T, E>() -> OptionalKeyPath<Result<T, E>, E, impl for<'r> Fn(&'r Result<T, E>) -> Option<&'r E>> {
1524 OptionalKeyPath::new(|result: &Result<T, E>| result.as_ref().err())
1525 }
1526
1527 pub fn for_some<T>() -> OptionalKeyPath<Option<T>, T, impl for<'r> Fn(&'r Option<T>) -> Option<&'r T>> {
1529 OptionalKeyPath::new(|opt: &Option<T>| opt.as_ref())
1530 }
1531
1532 pub fn for_option<T>() -> OptionalKeyPath<Option<T>, T, impl for<'r> Fn(&'r Option<T>) -> Option<&'r T>> {
1534 OptionalKeyPath::new(|opt: &Option<T>| opt.as_ref())
1535 }
1536
1537 pub fn for_box<T>() -> KeyPath<Box<T>, T, impl for<'r> Fn(&'r Box<T>) -> &'r T> {
1539 KeyPath::new(|b: &Box<T>| b.as_ref())
1540 }
1541
1542 pub fn for_arc<T>() -> KeyPath<Arc<T>, T, impl for<'r> Fn(&'r Arc<T>) -> &'r T> {
1544 KeyPath::new(|arc: &Arc<T>| arc.as_ref())
1545 }
1546
1547 pub fn for_rc<T>() -> KeyPath<std::rc::Rc<T>, T, impl for<'r> Fn(&'r std::rc::Rc<T>) -> &'r T> {
1549 KeyPath::new(|rc: &std::rc::Rc<T>| rc.as_ref())
1550 }
1551
1552 pub fn for_box_mut<T>() -> WritableKeyPath<Box<T>, T, impl for<'r> Fn(&'r mut Box<T>) -> &'r mut T> {
1554 WritableKeyPath::new(|b: &mut Box<T>| b.as_mut())
1555 }
1556
1557 }
1561
1562pub fn variant_of<Enum, Variant, F>(extractor: F) -> OptionalKeyPath<Enum, Variant, F>
1564where
1565 F: for<'r> Fn(&'r Enum) -> Option<&'r Variant>,
1566{
1567 OptionalKeyPath::new(extractor)
1568}
1569
1570#[derive(Clone)]
1586pub struct PartialKeyPath<Root> {
1587 getter: Rc<dyn for<'r> Fn(&'r Root) -> &'r dyn Any>,
1588 value_type_id: TypeId,
1589 _phantom: PhantomData<Root>,
1590}
1591
1592impl<Root> PartialKeyPath<Root> {
1593 pub fn new<Value>(keypath: KeyPath<Root, Value, impl for<'r> Fn(&'r Root) -> &'r Value + 'static>) -> Self
1594 where
1595 Value: Any + 'static,
1596 Root: 'static,
1597 {
1598 let value_type_id = TypeId::of::<Value>();
1599 let getter = Rc::new(keypath.getter);
1600
1601 Self {
1602 getter: Rc::new(move |root: &Root| {
1603 let value: &Value = getter(root);
1604 value as &dyn Any
1605 }),
1606 value_type_id,
1607 _phantom: PhantomData,
1608 }
1609 }
1610
1611 pub fn from<Value>(keypath: KeyPath<Root, Value, impl for<'r> Fn(&'r Root) -> &'r Value + 'static>) -> Self
1614 where
1615 Value: Any + 'static,
1616 Root: 'static,
1617 {
1618 Self::new(keypath)
1619 }
1620
1621 pub fn get<'r>(&self, root: &'r Root) -> &'r dyn Any {
1622 (self.getter)(root)
1623 }
1624
1625 pub fn value_type_id(&self) -> TypeId {
1627 self.value_type_id
1628 }
1629
1630 pub fn get_as<'a, Value: Any>(&self, root: &'a Root) -> Option<&'a Value> {
1632 if self.value_type_id == TypeId::of::<Value>() {
1633 self.get(root).downcast_ref::<Value>()
1634 } else {
1635 None
1636 }
1637 }
1638
1639 pub fn kind_name(&self) -> String {
1642 format!("{:?}", self.value_type_id)
1643 }
1644}
1645
1646#[derive(Clone)]
1653pub struct PartialOptionalKeyPath<Root> {
1654 getter: Rc<dyn for<'r> Fn(&'r Root) -> Option<&'r dyn Any>>,
1655 value_type_id: TypeId,
1656 _phantom: PhantomData<Root>,
1657}
1658
1659impl<Root> PartialOptionalKeyPath<Root> {
1660 pub fn new<Value>(keypath: OptionalKeyPath<Root, Value, impl for<'r> Fn(&'r Root) -> Option<&'r Value> + 'static>) -> Self
1661 where
1662 Value: Any + 'static,
1663 Root: 'static,
1664 {
1665 let value_type_id = TypeId::of::<Value>();
1666 let getter = Rc::new(keypath.getter);
1667
1668 Self {
1669 getter: Rc::new(move |root: &Root| {
1670 getter(root).map(|value: &Value| value as &dyn Any)
1671 }),
1672 value_type_id,
1673 _phantom: PhantomData,
1674 }
1675 }
1676
1677 pub fn get<'r>(&self, root: &'r Root) -> Option<&'r dyn Any> {
1678 (self.getter)(root)
1679 }
1680
1681 pub fn value_type_id(&self) -> TypeId {
1683 self.value_type_id
1684 }
1685
1686 pub fn get_as<'a, Value: Any>(&self, root: &'a Root) -> Option<Option<&'a Value>> {
1688 if self.value_type_id == TypeId::of::<Value>() {
1689 self.get(root).map(|any| any.downcast_ref::<Value>())
1690 } else {
1691 None
1692 }
1693 }
1694
1695 pub fn then<MidValue>(
1699 self,
1700 next: PartialOptionalKeyPath<MidValue>,
1701 ) -> PartialOptionalKeyPath<Root>
1702 where
1703 MidValue: Any + 'static,
1704 Root: 'static,
1705 {
1706 let first = self.getter;
1707 let second = next.getter;
1708 let value_type_id = next.value_type_id;
1709
1710 PartialOptionalKeyPath {
1711 getter: Rc::new(move |root: &Root| {
1712 first(root).and_then(|any| {
1713 if let Some(mid_value) = any.downcast_ref::<MidValue>() {
1714 second(mid_value)
1715 } else {
1716 None
1717 }
1718 })
1719 }),
1720 value_type_id,
1721 _phantom: PhantomData,
1722 }
1723 }
1724}
1725
1726#[derive(Clone)]
1732pub struct PartialWritableKeyPath<Root> {
1733 getter: Rc<dyn for<'r> Fn(&'r mut Root) -> &'r mut dyn Any>,
1734 value_type_id: TypeId,
1735 _phantom: PhantomData<Root>,
1736}
1737
1738impl<Root> PartialWritableKeyPath<Root> {
1739 pub fn new<Value>(keypath: WritableKeyPath<Root, Value, impl for<'r> Fn(&'r mut Root) -> &'r mut Value + 'static>) -> Self
1740 where
1741 Value: Any + 'static,
1742 Root: 'static,
1743 {
1744 let value_type_id = TypeId::of::<Value>();
1745 let getter = Rc::new(keypath.getter);
1746
1747 Self {
1748 getter: Rc::new(move |root: &mut Root| {
1749 let value: &mut Value = getter(root);
1750 value as &mut dyn Any
1751 }),
1752 value_type_id,
1753 _phantom: PhantomData,
1754 }
1755 }
1756
1757 pub fn from<Value>(keypath: WritableKeyPath<Root, Value, impl for<'r> Fn(&'r mut Root) -> &'r mut Value + 'static>) -> Self
1760 where
1761 Value: Any + 'static,
1762 Root: 'static,
1763 {
1764 Self::new(keypath)
1765 }
1766
1767 pub fn get_mut<'r>(&self, root: &'r mut Root) -> &'r mut dyn Any {
1768 (self.getter)(root)
1769 }
1770
1771 pub fn value_type_id(&self) -> TypeId {
1773 self.value_type_id
1774 }
1775
1776 pub fn get_mut_as<'a, Value: Any>(&self, root: &'a mut Root) -> Option<&'a mut Value> {
1778 if self.value_type_id == TypeId::of::<Value>() {
1779 self.get_mut(root).downcast_mut::<Value>()
1780 } else {
1781 None
1782 }
1783 }
1784}
1785
1786#[derive(Clone)]
1792pub struct PartialWritableOptionalKeyPath<Root> {
1793 getter: Rc<dyn for<'r> Fn(&'r mut Root) -> Option<&'r mut dyn Any>>,
1794 value_type_id: TypeId,
1795 _phantom: PhantomData<Root>,
1796}
1797
1798impl<Root> PartialWritableOptionalKeyPath<Root> {
1799 pub fn new<Value>(keypath: WritableOptionalKeyPath<Root, Value, impl for<'r> Fn(&'r mut Root) -> Option<&'r mut Value> + 'static>) -> Self
1800 where
1801 Value: Any + 'static,
1802 Root: 'static,
1803 {
1804 let value_type_id = TypeId::of::<Value>();
1805 let getter = Rc::new(keypath.getter);
1806
1807 Self {
1808 getter: Rc::new(move |root: &mut Root| {
1809 getter(root).map(|value: &mut Value| value as &mut dyn Any)
1810 }),
1811 value_type_id,
1812 _phantom: PhantomData,
1813 }
1814 }
1815
1816 pub fn get_mut<'r>(&self, root: &'r mut Root) -> Option<&'r mut dyn Any> {
1817 (self.getter)(root)
1818 }
1819
1820 pub fn value_type_id(&self) -> TypeId {
1822 self.value_type_id
1823 }
1824
1825 pub fn get_mut_as<'a, Value: Any>(&self, root: &'a mut Root) -> Option<Option<&'a mut Value>> {
1827 if self.value_type_id == TypeId::of::<Value>() {
1828 self.get_mut(root).map(|any| any.downcast_mut::<Value>())
1829 } else {
1830 None
1831 }
1832 }
1833}
1834
1835#[derive(Clone)]
1849pub struct AnyKeyPath {
1850 getter: Rc<dyn for<'r> Fn(&'r dyn Any) -> Option<&'r dyn Any>>,
1851 root_type_id: TypeId,
1852 value_type_id: TypeId,
1853}
1854
1855impl AnyKeyPath {
1856 pub fn new<Root, Value>(keypath: OptionalKeyPath<Root, Value, impl for<'r> Fn(&'r Root) -> Option<&'r Value> + 'static>) -> Self
1857 where
1858 Root: Any + 'static,
1859 Value: Any + 'static,
1860 {
1861 let root_type_id = TypeId::of::<Root>();
1862 let value_type_id = TypeId::of::<Value>();
1863 let getter = keypath.getter;
1864
1865 Self {
1866 getter: Rc::new(move |any: &dyn Any| {
1867 if let Some(root) = any.downcast_ref::<Root>() {
1868 getter(root).map(|value: &Value| value as &dyn Any)
1869 } else {
1870 None
1871 }
1872 }),
1873 root_type_id,
1874 value_type_id,
1875 }
1876 }
1877
1878 pub fn from<Root, Value>(keypath: OptionalKeyPath<Root, Value, impl for<'r> Fn(&'r Root) -> Option<&'r Value> + 'static>) -> Self
1881 where
1882 Root: Any + 'static,
1883 Value: Any + 'static,
1884 {
1885 Self::new(keypath)
1886 }
1887
1888 pub fn get<'r>(&self, root: &'r dyn Any) -> Option<&'r dyn Any> {
1889 (self.getter)(root)
1890 }
1891
1892 pub fn root_type_id(&self) -> TypeId {
1894 self.root_type_id
1895 }
1896
1897 pub fn value_type_id(&self) -> TypeId {
1899 self.value_type_id
1900 }
1901
1902 pub fn get_as<'a, Root: Any, Value: Any>(&self, root: &'a Root) -> Option<Option<&'a Value>> {
1904 if self.root_type_id == TypeId::of::<Root>() && self.value_type_id == TypeId::of::<Value>() {
1905 self.get(root as &dyn Any).map(|any| any.downcast_ref::<Value>())
1906 } else {
1907 None
1908 }
1909 }
1910
1911 pub fn kind_name(&self) -> String {
1914 format!("{:?}", self.value_type_id)
1915 }
1916}
1917
1918#[derive(Clone)]
1920pub struct AnyWritableKeyPath {
1921 getter: Rc<dyn for<'r> Fn(&'r mut dyn Any) -> Option<&'r mut dyn Any>>,
1922 root_type_id: TypeId,
1923 value_type_id: TypeId,
1924}
1925
1926#[derive(Clone)]
1931pub struct FailableCombinedKeyPath<Root, Value, ReadFn, WriteFn, OwnedFn>
1932where
1933 ReadFn: for<'r> Fn(&'r Root) -> Option<&'r Value> + 'static,
1934 WriteFn: for<'r> Fn(&'r mut Root) -> Option<&'r mut Value> + 'static,
1935 OwnedFn: Fn(Root) -> Option<Value> + 'static,
1936{
1937 readable: ReadFn,
1938 writable: WriteFn,
1939 owned: OwnedFn,
1940 _phantom: PhantomData<(Root, Value)>,
1941}
1942
1943impl<Root, Value, ReadFn, WriteFn, OwnedFn> FailableCombinedKeyPath<Root, Value, ReadFn, WriteFn, OwnedFn>
1944where
1945 ReadFn: for<'r> Fn(&'r Root) -> Option<&'r Value> + 'static,
1946 WriteFn: for<'r> Fn(&'r mut Root) -> Option<&'r mut Value> + 'static,
1947 OwnedFn: Fn(Root) -> Option<Value> + 'static,
1948{
1949 pub fn new(readable: ReadFn, writable: WriteFn, owned: OwnedFn) -> Self {
1951 Self {
1952 readable,
1953 writable,
1954 owned,
1955 _phantom: PhantomData,
1956 }
1957 }
1958
1959 pub fn get<'r>(&self, root: &'r Root) -> Option<&'r Value> {
1961 (self.readable)(root)
1962 }
1963
1964 pub fn get_mut<'r>(&self, root: &'r mut Root) -> Option<&'r mut Value> {
1966 (self.writable)(root)
1967 }
1968
1969 pub fn get_failable_owned(&self, root: Root) -> Option<Value> {
1971 (self.owned)(root)
1972 }
1973
1974 pub fn to_optional(self) -> OptionalKeyPath<Root, Value, ReadFn> {
1976 OptionalKeyPath::new(self.readable)
1977 }
1978
1979 pub fn to_writable_optional(self) -> WritableOptionalKeyPath<Root, Value, WriteFn> {
1981 WritableOptionalKeyPath::new(self.writable)
1982 }
1983
1984 pub fn then<SubValue, SubReadFn, SubWriteFn, SubOwnedFn>(
1987 self,
1988 next: FailableCombinedKeyPath<Value, SubValue, SubReadFn, SubWriteFn, SubOwnedFn>,
1989 ) -> 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>
1990 where
1991 SubReadFn: for<'r> Fn(&'r Value) -> Option<&'r SubValue> + 'static,
1992 SubWriteFn: for<'r> Fn(&'r mut Value) -> Option<&'r mut SubValue> + 'static,
1993 SubOwnedFn: Fn(Value) -> Option<SubValue> + 'static,
1994 ReadFn: 'static,
1995 WriteFn: 'static,
1996 OwnedFn: 'static,
1997 Value: 'static,
1998 Root: 'static,
1999 SubValue: 'static,
2000 {
2001 let first_read = self.readable;
2002 let first_write = self.writable;
2003 let first_owned = self.owned;
2004 let second_read = next.readable;
2005 let second_write = next.writable;
2006 let second_owned = next.owned;
2007
2008 FailableCombinedKeyPath::new(
2009 move |root: &Root| {
2010 first_read(root).and_then(|value| second_read(value))
2011 },
2012 move |root: &mut Root| {
2013 first_write(root).and_then(|value| second_write(value))
2014 },
2015 move |root: Root| {
2016 first_owned(root).and_then(|value| second_owned(value))
2017 },
2018 )
2019 }
2020
2021 pub fn then_optional<SubValue, SubReadFn>(
2025 self,
2026 next: OptionalKeyPath<Value, SubValue, SubReadFn>,
2027 ) -> 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>
2028 where
2029 SubReadFn: for<'r> Fn(&'r Value) -> Option<&'r SubValue> + 'static,
2030 ReadFn: 'static,
2031 WriteFn: 'static,
2032 OwnedFn: 'static,
2033 Value: 'static,
2034 Root: 'static,
2035 SubValue: 'static,
2036 {
2037 let first_read = self.readable;
2038 let first_write = self.writable;
2039 let first_owned = self.owned;
2040 let second_read = next.getter;
2041
2042 FailableCombinedKeyPath::new(
2043 move |root: &Root| {
2044 first_read(root).and_then(|value| second_read(value))
2045 },
2046 move |_root: &mut Root| {
2047 None },
2049 move |root: Root| {
2050 first_owned(root).and_then(|value| {
2051 None
2053 })
2054 },
2055 )
2056 }
2057}
2058
2059impl FailableCombinedKeyPath<(), (), fn(&()) -> Option<&()>, fn(&mut ()) -> Option<&mut ()>, fn(()) -> Option<()>> {
2061 pub fn failable_combined<Root, Value, ReadFn, WriteFn, OwnedFn>(
2063 readable: ReadFn,
2064 writable: WriteFn,
2065 owned: OwnedFn,
2066 ) -> FailableCombinedKeyPath<Root, Value, ReadFn, WriteFn, OwnedFn>
2067 where
2068 ReadFn: for<'r> Fn(&'r Root) -> Option<&'r Value> + 'static,
2069 WriteFn: for<'r> Fn(&'r mut Root) -> Option<&'r mut Value> + 'static,
2070 OwnedFn: Fn(Root) -> Option<Value> + 'static,
2071 {
2072 FailableCombinedKeyPath::new(readable, writable, owned)
2073 }
2074}
2075
2076impl AnyWritableKeyPath {
2077 pub fn new<Root, Value>(keypath: WritableOptionalKeyPath<Root, Value, impl for<'r> Fn(&'r mut Root) -> Option<&'r mut Value> + 'static>) -> Self
2078 where
2079 Root: Any + 'static,
2080 Value: Any + 'static,
2081 {
2082 let root_type_id = TypeId::of::<Root>();
2083 let value_type_id = TypeId::of::<Value>();
2084 let getter = keypath.getter;
2085
2086 Self {
2087 getter: Rc::new(move |any: &mut dyn Any| {
2088 if let Some(root) = any.downcast_mut::<Root>() {
2089 getter(root).map(|value: &mut Value| value as &mut dyn Any)
2090 } else {
2091 None
2092 }
2093 }),
2094 root_type_id,
2095 value_type_id,
2096 }
2097 }
2098
2099 pub fn get_mut<'r>(&self, root: &'r mut dyn Any) -> Option<&'r mut dyn Any> {
2100 (self.getter)(root)
2101 }
2102
2103 pub fn root_type_id(&self) -> TypeId {
2105 self.root_type_id
2106 }
2107
2108 pub fn value_type_id(&self) -> TypeId {
2110 self.value_type_id
2111 }
2112
2113 pub fn get_mut_as<'a, Root: Any, Value: Any>(&self, root: &'a mut Root) -> Option<Option<&'a mut Value>> {
2115 if self.root_type_id == TypeId::of::<Root>() && self.value_type_id == TypeId::of::<Value>() {
2116 self.get_mut(root as &mut dyn Any).map(|any| any.downcast_mut::<Value>())
2117 } else {
2118 None
2119 }
2120 }
2121}
2122
2123impl<Root, Value, F> KeyPath<Root, Value, F>
2125where
2126 F: for<'r> Fn(&'r Root) -> &'r Value + 'static,
2127 Root: 'static,
2128 Value: Any + 'static,
2129{
2130 pub fn to_partial(self) -> PartialKeyPath<Root> {
2132 PartialKeyPath::new(self)
2133 }
2134
2135 pub fn to(self) -> PartialKeyPath<Root> {
2137 self.to_partial()
2138 }
2139}
2140
2141impl<Root, Value, F> OptionalKeyPath<Root, Value, F>
2142where
2143 F: for<'r> Fn(&'r Root) -> Option<&'r Value> + 'static,
2144 Root: Any + 'static,
2145 Value: Any + 'static,
2146{
2147 pub fn to_partial(self) -> PartialOptionalKeyPath<Root> {
2149 PartialOptionalKeyPath::new(self)
2150 }
2151
2152 pub fn to_any(self) -> AnyKeyPath {
2154 AnyKeyPath::new(self)
2155 }
2156
2157 pub fn to(self) -> PartialOptionalKeyPath<Root> {
2159 self.to_partial()
2160 }
2161}
2162
2163impl<Root, Value, F> WritableKeyPath<Root, Value, F>
2164where
2165 F: for<'r> Fn(&'r mut Root) -> &'r mut Value + 'static,
2166 Root: 'static,
2167 Value: Any + 'static,
2168{
2169 pub fn to_partial(self) -> PartialWritableKeyPath<Root> {
2171 PartialWritableKeyPath::new(self)
2172 }
2173
2174 pub fn to(self) -> PartialWritableKeyPath<Root> {
2176 self.to_partial()
2177 }
2178}
2179
2180impl<Root, Value, F> WritableOptionalKeyPath<Root, Value, F>
2181where
2182 F: for<'r> Fn(&'r mut Root) -> Option<&'r mut Value> + 'static,
2183 Root: Any + 'static,
2184 Value: Any + 'static,
2185{
2186 pub fn to_partial(self) -> PartialWritableOptionalKeyPath<Root> {
2188 PartialWritableOptionalKeyPath::new(self)
2189 }
2190
2191 pub fn to_any(self) -> AnyWritableKeyPath {
2193 AnyWritableKeyPath::new(self)
2194 }
2195
2196 pub fn to(self) -> PartialWritableOptionalKeyPath<Root> {
2198 self.to_partial()
2199 }
2200}
2201
2202#[cfg(test)]
2203mod tests {
2204 use super::*;
2205 use std::sync::atomic::{AtomicUsize, Ordering};
2206 use std::rc::Rc;
2207
2208 static ALLOC_COUNT: AtomicUsize = AtomicUsize::new(0);
2210 static DEALLOC_COUNT: AtomicUsize = AtomicUsize::new(0);
2211
2212 #[derive(Debug)]
2214 struct NoCloneType {
2215 id: usize,
2216 data: String,
2217 }
2218
2219 impl NoCloneType {
2220 fn new(data: String) -> Self {
2221 ALLOC_COUNT.fetch_add(1, Ordering::SeqCst);
2222 Self {
2223 id: ALLOC_COUNT.load(Ordering::SeqCst),
2224 data,
2225 }
2226 }
2227 }
2228
2229 impl Clone for NoCloneType {
2230 fn clone(&self) -> Self {
2231 eprintln!("[DEBUG] NoCloneType should not be cloned! ID: {}", self.id);
2232 unreachable!("NoCloneType should not be cloned! ID: {}", self.id);
2233 }
2234 }
2235
2236 impl Drop for NoCloneType {
2237 fn drop(&mut self) {
2238 DEALLOC_COUNT.fetch_add(1, Ordering::SeqCst);
2239 }
2240 }
2241
2242 fn reset_memory_counters() {
2244 ALLOC_COUNT.store(0, Ordering::SeqCst);
2245 DEALLOC_COUNT.store(0, Ordering::SeqCst);
2246 }
2247
2248 fn get_alloc_count() -> usize {
2249 ALLOC_COUNT.load(Ordering::SeqCst)
2250 }
2251
2252 fn get_dealloc_count() -> usize {
2253 DEALLOC_COUNT.load(Ordering::SeqCst)
2254 }
2255
2256#[derive(Debug)]
2258struct User {
2259 name: String,
2260 metadata: Option<Box<UserMetadata>>,
2261 friends: Vec<Arc<User>>,
2262}
2263
2264#[derive(Debug)]
2265struct UserMetadata {
2266 created_at: String,
2267}
2268
2269fn some_fn() {
2270 let akash = User {
2271 name: "Alice".to_string(),
2272 metadata: Some(Box::new(UserMetadata {
2273 created_at: "2024-01-01".to_string(),
2274 })),
2275 friends: vec![
2276 Arc::new(User {
2277 name: "Bob".to_string(),
2278 metadata: None,
2279 friends: vec![],
2280 }),
2281 ],
2282 };
2283
2284 let name_kp = KeyPath::new(|u: &User| &u.name);
2286 let metadata_kp = OptionalKeyPath::new(|u: &User| u.metadata.as_ref());
2287 let friends_kp = KeyPath::new(|u: &User| &u.friends);
2288
2289 println!("Name: {}", name_kp.get(&akash));
2291
2292 if let Some(metadata) = metadata_kp.get(&akash) {
2293 println!("Has metadata: {:?}", metadata);
2294 }
2295
2296 if let Some(first_friend) = akash.friends.get(0) {
2298 println!("First friend: {}", name_kp.get(first_friend));
2299 }
2300
2301 let created_at_kp = KeyPath::new(|m: &UserMetadata| &m.created_at);
2303
2304 if let Some(metadata) = akash.metadata.as_ref() {
2305 let boxed_metadata: &Box<UserMetadata> = metadata;
2307 let unwrapped = boxed_metadata.as_ref();
2308 println!("Created at: {:?}", created_at_kp.get(unwrapped));
2309 }
2310 }
2311
2312 #[test]
2313 fn test_name() {
2314 some_fn();
2315 }
2316
2317 #[test]
2318 fn test_no_cloning_on_keypath_operations() {
2319 reset_memory_counters();
2320
2321 let value = NoCloneType::new("test".to_string());
2323 let boxed = Box::new(value);
2324
2325 let kp = KeyPath::new(|b: &Box<NoCloneType>| b.as_ref());
2327
2328 let _ref = kp.get(&boxed);
2330
2331 let _kp_clone = kp.clone();
2333
2334 let _ref2 = _kp_clone.get(&boxed);
2336
2337 assert_eq!(get_alloc_count(), 1);
2339 }
2340
2341 #[test]
2342 fn test_no_cloning_on_optional_keypath_operations() {
2343 reset_memory_counters();
2344
2345 let value = NoCloneType::new("test".to_string());
2346 let opt = Some(Box::new(value));
2347
2348 let okp = OptionalKeyPath::new(|o: &Option<Box<NoCloneType>>| o.as_ref());
2350
2351 let _ref = okp.get(&opt);
2353
2354 let _okp_clone = okp.clone();
2356
2357 let chained = okp.then(OptionalKeyPath::new(|b: &Box<NoCloneType>| Some(b.as_ref())));
2359 let _ref2 = chained.get(&opt);
2360
2361 assert_eq!(get_alloc_count(), 1);
2362 }
2363
2364 #[test]
2365 fn test_memory_release() {
2366 reset_memory_counters();
2367
2368 {
2369 let value = NoCloneType::new("test".to_string());
2370 let boxed = Box::new(value);
2371 let kp = KeyPath::new(|b: &Box<NoCloneType>| b.as_ref());
2372
2373 let _ref = kp.get(&boxed);
2375
2376 }
2378
2379 assert_eq!(get_alloc_count(), 1);
2382 }
2385
2386 #[test]
2387 fn test_keypath_clone_does_not_clone_underlying_data() {
2388 reset_memory_counters();
2389
2390 let value = NoCloneType::new("data".to_string());
2391 let rc_value = Rc::new(value);
2392
2393 let kp = KeyPath::new(|r: &Rc<NoCloneType>| r.as_ref());
2395
2396 let kp1 = kp.clone();
2398 let kp2 = kp.clone();
2399 let kp3 = kp1.clone();
2400
2401 let _ref1 = kp.get(&rc_value);
2403 let _ref2 = kp1.get(&rc_value);
2404 let _ref3 = kp2.get(&rc_value);
2405 let _ref4 = kp3.get(&rc_value);
2406
2407 assert_eq!(get_alloc_count(), 1);
2409 }
2410
2411 #[test]
2412 fn test_optional_keypath_chaining_no_clone() {
2413 reset_memory_counters();
2414
2415 let value = NoCloneType::new("value1".to_string());
2416
2417 struct Container {
2418 inner: Option<Box<NoCloneType>>,
2419 }
2420
2421 let container = Container {
2422 inner: Some(Box::new(value)),
2423 };
2424
2425 let kp1 = OptionalKeyPath::new(|c: &Container| c.inner.as_ref());
2427 let kp2 = OptionalKeyPath::new(|b: &Box<NoCloneType>| Some(b.as_ref()));
2428
2429 let chained = kp1.then(kp2);
2431
2432 let _result = chained.get(&container);
2434
2435 assert_eq!(get_alloc_count(), 1);
2437 }
2438
2439 #[test]
2440 fn test_for_box_no_clone() {
2441 reset_memory_counters();
2442
2443 let value = NoCloneType::new("test".to_string());
2444 let boxed = Box::new(value);
2445 let opt_boxed = Some(boxed);
2446
2447 let kp = OptionalKeyPath::new(|o: &Option<Box<NoCloneType>>| o.as_ref());
2449 let unwrapped = kp.for_box();
2450
2451 let _ref = unwrapped.get(&opt_boxed);
2453
2454 assert_eq!(get_alloc_count(), 1);
2455 }
2456
2457 #[derive(Debug, PartialEq)]
2460 struct TestUser {
2461 name: String,
2462 age: u32,
2463 metadata: Option<String>,
2464 address: Option<TestAddress>,
2465 }
2466
2467 #[derive(Debug, PartialEq)]
2468 struct TestAddress {
2469 street: String,
2470 city: String,
2471 country: Option<TestCountry>,
2472 }
2473
2474 #[derive(Debug, PartialEq)]
2475 struct TestCountry {
2476 name: String,
2477 }
2478
2479 #[test]
2480 fn test_keypath_macro() {
2481 let user = TestUser {
2482 name: "Alice".to_string(),
2483 age: 30,
2484 metadata: None,
2485 address: None,
2486 };
2487
2488 let name_kp = keypath!(|u: &TestUser| &u.name);
2490 assert_eq!(name_kp.get(&user), "Alice");
2491
2492 let user_with_address = TestUser {
2494 name: "Bob".to_string(),
2495 age: 25,
2496 metadata: None,
2497 address: Some(TestAddress {
2498 street: "123 Main St".to_string(),
2499 city: "New York".to_string(),
2500 country: None,
2501 }),
2502 };
2503
2504 let street_kp = keypath!(|u: &TestUser| &u.address.as_ref().unwrap().street);
2505 assert_eq!(street_kp.get(&user_with_address), "123 Main St");
2506
2507 let user_with_country = TestUser {
2509 name: "Charlie".to_string(),
2510 age: 35,
2511 metadata: None,
2512 address: Some(TestAddress {
2513 street: "456 Oak Ave".to_string(),
2514 city: "London".to_string(),
2515 country: Some(TestCountry {
2516 name: "UK".to_string(),
2517 }),
2518 }),
2519 };
2520
2521 let country_name_kp = keypath!(|u: &TestUser| &u.address.as_ref().unwrap().country.as_ref().unwrap().name);
2522 assert_eq!(country_name_kp.get(&user_with_country), "UK");
2523
2524 let age_kp = keypath!(|u: &TestUser| &u.age);
2526 assert_eq!(age_kp.get(&user), &30);
2527 }
2528
2529 #[test]
2530 fn test_opt_keypath_macro() {
2531 let user = TestUser {
2532 name: "Alice".to_string(),
2533 age: 30,
2534 metadata: Some("admin".to_string()),
2535 address: None,
2536 };
2537
2538 let metadata_kp = opt_keypath!(|u: &TestUser| u.metadata.as_ref());
2540 assert_eq!(metadata_kp.get(&user), Some(&"admin".to_string()));
2541
2542 let user_no_metadata = TestUser {
2544 name: "Bob".to_string(),
2545 age: 25,
2546 metadata: None,
2547 address: None,
2548 };
2549 assert_eq!(metadata_kp.get(&user_no_metadata), None);
2550
2551 let user_with_address = TestUser {
2553 name: "Charlie".to_string(),
2554 age: 35,
2555 metadata: None,
2556 address: Some(TestAddress {
2557 street: "789 Pine Rd".to_string(),
2558 city: "Paris".to_string(),
2559 country: None,
2560 }),
2561 };
2562
2563 let street_kp = opt_keypath!(|u: &TestUser| u.address.as_ref().map(|a| &a.street));
2564 assert_eq!(street_kp.get(&user_with_address), Some(&"789 Pine Rd".to_string()));
2565
2566 let user_with_country = TestUser {
2568 name: "David".to_string(),
2569 age: 40,
2570 metadata: None,
2571 address: Some(TestAddress {
2572 street: "321 Elm St".to_string(),
2573 city: "Tokyo".to_string(),
2574 country: Some(TestCountry {
2575 name: "Japan".to_string(),
2576 }),
2577 }),
2578 };
2579
2580 let country_name_kp = opt_keypath!(|u: &TestUser| u.address.as_ref().and_then(|a| a.country.as_ref().map(|c| &c.name)));
2581 assert_eq!(country_name_kp.get(&user_with_country), Some(&"Japan".to_string()));
2582
2583 let metadata_kp2 = opt_keypath!(|u: &TestUser| u.metadata.as_ref());
2585 assert_eq!(metadata_kp2.get(&user), Some(&"admin".to_string()));
2586 }
2587
2588 #[test]
2589 fn test_writable_keypath_macro() {
2590 let mut user = TestUser {
2591 name: "Alice".to_string(),
2592 age: 30,
2593 metadata: None,
2594 address: None,
2595 };
2596
2597 let name_kp = writable_keypath!(|u: &mut TestUser| &mut u.name);
2599 *name_kp.get_mut(&mut user) = "Bob".to_string();
2600 assert_eq!(user.name, "Bob");
2601
2602 let mut user_with_address = TestUser {
2604 name: "Charlie".to_string(),
2605 age: 25,
2606 metadata: None,
2607 address: Some(TestAddress {
2608 street: "123 Main St".to_string(),
2609 city: "New York".to_string(),
2610 country: None,
2611 }),
2612 };
2613
2614 let street_kp = writable_keypath!(|u: &mut TestUser| &mut u.address.as_mut().unwrap().street);
2615 *street_kp.get_mut(&mut user_with_address) = "456 Oak Ave".to_string();
2616 assert_eq!(user_with_address.address.as_ref().unwrap().street, "456 Oak Ave");
2617
2618 let mut user_with_country = TestUser {
2620 name: "David".to_string(),
2621 age: 35,
2622 metadata: None,
2623 address: Some(TestAddress {
2624 street: "789 Pine Rd".to_string(),
2625 city: "London".to_string(),
2626 country: Some(TestCountry {
2627 name: "UK".to_string(),
2628 }),
2629 }),
2630 };
2631
2632 let country_name_kp = writable_keypath!(|u: &mut TestUser| &mut u.address.as_mut().unwrap().country.as_mut().unwrap().name);
2633 *country_name_kp.get_mut(&mut user_with_country) = "United Kingdom".to_string();
2634 assert_eq!(user_with_country.address.as_ref().unwrap().country.as_ref().unwrap().name, "United Kingdom");
2635
2636 let age_kp = writable_keypath!(|u: &mut TestUser| &mut u.age);
2638 *age_kp.get_mut(&mut user) = 31;
2639 assert_eq!(user.age, 31);
2640 }
2641
2642 #[test]
2643 fn test_writable_opt_keypath_macro() {
2644 let mut user = TestUser {
2645 name: "Alice".to_string(),
2646 age: 30,
2647 metadata: Some("user".to_string()),
2648 address: None,
2649 };
2650
2651 let metadata_kp = writable_opt_keypath!(|u: &mut TestUser| u.metadata.as_mut());
2653 if let Some(metadata) = metadata_kp.get_mut(&mut user) {
2654 *metadata = "admin".to_string();
2655 }
2656 assert_eq!(user.metadata, Some("admin".to_string()));
2657
2658 let mut user_no_metadata = TestUser {
2660 name: "Bob".to_string(),
2661 age: 25,
2662 metadata: None,
2663 address: None,
2664 };
2665 assert_eq!(metadata_kp.get_mut(&mut user_no_metadata), None);
2666
2667 let mut user_with_address = TestUser {
2669 name: "Charlie".to_string(),
2670 age: 35,
2671 metadata: None,
2672 address: Some(TestAddress {
2673 street: "123 Main St".to_string(),
2674 city: "New York".to_string(),
2675 country: None,
2676 }),
2677 };
2678
2679 let street_kp = writable_opt_keypath!(|u: &mut TestUser| u.address.as_mut().map(|a| &mut a.street));
2680 if let Some(street) = street_kp.get_mut(&mut user_with_address) {
2681 *street = "456 Oak Ave".to_string();
2682 }
2683 assert_eq!(user_with_address.address.as_ref().unwrap().street, "456 Oak Ave");
2684
2685 let mut user_with_country = TestUser {
2687 name: "David".to_string(),
2688 age: 40,
2689 metadata: None,
2690 address: Some(TestAddress {
2691 street: "789 Pine Rd".to_string(),
2692 city: "Tokyo".to_string(),
2693 country: Some(TestCountry {
2694 name: "Japan".to_string(),
2695 }),
2696 }),
2697 };
2698
2699 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)));
2700 if let Some(country_name) = country_name_kp.get_mut(&mut user_with_country) {
2701 *country_name = "Nippon".to_string();
2702 }
2703 assert_eq!(user_with_country.address.as_ref().unwrap().country.as_ref().unwrap().name, "Nippon");
2704
2705 let metadata_kp2 = writable_opt_keypath!(|u: &mut TestUser| u.metadata.as_mut());
2707 if let Some(metadata) = metadata_kp2.get_mut(&mut user) {
2708 *metadata = "super_admin".to_string();
2709 }
2710 assert_eq!(user.metadata, Some("super_admin".to_string()));
2711 }
2712}
2713
2714pub trait WithContainer<Root, Value> {
2720 fn with_arc<F, R>(&self, arc: &Arc<Root>, f: F) -> R
2722 where
2723 F: FnOnce(&Value) -> R;
2724
2725 fn with_box<F, R>(&self, boxed: &Box<Root>, f: F) -> R
2727 where
2728 F: FnOnce(&Value) -> R;
2729
2730 fn with_box_mut<F, R>(&self, boxed: &mut Box<Root>, f: F) -> R
2732 where
2733 F: FnOnce(&mut Value) -> R;
2734
2735 fn with_rc<F, R>(&self, rc: &Rc<Root>, f: F) -> R
2737 where
2738 F: FnOnce(&Value) -> R;
2739
2740 fn with_result<F, R, E>(&self, result: &Result<Root, E>, f: F) -> Option<R>
2742 where
2743 F: FnOnce(&Value) -> R;
2744
2745 fn with_result_mut<F, R, E>(&self, result: &mut Result<Root, E>, f: F) -> Option<R>
2747 where
2748 F: FnOnce(&mut Value) -> R;
2749
2750 fn with_option<F, R>(&self, option: &Option<Root>, f: F) -> Option<R>
2752 where
2753 F: FnOnce(&Value) -> R;
2754
2755 fn with_option_mut<F, R>(&self, option: &mut Option<Root>, f: F) -> Option<R>
2757 where
2758 F: FnOnce(&mut Value) -> R;
2759
2760 fn with_refcell<F, R>(&self, refcell: &RefCell<Root>, f: F) -> Option<R>
2762 where
2763 F: FnOnce(&Value) -> R;
2764
2765 fn with_refcell_mut<F, R>(&self, refcell: &RefCell<Root>, f: F) -> Option<R>
2767 where
2768 F: FnOnce(&mut Value) -> R;
2769
2770 #[cfg(feature = "tagged")]
2771 fn with_tagged<F, R, Tag>(&self, tagged: &Tagged<Root, Tag>, f: F) -> R
2773 where
2774 Tagged<Root, Tag>: std::ops::Deref<Target = Root>,
2775 F: FnOnce(&Value) -> R;
2776
2777 fn with_mutex<F, R>(&self, mutex: &Mutex<Root>, f: F) -> Option<R>
2779 where
2780 F: FnOnce(&Value) -> R;
2781
2782 fn with_mutex_mut<F, R>(&self, mutex: &mut Mutex<Root>, f: F) -> Option<R>
2784 where
2785 F: FnOnce(&mut Value) -> R;
2786
2787 fn with_rwlock<F, R>(&self, rwlock: &RwLock<Root>, f: F) -> Option<R>
2789 where
2790 F: FnOnce(&Value) -> R;
2791
2792 fn with_rwlock_mut<F, R>(&self, rwlock: &mut RwLock<Root>, f: F) -> Option<R>
2794 where
2795 F: FnOnce(&mut Value) -> R;
2796
2797 fn with_arc_rwlock<F, R>(&self, arc_rwlock: &Arc<RwLock<Root>>, f: F) -> Option<R>
2799 where
2800 F: FnOnce(&Value) -> R;
2801
2802 fn with_arc_rwlock_mut<F, R>(&self, arc_rwlock: &Arc<RwLock<Root>>, f: F) -> Option<R>
2804 where
2805 F: FnOnce(&mut Value) -> R;
2806}
2807
2808impl<Root, Value, F> WithContainer<Root, Value> for KeyPath<Root, Value, F>
2810where
2811 F: for<'r> Fn(&'r Root) -> &'r Value + Clone,
2812{
2813 fn with_arc<Callback, R>(&self, arc: &Arc<Root>, f: Callback) -> R
2814 where
2815 Callback: FnOnce(&Value) -> R,
2816 {
2817 self.with_arc(arc, f)
2818 }
2819
2820 fn with_box<Callback, R>(&self, boxed: &Box<Root>, f: Callback) -> R
2821 where
2822 Callback: FnOnce(&Value) -> R,
2823 {
2824 self.with_box(boxed, f)
2825 }
2826
2827 fn with_box_mut<Callback, R>(&self, _boxed: &mut Box<Root>, _f: Callback) -> R
2828 where
2829 Callback: FnOnce(&mut Value) -> R,
2830 {
2831 eprintln!("[DEBUG] KeyPath does not support mutable access - use WritableKeyPath instead");
2832 unreachable!("KeyPath does not support mutable access - use WritableKeyPath instead")
2833 }
2834
2835 fn with_rc<Callback, R>(&self, rc: &Rc<Root>, f: Callback) -> R
2836 where
2837 Callback: FnOnce(&Value) -> R,
2838 {
2839 self.with_rc(rc, f)
2840 }
2841
2842 fn with_result<Callback, R, E>(&self, result: &Result<Root, E>, f: Callback) -> Option<R>
2843 where
2844 Callback: FnOnce(&Value) -> R,
2845 {
2846 self.with_result(result, f)
2847 }
2848
2849 fn with_result_mut<Callback, R, E>(&self, _result: &mut Result<Root, E>, _f: Callback) -> Option<R>
2850 where
2851 Callback: FnOnce(&mut Value) -> R,
2852 {
2853 None
2854 }
2855
2856 fn with_option<Callback, R>(&self, option: &Option<Root>, f: Callback) -> Option<R>
2857 where
2858 Callback: FnOnce(&Value) -> R,
2859 {
2860 self.with_option(option, f)
2861 }
2862
2863 fn with_option_mut<Callback, R>(&self, _option: &mut Option<Root>, _f: Callback) -> Option<R>
2864 where
2865 Callback: FnOnce(&mut Value) -> R,
2866 {
2867 None
2868 }
2869
2870 fn with_refcell<Callback, R>(&self, refcell: &RefCell<Root>, f: Callback) -> Option<R>
2871 where
2872 Callback: FnOnce(&Value) -> R,
2873 {
2874 self.with_refcell(refcell, f)
2875 }
2876
2877 fn with_refcell_mut<Callback, R>(&self, _refcell: &RefCell<Root>, _f: Callback) -> Option<R>
2878 where
2879 Callback: FnOnce(&mut Value) -> R,
2880 {
2881 None
2882 }
2883
2884 #[cfg(feature = "tagged")]
2885 fn with_tagged<Tag, Callback, R>(&self, tagged: &Tagged<Root, Tag>, f: Callback) -> R
2886 where
2887 Tagged<Root, Tag>: std::ops::Deref<Target = Root>,
2888 Callback: FnOnce(&Value) -> R,
2889 {
2890 self.with_tagged(tagged, f)
2891 }
2892
2893 fn with_mutex<Callback, R>(&self, mutex: &Mutex<Root>, f: Callback) -> Option<R>
2894 where
2895 Callback: FnOnce(&Value) -> R,
2896 {
2897 self.with_mutex(mutex, f)
2898 }
2899
2900 fn with_mutex_mut<Callback, R>(&self, _mutex: &mut Mutex<Root>, _f: Callback) -> Option<R>
2901 where
2902 Callback: FnOnce(&mut Value) -> R,
2903 {
2904 None
2905 }
2906
2907 fn with_rwlock<Callback, R>(&self, rwlock: &RwLock<Root>, f: Callback) -> Option<R>
2908 where
2909 Callback: FnOnce(&Value) -> R,
2910 {
2911 self.with_rwlock(rwlock, f)
2912 }
2913
2914 fn with_rwlock_mut<Callback, R>(&self, _rwlock: &mut RwLock<Root>, _f: Callback) -> Option<R>
2915 where
2916 Callback: FnOnce(&mut Value) -> R,
2917 {
2918 None
2919 }
2920
2921 fn with_arc_rwlock<Callback, R>(&self, arc_rwlock: &Arc<RwLock<Root>>, f: Callback) -> Option<R>
2922 where
2923 Callback: FnOnce(&Value) -> R,
2924 {
2925 self.with_arc_rwlock(arc_rwlock, f)
2926 }
2927
2928 fn with_arc_rwlock_mut<Callback, R>(&self, _arc_rwlock: &Arc<RwLock<Root>>, _f: Callback) -> Option<R>
2929 where
2930 Callback: FnOnce(&mut Value) -> R,
2931 {
2932 None
2933 }
2934}
2935
2936impl<Root, Value, F> WithContainer<Root, Value> for OptionalKeyPath<Root, Value, F>
2938where
2939 F: for<'r> Fn(&'r Root) -> Option<&'r Value> + Clone,
2940{
2941 fn with_arc<Callback, R>(&self, arc: &Arc<Root>, f: Callback) -> R
2942 where
2943 Callback: FnOnce(&Value) -> R,
2944 {
2945 self.with_arc(arc, f)
2946 }
2947
2948 fn with_box<Callback, R>(&self, boxed: &Box<Root>, f: Callback) -> R
2949 where
2950 Callback: FnOnce(&Value) -> R,
2951 {
2952 self.with_box(boxed, f)
2953 }
2954
2955 fn with_box_mut<Callback, R>(&self, _boxed: &mut Box<Root>, _f: Callback) -> R
2956 where
2957 Callback: FnOnce(&mut Value) -> R,
2958 {
2959 eprintln!("[DEBUG] OptionalKeyPath does not support mutable access - use WritableOptionalKeyPath instead");
2960 unreachable!("OptionalKeyPath does not support mutable access - use WritableOptionalKeyPath instead")
2961 }
2962
2963 fn with_rc<Callback, R>(&self, rc: &Rc<Root>, f: Callback) -> R
2964 where
2965 Callback: FnOnce(&Value) -> R,
2966 {
2967 self.with_rc(rc, f)
2968 }
2969
2970 fn with_result<Callback, R, E>(&self, result: &Result<Root, E>, f: Callback) -> Option<R>
2971 where
2972 Callback: FnOnce(&Value) -> R,
2973 {
2974 self.with_result(result, f)
2975 }
2976
2977 fn with_result_mut<Callback, R, E>(&self, _result: &mut Result<Root, E>, _f: Callback) -> Option<R>
2978 where
2979 Callback: FnOnce(&mut Value) -> R,
2980 {
2981 None }
2983
2984 fn with_option<Callback, R>(&self, option: &Option<Root>, f: Callback) -> Option<R>
2985 where
2986 Callback: FnOnce(&Value) -> R,
2987 {
2988 self.with_option(option, f)
2989 }
2990
2991 fn with_option_mut<Callback, R>(&self, _option: &mut Option<Root>, _f: Callback) -> Option<R>
2992 where
2993 Callback: FnOnce(&mut Value) -> R,
2994 {
2995 None }
2997
2998 fn with_refcell<Callback, R>(&self, refcell: &RefCell<Root>, f: Callback) -> Option<R>
2999 where
3000 Callback: FnOnce(&Value) -> R,
3001 {
3002 self.with_refcell(refcell, f)
3003 }
3004
3005 fn with_refcell_mut<Callback, R>(&self, _refcell: &RefCell<Root>, _f: Callback) -> Option<R>
3006 where
3007 Callback: FnOnce(&mut Value) -> R,
3008 {
3009 None }
3011
3012 #[cfg(feature = "tagged")]
3013 fn with_tagged<Tag, Callback, R>(&self, tagged: &Tagged<Root, Tag>, f: Callback) -> R
3014 where
3015 Tagged<Root, Tag>: std::ops::Deref<Target = Root>,
3016 Callback: FnOnce(&Value) -> R,
3017 {
3018 self.with_tagged(tagged, f)
3019 }
3020
3021 fn with_mutex<Callback, R>(&self, mutex: &Mutex<Root>, f: Callback) -> Option<R>
3022 where
3023 Callback: FnOnce(&Value) -> R,
3024 {
3025 self.with_mutex(mutex, f)
3026 }
3027
3028 fn with_mutex_mut<Callback, R>(&self, _mutex: &mut Mutex<Root>, _f: Callback) -> Option<R>
3029 where
3030 Callback: FnOnce(&mut Value) -> R,
3031 {
3032 None }
3034
3035 fn with_rwlock<Callback, R>(&self, rwlock: &RwLock<Root>, f: Callback) -> Option<R>
3036 where
3037 Callback: FnOnce(&Value) -> R,
3038 {
3039 self.with_rwlock(rwlock, f)
3040 }
3041
3042 fn with_rwlock_mut<Callback, R>(&self, _rwlock: &mut RwLock<Root>, _f: Callback) -> Option<R>
3043 where
3044 Callback: FnOnce(&mut Value) -> R,
3045 {
3046 None }
3048
3049 fn with_arc_rwlock<Callback, R>(&self, arc_rwlock: &Arc<RwLock<Root>>, f: Callback) -> Option<R>
3050 where
3051 Callback: FnOnce(&Value) -> R,
3052 {
3053 self.with_arc_rwlock(arc_rwlock, f)
3054 }
3055
3056 fn with_arc_rwlock_mut<Callback, R>(&self, _arc_rwlock: &Arc<RwLock<Root>>, _f: Callback) -> Option<R>
3057 where
3058 Callback: FnOnce(&mut Value) -> R,
3059 {
3060 None }
3062}
3063
3064impl<Root, Value, F> WithContainer<Root, Value> for WritableKeyPath<Root, Value, F>
3066where
3067 F: for<'r> Fn(&'r mut Root) -> &'r mut Value,
3068{
3069 fn with_arc<Callback, R>(&self, _arc: &Arc<Root>, _f: Callback) -> R
3070 where
3071 Callback: FnOnce(&Value) -> R,
3072 {
3073 eprintln!("[DEBUG] WritableKeyPath::with_arc requires &mut Arc<Root> or interior mutability");
3076 unreachable!("WritableKeyPath::with_arc requires &mut Arc<Root> or interior mutability")
3077 }
3078
3079 fn with_box<Callback, R>(&self, boxed: &Box<Root>, f: Callback) -> R
3080 where
3081 Callback: FnOnce(&Value) -> R,
3082 {
3083 eprintln!("[DEBUG] WritableKeyPath::with_box requires &mut Box<Root> - use with_box_mut instead");
3086 unreachable!("WritableKeyPath::with_box requires &mut Box<Root> - use with_box_mut instead")
3087 }
3088
3089 fn with_box_mut<Callback, R>(&self, boxed: &mut Box<Root>, f: Callback) -> R
3090 where
3091 Callback: FnOnce(&mut Value) -> R,
3092 {
3093 let value = self.get_mut(boxed.as_mut());
3094 f(value)
3095 }
3096
3097 fn with_rc<Callback, R>(&self, _rc: &Rc<Root>, _f: Callback) -> R
3098 where
3099 Callback: FnOnce(&Value) -> R,
3100 {
3101 eprintln!("[DEBUG] WritableKeyPath::with_rc requires &mut Rc<Root> or interior mutability");
3104 unreachable!("WritableKeyPath::with_rc requires &mut Rc<Root> or interior mutability")
3105 }
3106
3107 fn with_result<Callback, R, E>(&self, _result: &Result<Root, E>, _f: Callback) -> Option<R>
3108 where
3109 Callback: FnOnce(&Value) -> R,
3110 {
3111 None
3114 }
3115
3116 fn with_result_mut<Callback, R, E>(&self, result: &mut Result<Root, E>, f: Callback) -> Option<R>
3117 where
3118 Callback: FnOnce(&mut Value) -> R,
3119 {
3120 result.as_mut().ok().map(|root| {
3121 let value = self.get_mut(root);
3122 f(value)
3123 })
3124 }
3125
3126 fn with_option<Callback, R>(&self, _option: &Option<Root>, _f: Callback) -> Option<R>
3127 where
3128 Callback: FnOnce(&Value) -> R,
3129 {
3130 None
3133 }
3134
3135 fn with_option_mut<Callback, R>(&self, option: &mut Option<Root>, f: Callback) -> Option<R>
3136 where
3137 Callback: FnOnce(&mut Value) -> R,
3138 {
3139 option.as_mut().map(|root| {
3140 let value = self.get_mut(root);
3141 f(value)
3142 })
3143 }
3144
3145 fn with_refcell<Callback, R>(&self, refcell: &RefCell<Root>, f: Callback) -> Option<R>
3146 where
3147 Callback: FnOnce(&Value) -> R,
3148 {
3149 None
3152 }
3153
3154 fn with_refcell_mut<Callback, R>(&self, refcell: &RefCell<Root>, f: Callback) -> Option<R>
3155 where
3156 Callback: FnOnce(&mut Value) -> R,
3157 {
3158 refcell.try_borrow_mut().ok().map(|mut borrow| {
3159 let value = self.get_mut(&mut *borrow);
3160 f(value)
3161 })
3162 }
3163
3164 #[cfg(feature = "tagged")]
3165 fn with_tagged<Tag, Callback, R>(&self, _tagged: &Tagged<Root, Tag>, _f: Callback) -> R
3166 where
3167 Tagged<Root, Tag>: std::ops::Deref<Target = Root>,
3168 Callback: FnOnce(&Value) -> R,
3169 {
3170 eprintln!("[DEBUG] WritableKeyPath::with_tagged requires &mut Tagged<Root, Tag> or interior mutability");
3173 unreachable!("WritableKeyPath::with_tagged requires &mut Tagged<Root, Tag> or interior mutability")
3174 }
3175
3176 fn with_mutex<Callback, R>(&self, mutex: &Mutex<Root>, f: Callback) -> Option<R>
3177 where
3178 Callback: FnOnce(&Value) -> R,
3179 {
3180 mutex.lock().ok().map(|mut guard| {
3181 let value = self.get_mut(&mut *guard);
3182 f(value)
3183 })
3184 }
3185
3186 fn with_mutex_mut<Callback, R>(&self, mutex: &mut Mutex<Root>, f: Callback) -> Option<R>
3187 where
3188 Callback: FnOnce(&mut Value) -> R,
3189 {
3190 mutex.get_mut().ok().map(|root| {
3192 let value = self.get_mut(root);
3193 f(value)
3194 })
3195 }
3196
3197 fn with_rwlock<Callback, R>(&self, rwlock: &RwLock<Root>, f: Callback) -> Option<R>
3198 where
3199 Callback: FnOnce(&Value) -> R,
3200 {
3201 None
3204 }
3205
3206 fn with_rwlock_mut<Callback, R>(&self, rwlock: &mut RwLock<Root>, f: Callback) -> Option<R>
3207 where
3208 Callback: FnOnce(&mut Value) -> R,
3209 {
3210 rwlock.get_mut().ok().map(|root| {
3212 let value = self.get_mut(root);
3213 f(value)
3214 })
3215 }
3216
3217 fn with_arc_rwlock<Callback, R>(&self, arc_rwlock: &Arc<RwLock<Root>>, f: Callback) -> Option<R>
3218 where
3219 Callback: FnOnce(&Value) -> R,
3220 {
3221 None
3224 }
3225
3226 fn with_arc_rwlock_mut<Callback, R>(&self, arc_rwlock: &Arc<RwLock<Root>>, f: Callback) -> Option<R>
3227 where
3228 Callback: FnOnce(&mut Value) -> R,
3229 {
3230 arc_rwlock.write().ok().map(|mut guard| {
3231 let value = self.get_mut(&mut *guard);
3232 f(value)
3233 })
3234 }
3235}
3236
3237impl<Root, Value, F> WithContainer<Root, Value> for WritableOptionalKeyPath<Root, Value, F>
3239where
3240 F: for<'r> Fn(&'r mut Root) -> Option<&'r mut Value>,
3241{
3242 fn with_arc<Callback, R>(&self, _arc: &Arc<Root>, _f: Callback) -> R
3243 where
3244 Callback: FnOnce(&Value) -> R,
3245 {
3246 eprintln!("[DEBUG] WritableOptionalKeyPath::with_arc requires &mut Arc<Root> or interior mutability");
3249 unreachable!("WritableOptionalKeyPath::with_arc requires &mut Arc<Root> or interior mutability")
3250 }
3251
3252 fn with_box<Callback, R>(&self, _boxed: &Box<Root>, _f: Callback) -> R
3253 where
3254 Callback: FnOnce(&Value) -> R,
3255 {
3256 eprintln!("[DEBUG] WritableOptionalKeyPath::with_box requires &mut Box<Root> - use with_box_mut instead");
3259 unreachable!("WritableOptionalKeyPath::with_box requires &mut Box<Root> - use with_box_mut instead")
3260 }
3261
3262 fn with_box_mut<Callback, R>(&self, boxed: &mut Box<Root>, f: Callback) -> R
3263 where
3264 Callback: FnOnce(&mut Value) -> R,
3265 {
3266 if let Some(value) = self.get_mut(boxed.as_mut()) {
3267 f(value)
3268 } else {
3269 eprintln!("[DEBUG] WritableOptionalKeyPath failed to get value from Box");
3270 unreachable!("WritableOptionalKeyPath failed to get value from Box")
3271 }
3272 }
3273
3274 fn with_rc<Callback, R>(&self, _rc: &Rc<Root>, _f: Callback) -> R
3275 where
3276 Callback: FnOnce(&Value) -> R,
3277 {
3278 eprintln!("[DEBUG] WritableOptionalKeyPath::with_rc requires &mut Rc<Root> or interior mutability");
3281 unreachable!("WritableOptionalKeyPath::with_rc requires &mut Rc<Root> or interior mutability")
3282 }
3283
3284 fn with_result<Callback, R, E>(&self, _result: &Result<Root, E>, _f: Callback) -> Option<R>
3285 where
3286 Callback: FnOnce(&Value) -> R,
3287 {
3288 None
3291 }
3292
3293 fn with_result_mut<Callback, R, E>(&self, result: &mut Result<Root, E>, f: Callback) -> Option<R>
3294 where
3295 Callback: FnOnce(&mut Value) -> R,
3296 {
3297 result.as_mut().ok().and_then(|root| {
3298 self.get_mut(root).map(|value| f(value))
3299 })
3300 }
3301
3302 fn with_option<Callback, R>(&self, _option: &Option<Root>, _f: Callback) -> Option<R>
3303 where
3304 Callback: FnOnce(&Value) -> R,
3305 {
3306 None
3309 }
3310
3311 fn with_option_mut<Callback, R>(&self, option: &mut Option<Root>, f: Callback) -> Option<R>
3312 where
3313 Callback: FnOnce(&mut Value) -> R,
3314 {
3315 option.as_mut().and_then(|root| {
3316 self.get_mut(root).map(|value| f(value))
3317 })
3318 }
3319
3320 fn with_refcell<Callback, R>(&self, _refcell: &RefCell<Root>, _f: Callback) -> Option<R>
3321 where
3322 Callback: FnOnce(&Value) -> R,
3323 {
3324 None
3327 }
3328
3329 fn with_refcell_mut<Callback, R>(&self, refcell: &RefCell<Root>, f: Callback) -> Option<R>
3330 where
3331 Callback: FnOnce(&mut Value) -> R,
3332 {
3333 refcell.try_borrow_mut().ok().and_then(|mut borrow| {
3334 self.get_mut(&mut *borrow).map(|value| f(value))
3335 })
3336 }
3337
3338 #[cfg(feature = "tagged")]
3339 fn with_tagged<Tag, Callback, R>(&self, _tagged: &Tagged<Root, Tag>, _f: Callback) -> R
3340 where
3341 Tagged<Root, Tag>: std::ops::Deref<Target = Root>,
3342 Callback: FnOnce(&Value) -> R,
3343 {
3344 eprintln!("[DEBUG] WritableOptionalKeyPath::with_tagged requires &mut Tagged<Root, Tag> or interior mutability");
3347 unreachable!("WritableOptionalKeyPath::with_tagged requires &mut Tagged<Root, Tag> or interior mutability")
3348 }
3349
3350 fn with_mutex<Callback, R>(&self, mutex: &Mutex<Root>, f: Callback) -> Option<R>
3351 where
3352 Callback: FnOnce(&Value) -> R,
3353 {
3354 mutex.lock().ok().and_then(|mut guard| {
3355 self.get_mut(&mut *guard).map(|value| f(value))
3356 })
3357 }
3358
3359 fn with_mutex_mut<Callback, R>(&self, mutex: &mut Mutex<Root>, f: Callback) -> Option<R>
3360 where
3361 Callback: FnOnce(&mut Value) -> R,
3362 {
3363 mutex.get_mut().ok().and_then(|root| {
3365 self.get_mut(root).map(|value| f(value))
3366 })
3367 }
3368
3369 fn with_rwlock<Callback, R>(&self, _rwlock: &RwLock<Root>, _f: Callback) -> Option<R>
3370 where
3371 Callback: FnOnce(&Value) -> R,
3372 {
3373 None
3376 }
3377
3378 fn with_rwlock_mut<Callback, R>(&self, rwlock: &mut RwLock<Root>, f: Callback) -> Option<R>
3379 where
3380 Callback: FnOnce(&mut Value) -> R,
3381 {
3382 rwlock.get_mut().ok().and_then(|root| {
3384 self.get_mut(root).map(|value| f(value))
3385 })
3386 }
3387
3388 fn with_arc_rwlock<Callback, R>(&self, _arc_rwlock: &Arc<RwLock<Root>>, _f: Callback) -> Option<R>
3389 where
3390 Callback: FnOnce(&Value) -> R,
3391 {
3392 None
3395 }
3396
3397 fn with_arc_rwlock_mut<Callback, R>(&self, arc_rwlock: &Arc<RwLock<Root>>, f: Callback) -> Option<R>
3398 where
3399 Callback: FnOnce(&mut Value) -> R,
3400 {
3401 arc_rwlock.write().ok().and_then(|mut guard| {
3402 self.get_mut(&mut *guard).map(|value| f(value))
3403 })
3404 }
3405}