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}
450
451impl<Root, Value, F> KeyPath<Root, Value, F>
453where
454 F: for<'r> Fn(&'r Root) -> &'r Value,
455{
456 pub fn with_arc_rwlock_direct<Callback, R>(&self, arc_rwlock: &Arc<RwLock<Root>>, f: Callback) -> Option<R>
459 where
460 Callback: FnOnce(&Value) -> R,
461 {
462 arc_rwlock.read().ok().map(|guard| {
463 let value = self.get(&*guard);
464 f(value)
465 })
466 }
467
468 pub fn with_arc_mutex_direct<Callback, R>(&self, arc_mutex: &Arc<Mutex<Root>>, f: Callback) -> Option<R>
471 where
472 Callback: FnOnce(&Value) -> R,
473 {
474 arc_mutex.lock().ok().map(|guard| {
475 let value = self.get(&*guard);
476 f(value)
477 })
478 }
479}
480
481pub fn for_slice<T>() -> impl for<'r> Fn(&'r [T], usize) -> Option<&'r T> {
483 |slice: &[T], index: usize| slice.get(index)
484}
485
486pub mod containers {
488 use super::{OptionalKeyPath, WritableOptionalKeyPath, KeyPath, WritableKeyPath};
489 use std::collections::{HashMap, BTreeMap, HashSet, BTreeSet, VecDeque, LinkedList, BinaryHeap};
490 use std::sync::{Mutex, RwLock, Weak as StdWeak, Arc};
491 use std::rc::{Weak as RcWeak, Rc};
492 use std::ops::{Deref, DerefMut};
493
494 #[cfg(feature = "parking_lot")]
495 use parking_lot::{Mutex as ParkingMutex, RwLock as ParkingRwLock};
496
497 #[cfg(feature = "tagged")]
498 use tagged_core::Tagged;
499
500 pub fn for_vec_index<T>(index: usize) -> OptionalKeyPath<Vec<T>, T, impl for<'r> Fn(&'r Vec<T>) -> Option<&'r T>> {
502 OptionalKeyPath::new(move |vec: &Vec<T>| vec.get(index))
503 }
504
505 pub fn for_vecdeque_index<T>(index: usize) -> OptionalKeyPath<VecDeque<T>, T, impl for<'r> Fn(&'r VecDeque<T>) -> Option<&'r T>> {
507 OptionalKeyPath::new(move |deque: &VecDeque<T>| deque.get(index))
508 }
509
510 pub fn for_linkedlist_index<T>(index: usize) -> OptionalKeyPath<LinkedList<T>, T, impl for<'r> Fn(&'r LinkedList<T>) -> Option<&'r T>> {
512 OptionalKeyPath::new(move |list: &LinkedList<T>| {
513 list.iter().nth(index)
514 })
515 }
516
517 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>>
519 where
520 K: std::hash::Hash + Eq + Clone + 'static,
521 V: 'static,
522 {
523 OptionalKeyPath::new(move |map: &HashMap<K, V>| map.get(&key))
524 }
525
526 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>>
528 where
529 K: Ord + Clone + 'static,
530 V: 'static,
531 {
532 OptionalKeyPath::new(move |map: &BTreeMap<K, V>| map.get(&key))
533 }
534
535 pub fn for_hashset_get<T>(value: T) -> OptionalKeyPath<HashSet<T>, T, impl for<'r> Fn(&'r HashSet<T>) -> Option<&'r T>>
537 where
538 T: std::hash::Hash + Eq + Clone + 'static,
539 {
540 OptionalKeyPath::new(move |set: &HashSet<T>| set.get(&value))
541 }
542
543 pub fn for_btreeset_get<T>(value: T) -> OptionalKeyPath<BTreeSet<T>, T, impl for<'r> Fn(&'r BTreeSet<T>) -> Option<&'r T>>
545 where
546 T: Ord + Clone + 'static,
547 {
548 OptionalKeyPath::new(move |set: &BTreeSet<T>| set.get(&value))
549 }
550
551 pub fn for_binaryheap_peek<T>() -> OptionalKeyPath<BinaryHeap<T>, T, impl for<'r> Fn(&'r BinaryHeap<T>) -> Option<&'r T>>
553 where
554 T: Ord + 'static,
555 {
556 OptionalKeyPath::new(|heap: &BinaryHeap<T>| heap.peek())
557 }
558
559 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>> {
563 WritableOptionalKeyPath::new(move |vec: &mut Vec<T>| vec.get_mut(index))
564 }
565
566 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>> {
568 WritableOptionalKeyPath::new(move |deque: &mut VecDeque<T>| deque.get_mut(index))
569 }
570
571 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>> {
573 WritableOptionalKeyPath::new(move |list: &mut LinkedList<T>| {
574 let mut iter = list.iter_mut();
576 iter.nth(index)
577 })
578 }
579
580 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>>
582 where
583 K: std::hash::Hash + Eq + Clone + 'static,
584 V: 'static,
585 {
586 WritableOptionalKeyPath::new(move |map: &mut HashMap<K, V>| map.get_mut(&key))
587 }
588
589 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>>
591 where
592 K: Ord + Clone + 'static,
593 V: 'static,
594 {
595 WritableOptionalKeyPath::new(move |map: &mut BTreeMap<K, V>| map.get_mut(&key))
596 }
597
598 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>>
601 where
602 T: std::hash::Hash + Eq + Clone + 'static,
603 {
604 WritableOptionalKeyPath::new(move |set: &mut HashSet<T>| {
605 if set.contains(&value) {
608 None
611 } else {
612 None
613 }
614 })
615 }
616
617 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>>
620 where
621 T: Ord + Clone + 'static,
622 {
623 WritableOptionalKeyPath::new(move |set: &mut BTreeSet<T>| {
624 if set.contains(&value) {
627 None
630 } else {
631 None
632 }
633 })
634 }
635
636 pub fn for_binaryheap_peek_mut<T>() -> WritableOptionalKeyPath<BinaryHeap<T>, T, impl for<'r> Fn(&'r mut BinaryHeap<T>) -> Option<&'r mut T>>
642 where
643 T: Ord + 'static,
644 {
645 WritableOptionalKeyPath::new(|_heap: &mut BinaryHeap<T>| {
649 None
650 })
651 }
652
653 pub fn lock_mutex<T>(mutex: &Mutex<T>) -> Option<std::sync::MutexGuard<'_, T>> {
662 mutex.lock().ok()
663 }
664
665 pub fn read_rwlock<T>(rwlock: &RwLock<T>) -> Option<std::sync::RwLockReadGuard<'_, T>> {
669 rwlock.read().ok()
670 }
671
672 pub fn write_rwlock<T>(rwlock: &RwLock<T>) -> Option<std::sync::RwLockWriteGuard<'_, T>> {
676 rwlock.write().ok()
677 }
678
679 pub fn lock_arc_mutex<T>(arc_mutex: &Arc<Mutex<T>>) -> Option<std::sync::MutexGuard<'_, T>> {
683 arc_mutex.lock().ok()
684 }
685
686 pub fn read_arc_rwlock<T>(arc_rwlock: &Arc<RwLock<T>>) -> Option<std::sync::RwLockReadGuard<'_, T>> {
690 arc_rwlock.read().ok()
691 }
692
693 pub fn write_arc_rwlock<T>(arc_rwlock: &Arc<RwLock<T>>) -> Option<std::sync::RwLockWriteGuard<'_, T>> {
697 arc_rwlock.write().ok()
698 }
699
700 pub fn upgrade_weak<T>(weak: &StdWeak<T>) -> Option<Arc<T>> {
704 weak.upgrade()
705 }
706
707 pub fn upgrade_rc_weak<T>(weak: &RcWeak<T>) -> Option<Rc<T>> {
711 weak.upgrade()
712 }
713
714 #[cfg(feature = "parking_lot")]
715 pub fn lock_parking_mutex<T>(mutex: &ParkingMutex<T>) -> parking_lot::MutexGuard<'_, T> {
718 mutex.lock()
719 }
720
721 #[cfg(feature = "parking_lot")]
722 pub fn read_parking_rwlock<T>(rwlock: &ParkingRwLock<T>) -> parking_lot::RwLockReadGuard<'_, T> {
725 rwlock.read()
726 }
727
728 #[cfg(feature = "parking_lot")]
729 pub fn write_parking_rwlock<T>(rwlock: &ParkingRwLock<T>) -> parking_lot::RwLockWriteGuard<'_, T> {
732 rwlock.write()
733 }
734
735 #[cfg(feature = "tagged")]
736 pub fn for_tagged<Tag, T>() -> KeyPath<Tagged<Tag, T>, T, impl for<'r> Fn(&'r Tagged<Tag, T>) -> &'r T>
739 where
740 Tagged<Tag, T>: std::ops::Deref<Target = T>,
741 Tag: 'static,
742 T: 'static,
743 {
744 KeyPath::new(|tagged: &Tagged<Tag, T>| tagged.deref())
745 }
746
747 #[cfg(feature = "tagged")]
748 pub fn for_tagged_mut<Tag, T>() -> WritableKeyPath<Tagged<Tag, T>, T, impl for<'r> Fn(&'r mut Tagged<Tag, T>) -> &'r mut T>
751 where
752 Tagged<Tag, T>: std::ops::DerefMut<Target = T>,
753 Tag: 'static,
754 T: 'static,
755 {
756 WritableKeyPath::new(|tagged: &mut Tagged<Tag, T>| tagged.deref_mut())
757 }
758}
759
760#[derive(Clone)]
762pub struct OptionalKeyPath<Root, Value, F>
763where
764 F: for<'r> Fn(&'r Root) -> Option<&'r Value>,
765{
766 getter: F,
767 _phantom: PhantomData<(Root, Value)>,
768}
769
770impl<Root, Value, F> OptionalKeyPath<Root, Value, F>
771where
772 F: for<'r> Fn(&'r Root) -> Option<&'r Value>,
773{
774 pub fn new(getter: F) -> Self {
775 Self {
776 getter,
777 _phantom: PhantomData,
778 }
779 }
780
781 pub fn get<'r>(&self, root: &'r Root) -> Option<&'r Value> {
782 (self.getter)(root)
783 }
784
785 pub fn then<SubValue, G>(
787 self,
788 next: OptionalKeyPath<Value, SubValue, G>,
789 ) -> OptionalKeyPath<Root, SubValue, impl for<'r> Fn(&'r Root) -> Option<&'r SubValue>>
790 where
791 G: for<'r> Fn(&'r Value) -> Option<&'r SubValue>,
792 F: 'static,
793 G: 'static,
794 Value: 'static,
795 {
796 let first = self.getter;
797 let second = next.getter;
798
799 OptionalKeyPath::new(move |root: &Root| {
800 first(root).and_then(|value| second(value))
801 })
802 }
803
804 pub fn for_box<Target>(self) -> OptionalKeyPath<Root, Target, impl for<'r> Fn(&'r Root) -> Option<&'r Target> + 'static>
807 where
808 Value: std::ops::Deref<Target = Target>,
809 F: 'static,
810 Value: 'static,
811 {
812 let getter = self.getter;
813
814 OptionalKeyPath {
815 getter: move |root: &Root| {
816 getter(root).map(|boxed| boxed.deref())
817 },
818 _phantom: PhantomData,
819 }
820 }
821
822 pub fn for_arc<Target>(self) -> OptionalKeyPath<Root, Target, impl for<'r> Fn(&'r Root) -> Option<&'r Target> + 'static>
824 where
825 Value: std::ops::Deref<Target = Target>,
826 F: 'static,
827 Value: 'static,
828 {
829 let getter = self.getter;
830
831 OptionalKeyPath {
832 getter: move |root: &Root| {
833 getter(root).map(|arc| arc.deref())
834 },
835 _phantom: PhantomData,
836 }
837 }
838
839 pub fn for_rc<Target>(self) -> OptionalKeyPath<Root, Target, impl for<'r> Fn(&'r Root) -> Option<&'r Target> + 'static>
841 where
842 Value: std::ops::Deref<Target = Target>,
843 F: 'static,
844 Value: 'static,
845 {
846 let getter = self.getter;
847
848 OptionalKeyPath {
849 getter: move |root: &Root| {
850 getter(root).map(|rc| rc.deref())
851 },
852 _phantom: PhantomData,
853 }
854 }
855
856 #[cfg(feature = "tagged")]
857 pub fn for_tagged<Tag>(self) -> OptionalKeyPath<Tagged<Root, Tag>, Value, impl for<'r> Fn(&'r Tagged<Root, Tag>) -> Option<&'r Value> + 'static>
860 where
861 Tagged<Root, Tag>: std::ops::Deref<Target = Root>,
862 F: 'static,
863 Root: 'static,
864 Value: 'static,
865 Tag: 'static,
866 {
867 use std::ops::Deref;
868 let getter = self.getter;
869
870 OptionalKeyPath {
871 getter: move |tagged: &Tagged<Root, Tag>| {
872 getter(tagged.deref())
873 },
874 _phantom: PhantomData,
875 }
876 }
877
878 #[cfg(feature = "tagged")]
879 pub fn with_tagged<Tag, Callback, R>(&self, tagged: &Tagged<Root, Tag>, f: Callback) -> Option<R>
882 where
883 Tagged<Root, Tag>: std::ops::Deref<Target = Root>,
884 F: Clone,
885 Callback: FnOnce(&Value) -> R,
886 {
887 use std::ops::Deref;
888 self.get(tagged.deref()).map(|value| f(value))
889 }
890
891 pub fn for_option(self) -> OptionalKeyPath<Option<Root>, Value, impl for<'r> Fn(&'r Option<Root>) -> Option<&'r Value> + 'static>
894 where
895 F: 'static,
896 Root: 'static,
897 Value: 'static,
898 {
899 let getter = self.getter;
900
901 OptionalKeyPath {
902 getter: move |opt: &Option<Root>| {
903 opt.as_ref().and_then(|root| getter(root))
904 },
905 _phantom: PhantomData,
906 }
907 }
908
909 pub fn for_result<E>(self) -> OptionalKeyPath<Result<Root, E>, Value, impl for<'r> Fn(&'r Result<Root, E>) -> Option<&'r Value> + 'static>
912 where
913 F: 'static,
914 Root: 'static,
915 Value: 'static,
916 E: 'static,
917 {
918 let getter = self.getter;
919
920 OptionalKeyPath {
921 getter: move |result: &Result<Root, E>| {
922 result.as_ref().ok().and_then(|root| getter(root))
923 },
924 _phantom: PhantomData,
925 }
926 }
927
928 pub fn for_arc_root(self) -> OptionalKeyPath<Arc<Root>, Value, impl for<'r> Fn(&'r Arc<Root>) -> Option<&'r Value> + 'static>
930 where
931 Value: Sized,
932 F: 'static,
933 Root: 'static,
934 Value: 'static,
935 {
936 let getter = self.getter;
937
938 OptionalKeyPath {
939 getter: move |arc: &Arc<Root>| {
940 getter(arc.as_ref())
941 },
942 _phantom: PhantomData,
943 }
944 }
945
946 pub fn for_rc_root(self) -> OptionalKeyPath<Rc<Root>, Value, impl for<'r> Fn(&'r Rc<Root>) -> Option<&'r Value> + 'static>
948 where
949 Value: Sized,
950 F: 'static,
951 Root: 'static,
952 Value: 'static,
953 {
954 let getter = self.getter;
955
956 OptionalKeyPath {
957 getter: move |rc: &Rc<Root>| {
958 getter(rc.as_ref())
959 },
960 _phantom: PhantomData,
961 }
962 }
963
964 pub fn with_option<Callback, R>(&self, option: &Option<Root>, f: Callback) -> Option<R>
966 where
967 F: Clone,
968 Callback: FnOnce(&Value) -> R,
969 {
970 option.as_ref().and_then(|root| {
971 self.get(root).map(|value| f(value))
972 })
973 }
974
975 pub fn with_mutex<Callback, R>(&self, mutex: &Mutex<Root>, f: Callback) -> Option<R>
977 where
978 F: Clone,
979 Callback: FnOnce(&Value) -> R,
980 {
981 mutex.lock().ok().and_then(|guard| {
982 self.get(&*guard).map(|value| f(value))
983 })
984 }
985
986 pub fn with_rwlock<Callback, R>(&self, rwlock: &RwLock<Root>, f: Callback) -> Option<R>
988 where
989 F: Clone,
990 Callback: FnOnce(&Value) -> R,
991 {
992 rwlock.read().ok().and_then(|guard| {
993 self.get(&*guard).map(|value| f(value))
994 })
995 }
996
997 pub fn with_arc_rwlock<Callback, R>(&self, arc_rwlock: &Arc<RwLock<Root>>, f: Callback) -> Option<R>
999 where
1000 F: Clone,
1001 Callback: FnOnce(&Value) -> R,
1002 {
1003 arc_rwlock.read().ok().and_then(|guard| {
1004 self.get(&*guard).map(|value| f(value))
1005 })
1006 }
1007
1008 pub fn with_arc_rwlock_direct<Callback, R>(&self, arc_rwlock: &Arc<RwLock<Root>>, f: Callback) -> Option<R>
1012 where
1013 Callback: FnOnce(&Value) -> R,
1014 {
1015 arc_rwlock.read().ok().and_then(|guard| {
1016 self.get(&*guard).map(|value| f(value))
1017 })
1018 }
1019
1020 pub fn with_arc_mutex<Callback, R>(&self, arc_mutex: &Arc<Mutex<Root>>, f: Callback) -> Option<R>
1022 where
1023 F: Clone,
1024 Callback: FnOnce(&Value) -> R,
1025 {
1026 arc_mutex.lock().ok().and_then(|guard| {
1027 self.get(&*guard).map(|value| f(value))
1028 })
1029 }
1030}
1031
1032
1033#[derive(Clone)]
1035pub struct WritableKeyPath<Root, Value, F>
1036where
1037 F: for<'r> Fn(&'r mut Root) -> &'r mut Value,
1038{
1039 getter: F,
1040 _phantom: PhantomData<(Root, Value)>,
1041}
1042
1043impl<Root, Value, F> WritableKeyPath<Root, Value, F>
1044where
1045 F: for<'r> Fn(&'r mut Root) -> &'r mut Value,
1046{
1047 pub fn new(getter: F) -> Self {
1048 Self {
1049 getter,
1050 _phantom: PhantomData,
1051 }
1052 }
1053
1054 pub fn get_mut<'r>(&self, root: &'r mut Root) -> &'r mut Value {
1055 (self.getter)(root)
1056 }
1057
1058 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>
1061 where
1062 F: 'static,
1063 Root: 'static,
1064 Value: 'static,
1065 E: 'static,
1066 {
1067 let getter = self.getter;
1068
1069 WritableOptionalKeyPath {
1070 getter: move |result: &mut Result<Root, E>| {
1071 result.as_mut().ok().map(|root| getter(root))
1072 },
1073 _phantom: PhantomData,
1074 }
1075 }
1076
1077 pub fn for_box_root(self) -> WritableKeyPath<Box<Root>, Value, impl for<'r> Fn(&'r mut Box<Root>) -> &'r mut Value + 'static>
1079 where
1080 Value: Sized,
1081 F: 'static,
1082 Root: 'static,
1083 Value: 'static,
1084 {
1085 let getter = self.getter;
1086
1087 WritableKeyPath {
1088 getter: move |boxed: &mut Box<Root>| {
1089 getter(boxed.as_mut())
1090 },
1091 _phantom: PhantomData,
1092 }
1093 }
1094
1095 pub fn to_optional(self) -> WritableOptionalKeyPath<Root, Value, impl for<'r> Fn(&'r mut Root) -> Option<&'r mut Value> + 'static>
1098 where
1099 F: 'static,
1100 {
1101 let getter = self.getter;
1102 WritableOptionalKeyPath::new(move |root: &mut Root| Some(getter(root)))
1103 }
1104
1105 pub fn for_box<Target>(self) -> WritableKeyPath<Root, Target, impl for<'r> Fn(&'r mut Root) -> &'r mut Target + 'static>
1108 where
1109 Value: std::ops::DerefMut<Target = Target>,
1110 F: 'static,
1111 Value: 'static,
1112 {
1113 let getter = self.getter;
1114
1115 WritableKeyPath {
1116 getter: move |root: &mut Root| {
1117 getter(root).deref_mut()
1118 },
1119 _phantom: PhantomData,
1120 }
1121 }
1122
1123 pub fn for_arc<Target>(self) -> WritableKeyPath<Root, Target, impl for<'r> Fn(&'r mut Root) -> &'r mut Target + 'static>
1126 where
1127 Value: std::ops::DerefMut<Target = Target>,
1128 F: 'static,
1129 Value: 'static,
1130 {
1131 let getter = self.getter;
1132
1133 WritableKeyPath {
1134 getter: move |root: &mut Root| {
1135 getter(root).deref_mut()
1136 },
1137 _phantom: PhantomData,
1138 }
1139 }
1140
1141 pub fn for_rc<Target>(self) -> WritableKeyPath<Root, Target, impl for<'r> Fn(&'r mut Root) -> &'r mut Target + 'static>
1144 where
1145 Value: std::ops::DerefMut<Target = Target>,
1146 F: 'static,
1147 Value: 'static,
1148 {
1149 let getter = self.getter;
1150
1151 WritableKeyPath {
1152 getter: move |root: &mut Root| {
1153 getter(root).deref_mut()
1154 },
1155 _phantom: PhantomData,
1156 }
1157 }
1158
1159 pub fn with_box_mut<Callback, R>(&self, boxed: &mut Box<Root>, f: Callback) -> R
1161 where
1162 F: Clone,
1163 Callback: FnOnce(&mut Value) -> R,
1164 {
1165 let value = self.get_mut(boxed);
1166 f(value)
1167 }
1168
1169 pub fn with_result_mut<Callback, R, E>(&self, result: &mut Result<Root, E>, f: Callback) -> Option<R>
1171 where
1172 F: Clone,
1173 Callback: FnOnce(&mut Value) -> R,
1174 {
1175 result.as_mut().ok().map(|root| {
1176 let value = self.get_mut(root);
1177 f(value)
1178 })
1179 }
1180
1181 pub fn with_option_mut<Callback, R>(&self, option: &mut Option<Root>, f: Callback) -> Option<R>
1183 where
1184 F: Clone,
1185 Callback: FnOnce(&mut Value) -> R,
1186 {
1187 option.as_mut().map(|root| {
1188 let value = self.get_mut(root);
1189 f(value)
1190 })
1191 }
1192
1193 pub fn with_refcell_mut<Callback, R>(&self, refcell: &RefCell<Root>, f: Callback) -> Option<R>
1195 where
1196 F: Clone,
1197 Callback: FnOnce(&mut Value) -> R,
1198 {
1199 refcell.try_borrow_mut().ok().map(|mut borrow| {
1200 let value = self.get_mut(&mut *borrow);
1201 f(value)
1202 })
1203 }
1204
1205 pub fn with_mutex_mut<Callback, R>(&self, mutex: &mut Mutex<Root>, f: Callback) -> Option<R>
1207 where
1208 F: Clone,
1209 Callback: FnOnce(&mut Value) -> R,
1210 {
1211 mutex.get_mut().ok().map(|root| {
1212 let value = self.get_mut(root);
1213 f(value)
1214 })
1215 }
1216
1217 pub fn with_rwlock_mut<Callback, R>(&self, rwlock: &mut RwLock<Root>, f: Callback) -> Option<R>
1219 where
1220 F: Clone,
1221 Callback: FnOnce(&mut Value) -> R,
1222 {
1223 rwlock.write().ok().map(|mut guard| {
1224 let value = self.get_mut(&mut *guard);
1225 f(value)
1226 })
1227 }
1228}
1229
1230#[derive(Clone)]
1232pub struct WritableOptionalKeyPath<Root, Value, F>
1233where
1234 F: for<'r> Fn(&'r mut Root) -> Option<&'r mut Value>,
1235{
1236 getter: F,
1237 _phantom: PhantomData<(Root, Value)>,
1238}
1239
1240impl<Root, Value, F> WritableOptionalKeyPath<Root, Value, F>
1241where
1242 F: for<'r> Fn(&'r mut Root) -> Option<&'r mut Value>,
1243{
1244 pub fn new(getter: F) -> Self {
1245 Self {
1246 getter,
1247 _phantom: PhantomData,
1248 }
1249 }
1250
1251 pub fn get_mut<'r>(&self, root: &'r mut Root) -> Option<&'r mut Value> {
1252 (self.getter)(root)
1253 }
1254
1255 pub fn then<SubValue, G>(
1257 self,
1258 next: WritableOptionalKeyPath<Value, SubValue, G>,
1259 ) -> WritableOptionalKeyPath<Root, SubValue, impl for<'r> Fn(&'r mut Root) -> Option<&'r mut SubValue>>
1260 where
1261 G: for<'r> Fn(&'r mut Value) -> Option<&'r mut SubValue>,
1262 F: 'static,
1263 G: 'static,
1264 Value: 'static,
1265 {
1266 let first = self.getter;
1267 let second = next.getter;
1268
1269 WritableOptionalKeyPath::new(move |root: &mut Root| {
1270 first(root).and_then(|value| second(value))
1271 })
1272 }
1273
1274 pub fn for_box<Target>(self) -> WritableOptionalKeyPath<Root, Target, impl for<'r> Fn(&'r mut Root) -> Option<&'r mut Target> + 'static>
1277 where
1278 Value: std::ops::DerefMut<Target = Target>,
1279 F: 'static,
1280 Value: 'static,
1281 {
1282 let getter = self.getter;
1283
1284 WritableOptionalKeyPath {
1285 getter: move |root: &mut Root| {
1286 getter(root).map(|boxed| boxed.deref_mut())
1287 },
1288 _phantom: PhantomData,
1289 }
1290 }
1291
1292 pub fn for_arc<Target>(self) -> WritableOptionalKeyPath<Root, Target, impl for<'r> Fn(&'r mut Root) -> Option<&'r mut Target> + 'static>
1294 where
1295 Value: std::ops::DerefMut<Target = Target>,
1296 F: 'static,
1297 Value: 'static,
1298 {
1299 let getter = self.getter;
1300
1301 WritableOptionalKeyPath {
1302 getter: move |root: &mut Root| {
1303 getter(root).map(|arc| arc.deref_mut())
1304 },
1305 _phantom: PhantomData,
1306 }
1307 }
1308
1309 pub fn for_rc<Target>(self) -> WritableOptionalKeyPath<Root, Target, impl for<'r> Fn(&'r mut Root) -> Option<&'r mut Target> + 'static>
1311 where
1312 Value: std::ops::DerefMut<Target = Target>,
1313 F: 'static,
1314 Value: 'static,
1315 {
1316 let getter = self.getter;
1317
1318 WritableOptionalKeyPath {
1319 getter: move |root: &mut Root| {
1320 getter(root).map(|rc| rc.deref_mut())
1321 },
1322 _phantom: PhantomData,
1323 }
1324 }
1325
1326 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>
1329 where
1330 F: 'static,
1331 Root: 'static,
1332 Value: 'static,
1333 E: 'static,
1334 {
1335 let getter = self.getter;
1336
1337 WritableOptionalKeyPath {
1338 getter: move |result: &mut Result<Root, E>| {
1339 result.as_mut().ok().and_then(|root| getter(root))
1340 },
1341 _phantom: PhantomData,
1342 }
1343 }
1344
1345 pub fn for_box_root(self) -> WritableOptionalKeyPath<Box<Root>, Value, impl for<'r> Fn(&'r mut Box<Root>) -> Option<&'r mut Value> + 'static>
1347 where
1348 Value: Sized,
1349 F: 'static,
1350 Root: 'static,
1351 Value: 'static,
1352 {
1353 let getter = self.getter;
1354
1355 WritableOptionalKeyPath {
1356 getter: move |boxed: &mut Box<Root>| {
1357 getter(boxed.as_mut())
1358 },
1359 _phantom: PhantomData,
1360 }
1361 }
1362
1363 pub fn for_arc_root(self) -> WritableOptionalKeyPath<Arc<Root>, Value, impl for<'r> Fn(&'r mut Arc<Root>) -> Option<&'r mut Value> + 'static>
1365 where
1366 Value: Sized,
1367 F: 'static,
1368 Root: 'static,
1369 Value: 'static,
1370 {
1371 let getter = self.getter;
1372
1373 WritableOptionalKeyPath {
1374 getter: move |arc: &mut Arc<Root>| {
1375 None
1378 },
1379 _phantom: PhantomData,
1380 }
1381 }
1382
1383 pub fn for_rc_root(self) -> WritableOptionalKeyPath<Rc<Root>, Value, impl for<'r> Fn(&'r mut Rc<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 |rc: &mut Rc<Root>| {
1395 None
1398 },
1399 _phantom: PhantomData,
1400 }
1401 }
1402
1403 pub fn for_option<T>() -> WritableOptionalKeyPath<Option<T>, T, impl for<'r> Fn(&'r mut Option<T>) -> Option<&'r mut T>> {
1405 WritableOptionalKeyPath::new(|opt: &mut Option<T>| opt.as_mut())
1406 }
1407}
1408
1409pub struct EnumKeyPath<Enum = (), Variant = (), ExtractFn = fn(&()) -> Option<&()>, EmbedFn = fn(()) -> ()>
1417where
1418 ExtractFn: for<'r> Fn(&'r Enum) -> Option<&'r Variant> + 'static,
1419 EmbedFn: Fn(Variant) -> Enum + 'static,
1420{
1421 extractor: OptionalKeyPath<Enum, Variant, ExtractFn>,
1422 embedder: EmbedFn,
1423}
1424
1425impl<Enum, Variant, ExtractFn, EmbedFn> EnumKeyPath<Enum, Variant, ExtractFn, EmbedFn>
1426where
1427 ExtractFn: for<'r> Fn(&'r Enum) -> Option<&'r Variant> + 'static,
1428 EmbedFn: Fn(Variant) -> Enum + 'static,
1429{
1430 pub fn new(
1432 extractor: ExtractFn,
1433 embedder: EmbedFn,
1434 ) -> Self {
1435 Self {
1436 extractor: OptionalKeyPath::new(extractor),
1437 embedder,
1438 }
1439 }
1440
1441 pub fn get<'r>(&self, enum_value: &'r Enum) -> Option<&'r Variant> {
1443 self.extractor.get(enum_value)
1444 }
1445
1446 pub fn embed(&self, value: Variant) -> Enum {
1448 (self.embedder)(value)
1449 }
1450
1451 pub fn as_optional(&self) -> &OptionalKeyPath<Enum, Variant, ExtractFn> {
1453 &self.extractor
1454 }
1455
1456 pub fn to_optional(self) -> OptionalKeyPath<Enum, Variant, ExtractFn> {
1458 self.extractor
1459 }
1460}
1461
1462impl EnumKeyPath {
1464 pub fn readable_enum<Enum, Variant, ExtractFn, EmbedFn>(
1467 embedder: EmbedFn,
1468 extractor: ExtractFn,
1469 ) -> EnumKeyPath<Enum, Variant, ExtractFn, EmbedFn>
1470 where
1471 ExtractFn: for<'r> Fn(&'r Enum) -> Option<&'r Variant> + 'static,
1472 EmbedFn: Fn(Variant) -> Enum + 'static,
1473 {
1474 EnumKeyPath::new(extractor, embedder)
1475 }
1476
1477 pub fn for_variant<Enum, Variant, ExtractFn>(
1479 extractor: ExtractFn
1480 ) -> OptionalKeyPath<Enum, Variant, impl for<'r> Fn(&'r Enum) -> Option<&'r Variant>>
1481 where
1482 ExtractFn: Fn(&Enum) -> Option<&Variant>,
1483 {
1484 OptionalKeyPath::new(extractor)
1485 }
1486
1487 pub fn for_match<Enum, Output, MatchFn>(
1489 matcher: MatchFn
1490 ) -> KeyPath<Enum, Output, impl for<'r> Fn(&'r Enum) -> &'r Output>
1491 where
1492 MatchFn: Fn(&Enum) -> &Output,
1493 {
1494 KeyPath::new(matcher)
1495 }
1496
1497 pub fn for_ok<T, E>() -> OptionalKeyPath<Result<T, E>, T, impl for<'r> Fn(&'r Result<T, E>) -> Option<&'r T>> {
1499 OptionalKeyPath::new(|result: &Result<T, E>| result.as_ref().ok())
1500 }
1501
1502 pub fn for_err<T, E>() -> OptionalKeyPath<Result<T, E>, E, impl for<'r> Fn(&'r Result<T, E>) -> Option<&'r E>> {
1504 OptionalKeyPath::new(|result: &Result<T, E>| result.as_ref().err())
1505 }
1506
1507 pub fn for_some<T>() -> OptionalKeyPath<Option<T>, T, impl for<'r> Fn(&'r Option<T>) -> Option<&'r T>> {
1509 OptionalKeyPath::new(|opt: &Option<T>| opt.as_ref())
1510 }
1511
1512 pub fn for_option<T>() -> OptionalKeyPath<Option<T>, T, impl for<'r> Fn(&'r Option<T>) -> Option<&'r T>> {
1514 OptionalKeyPath::new(|opt: &Option<T>| opt.as_ref())
1515 }
1516
1517 pub fn for_box<T>() -> KeyPath<Box<T>, T, impl for<'r> Fn(&'r Box<T>) -> &'r T> {
1519 KeyPath::new(|b: &Box<T>| b.as_ref())
1520 }
1521
1522 pub fn for_arc<T>() -> KeyPath<Arc<T>, T, impl for<'r> Fn(&'r Arc<T>) -> &'r T> {
1524 KeyPath::new(|arc: &Arc<T>| arc.as_ref())
1525 }
1526
1527 pub fn for_rc<T>() -> KeyPath<std::rc::Rc<T>, T, impl for<'r> Fn(&'r std::rc::Rc<T>) -> &'r T> {
1529 KeyPath::new(|rc: &std::rc::Rc<T>| rc.as_ref())
1530 }
1531
1532 pub fn for_box_mut<T>() -> WritableKeyPath<Box<T>, T, impl for<'r> Fn(&'r mut Box<T>) -> &'r mut T> {
1534 WritableKeyPath::new(|b: &mut Box<T>| b.as_mut())
1535 }
1536
1537 }
1541
1542pub fn variant_of<Enum, Variant, F>(extractor: F) -> OptionalKeyPath<Enum, Variant, F>
1544where
1545 F: for<'r> Fn(&'r Enum) -> Option<&'r Variant>,
1546{
1547 OptionalKeyPath::new(extractor)
1548}
1549
1550#[derive(Clone)]
1566pub struct PartialKeyPath<Root> {
1567 getter: Rc<dyn for<'r> Fn(&'r Root) -> &'r dyn Any>,
1568 value_type_id: TypeId,
1569 _phantom: PhantomData<Root>,
1570}
1571
1572impl<Root> PartialKeyPath<Root> {
1573 pub fn new<Value>(keypath: KeyPath<Root, Value, impl for<'r> Fn(&'r Root) -> &'r Value + 'static>) -> Self
1574 where
1575 Value: Any + 'static,
1576 Root: 'static,
1577 {
1578 let value_type_id = TypeId::of::<Value>();
1579 let getter = Rc::new(keypath.getter);
1580
1581 Self {
1582 getter: Rc::new(move |root: &Root| {
1583 let value: &Value = getter(root);
1584 value as &dyn Any
1585 }),
1586 value_type_id,
1587 _phantom: PhantomData,
1588 }
1589 }
1590
1591 pub fn from<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 Self::new(keypath)
1599 }
1600
1601 pub fn get<'r>(&self, root: &'r Root) -> &'r dyn Any {
1602 (self.getter)(root)
1603 }
1604
1605 pub fn value_type_id(&self) -> TypeId {
1607 self.value_type_id
1608 }
1609
1610 pub fn get_as<'a, Value: Any>(&self, root: &'a Root) -> Option<&'a Value> {
1612 if self.value_type_id == TypeId::of::<Value>() {
1613 self.get(root).downcast_ref::<Value>()
1614 } else {
1615 None
1616 }
1617 }
1618
1619 pub fn kind_name(&self) -> String {
1622 format!("{:?}", self.value_type_id)
1623 }
1624}
1625
1626#[derive(Clone)]
1633pub struct PartialOptionalKeyPath<Root> {
1634 getter: Rc<dyn for<'r> Fn(&'r Root) -> Option<&'r dyn Any>>,
1635 value_type_id: TypeId,
1636 _phantom: PhantomData<Root>,
1637}
1638
1639impl<Root> PartialOptionalKeyPath<Root> {
1640 pub fn new<Value>(keypath: OptionalKeyPath<Root, Value, impl for<'r> Fn(&'r Root) -> Option<&'r Value> + 'static>) -> Self
1641 where
1642 Value: Any + 'static,
1643 Root: 'static,
1644 {
1645 let value_type_id = TypeId::of::<Value>();
1646 let getter = Rc::new(keypath.getter);
1647
1648 Self {
1649 getter: Rc::new(move |root: &Root| {
1650 getter(root).map(|value: &Value| value as &dyn Any)
1651 }),
1652 value_type_id,
1653 _phantom: PhantomData,
1654 }
1655 }
1656
1657 pub fn get<'r>(&self, root: &'r Root) -> Option<&'r dyn Any> {
1658 (self.getter)(root)
1659 }
1660
1661 pub fn value_type_id(&self) -> TypeId {
1663 self.value_type_id
1664 }
1665
1666 pub fn get_as<'a, Value: Any>(&self, root: &'a Root) -> Option<Option<&'a Value>> {
1668 if self.value_type_id == TypeId::of::<Value>() {
1669 self.get(root).map(|any| any.downcast_ref::<Value>())
1670 } else {
1671 None
1672 }
1673 }
1674
1675 pub fn then<MidValue>(
1679 self,
1680 next: PartialOptionalKeyPath<MidValue>,
1681 ) -> PartialOptionalKeyPath<Root>
1682 where
1683 MidValue: Any + 'static,
1684 Root: 'static,
1685 {
1686 let first = self.getter;
1687 let second = next.getter;
1688 let value_type_id = next.value_type_id;
1689
1690 PartialOptionalKeyPath {
1691 getter: Rc::new(move |root: &Root| {
1692 first(root).and_then(|any| {
1693 if let Some(mid_value) = any.downcast_ref::<MidValue>() {
1694 second(mid_value)
1695 } else {
1696 None
1697 }
1698 })
1699 }),
1700 value_type_id,
1701 _phantom: PhantomData,
1702 }
1703 }
1704}
1705
1706#[derive(Clone)]
1712pub struct PartialWritableKeyPath<Root> {
1713 getter: Rc<dyn for<'r> Fn(&'r mut Root) -> &'r mut dyn Any>,
1714 value_type_id: TypeId,
1715 _phantom: PhantomData<Root>,
1716}
1717
1718impl<Root> PartialWritableKeyPath<Root> {
1719 pub fn new<Value>(keypath: WritableKeyPath<Root, Value, impl for<'r> Fn(&'r mut Root) -> &'r mut Value + 'static>) -> Self
1720 where
1721 Value: Any + 'static,
1722 Root: 'static,
1723 {
1724 let value_type_id = TypeId::of::<Value>();
1725 let getter = Rc::new(keypath.getter);
1726
1727 Self {
1728 getter: Rc::new(move |root: &mut Root| {
1729 let value: &mut Value = getter(root);
1730 value as &mut dyn Any
1731 }),
1732 value_type_id,
1733 _phantom: PhantomData,
1734 }
1735 }
1736
1737 pub fn from<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 Self::new(keypath)
1745 }
1746
1747 pub fn get_mut<'r>(&self, root: &'r mut Root) -> &'r mut dyn Any {
1748 (self.getter)(root)
1749 }
1750
1751 pub fn value_type_id(&self) -> TypeId {
1753 self.value_type_id
1754 }
1755
1756 pub fn get_mut_as<'a, Value: Any>(&self, root: &'a mut Root) -> Option<&'a mut Value> {
1758 if self.value_type_id == TypeId::of::<Value>() {
1759 self.get_mut(root).downcast_mut::<Value>()
1760 } else {
1761 None
1762 }
1763 }
1764}
1765
1766#[derive(Clone)]
1772pub struct PartialWritableOptionalKeyPath<Root> {
1773 getter: Rc<dyn for<'r> Fn(&'r mut Root) -> Option<&'r mut dyn Any>>,
1774 value_type_id: TypeId,
1775 _phantom: PhantomData<Root>,
1776}
1777
1778impl<Root> PartialWritableOptionalKeyPath<Root> {
1779 pub fn new<Value>(keypath: WritableOptionalKeyPath<Root, Value, impl for<'r> Fn(&'r mut Root) -> Option<&'r mut Value> + 'static>) -> Self
1780 where
1781 Value: Any + 'static,
1782 Root: 'static,
1783 {
1784 let value_type_id = TypeId::of::<Value>();
1785 let getter = Rc::new(keypath.getter);
1786
1787 Self {
1788 getter: Rc::new(move |root: &mut Root| {
1789 getter(root).map(|value: &mut Value| value as &mut dyn Any)
1790 }),
1791 value_type_id,
1792 _phantom: PhantomData,
1793 }
1794 }
1795
1796 pub fn get_mut<'r>(&self, root: &'r mut Root) -> Option<&'r mut dyn Any> {
1797 (self.getter)(root)
1798 }
1799
1800 pub fn value_type_id(&self) -> TypeId {
1802 self.value_type_id
1803 }
1804
1805 pub fn get_mut_as<'a, Value: Any>(&self, root: &'a mut Root) -> Option<Option<&'a mut Value>> {
1807 if self.value_type_id == TypeId::of::<Value>() {
1808 self.get_mut(root).map(|any| any.downcast_mut::<Value>())
1809 } else {
1810 None
1811 }
1812 }
1813}
1814
1815#[derive(Clone)]
1829pub struct AnyKeyPath {
1830 getter: Rc<dyn for<'r> Fn(&'r dyn Any) -> Option<&'r dyn Any>>,
1831 root_type_id: TypeId,
1832 value_type_id: TypeId,
1833}
1834
1835impl AnyKeyPath {
1836 pub fn new<Root, Value>(keypath: OptionalKeyPath<Root, Value, impl for<'r> Fn(&'r Root) -> Option<&'r Value> + 'static>) -> Self
1837 where
1838 Root: Any + 'static,
1839 Value: Any + 'static,
1840 {
1841 let root_type_id = TypeId::of::<Root>();
1842 let value_type_id = TypeId::of::<Value>();
1843 let getter = keypath.getter;
1844
1845 Self {
1846 getter: Rc::new(move |any: &dyn Any| {
1847 if let Some(root) = any.downcast_ref::<Root>() {
1848 getter(root).map(|value: &Value| value as &dyn Any)
1849 } else {
1850 None
1851 }
1852 }),
1853 root_type_id,
1854 value_type_id,
1855 }
1856 }
1857
1858 pub fn from<Root, Value>(keypath: OptionalKeyPath<Root, Value, impl for<'r> Fn(&'r Root) -> Option<&'r Value> + 'static>) -> Self
1861 where
1862 Root: Any + 'static,
1863 Value: Any + 'static,
1864 {
1865 Self::new(keypath)
1866 }
1867
1868 pub fn get<'r>(&self, root: &'r dyn Any) -> Option<&'r dyn Any> {
1869 (self.getter)(root)
1870 }
1871
1872 pub fn root_type_id(&self) -> TypeId {
1874 self.root_type_id
1875 }
1876
1877 pub fn value_type_id(&self) -> TypeId {
1879 self.value_type_id
1880 }
1881
1882 pub fn get_as<'a, Root: Any, Value: Any>(&self, root: &'a Root) -> Option<Option<&'a Value>> {
1884 if self.root_type_id == TypeId::of::<Root>() && self.value_type_id == TypeId::of::<Value>() {
1885 self.get(root as &dyn Any).map(|any| any.downcast_ref::<Value>())
1886 } else {
1887 None
1888 }
1889 }
1890
1891 pub fn kind_name(&self) -> String {
1894 format!("{:?}", self.value_type_id)
1895 }
1896}
1897
1898#[derive(Clone)]
1900pub struct AnyWritableKeyPath {
1901 getter: Rc<dyn for<'r> Fn(&'r mut dyn Any) -> Option<&'r mut dyn Any>>,
1902 root_type_id: TypeId,
1903 value_type_id: TypeId,
1904}
1905
1906impl AnyWritableKeyPath {
1907 pub fn new<Root, Value>(keypath: WritableOptionalKeyPath<Root, Value, impl for<'r> Fn(&'r mut Root) -> Option<&'r mut Value> + 'static>) -> Self
1908 where
1909 Root: Any + 'static,
1910 Value: Any + 'static,
1911 {
1912 let root_type_id = TypeId::of::<Root>();
1913 let value_type_id = TypeId::of::<Value>();
1914 let getter = keypath.getter;
1915
1916 Self {
1917 getter: Rc::new(move |any: &mut dyn Any| {
1918 if let Some(root) = any.downcast_mut::<Root>() {
1919 getter(root).map(|value: &mut Value| value as &mut dyn Any)
1920 } else {
1921 None
1922 }
1923 }),
1924 root_type_id,
1925 value_type_id,
1926 }
1927 }
1928
1929 pub fn get_mut<'r>(&self, root: &'r mut dyn Any) -> Option<&'r mut dyn Any> {
1930 (self.getter)(root)
1931 }
1932
1933 pub fn root_type_id(&self) -> TypeId {
1935 self.root_type_id
1936 }
1937
1938 pub fn value_type_id(&self) -> TypeId {
1940 self.value_type_id
1941 }
1942
1943 pub fn get_mut_as<'a, Root: Any, Value: Any>(&self, root: &'a mut Root) -> Option<Option<&'a mut Value>> {
1945 if self.root_type_id == TypeId::of::<Root>() && self.value_type_id == TypeId::of::<Value>() {
1946 self.get_mut(root as &mut dyn Any).map(|any| any.downcast_mut::<Value>())
1947 } else {
1948 None
1949 }
1950 }
1951}
1952
1953impl<Root, Value, F> KeyPath<Root, Value, F>
1955where
1956 F: for<'r> Fn(&'r Root) -> &'r Value + 'static,
1957 Root: 'static,
1958 Value: Any + 'static,
1959{
1960 pub fn to_partial(self) -> PartialKeyPath<Root> {
1962 PartialKeyPath::new(self)
1963 }
1964
1965 pub fn to(self) -> PartialKeyPath<Root> {
1967 self.to_partial()
1968 }
1969}
1970
1971impl<Root, Value, F> OptionalKeyPath<Root, Value, F>
1972where
1973 F: for<'r> Fn(&'r Root) -> Option<&'r Value> + 'static,
1974 Root: Any + 'static,
1975 Value: Any + 'static,
1976{
1977 pub fn to_partial(self) -> PartialOptionalKeyPath<Root> {
1979 PartialOptionalKeyPath::new(self)
1980 }
1981
1982 pub fn to_any(self) -> AnyKeyPath {
1984 AnyKeyPath::new(self)
1985 }
1986
1987 pub fn to(self) -> PartialOptionalKeyPath<Root> {
1989 self.to_partial()
1990 }
1991}
1992
1993impl<Root, Value, F> WritableKeyPath<Root, Value, F>
1994where
1995 F: for<'r> Fn(&'r mut Root) -> &'r mut Value + 'static,
1996 Root: 'static,
1997 Value: Any + 'static,
1998{
1999 pub fn to_partial(self) -> PartialWritableKeyPath<Root> {
2001 PartialWritableKeyPath::new(self)
2002 }
2003
2004 pub fn to(self) -> PartialWritableKeyPath<Root> {
2006 self.to_partial()
2007 }
2008}
2009
2010impl<Root, Value, F> WritableOptionalKeyPath<Root, Value, F>
2011where
2012 F: for<'r> Fn(&'r mut Root) -> Option<&'r mut Value> + 'static,
2013 Root: Any + 'static,
2014 Value: Any + 'static,
2015{
2016 pub fn to_partial(self) -> PartialWritableOptionalKeyPath<Root> {
2018 PartialWritableOptionalKeyPath::new(self)
2019 }
2020
2021 pub fn to_any(self) -> AnyWritableKeyPath {
2023 AnyWritableKeyPath::new(self)
2024 }
2025
2026 pub fn to(self) -> PartialWritableOptionalKeyPath<Root> {
2028 self.to_partial()
2029 }
2030}
2031
2032#[cfg(test)]
2033mod tests {
2034 use super::*;
2035 use std::sync::atomic::{AtomicUsize, Ordering};
2036 use std::rc::Rc;
2037
2038 static ALLOC_COUNT: AtomicUsize = AtomicUsize::new(0);
2040 static DEALLOC_COUNT: AtomicUsize = AtomicUsize::new(0);
2041
2042 #[derive(Debug)]
2044 struct NoCloneType {
2045 id: usize,
2046 data: String,
2047 }
2048
2049 impl NoCloneType {
2050 fn new(data: String) -> Self {
2051 ALLOC_COUNT.fetch_add(1, Ordering::SeqCst);
2052 Self {
2053 id: ALLOC_COUNT.load(Ordering::SeqCst),
2054 data,
2055 }
2056 }
2057 }
2058
2059 impl Clone for NoCloneType {
2060 fn clone(&self) -> Self {
2061 eprintln!("[DEBUG] NoCloneType should not be cloned! ID: {}", self.id);
2062 unreachable!("NoCloneType should not be cloned! ID: {}", self.id);
2063 }
2064 }
2065
2066 impl Drop for NoCloneType {
2067 fn drop(&mut self) {
2068 DEALLOC_COUNT.fetch_add(1, Ordering::SeqCst);
2069 }
2070 }
2071
2072 fn reset_memory_counters() {
2074 ALLOC_COUNT.store(0, Ordering::SeqCst);
2075 DEALLOC_COUNT.store(0, Ordering::SeqCst);
2076 }
2077
2078 fn get_alloc_count() -> usize {
2079 ALLOC_COUNT.load(Ordering::SeqCst)
2080 }
2081
2082 fn get_dealloc_count() -> usize {
2083 DEALLOC_COUNT.load(Ordering::SeqCst)
2084 }
2085
2086#[derive(Debug)]
2088struct User {
2089 name: String,
2090 metadata: Option<Box<UserMetadata>>,
2091 friends: Vec<Arc<User>>,
2092}
2093
2094#[derive(Debug)]
2095struct UserMetadata {
2096 created_at: String,
2097}
2098
2099fn some_fn() {
2100 let akash = User {
2101 name: "Alice".to_string(),
2102 metadata: Some(Box::new(UserMetadata {
2103 created_at: "2024-01-01".to_string(),
2104 })),
2105 friends: vec![
2106 Arc::new(User {
2107 name: "Bob".to_string(),
2108 metadata: None,
2109 friends: vec![],
2110 }),
2111 ],
2112 };
2113
2114 let name_kp = KeyPath::new(|u: &User| &u.name);
2116 let metadata_kp = OptionalKeyPath::new(|u: &User| u.metadata.as_ref());
2117 let friends_kp = KeyPath::new(|u: &User| &u.friends);
2118
2119 println!("Name: {}", name_kp.get(&akash));
2121
2122 if let Some(metadata) = metadata_kp.get(&akash) {
2123 println!("Has metadata: {:?}", metadata);
2124 }
2125
2126 if let Some(first_friend) = akash.friends.get(0) {
2128 println!("First friend: {}", name_kp.get(first_friend));
2129 }
2130
2131 let created_at_kp = KeyPath::new(|m: &UserMetadata| &m.created_at);
2133
2134 if let Some(metadata) = akash.metadata.as_ref() {
2135 let boxed_metadata: &Box<UserMetadata> = metadata;
2137 let unwrapped = boxed_metadata.as_ref();
2138 println!("Created at: {:?}", created_at_kp.get(unwrapped));
2139 }
2140 }
2141
2142 #[test]
2143 fn test_name() {
2144 some_fn();
2145 }
2146
2147 #[test]
2148 fn test_no_cloning_on_keypath_operations() {
2149 reset_memory_counters();
2150
2151 let value = NoCloneType::new("test".to_string());
2153 let boxed = Box::new(value);
2154
2155 let kp = KeyPath::new(|b: &Box<NoCloneType>| b.as_ref());
2157
2158 let _ref = kp.get(&boxed);
2160
2161 let _kp_clone = kp.clone();
2163
2164 let _ref2 = _kp_clone.get(&boxed);
2166
2167 assert_eq!(get_alloc_count(), 1);
2169 }
2170
2171 #[test]
2172 fn test_no_cloning_on_optional_keypath_operations() {
2173 reset_memory_counters();
2174
2175 let value = NoCloneType::new("test".to_string());
2176 let opt = Some(Box::new(value));
2177
2178 let okp = OptionalKeyPath::new(|o: &Option<Box<NoCloneType>>| o.as_ref());
2180
2181 let _ref = okp.get(&opt);
2183
2184 let _okp_clone = okp.clone();
2186
2187 let chained = okp.then(OptionalKeyPath::new(|b: &Box<NoCloneType>| Some(b.as_ref())));
2189 let _ref2 = chained.get(&opt);
2190
2191 assert_eq!(get_alloc_count(), 1);
2192 }
2193
2194 #[test]
2195 fn test_memory_release() {
2196 reset_memory_counters();
2197
2198 {
2199 let value = NoCloneType::new("test".to_string());
2200 let boxed = Box::new(value);
2201 let kp = KeyPath::new(|b: &Box<NoCloneType>| b.as_ref());
2202
2203 let _ref = kp.get(&boxed);
2205
2206 }
2208
2209 assert_eq!(get_alloc_count(), 1);
2212 }
2215
2216 #[test]
2217 fn test_keypath_clone_does_not_clone_underlying_data() {
2218 reset_memory_counters();
2219
2220 let value = NoCloneType::new("data".to_string());
2221 let rc_value = Rc::new(value);
2222
2223 let kp = KeyPath::new(|r: &Rc<NoCloneType>| r.as_ref());
2225
2226 let kp1 = kp.clone();
2228 let kp2 = kp.clone();
2229 let kp3 = kp1.clone();
2230
2231 let _ref1 = kp.get(&rc_value);
2233 let _ref2 = kp1.get(&rc_value);
2234 let _ref3 = kp2.get(&rc_value);
2235 let _ref4 = kp3.get(&rc_value);
2236
2237 assert_eq!(get_alloc_count(), 1);
2239 }
2240
2241 #[test]
2242 fn test_optional_keypath_chaining_no_clone() {
2243 reset_memory_counters();
2244
2245 let value = NoCloneType::new("value1".to_string());
2246
2247 struct Container {
2248 inner: Option<Box<NoCloneType>>,
2249 }
2250
2251 let container = Container {
2252 inner: Some(Box::new(value)),
2253 };
2254
2255 let kp1 = OptionalKeyPath::new(|c: &Container| c.inner.as_ref());
2257 let kp2 = OptionalKeyPath::new(|b: &Box<NoCloneType>| Some(b.as_ref()));
2258
2259 let chained = kp1.then(kp2);
2261
2262 let _result = chained.get(&container);
2264
2265 assert_eq!(get_alloc_count(), 1);
2267 }
2268
2269 #[test]
2270 fn test_for_box_no_clone() {
2271 reset_memory_counters();
2272
2273 let value = NoCloneType::new("test".to_string());
2274 let boxed = Box::new(value);
2275 let opt_boxed = Some(boxed);
2276
2277 let kp = OptionalKeyPath::new(|o: &Option<Box<NoCloneType>>| o.as_ref());
2279 let unwrapped = kp.for_box();
2280
2281 let _ref = unwrapped.get(&opt_boxed);
2283
2284 assert_eq!(get_alloc_count(), 1);
2285 }
2286
2287 #[derive(Debug, PartialEq)]
2290 struct TestUser {
2291 name: String,
2292 age: u32,
2293 metadata: Option<String>,
2294 address: Option<TestAddress>,
2295 }
2296
2297 #[derive(Debug, PartialEq)]
2298 struct TestAddress {
2299 street: String,
2300 city: String,
2301 country: Option<TestCountry>,
2302 }
2303
2304 #[derive(Debug, PartialEq)]
2305 struct TestCountry {
2306 name: String,
2307 }
2308
2309 #[test]
2310 fn test_keypath_macro() {
2311 let user = TestUser {
2312 name: "Alice".to_string(),
2313 age: 30,
2314 metadata: None,
2315 address: None,
2316 };
2317
2318 let name_kp = keypath!(|u: &TestUser| &u.name);
2320 assert_eq!(name_kp.get(&user), "Alice");
2321
2322 let user_with_address = TestUser {
2324 name: "Bob".to_string(),
2325 age: 25,
2326 metadata: None,
2327 address: Some(TestAddress {
2328 street: "123 Main St".to_string(),
2329 city: "New York".to_string(),
2330 country: None,
2331 }),
2332 };
2333
2334 let street_kp = keypath!(|u: &TestUser| &u.address.as_ref().unwrap().street);
2335 assert_eq!(street_kp.get(&user_with_address), "123 Main St");
2336
2337 let user_with_country = TestUser {
2339 name: "Charlie".to_string(),
2340 age: 35,
2341 metadata: None,
2342 address: Some(TestAddress {
2343 street: "456 Oak Ave".to_string(),
2344 city: "London".to_string(),
2345 country: Some(TestCountry {
2346 name: "UK".to_string(),
2347 }),
2348 }),
2349 };
2350
2351 let country_name_kp = keypath!(|u: &TestUser| &u.address.as_ref().unwrap().country.as_ref().unwrap().name);
2352 assert_eq!(country_name_kp.get(&user_with_country), "UK");
2353
2354 let age_kp = keypath!(|u: &TestUser| &u.age);
2356 assert_eq!(age_kp.get(&user), &30);
2357 }
2358
2359 #[test]
2360 fn test_opt_keypath_macro() {
2361 let user = TestUser {
2362 name: "Alice".to_string(),
2363 age: 30,
2364 metadata: Some("admin".to_string()),
2365 address: None,
2366 };
2367
2368 let metadata_kp = opt_keypath!(|u: &TestUser| u.metadata.as_ref());
2370 assert_eq!(metadata_kp.get(&user), Some(&"admin".to_string()));
2371
2372 let user_no_metadata = TestUser {
2374 name: "Bob".to_string(),
2375 age: 25,
2376 metadata: None,
2377 address: None,
2378 };
2379 assert_eq!(metadata_kp.get(&user_no_metadata), None);
2380
2381 let user_with_address = TestUser {
2383 name: "Charlie".to_string(),
2384 age: 35,
2385 metadata: None,
2386 address: Some(TestAddress {
2387 street: "789 Pine Rd".to_string(),
2388 city: "Paris".to_string(),
2389 country: None,
2390 }),
2391 };
2392
2393 let street_kp = opt_keypath!(|u: &TestUser| u.address.as_ref().map(|a| &a.street));
2394 assert_eq!(street_kp.get(&user_with_address), Some(&"789 Pine Rd".to_string()));
2395
2396 let user_with_country = TestUser {
2398 name: "David".to_string(),
2399 age: 40,
2400 metadata: None,
2401 address: Some(TestAddress {
2402 street: "321 Elm St".to_string(),
2403 city: "Tokyo".to_string(),
2404 country: Some(TestCountry {
2405 name: "Japan".to_string(),
2406 }),
2407 }),
2408 };
2409
2410 let country_name_kp = opt_keypath!(|u: &TestUser| u.address.as_ref().and_then(|a| a.country.as_ref().map(|c| &c.name)));
2411 assert_eq!(country_name_kp.get(&user_with_country), Some(&"Japan".to_string()));
2412
2413 let metadata_kp2 = opt_keypath!(|u: &TestUser| u.metadata.as_ref());
2415 assert_eq!(metadata_kp2.get(&user), Some(&"admin".to_string()));
2416 }
2417
2418 #[test]
2419 fn test_writable_keypath_macro() {
2420 let mut user = TestUser {
2421 name: "Alice".to_string(),
2422 age: 30,
2423 metadata: None,
2424 address: None,
2425 };
2426
2427 let name_kp = writable_keypath!(|u: &mut TestUser| &mut u.name);
2429 *name_kp.get_mut(&mut user) = "Bob".to_string();
2430 assert_eq!(user.name, "Bob");
2431
2432 let mut user_with_address = TestUser {
2434 name: "Charlie".to_string(),
2435 age: 25,
2436 metadata: None,
2437 address: Some(TestAddress {
2438 street: "123 Main St".to_string(),
2439 city: "New York".to_string(),
2440 country: None,
2441 }),
2442 };
2443
2444 let street_kp = writable_keypath!(|u: &mut TestUser| &mut u.address.as_mut().unwrap().street);
2445 *street_kp.get_mut(&mut user_with_address) = "456 Oak Ave".to_string();
2446 assert_eq!(user_with_address.address.as_ref().unwrap().street, "456 Oak Ave");
2447
2448 let mut user_with_country = TestUser {
2450 name: "David".to_string(),
2451 age: 35,
2452 metadata: None,
2453 address: Some(TestAddress {
2454 street: "789 Pine Rd".to_string(),
2455 city: "London".to_string(),
2456 country: Some(TestCountry {
2457 name: "UK".to_string(),
2458 }),
2459 }),
2460 };
2461
2462 let country_name_kp = writable_keypath!(|u: &mut TestUser| &mut u.address.as_mut().unwrap().country.as_mut().unwrap().name);
2463 *country_name_kp.get_mut(&mut user_with_country) = "United Kingdom".to_string();
2464 assert_eq!(user_with_country.address.as_ref().unwrap().country.as_ref().unwrap().name, "United Kingdom");
2465
2466 let age_kp = writable_keypath!(|u: &mut TestUser| &mut u.age);
2468 *age_kp.get_mut(&mut user) = 31;
2469 assert_eq!(user.age, 31);
2470 }
2471
2472 #[test]
2473 fn test_writable_opt_keypath_macro() {
2474 let mut user = TestUser {
2475 name: "Alice".to_string(),
2476 age: 30,
2477 metadata: Some("user".to_string()),
2478 address: None,
2479 };
2480
2481 let metadata_kp = writable_opt_keypath!(|u: &mut TestUser| u.metadata.as_mut());
2483 if let Some(metadata) = metadata_kp.get_mut(&mut user) {
2484 *metadata = "admin".to_string();
2485 }
2486 assert_eq!(user.metadata, Some("admin".to_string()));
2487
2488 let mut user_no_metadata = TestUser {
2490 name: "Bob".to_string(),
2491 age: 25,
2492 metadata: None,
2493 address: None,
2494 };
2495 assert_eq!(metadata_kp.get_mut(&mut user_no_metadata), None);
2496
2497 let mut user_with_address = TestUser {
2499 name: "Charlie".to_string(),
2500 age: 35,
2501 metadata: None,
2502 address: Some(TestAddress {
2503 street: "123 Main St".to_string(),
2504 city: "New York".to_string(),
2505 country: None,
2506 }),
2507 };
2508
2509 let street_kp = writable_opt_keypath!(|u: &mut TestUser| u.address.as_mut().map(|a| &mut a.street));
2510 if let Some(street) = street_kp.get_mut(&mut user_with_address) {
2511 *street = "456 Oak Ave".to_string();
2512 }
2513 assert_eq!(user_with_address.address.as_ref().unwrap().street, "456 Oak Ave");
2514
2515 let mut user_with_country = TestUser {
2517 name: "David".to_string(),
2518 age: 40,
2519 metadata: None,
2520 address: Some(TestAddress {
2521 street: "789 Pine Rd".to_string(),
2522 city: "Tokyo".to_string(),
2523 country: Some(TestCountry {
2524 name: "Japan".to_string(),
2525 }),
2526 }),
2527 };
2528
2529 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)));
2530 if let Some(country_name) = country_name_kp.get_mut(&mut user_with_country) {
2531 *country_name = "Nippon".to_string();
2532 }
2533 assert_eq!(user_with_country.address.as_ref().unwrap().country.as_ref().unwrap().name, "Nippon");
2534
2535 let metadata_kp2 = writable_opt_keypath!(|u: &mut TestUser| u.metadata.as_mut());
2537 if let Some(metadata) = metadata_kp2.get_mut(&mut user) {
2538 *metadata = "super_admin".to_string();
2539 }
2540 assert_eq!(user.metadata, Some("super_admin".to_string()));
2541 }
2542}
2543
2544pub trait WithContainer<Root, Value> {
2550 fn with_arc<F, R>(&self, arc: &Arc<Root>, f: F) -> R
2552 where
2553 F: FnOnce(&Value) -> R;
2554
2555 fn with_box<F, R>(&self, boxed: &Box<Root>, f: F) -> R
2557 where
2558 F: FnOnce(&Value) -> R;
2559
2560 fn with_box_mut<F, R>(&self, boxed: &mut Box<Root>, f: F) -> R
2562 where
2563 F: FnOnce(&mut Value) -> R;
2564
2565 fn with_rc<F, R>(&self, rc: &Rc<Root>, f: F) -> R
2567 where
2568 F: FnOnce(&Value) -> R;
2569
2570 fn with_result<F, R, E>(&self, result: &Result<Root, E>, f: F) -> Option<R>
2572 where
2573 F: FnOnce(&Value) -> R;
2574
2575 fn with_result_mut<F, R, E>(&self, result: &mut Result<Root, E>, f: F) -> Option<R>
2577 where
2578 F: FnOnce(&mut Value) -> R;
2579
2580 fn with_option<F, R>(&self, option: &Option<Root>, f: F) -> Option<R>
2582 where
2583 F: FnOnce(&Value) -> R;
2584
2585 fn with_option_mut<F, R>(&self, option: &mut Option<Root>, f: F) -> Option<R>
2587 where
2588 F: FnOnce(&mut Value) -> R;
2589
2590 fn with_refcell<F, R>(&self, refcell: &RefCell<Root>, f: F) -> Option<R>
2592 where
2593 F: FnOnce(&Value) -> R;
2594
2595 fn with_refcell_mut<F, R>(&self, refcell: &RefCell<Root>, f: F) -> Option<R>
2597 where
2598 F: FnOnce(&mut Value) -> R;
2599
2600 #[cfg(feature = "tagged")]
2601 fn with_tagged<F, R, Tag>(&self, tagged: &Tagged<Root, Tag>, f: F) -> R
2603 where
2604 Tagged<Root, Tag>: std::ops::Deref<Target = Root>,
2605 F: FnOnce(&Value) -> R;
2606
2607 fn with_mutex<F, R>(&self, mutex: &Mutex<Root>, f: F) -> Option<R>
2609 where
2610 F: FnOnce(&Value) -> R;
2611
2612 fn with_mutex_mut<F, R>(&self, mutex: &mut Mutex<Root>, f: F) -> Option<R>
2614 where
2615 F: FnOnce(&mut Value) -> R;
2616
2617 fn with_rwlock<F, R>(&self, rwlock: &RwLock<Root>, f: F) -> Option<R>
2619 where
2620 F: FnOnce(&Value) -> R;
2621
2622 fn with_rwlock_mut<F, R>(&self, rwlock: &mut RwLock<Root>, f: F) -> Option<R>
2624 where
2625 F: FnOnce(&mut Value) -> R;
2626
2627 fn with_arc_rwlock<F, R>(&self, arc_rwlock: &Arc<RwLock<Root>>, f: F) -> Option<R>
2629 where
2630 F: FnOnce(&Value) -> R;
2631
2632 fn with_arc_rwlock_mut<F, R>(&self, arc_rwlock: &Arc<RwLock<Root>>, f: F) -> Option<R>
2634 where
2635 F: FnOnce(&mut Value) -> R;
2636}
2637
2638impl<Root, Value, F> WithContainer<Root, Value> for KeyPath<Root, Value, F>
2640where
2641 F: for<'r> Fn(&'r Root) -> &'r Value + Clone,
2642{
2643 fn with_arc<Callback, R>(&self, arc: &Arc<Root>, f: Callback) -> R
2644 where
2645 Callback: FnOnce(&Value) -> R,
2646 {
2647 self.with_arc(arc, f)
2648 }
2649
2650 fn with_box<Callback, R>(&self, boxed: &Box<Root>, f: Callback) -> R
2651 where
2652 Callback: FnOnce(&Value) -> R,
2653 {
2654 self.with_box(boxed, f)
2655 }
2656
2657 fn with_box_mut<Callback, R>(&self, _boxed: &mut Box<Root>, _f: Callback) -> R
2658 where
2659 Callback: FnOnce(&mut Value) -> R,
2660 {
2661 eprintln!("[DEBUG] KeyPath does not support mutable access - use WritableKeyPath instead");
2662 unreachable!("KeyPath does not support mutable access - use WritableKeyPath instead")
2663 }
2664
2665 fn with_rc<Callback, R>(&self, rc: &Rc<Root>, f: Callback) -> R
2666 where
2667 Callback: FnOnce(&Value) -> R,
2668 {
2669 self.with_rc(rc, f)
2670 }
2671
2672 fn with_result<Callback, R, E>(&self, result: &Result<Root, E>, f: Callback) -> Option<R>
2673 where
2674 Callback: FnOnce(&Value) -> R,
2675 {
2676 self.with_result(result, f)
2677 }
2678
2679 fn with_result_mut<Callback, R, E>(&self, _result: &mut Result<Root, E>, _f: Callback) -> Option<R>
2680 where
2681 Callback: FnOnce(&mut Value) -> R,
2682 {
2683 None
2684 }
2685
2686 fn with_option<Callback, R>(&self, option: &Option<Root>, f: Callback) -> Option<R>
2687 where
2688 Callback: FnOnce(&Value) -> R,
2689 {
2690 self.with_option(option, f)
2691 }
2692
2693 fn with_option_mut<Callback, R>(&self, _option: &mut Option<Root>, _f: Callback) -> Option<R>
2694 where
2695 Callback: FnOnce(&mut Value) -> R,
2696 {
2697 None
2698 }
2699
2700 fn with_refcell<Callback, R>(&self, refcell: &RefCell<Root>, f: Callback) -> Option<R>
2701 where
2702 Callback: FnOnce(&Value) -> R,
2703 {
2704 self.with_refcell(refcell, f)
2705 }
2706
2707 fn with_refcell_mut<Callback, R>(&self, _refcell: &RefCell<Root>, _f: Callback) -> Option<R>
2708 where
2709 Callback: FnOnce(&mut Value) -> R,
2710 {
2711 None
2712 }
2713
2714 #[cfg(feature = "tagged")]
2715 fn with_tagged<Tag, Callback, R>(&self, tagged: &Tagged<Root, Tag>, f: Callback) -> R
2716 where
2717 Tagged<Root, Tag>: std::ops::Deref<Target = Root>,
2718 Callback: FnOnce(&Value) -> R,
2719 {
2720 self.with_tagged(tagged, f)
2721 }
2722
2723 fn with_mutex<Callback, R>(&self, mutex: &Mutex<Root>, f: Callback) -> Option<R>
2724 where
2725 Callback: FnOnce(&Value) -> R,
2726 {
2727 self.with_mutex(mutex, f)
2728 }
2729
2730 fn with_mutex_mut<Callback, R>(&self, _mutex: &mut Mutex<Root>, _f: Callback) -> Option<R>
2731 where
2732 Callback: FnOnce(&mut Value) -> R,
2733 {
2734 None
2735 }
2736
2737 fn with_rwlock<Callback, R>(&self, rwlock: &RwLock<Root>, f: Callback) -> Option<R>
2738 where
2739 Callback: FnOnce(&Value) -> R,
2740 {
2741 self.with_rwlock(rwlock, f)
2742 }
2743
2744 fn with_rwlock_mut<Callback, R>(&self, _rwlock: &mut RwLock<Root>, _f: Callback) -> Option<R>
2745 where
2746 Callback: FnOnce(&mut Value) -> R,
2747 {
2748 None
2749 }
2750
2751 fn with_arc_rwlock<Callback, R>(&self, arc_rwlock: &Arc<RwLock<Root>>, f: Callback) -> Option<R>
2752 where
2753 Callback: FnOnce(&Value) -> R,
2754 {
2755 self.with_arc_rwlock(arc_rwlock, f)
2756 }
2757
2758 fn with_arc_rwlock_mut<Callback, R>(&self, _arc_rwlock: &Arc<RwLock<Root>>, _f: Callback) -> Option<R>
2759 where
2760 Callback: FnOnce(&mut Value) -> R,
2761 {
2762 None
2763 }
2764}
2765
2766impl<Root, Value, F> WithContainer<Root, Value> for OptionalKeyPath<Root, Value, F>
2768where
2769 F: for<'r> Fn(&'r Root) -> Option<&'r Value> + Clone,
2770{
2771 fn with_arc<Callback, R>(&self, arc: &Arc<Root>, f: Callback) -> R
2772 where
2773 Callback: FnOnce(&Value) -> R,
2774 {
2775 self.with_arc(arc, f)
2776 }
2777
2778 fn with_box<Callback, R>(&self, boxed: &Box<Root>, f: Callback) -> R
2779 where
2780 Callback: FnOnce(&Value) -> R,
2781 {
2782 self.with_box(boxed, f)
2783 }
2784
2785 fn with_box_mut<Callback, R>(&self, _boxed: &mut Box<Root>, _f: Callback) -> R
2786 where
2787 Callback: FnOnce(&mut Value) -> R,
2788 {
2789 eprintln!("[DEBUG] OptionalKeyPath does not support mutable access - use WritableOptionalKeyPath instead");
2790 unreachable!("OptionalKeyPath does not support mutable access - use WritableOptionalKeyPath instead")
2791 }
2792
2793 fn with_rc<Callback, R>(&self, rc: &Rc<Root>, f: Callback) -> R
2794 where
2795 Callback: FnOnce(&Value) -> R,
2796 {
2797 self.with_rc(rc, f)
2798 }
2799
2800 fn with_result<Callback, R, E>(&self, result: &Result<Root, E>, f: Callback) -> Option<R>
2801 where
2802 Callback: FnOnce(&Value) -> R,
2803 {
2804 self.with_result(result, f)
2805 }
2806
2807 fn with_result_mut<Callback, R, E>(&self, _result: &mut Result<Root, E>, _f: Callback) -> Option<R>
2808 where
2809 Callback: FnOnce(&mut Value) -> R,
2810 {
2811 None }
2813
2814 fn with_option<Callback, R>(&self, option: &Option<Root>, f: Callback) -> Option<R>
2815 where
2816 Callback: FnOnce(&Value) -> R,
2817 {
2818 self.with_option(option, f)
2819 }
2820
2821 fn with_option_mut<Callback, R>(&self, _option: &mut Option<Root>, _f: Callback) -> Option<R>
2822 where
2823 Callback: FnOnce(&mut Value) -> R,
2824 {
2825 None }
2827
2828 fn with_refcell<Callback, R>(&self, refcell: &RefCell<Root>, f: Callback) -> Option<R>
2829 where
2830 Callback: FnOnce(&Value) -> R,
2831 {
2832 self.with_refcell(refcell, f)
2833 }
2834
2835 fn with_refcell_mut<Callback, R>(&self, _refcell: &RefCell<Root>, _f: Callback) -> Option<R>
2836 where
2837 Callback: FnOnce(&mut Value) -> R,
2838 {
2839 None }
2841
2842 #[cfg(feature = "tagged")]
2843 fn with_tagged<Tag, Callback, R>(&self, tagged: &Tagged<Root, Tag>, f: Callback) -> R
2844 where
2845 Tagged<Root, Tag>: std::ops::Deref<Target = Root>,
2846 Callback: FnOnce(&Value) -> R,
2847 {
2848 self.with_tagged(tagged, f)
2849 }
2850
2851 fn with_mutex<Callback, R>(&self, mutex: &Mutex<Root>, f: Callback) -> Option<R>
2852 where
2853 Callback: FnOnce(&Value) -> R,
2854 {
2855 self.with_mutex(mutex, f)
2856 }
2857
2858 fn with_mutex_mut<Callback, R>(&self, _mutex: &mut Mutex<Root>, _f: Callback) -> Option<R>
2859 where
2860 Callback: FnOnce(&mut Value) -> R,
2861 {
2862 None }
2864
2865 fn with_rwlock<Callback, R>(&self, rwlock: &RwLock<Root>, f: Callback) -> Option<R>
2866 where
2867 Callback: FnOnce(&Value) -> R,
2868 {
2869 self.with_rwlock(rwlock, f)
2870 }
2871
2872 fn with_rwlock_mut<Callback, R>(&self, _rwlock: &mut RwLock<Root>, _f: Callback) -> Option<R>
2873 where
2874 Callback: FnOnce(&mut Value) -> R,
2875 {
2876 None }
2878
2879 fn with_arc_rwlock<Callback, R>(&self, arc_rwlock: &Arc<RwLock<Root>>, f: Callback) -> Option<R>
2880 where
2881 Callback: FnOnce(&Value) -> R,
2882 {
2883 self.with_arc_rwlock(arc_rwlock, f)
2884 }
2885
2886 fn with_arc_rwlock_mut<Callback, R>(&self, _arc_rwlock: &Arc<RwLock<Root>>, _f: Callback) -> Option<R>
2887 where
2888 Callback: FnOnce(&mut Value) -> R,
2889 {
2890 None }
2892}
2893
2894impl<Root, Value, F> WithContainer<Root, Value> for WritableKeyPath<Root, Value, F>
2896where
2897 F: for<'r> Fn(&'r mut Root) -> &'r mut Value,
2898{
2899 fn with_arc<Callback, R>(&self, _arc: &Arc<Root>, _f: Callback) -> R
2900 where
2901 Callback: FnOnce(&Value) -> R,
2902 {
2903 eprintln!("[DEBUG] WritableKeyPath::with_arc requires &mut Arc<Root> or interior mutability");
2906 unreachable!("WritableKeyPath::with_arc requires &mut Arc<Root> or interior mutability")
2907 }
2908
2909 fn with_box<Callback, R>(&self, boxed: &Box<Root>, f: Callback) -> R
2910 where
2911 Callback: FnOnce(&Value) -> R,
2912 {
2913 eprintln!("[DEBUG] WritableKeyPath::with_box requires &mut Box<Root> - use with_box_mut instead");
2916 unreachable!("WritableKeyPath::with_box requires &mut Box<Root> - use with_box_mut instead")
2917 }
2918
2919 fn with_box_mut<Callback, R>(&self, boxed: &mut Box<Root>, f: Callback) -> R
2920 where
2921 Callback: FnOnce(&mut Value) -> R,
2922 {
2923 let value = self.get_mut(boxed.as_mut());
2924 f(value)
2925 }
2926
2927 fn with_rc<Callback, R>(&self, _rc: &Rc<Root>, _f: Callback) -> R
2928 where
2929 Callback: FnOnce(&Value) -> R,
2930 {
2931 eprintln!("[DEBUG] WritableKeyPath::with_rc requires &mut Rc<Root> or interior mutability");
2934 unreachable!("WritableKeyPath::with_rc requires &mut Rc<Root> or interior mutability")
2935 }
2936
2937 fn with_result<Callback, R, E>(&self, _result: &Result<Root, E>, _f: Callback) -> Option<R>
2938 where
2939 Callback: FnOnce(&Value) -> R,
2940 {
2941 None
2944 }
2945
2946 fn with_result_mut<Callback, R, E>(&self, result: &mut Result<Root, E>, f: Callback) -> Option<R>
2947 where
2948 Callback: FnOnce(&mut Value) -> R,
2949 {
2950 result.as_mut().ok().map(|root| {
2951 let value = self.get_mut(root);
2952 f(value)
2953 })
2954 }
2955
2956 fn with_option<Callback, R>(&self, _option: &Option<Root>, _f: Callback) -> Option<R>
2957 where
2958 Callback: FnOnce(&Value) -> R,
2959 {
2960 None
2963 }
2964
2965 fn with_option_mut<Callback, R>(&self, option: &mut Option<Root>, f: Callback) -> Option<R>
2966 where
2967 Callback: FnOnce(&mut Value) -> R,
2968 {
2969 option.as_mut().map(|root| {
2970 let value = self.get_mut(root);
2971 f(value)
2972 })
2973 }
2974
2975 fn with_refcell<Callback, R>(&self, refcell: &RefCell<Root>, f: Callback) -> Option<R>
2976 where
2977 Callback: FnOnce(&Value) -> R,
2978 {
2979 None
2982 }
2983
2984 fn with_refcell_mut<Callback, R>(&self, refcell: &RefCell<Root>, f: Callback) -> Option<R>
2985 where
2986 Callback: FnOnce(&mut Value) -> R,
2987 {
2988 refcell.try_borrow_mut().ok().map(|mut borrow| {
2989 let value = self.get_mut(&mut *borrow);
2990 f(value)
2991 })
2992 }
2993
2994 #[cfg(feature = "tagged")]
2995 fn with_tagged<Tag, Callback, R>(&self, _tagged: &Tagged<Root, Tag>, _f: Callback) -> R
2996 where
2997 Tagged<Root, Tag>: std::ops::Deref<Target = Root>,
2998 Callback: FnOnce(&Value) -> R,
2999 {
3000 eprintln!("[DEBUG] WritableKeyPath::with_tagged requires &mut Tagged<Root, Tag> or interior mutability");
3003 unreachable!("WritableKeyPath::with_tagged requires &mut Tagged<Root, Tag> or interior mutability")
3004 }
3005
3006 fn with_mutex<Callback, R>(&self, mutex: &Mutex<Root>, f: Callback) -> Option<R>
3007 where
3008 Callback: FnOnce(&Value) -> R,
3009 {
3010 mutex.lock().ok().map(|mut guard| {
3011 let value = self.get_mut(&mut *guard);
3012 f(value)
3013 })
3014 }
3015
3016 fn with_mutex_mut<Callback, R>(&self, mutex: &mut Mutex<Root>, f: Callback) -> Option<R>
3017 where
3018 Callback: FnOnce(&mut Value) -> R,
3019 {
3020 mutex.get_mut().ok().map(|root| {
3022 let value = self.get_mut(root);
3023 f(value)
3024 })
3025 }
3026
3027 fn with_rwlock<Callback, R>(&self, rwlock: &RwLock<Root>, f: Callback) -> Option<R>
3028 where
3029 Callback: FnOnce(&Value) -> R,
3030 {
3031 None
3034 }
3035
3036 fn with_rwlock_mut<Callback, R>(&self, rwlock: &mut RwLock<Root>, f: Callback) -> Option<R>
3037 where
3038 Callback: FnOnce(&mut Value) -> R,
3039 {
3040 rwlock.get_mut().ok().map(|root| {
3042 let value = self.get_mut(root);
3043 f(value)
3044 })
3045 }
3046
3047 fn with_arc_rwlock<Callback, R>(&self, arc_rwlock: &Arc<RwLock<Root>>, f: Callback) -> Option<R>
3048 where
3049 Callback: FnOnce(&Value) -> R,
3050 {
3051 None
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 arc_rwlock.write().ok().map(|mut guard| {
3061 let value = self.get_mut(&mut *guard);
3062 f(value)
3063 })
3064 }
3065}
3066
3067impl<Root, Value, F> WithContainer<Root, Value> for WritableOptionalKeyPath<Root, Value, F>
3069where
3070 F: for<'r> Fn(&'r mut Root) -> Option<&'r mut Value>,
3071{
3072 fn with_arc<Callback, R>(&self, _arc: &Arc<Root>, _f: Callback) -> R
3073 where
3074 Callback: FnOnce(&Value) -> R,
3075 {
3076 eprintln!("[DEBUG] WritableOptionalKeyPath::with_arc requires &mut Arc<Root> or interior mutability");
3079 unreachable!("WritableOptionalKeyPath::with_arc requires &mut Arc<Root> or interior mutability")
3080 }
3081
3082 fn with_box<Callback, R>(&self, _boxed: &Box<Root>, _f: Callback) -> R
3083 where
3084 Callback: FnOnce(&Value) -> R,
3085 {
3086 eprintln!("[DEBUG] WritableOptionalKeyPath::with_box requires &mut Box<Root> - use with_box_mut instead");
3089 unreachable!("WritableOptionalKeyPath::with_box requires &mut Box<Root> - use with_box_mut instead")
3090 }
3091
3092 fn with_box_mut<Callback, R>(&self, boxed: &mut Box<Root>, f: Callback) -> R
3093 where
3094 Callback: FnOnce(&mut Value) -> R,
3095 {
3096 if let Some(value) = self.get_mut(boxed.as_mut()) {
3097 f(value)
3098 } else {
3099 eprintln!("[DEBUG] WritableOptionalKeyPath failed to get value from Box");
3100 unreachable!("WritableOptionalKeyPath failed to get value from Box")
3101 }
3102 }
3103
3104 fn with_rc<Callback, R>(&self, _rc: &Rc<Root>, _f: Callback) -> R
3105 where
3106 Callback: FnOnce(&Value) -> R,
3107 {
3108 eprintln!("[DEBUG] WritableOptionalKeyPath::with_rc requires &mut Rc<Root> or interior mutability");
3111 unreachable!("WritableOptionalKeyPath::with_rc requires &mut Rc<Root> or interior mutability")
3112 }
3113
3114 fn with_result<Callback, R, E>(&self, _result: &Result<Root, E>, _f: Callback) -> Option<R>
3115 where
3116 Callback: FnOnce(&Value) -> R,
3117 {
3118 None
3121 }
3122
3123 fn with_result_mut<Callback, R, E>(&self, result: &mut Result<Root, E>, f: Callback) -> Option<R>
3124 where
3125 Callback: FnOnce(&mut Value) -> R,
3126 {
3127 result.as_mut().ok().and_then(|root| {
3128 self.get_mut(root).map(|value| f(value))
3129 })
3130 }
3131
3132 fn with_option<Callback, R>(&self, _option: &Option<Root>, _f: Callback) -> Option<R>
3133 where
3134 Callback: FnOnce(&Value) -> R,
3135 {
3136 None
3139 }
3140
3141 fn with_option_mut<Callback, R>(&self, option: &mut Option<Root>, f: Callback) -> Option<R>
3142 where
3143 Callback: FnOnce(&mut Value) -> R,
3144 {
3145 option.as_mut().and_then(|root| {
3146 self.get_mut(root).map(|value| f(value))
3147 })
3148 }
3149
3150 fn with_refcell<Callback, R>(&self, _refcell: &RefCell<Root>, _f: Callback) -> Option<R>
3151 where
3152 Callback: FnOnce(&Value) -> R,
3153 {
3154 None
3157 }
3158
3159 fn with_refcell_mut<Callback, R>(&self, refcell: &RefCell<Root>, f: Callback) -> Option<R>
3160 where
3161 Callback: FnOnce(&mut Value) -> R,
3162 {
3163 refcell.try_borrow_mut().ok().and_then(|mut borrow| {
3164 self.get_mut(&mut *borrow).map(|value| f(value))
3165 })
3166 }
3167
3168 #[cfg(feature = "tagged")]
3169 fn with_tagged<Tag, Callback, R>(&self, _tagged: &Tagged<Root, Tag>, _f: Callback) -> R
3170 where
3171 Tagged<Root, Tag>: std::ops::Deref<Target = Root>,
3172 Callback: FnOnce(&Value) -> R,
3173 {
3174 eprintln!("[DEBUG] WritableOptionalKeyPath::with_tagged requires &mut Tagged<Root, Tag> or interior mutability");
3177 unreachable!("WritableOptionalKeyPath::with_tagged requires &mut Tagged<Root, Tag> or interior mutability")
3178 }
3179
3180 fn with_mutex<Callback, R>(&self, mutex: &Mutex<Root>, f: Callback) -> Option<R>
3181 where
3182 Callback: FnOnce(&Value) -> R,
3183 {
3184 mutex.lock().ok().and_then(|mut guard| {
3185 self.get_mut(&mut *guard).map(|value| f(value))
3186 })
3187 }
3188
3189 fn with_mutex_mut<Callback, R>(&self, mutex: &mut Mutex<Root>, f: Callback) -> Option<R>
3190 where
3191 Callback: FnOnce(&mut Value) -> R,
3192 {
3193 mutex.get_mut().ok().and_then(|root| {
3195 self.get_mut(root).map(|value| f(value))
3196 })
3197 }
3198
3199 fn with_rwlock<Callback, R>(&self, _rwlock: &RwLock<Root>, _f: Callback) -> Option<R>
3200 where
3201 Callback: FnOnce(&Value) -> R,
3202 {
3203 None
3206 }
3207
3208 fn with_rwlock_mut<Callback, R>(&self, rwlock: &mut RwLock<Root>, f: Callback) -> Option<R>
3209 where
3210 Callback: FnOnce(&mut Value) -> R,
3211 {
3212 rwlock.get_mut().ok().and_then(|root| {
3214 self.get_mut(root).map(|value| f(value))
3215 })
3216 }
3217
3218 fn with_arc_rwlock<Callback, R>(&self, _arc_rwlock: &Arc<RwLock<Root>>, _f: Callback) -> Option<R>
3219 where
3220 Callback: FnOnce(&Value) -> R,
3221 {
3222 None
3225 }
3226
3227 fn with_arc_rwlock_mut<Callback, R>(&self, arc_rwlock: &Arc<RwLock<Root>>, f: Callback) -> Option<R>
3228 where
3229 Callback: FnOnce(&mut Value) -> R,
3230 {
3231 arc_rwlock.write().ok().and_then(|mut guard| {
3232 self.get_mut(&mut *guard).map(|value| f(value))
3233 })
3234 }
3235}