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 for_option(self) -> WritableOptionalKeyPath<Option<Root>, Value, impl for<'r> Fn(&'r mut Option<Root>) -> Option<&'r mut Value> + 'static>
1108 where
1109 F: 'static,
1110 Root: 'static,
1111 Value: 'static,
1112 {
1113 let getter = self.getter;
1114
1115 WritableOptionalKeyPath {
1116 getter: move |option: &mut Option<Root>| {
1117 option.as_mut().map(|root| getter(root))
1118 },
1119 _phantom: PhantomData,
1120 }
1121 }
1122
1123 pub fn to_optional(self) -> WritableOptionalKeyPath<Root, Value, impl for<'r> Fn(&'r mut Root) -> Option<&'r mut Value> + 'static>
1126 where
1127 F: 'static,
1128 {
1129 let getter = self.getter;
1130 WritableOptionalKeyPath::new(move |root: &mut Root| Some(getter(root)))
1131 }
1132
1133 pub fn for_box<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_arc<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 for_rc<Target>(self) -> WritableKeyPath<Root, Target, impl for<'r> Fn(&'r mut Root) -> &'r mut Target + 'static>
1172 where
1173 Value: std::ops::DerefMut<Target = Target>,
1174 F: 'static,
1175 Value: 'static,
1176 {
1177 let getter = self.getter;
1178
1179 WritableKeyPath {
1180 getter: move |root: &mut Root| {
1181 getter(root).deref_mut()
1182 },
1183 _phantom: PhantomData,
1184 }
1185 }
1186
1187 pub fn with_box_mut<Callback, R>(&self, boxed: &mut Box<Root>, f: Callback) -> R
1189 where
1190 F: Clone,
1191 Callback: FnOnce(&mut Value) -> R,
1192 {
1193 let value = self.get_mut(boxed);
1194 f(value)
1195 }
1196
1197 pub fn with_result_mut<Callback, R, E>(&self, result: &mut Result<Root, E>, f: Callback) -> Option<R>
1199 where
1200 F: Clone,
1201 Callback: FnOnce(&mut Value) -> R,
1202 {
1203 result.as_mut().ok().map(|root| {
1204 let value = self.get_mut(root);
1205 f(value)
1206 })
1207 }
1208
1209 pub fn with_option_mut<Callback, R>(&self, option: &mut Option<Root>, f: Callback) -> Option<R>
1211 where
1212 F: Clone,
1213 Callback: FnOnce(&mut Value) -> R,
1214 {
1215 option.as_mut().map(|root| {
1216 let value = self.get_mut(root);
1217 f(value)
1218 })
1219 }
1220
1221 pub fn with_refcell_mut<Callback, R>(&self, refcell: &RefCell<Root>, f: Callback) -> Option<R>
1223 where
1224 F: Clone,
1225 Callback: FnOnce(&mut Value) -> R,
1226 {
1227 refcell.try_borrow_mut().ok().map(|mut borrow| {
1228 let value = self.get_mut(&mut *borrow);
1229 f(value)
1230 })
1231 }
1232
1233 pub fn with_mutex_mut<Callback, R>(&self, mutex: &mut Mutex<Root>, f: Callback) -> Option<R>
1235 where
1236 F: Clone,
1237 Callback: FnOnce(&mut Value) -> R,
1238 {
1239 mutex.get_mut().ok().map(|root| {
1240 let value = self.get_mut(root);
1241 f(value)
1242 })
1243 }
1244
1245 pub fn with_rwlock_mut<Callback, R>(&self, rwlock: &mut RwLock<Root>, f: Callback) -> Option<R>
1247 where
1248 F: Clone,
1249 Callback: FnOnce(&mut Value) -> R,
1250 {
1251 rwlock.write().ok().map(|mut guard| {
1252 let value = self.get_mut(&mut *guard);
1253 f(value)
1254 })
1255 }
1256
1257 pub fn iter_mut<'r, T>(&self, root: &'r mut Root) -> Option<std::slice::IterMut<'r, T>>
1260 where
1261 Value: AsMut<[T]> + 'r,
1262 {
1263 let value_ref: &'r mut Value = self.get_mut(root);
1264 Some(value_ref.as_mut().iter_mut())
1265 }
1266}
1267
1268#[derive(Clone)]
1270pub struct WritableOptionalKeyPath<Root, Value, F>
1271where
1272 F: for<'r> Fn(&'r mut Root) -> Option<&'r mut Value>,
1273{
1274 getter: F,
1275 _phantom: PhantomData<(Root, Value)>,
1276}
1277
1278impl<Root, Value, F> WritableOptionalKeyPath<Root, Value, F>
1279where
1280 F: for<'r> Fn(&'r mut Root) -> Option<&'r mut Value>,
1281{
1282 pub fn new(getter: F) -> Self {
1283 Self {
1284 getter,
1285 _phantom: PhantomData,
1286 }
1287 }
1288
1289 pub fn get_mut<'r>(&self, root: &'r mut Root) -> Option<&'r mut Value> {
1290 (self.getter)(root)
1291 }
1292
1293 pub fn for_option(self) -> WritableOptionalKeyPath<Option<Root>, Value, impl for<'r> Fn(&'r mut Option<Root>) -> Option<&'r mut Value> + 'static>
1296 where
1297 F: 'static,
1298 Root: 'static,
1299 Value: 'static,
1300 {
1301 let getter = self.getter;
1302
1303 WritableOptionalKeyPath {
1304 getter: move |option: &mut Option<Root>| {
1305 option.as_mut().and_then(|root| getter(root))
1306 },
1307 _phantom: PhantomData,
1308 }
1309 }
1310
1311 pub fn then<SubValue, G>(
1313 self,
1314 next: WritableOptionalKeyPath<Value, SubValue, G>,
1315 ) -> WritableOptionalKeyPath<Root, SubValue, impl for<'r> Fn(&'r mut Root) -> Option<&'r mut SubValue>>
1316 where
1317 G: for<'r> Fn(&'r mut Value) -> Option<&'r mut SubValue>,
1318 F: 'static,
1319 G: 'static,
1320 Value: 'static,
1321 {
1322 let first = self.getter;
1323 let second = next.getter;
1324
1325 WritableOptionalKeyPath::new(move |root: &mut Root| {
1326 first(root).and_then(|value| second(value))
1327 })
1328 }
1329
1330 pub fn for_box<Target>(self) -> WritableOptionalKeyPath<Root, Target, impl for<'r> Fn(&'r mut Root) -> Option<&'r mut Target> + 'static>
1333 where
1334 Value: std::ops::DerefMut<Target = Target>,
1335 F: 'static,
1336 Value: 'static,
1337 {
1338 let getter = self.getter;
1339
1340 WritableOptionalKeyPath {
1341 getter: move |root: &mut Root| {
1342 getter(root).map(|boxed| boxed.deref_mut())
1343 },
1344 _phantom: PhantomData,
1345 }
1346 }
1347
1348 pub fn for_arc<Target>(self) -> WritableOptionalKeyPath<Root, Target, impl for<'r> Fn(&'r mut Root) -> Option<&'r mut Target> + 'static>
1350 where
1351 Value: std::ops::DerefMut<Target = Target>,
1352 F: 'static,
1353 Value: 'static,
1354 {
1355 let getter = self.getter;
1356
1357 WritableOptionalKeyPath {
1358 getter: move |root: &mut Root| {
1359 getter(root).map(|arc| arc.deref_mut())
1360 },
1361 _phantom: PhantomData,
1362 }
1363 }
1364
1365 pub fn for_rc<Target>(self) -> WritableOptionalKeyPath<Root, Target, impl for<'r> Fn(&'r mut Root) -> Option<&'r mut Target> + 'static>
1367 where
1368 Value: std::ops::DerefMut<Target = Target>,
1369 F: 'static,
1370 Value: 'static,
1371 {
1372 let getter = self.getter;
1373
1374 WritableOptionalKeyPath {
1375 getter: move |root: &mut Root| {
1376 getter(root).map(|rc| rc.deref_mut())
1377 },
1378 _phantom: PhantomData,
1379 }
1380 }
1381
1382 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>
1385 where
1386 F: 'static,
1387 Root: 'static,
1388 Value: 'static,
1389 E: 'static,
1390 {
1391 let getter = self.getter;
1392
1393 WritableOptionalKeyPath {
1394 getter: move |result: &mut Result<Root, E>| {
1395 result.as_mut().ok().and_then(|root| getter(root))
1396 },
1397 _phantom: PhantomData,
1398 }
1399 }
1400
1401 pub fn for_box_root(self) -> WritableOptionalKeyPath<Box<Root>, Value, impl for<'r> Fn(&'r mut Box<Root>) -> Option<&'r mut Value> + 'static>
1403 where
1404 Value: Sized,
1405 F: 'static,
1406 Root: 'static,
1407 Value: 'static,
1408 {
1409 let getter = self.getter;
1410
1411 WritableOptionalKeyPath {
1412 getter: move |boxed: &mut Box<Root>| {
1413 getter(boxed.as_mut())
1414 },
1415 _phantom: PhantomData,
1416 }
1417 }
1418
1419 pub fn for_arc_root(self) -> WritableOptionalKeyPath<Arc<Root>, Value, impl for<'r> Fn(&'r mut Arc<Root>) -> Option<&'r mut Value> + 'static>
1421 where
1422 Value: Sized,
1423 F: 'static,
1424 Root: 'static,
1425 Value: 'static,
1426 {
1427 let getter = self.getter;
1428
1429 WritableOptionalKeyPath {
1430 getter: move |arc: &mut Arc<Root>| {
1431 None
1434 },
1435 _phantom: PhantomData,
1436 }
1437 }
1438
1439 pub fn for_rc_root(self) -> WritableOptionalKeyPath<Rc<Root>, Value, impl for<'r> Fn(&'r mut Rc<Root>) -> Option<&'r mut Value> + 'static>
1441 where
1442 Value: Sized,
1443 F: 'static,
1444 Root: 'static,
1445 Value: 'static,
1446 {
1447 let getter = self.getter;
1448
1449 WritableOptionalKeyPath {
1450 getter: move |rc: &mut Rc<Root>| {
1451 None
1454 },
1455 _phantom: PhantomData,
1456 }
1457 }
1458}
1459
1460impl WritableOptionalKeyPath<(), (), fn(&mut ()) -> Option<&mut ()>> {
1462 pub fn for_option_static<T>() -> WritableOptionalKeyPath<Option<T>, T, impl for<'r> Fn(&'r mut Option<T>) -> Option<&'r mut T>> {
1465 WritableOptionalKeyPath::new(|opt: &mut Option<T>| opt.as_mut())
1466 }
1467}
1468
1469pub struct EnumKeyPath<Enum = (), Variant = (), ExtractFn = fn(&()) -> Option<&()>, EmbedFn = fn(()) -> ()>
1477where
1478 ExtractFn: for<'r> Fn(&'r Enum) -> Option<&'r Variant> + 'static,
1479 EmbedFn: Fn(Variant) -> Enum + 'static,
1480{
1481 extractor: OptionalKeyPath<Enum, Variant, ExtractFn>,
1482 embedder: EmbedFn,
1483}
1484
1485impl<Enum, Variant, ExtractFn, EmbedFn> EnumKeyPath<Enum, Variant, ExtractFn, EmbedFn>
1486where
1487 ExtractFn: for<'r> Fn(&'r Enum) -> Option<&'r Variant> + 'static,
1488 EmbedFn: Fn(Variant) -> Enum + 'static,
1489{
1490 pub fn new(
1492 extractor: ExtractFn,
1493 embedder: EmbedFn,
1494 ) -> Self {
1495 Self {
1496 extractor: OptionalKeyPath::new(extractor),
1497 embedder,
1498 }
1499 }
1500
1501 pub fn get<'r>(&self, enum_value: &'r Enum) -> Option<&'r Variant> {
1503 self.extractor.get(enum_value)
1504 }
1505
1506 pub fn embed(&self, value: Variant) -> Enum {
1508 (self.embedder)(value)
1509 }
1510
1511 pub fn as_optional(&self) -> &OptionalKeyPath<Enum, Variant, ExtractFn> {
1513 &self.extractor
1514 }
1515
1516 pub fn to_optional(self) -> OptionalKeyPath<Enum, Variant, ExtractFn> {
1518 self.extractor
1519 }
1520}
1521
1522impl EnumKeyPath {
1524 pub fn readable_enum<Enum, Variant, ExtractFn, EmbedFn>(
1527 embedder: EmbedFn,
1528 extractor: ExtractFn,
1529 ) -> EnumKeyPath<Enum, Variant, ExtractFn, EmbedFn>
1530 where
1531 ExtractFn: for<'r> Fn(&'r Enum) -> Option<&'r Variant> + 'static,
1532 EmbedFn: Fn(Variant) -> Enum + 'static,
1533 {
1534 EnumKeyPath::new(extractor, embedder)
1535 }
1536
1537 pub fn for_variant<Enum, Variant, ExtractFn>(
1539 extractor: ExtractFn
1540 ) -> OptionalKeyPath<Enum, Variant, impl for<'r> Fn(&'r Enum) -> Option<&'r Variant>>
1541 where
1542 ExtractFn: Fn(&Enum) -> Option<&Variant>,
1543 {
1544 OptionalKeyPath::new(extractor)
1545 }
1546
1547 pub fn for_match<Enum, Output, MatchFn>(
1549 matcher: MatchFn
1550 ) -> KeyPath<Enum, Output, impl for<'r> Fn(&'r Enum) -> &'r Output>
1551 where
1552 MatchFn: Fn(&Enum) -> &Output,
1553 {
1554 KeyPath::new(matcher)
1555 }
1556
1557 pub fn for_ok<T, E>() -> OptionalKeyPath<Result<T, E>, T, impl for<'r> Fn(&'r Result<T, E>) -> Option<&'r T>> {
1559 OptionalKeyPath::new(|result: &Result<T, E>| result.as_ref().ok())
1560 }
1561
1562 pub fn for_err<T, E>() -> OptionalKeyPath<Result<T, E>, E, impl for<'r> Fn(&'r Result<T, E>) -> Option<&'r E>> {
1564 OptionalKeyPath::new(|result: &Result<T, E>| result.as_ref().err())
1565 }
1566
1567 pub fn for_some<T>() -> OptionalKeyPath<Option<T>, T, impl for<'r> Fn(&'r Option<T>) -> Option<&'r T>> {
1569 OptionalKeyPath::new(|opt: &Option<T>| opt.as_ref())
1570 }
1571
1572 pub fn for_option<T>() -> OptionalKeyPath<Option<T>, T, impl for<'r> Fn(&'r Option<T>) -> Option<&'r T>> {
1574 OptionalKeyPath::new(|opt: &Option<T>| opt.as_ref())
1575 }
1576
1577 pub fn for_box<T>() -> KeyPath<Box<T>, T, impl for<'r> Fn(&'r Box<T>) -> &'r T> {
1579 KeyPath::new(|b: &Box<T>| b.as_ref())
1580 }
1581
1582 pub fn for_arc<T>() -> KeyPath<Arc<T>, T, impl for<'r> Fn(&'r Arc<T>) -> &'r T> {
1584 KeyPath::new(|arc: &Arc<T>| arc.as_ref())
1585 }
1586
1587 pub fn for_rc<T>() -> KeyPath<std::rc::Rc<T>, T, impl for<'r> Fn(&'r std::rc::Rc<T>) -> &'r T> {
1589 KeyPath::new(|rc: &std::rc::Rc<T>| rc.as_ref())
1590 }
1591
1592 pub fn for_box_mut<T>() -> WritableKeyPath<Box<T>, T, impl for<'r> Fn(&'r mut Box<T>) -> &'r mut T> {
1594 WritableKeyPath::new(|b: &mut Box<T>| b.as_mut())
1595 }
1596
1597 }
1601
1602pub fn variant_of<Enum, Variant, F>(extractor: F) -> OptionalKeyPath<Enum, Variant, F>
1604where
1605 F: for<'r> Fn(&'r Enum) -> Option<&'r Variant>,
1606{
1607 OptionalKeyPath::new(extractor)
1608}
1609
1610#[derive(Clone)]
1626pub struct PartialKeyPath<Root> {
1627 getter: Rc<dyn for<'r> Fn(&'r Root) -> &'r dyn Any>,
1628 value_type_id: TypeId,
1629 _phantom: PhantomData<Root>,
1630}
1631
1632impl<Root> PartialKeyPath<Root> {
1633 pub fn new<Value>(keypath: KeyPath<Root, Value, impl for<'r> Fn(&'r Root) -> &'r Value + 'static>) -> Self
1634 where
1635 Value: Any + 'static,
1636 Root: 'static,
1637 {
1638 let value_type_id = TypeId::of::<Value>();
1639 let getter = Rc::new(keypath.getter);
1640
1641 Self {
1642 getter: Rc::new(move |root: &Root| {
1643 let value: &Value = getter(root);
1644 value as &dyn Any
1645 }),
1646 value_type_id,
1647 _phantom: PhantomData,
1648 }
1649 }
1650
1651 pub fn from<Value>(keypath: KeyPath<Root, Value, impl for<'r> Fn(&'r Root) -> &'r Value + 'static>) -> Self
1654 where
1655 Value: Any + 'static,
1656 Root: 'static,
1657 {
1658 Self::new(keypath)
1659 }
1660
1661 pub fn get<'r>(&self, root: &'r Root) -> &'r dyn Any {
1662 (self.getter)(root)
1663 }
1664
1665 pub fn value_type_id(&self) -> TypeId {
1667 self.value_type_id
1668 }
1669
1670 pub fn get_as<'a, Value: Any>(&self, root: &'a Root) -> Option<&'a Value> {
1672 if self.value_type_id == TypeId::of::<Value>() {
1673 self.get(root).downcast_ref::<Value>()
1674 } else {
1675 None
1676 }
1677 }
1678
1679 pub fn kind_name(&self) -> String {
1682 format!("{:?}", self.value_type_id)
1683 }
1684}
1685
1686#[derive(Clone)]
1693pub struct PartialOptionalKeyPath<Root> {
1694 getter: Rc<dyn for<'r> Fn(&'r Root) -> Option<&'r dyn Any>>,
1695 value_type_id: TypeId,
1696 _phantom: PhantomData<Root>,
1697}
1698
1699impl<Root> PartialOptionalKeyPath<Root> {
1700 pub fn new<Value>(keypath: OptionalKeyPath<Root, Value, impl for<'r> Fn(&'r Root) -> Option<&'r Value> + 'static>) -> Self
1701 where
1702 Value: Any + 'static,
1703 Root: 'static,
1704 {
1705 let value_type_id = TypeId::of::<Value>();
1706 let getter = Rc::new(keypath.getter);
1707
1708 Self {
1709 getter: Rc::new(move |root: &Root| {
1710 getter(root).map(|value: &Value| value as &dyn Any)
1711 }),
1712 value_type_id,
1713 _phantom: PhantomData,
1714 }
1715 }
1716
1717 pub fn get<'r>(&self, root: &'r Root) -> Option<&'r dyn Any> {
1718 (self.getter)(root)
1719 }
1720
1721 pub fn value_type_id(&self) -> TypeId {
1723 self.value_type_id
1724 }
1725
1726 pub fn get_as<'a, Value: Any>(&self, root: &'a Root) -> Option<Option<&'a Value>> {
1728 if self.value_type_id == TypeId::of::<Value>() {
1729 self.get(root).map(|any| any.downcast_ref::<Value>())
1730 } else {
1731 None
1732 }
1733 }
1734
1735 pub fn then<MidValue>(
1739 self,
1740 next: PartialOptionalKeyPath<MidValue>,
1741 ) -> PartialOptionalKeyPath<Root>
1742 where
1743 MidValue: Any + 'static,
1744 Root: 'static,
1745 {
1746 let first = self.getter;
1747 let second = next.getter;
1748 let value_type_id = next.value_type_id;
1749
1750 PartialOptionalKeyPath {
1751 getter: Rc::new(move |root: &Root| {
1752 first(root).and_then(|any| {
1753 if let Some(mid_value) = any.downcast_ref::<MidValue>() {
1754 second(mid_value)
1755 } else {
1756 None
1757 }
1758 })
1759 }),
1760 value_type_id,
1761 _phantom: PhantomData,
1762 }
1763 }
1764}
1765
1766#[derive(Clone)]
1772pub struct PartialWritableKeyPath<Root> {
1773 getter: Rc<dyn for<'r> Fn(&'r mut Root) -> &'r mut dyn Any>,
1774 value_type_id: TypeId,
1775 _phantom: PhantomData<Root>,
1776}
1777
1778impl<Root> PartialWritableKeyPath<Root> {
1779 pub fn new<Value>(keypath: WritableKeyPath<Root, Value, impl for<'r> Fn(&'r mut Root) -> &'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 let value: &mut Value = getter(root);
1790 value as &mut dyn Any
1791 }),
1792 value_type_id,
1793 _phantom: PhantomData,
1794 }
1795 }
1796
1797 pub fn from<Value>(keypath: WritableKeyPath<Root, Value, impl for<'r> Fn(&'r mut Root) -> &'r mut Value + 'static>) -> Self
1800 where
1801 Value: Any + 'static,
1802 Root: 'static,
1803 {
1804 Self::new(keypath)
1805 }
1806
1807 pub fn get_mut<'r>(&self, root: &'r mut Root) -> &'r mut dyn Any {
1808 (self.getter)(root)
1809 }
1810
1811 pub fn value_type_id(&self) -> TypeId {
1813 self.value_type_id
1814 }
1815
1816 pub fn get_mut_as<'a, Value: Any>(&self, root: &'a mut Root) -> Option<&'a mut Value> {
1818 if self.value_type_id == TypeId::of::<Value>() {
1819 self.get_mut(root).downcast_mut::<Value>()
1820 } else {
1821 None
1822 }
1823 }
1824}
1825
1826#[derive(Clone)]
1832pub struct PartialWritableOptionalKeyPath<Root> {
1833 getter: Rc<dyn for<'r> Fn(&'r mut Root) -> Option<&'r mut dyn Any>>,
1834 value_type_id: TypeId,
1835 _phantom: PhantomData<Root>,
1836}
1837
1838impl<Root> PartialWritableOptionalKeyPath<Root> {
1839 pub fn new<Value>(keypath: WritableOptionalKeyPath<Root, Value, impl for<'r> Fn(&'r mut Root) -> Option<&'r mut Value> + 'static>) -> Self
1840 where
1841 Value: Any + 'static,
1842 Root: 'static,
1843 {
1844 let value_type_id = TypeId::of::<Value>();
1845 let getter = Rc::new(keypath.getter);
1846
1847 Self {
1848 getter: Rc::new(move |root: &mut Root| {
1849 getter(root).map(|value: &mut Value| value as &mut dyn Any)
1850 }),
1851 value_type_id,
1852 _phantom: PhantomData,
1853 }
1854 }
1855
1856 pub fn get_mut<'r>(&self, root: &'r mut Root) -> Option<&'r mut dyn Any> {
1857 (self.getter)(root)
1858 }
1859
1860 pub fn value_type_id(&self) -> TypeId {
1862 self.value_type_id
1863 }
1864
1865 pub fn get_mut_as<'a, Value: Any>(&self, root: &'a mut Root) -> Option<Option<&'a mut Value>> {
1867 if self.value_type_id == TypeId::of::<Value>() {
1868 self.get_mut(root).map(|any| any.downcast_mut::<Value>())
1869 } else {
1870 None
1871 }
1872 }
1873}
1874
1875#[derive(Clone)]
1889pub struct AnyKeyPath {
1890 getter: Rc<dyn for<'r> Fn(&'r dyn Any) -> Option<&'r dyn Any>>,
1891 root_type_id: TypeId,
1892 value_type_id: TypeId,
1893}
1894
1895impl AnyKeyPath {
1896 pub fn new<Root, Value>(keypath: OptionalKeyPath<Root, Value, impl for<'r> Fn(&'r Root) -> Option<&'r Value> + 'static>) -> Self
1897 where
1898 Root: Any + 'static,
1899 Value: Any + 'static,
1900 {
1901 let root_type_id = TypeId::of::<Root>();
1902 let value_type_id = TypeId::of::<Value>();
1903 let getter = keypath.getter;
1904
1905 Self {
1906 getter: Rc::new(move |any: &dyn Any| {
1907 if let Some(root) = any.downcast_ref::<Root>() {
1908 getter(root).map(|value: &Value| value as &dyn Any)
1909 } else {
1910 None
1911 }
1912 }),
1913 root_type_id,
1914 value_type_id,
1915 }
1916 }
1917
1918 pub fn from<Root, Value>(keypath: OptionalKeyPath<Root, Value, impl for<'r> Fn(&'r Root) -> Option<&'r Value> + 'static>) -> Self
1921 where
1922 Root: Any + 'static,
1923 Value: Any + 'static,
1924 {
1925 Self::new(keypath)
1926 }
1927
1928 pub fn get<'r>(&self, root: &'r dyn Any) -> Option<&'r dyn Any> {
1929 (self.getter)(root)
1930 }
1931
1932 pub fn root_type_id(&self) -> TypeId {
1934 self.root_type_id
1935 }
1936
1937 pub fn value_type_id(&self) -> TypeId {
1939 self.value_type_id
1940 }
1941
1942 pub fn get_as<'a, Root: Any, Value: Any>(&self, root: &'a Root) -> Option<Option<&'a Value>> {
1944 if self.root_type_id == TypeId::of::<Root>() && self.value_type_id == TypeId::of::<Value>() {
1945 self.get(root as &dyn Any).map(|any| any.downcast_ref::<Value>())
1946 } else {
1947 None
1948 }
1949 }
1950
1951 pub fn kind_name(&self) -> String {
1954 format!("{:?}", self.value_type_id)
1955 }
1956}
1957
1958#[derive(Clone)]
1960pub struct AnyWritableKeyPath {
1961 getter: Rc<dyn for<'r> Fn(&'r mut dyn Any) -> Option<&'r mut dyn Any>>,
1962 root_type_id: TypeId,
1963 value_type_id: TypeId,
1964}
1965
1966#[derive(Clone)]
1971pub struct FailableCombinedKeyPath<Root, Value, ReadFn, WriteFn, OwnedFn>
1972where
1973 ReadFn: for<'r> Fn(&'r Root) -> Option<&'r Value> + 'static,
1974 WriteFn: for<'r> Fn(&'r mut Root) -> Option<&'r mut Value> + 'static,
1975 OwnedFn: Fn(Root) -> Option<Value> + 'static,
1976{
1977 readable: ReadFn,
1978 writable: WriteFn,
1979 owned: OwnedFn,
1980 _phantom: PhantomData<(Root, Value)>,
1981}
1982
1983impl<Root, Value, ReadFn, WriteFn, OwnedFn> FailableCombinedKeyPath<Root, Value, ReadFn, WriteFn, OwnedFn>
1984where
1985 ReadFn: for<'r> Fn(&'r Root) -> Option<&'r Value> + 'static,
1986 WriteFn: for<'r> Fn(&'r mut Root) -> Option<&'r mut Value> + 'static,
1987 OwnedFn: Fn(Root) -> Option<Value> + 'static,
1988{
1989 pub fn new(readable: ReadFn, writable: WriteFn, owned: OwnedFn) -> Self {
1991 Self {
1992 readable,
1993 writable,
1994 owned,
1995 _phantom: PhantomData,
1996 }
1997 }
1998
1999 pub fn get<'r>(&self, root: &'r Root) -> Option<&'r Value> {
2001 (self.readable)(root)
2002 }
2003
2004 pub fn get_mut<'r>(&self, root: &'r mut Root) -> Option<&'r mut Value> {
2006 (self.writable)(root)
2007 }
2008
2009 pub fn get_failable_owned(&self, root: Root) -> Option<Value> {
2011 (self.owned)(root)
2012 }
2013
2014 pub fn to_optional(self) -> OptionalKeyPath<Root, Value, ReadFn> {
2016 OptionalKeyPath::new(self.readable)
2017 }
2018
2019 pub fn to_writable_optional(self) -> WritableOptionalKeyPath<Root, Value, WriteFn> {
2021 WritableOptionalKeyPath::new(self.writable)
2022 }
2023
2024 pub fn then<SubValue, SubReadFn, SubWriteFn, SubOwnedFn>(
2027 self,
2028 next: FailableCombinedKeyPath<Value, SubValue, SubReadFn, SubWriteFn, SubOwnedFn>,
2029 ) -> 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>
2030 where
2031 SubReadFn: for<'r> Fn(&'r Value) -> Option<&'r SubValue> + 'static,
2032 SubWriteFn: for<'r> Fn(&'r mut Value) -> Option<&'r mut SubValue> + 'static,
2033 SubOwnedFn: Fn(Value) -> Option<SubValue> + 'static,
2034 ReadFn: 'static,
2035 WriteFn: 'static,
2036 OwnedFn: 'static,
2037 Value: 'static,
2038 Root: 'static,
2039 SubValue: 'static,
2040 {
2041 let first_read = self.readable;
2042 let first_write = self.writable;
2043 let first_owned = self.owned;
2044 let second_read = next.readable;
2045 let second_write = next.writable;
2046 let second_owned = next.owned;
2047
2048 FailableCombinedKeyPath::new(
2049 move |root: &Root| {
2050 first_read(root).and_then(|value| second_read(value))
2051 },
2052 move |root: &mut Root| {
2053 first_write(root).and_then(|value| second_write(value))
2054 },
2055 move |root: Root| {
2056 first_owned(root).and_then(|value| second_owned(value))
2057 },
2058 )
2059 }
2060
2061 pub fn then_optional<SubValue, SubReadFn>(
2065 self,
2066 next: OptionalKeyPath<Value, SubValue, SubReadFn>,
2067 ) -> 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>
2068 where
2069 SubReadFn: for<'r> Fn(&'r Value) -> Option<&'r SubValue> + 'static,
2070 ReadFn: 'static,
2071 WriteFn: 'static,
2072 OwnedFn: 'static,
2073 Value: 'static,
2074 Root: 'static,
2075 SubValue: 'static,
2076 {
2077 let first_read = self.readable;
2078 let first_write = self.writable;
2079 let first_owned = self.owned;
2080 let second_read = next.getter;
2081
2082 FailableCombinedKeyPath::new(
2083 move |root: &Root| {
2084 first_read(root).and_then(|value| second_read(value))
2085 },
2086 move |_root: &mut Root| {
2087 None },
2089 move |root: Root| {
2090 first_owned(root).and_then(|value| {
2091 None
2093 })
2094 },
2095 )
2096 }
2097}
2098
2099impl FailableCombinedKeyPath<(), (), fn(&()) -> Option<&()>, fn(&mut ()) -> Option<&mut ()>, fn(()) -> Option<()>> {
2101 pub fn failable_combined<Root, Value, ReadFn, WriteFn, OwnedFn>(
2103 readable: ReadFn,
2104 writable: WriteFn,
2105 owned: OwnedFn,
2106 ) -> FailableCombinedKeyPath<Root, Value, ReadFn, WriteFn, OwnedFn>
2107 where
2108 ReadFn: for<'r> Fn(&'r Root) -> Option<&'r Value> + 'static,
2109 WriteFn: for<'r> Fn(&'r mut Root) -> Option<&'r mut Value> + 'static,
2110 OwnedFn: Fn(Root) -> Option<Value> + 'static,
2111 {
2112 FailableCombinedKeyPath::new(readable, writable, owned)
2113 }
2114}
2115
2116impl AnyWritableKeyPath {
2117 pub fn new<Root, Value>(keypath: WritableOptionalKeyPath<Root, Value, impl for<'r> Fn(&'r mut Root) -> Option<&'r mut Value> + 'static>) -> Self
2118 where
2119 Root: Any + 'static,
2120 Value: Any + 'static,
2121 {
2122 let root_type_id = TypeId::of::<Root>();
2123 let value_type_id = TypeId::of::<Value>();
2124 let getter = keypath.getter;
2125
2126 Self {
2127 getter: Rc::new(move |any: &mut dyn Any| {
2128 if let Some(root) = any.downcast_mut::<Root>() {
2129 getter(root).map(|value: &mut Value| value as &mut dyn Any)
2130 } else {
2131 None
2132 }
2133 }),
2134 root_type_id,
2135 value_type_id,
2136 }
2137 }
2138
2139 pub fn get_mut<'r>(&self, root: &'r mut dyn Any) -> Option<&'r mut dyn Any> {
2140 (self.getter)(root)
2141 }
2142
2143 pub fn root_type_id(&self) -> TypeId {
2145 self.root_type_id
2146 }
2147
2148 pub fn value_type_id(&self) -> TypeId {
2150 self.value_type_id
2151 }
2152
2153 pub fn get_mut_as<'a, Root: Any, Value: Any>(&self, root: &'a mut Root) -> Option<Option<&'a mut Value>> {
2155 if self.root_type_id == TypeId::of::<Root>() && self.value_type_id == TypeId::of::<Value>() {
2156 self.get_mut(root as &mut dyn Any).map(|any| any.downcast_mut::<Value>())
2157 } else {
2158 None
2159 }
2160 }
2161}
2162
2163impl<Root, Value, F> KeyPath<Root, Value, F>
2165where
2166 F: for<'r> Fn(&'r Root) -> &'r Value + 'static,
2167 Root: 'static,
2168 Value: Any + 'static,
2169{
2170 pub fn to_partial(self) -> PartialKeyPath<Root> {
2172 PartialKeyPath::new(self)
2173 }
2174
2175 pub fn to(self) -> PartialKeyPath<Root> {
2177 self.to_partial()
2178 }
2179}
2180
2181impl<Root, Value, F> OptionalKeyPath<Root, Value, F>
2182where
2183 F: for<'r> Fn(&'r Root) -> Option<&'r Value> + 'static,
2184 Root: Any + 'static,
2185 Value: Any + 'static,
2186{
2187 pub fn to_partial(self) -> PartialOptionalKeyPath<Root> {
2189 PartialOptionalKeyPath::new(self)
2190 }
2191
2192 pub fn to_any(self) -> AnyKeyPath {
2194 AnyKeyPath::new(self)
2195 }
2196
2197 pub fn to(self) -> PartialOptionalKeyPath<Root> {
2199 self.to_partial()
2200 }
2201}
2202
2203impl<Root, Value, F> WritableKeyPath<Root, Value, F>
2204where
2205 F: for<'r> Fn(&'r mut Root) -> &'r mut Value + 'static,
2206 Root: 'static,
2207 Value: Any + 'static,
2208{
2209 pub fn to_partial(self) -> PartialWritableKeyPath<Root> {
2211 PartialWritableKeyPath::new(self)
2212 }
2213
2214 pub fn to(self) -> PartialWritableKeyPath<Root> {
2216 self.to_partial()
2217 }
2218}
2219
2220impl<Root, Value, F> WritableOptionalKeyPath<Root, Value, F>
2221where
2222 F: for<'r> Fn(&'r mut Root) -> Option<&'r mut Value> + 'static,
2223 Root: Any + 'static,
2224 Value: Any + 'static,
2225{
2226 pub fn to_partial(self) -> PartialWritableOptionalKeyPath<Root> {
2228 PartialWritableOptionalKeyPath::new(self)
2229 }
2230
2231 pub fn to_any(self) -> AnyWritableKeyPath {
2233 AnyWritableKeyPath::new(self)
2234 }
2235
2236 pub fn to(self) -> PartialWritableOptionalKeyPath<Root> {
2238 self.to_partial()
2239 }
2240}
2241
2242#[cfg(test)]
2243mod tests {
2244 use super::*;
2245 use std::sync::atomic::{AtomicUsize, Ordering};
2246 use std::rc::Rc;
2247
2248 static ALLOC_COUNT: AtomicUsize = AtomicUsize::new(0);
2250 static DEALLOC_COUNT: AtomicUsize = AtomicUsize::new(0);
2251
2252 #[derive(Debug)]
2254 struct NoCloneType {
2255 id: usize,
2256 data: String,
2257 }
2258
2259 impl NoCloneType {
2260 fn new(data: String) -> Self {
2261 ALLOC_COUNT.fetch_add(1, Ordering::SeqCst);
2262 Self {
2263 id: ALLOC_COUNT.load(Ordering::SeqCst),
2264 data,
2265 }
2266 }
2267 }
2268
2269 impl Clone for NoCloneType {
2270 fn clone(&self) -> Self {
2271 eprintln!("[DEBUG] NoCloneType should not be cloned! ID: {}", self.id);
2272 unreachable!("NoCloneType should not be cloned! ID: {}", self.id);
2273 }
2274 }
2275
2276 impl Drop for NoCloneType {
2277 fn drop(&mut self) {
2278 DEALLOC_COUNT.fetch_add(1, Ordering::SeqCst);
2279 }
2280 }
2281
2282 fn reset_memory_counters() {
2284 ALLOC_COUNT.store(0, Ordering::SeqCst);
2285 DEALLOC_COUNT.store(0, Ordering::SeqCst);
2286 }
2287
2288 fn get_alloc_count() -> usize {
2289 ALLOC_COUNT.load(Ordering::SeqCst)
2290 }
2291
2292 fn get_dealloc_count() -> usize {
2293 DEALLOC_COUNT.load(Ordering::SeqCst)
2294 }
2295
2296#[derive(Debug)]
2298struct User {
2299 name: String,
2300 metadata: Option<Box<UserMetadata>>,
2301 friends: Vec<Arc<User>>,
2302}
2303
2304#[derive(Debug)]
2305struct UserMetadata {
2306 created_at: String,
2307}
2308
2309fn some_fn() {
2310 let akash = User {
2311 name: "Alice".to_string(),
2312 metadata: Some(Box::new(UserMetadata {
2313 created_at: "2024-01-01".to_string(),
2314 })),
2315 friends: vec![
2316 Arc::new(User {
2317 name: "Bob".to_string(),
2318 metadata: None,
2319 friends: vec![],
2320 }),
2321 ],
2322 };
2323
2324 let name_kp = KeyPath::new(|u: &User| &u.name);
2326 let metadata_kp = OptionalKeyPath::new(|u: &User| u.metadata.as_ref());
2327 let friends_kp = KeyPath::new(|u: &User| &u.friends);
2328
2329 println!("Name: {}", name_kp.get(&akash));
2331
2332 if let Some(metadata) = metadata_kp.get(&akash) {
2333 println!("Has metadata: {:?}", metadata);
2334 }
2335
2336 if let Some(first_friend) = akash.friends.get(0) {
2338 println!("First friend: {}", name_kp.get(first_friend));
2339 }
2340
2341 let created_at_kp = KeyPath::new(|m: &UserMetadata| &m.created_at);
2343
2344 if let Some(metadata) = akash.metadata.as_ref() {
2345 let boxed_metadata: &Box<UserMetadata> = metadata;
2347 let unwrapped = boxed_metadata.as_ref();
2348 println!("Created at: {:?}", created_at_kp.get(unwrapped));
2349 }
2350 }
2351
2352 #[test]
2353 fn test_name() {
2354 some_fn();
2355 }
2356
2357 #[test]
2358 fn test_no_cloning_on_keypath_operations() {
2359 reset_memory_counters();
2360
2361 let value = NoCloneType::new("test".to_string());
2363 let boxed = Box::new(value);
2364
2365 let kp = KeyPath::new(|b: &Box<NoCloneType>| b.as_ref());
2367
2368 let _ref = kp.get(&boxed);
2370
2371 let _kp_clone = kp.clone();
2373
2374 let _ref2 = _kp_clone.get(&boxed);
2376
2377 assert_eq!(get_alloc_count(), 1);
2379 }
2380
2381 #[test]
2382 fn test_no_cloning_on_optional_keypath_operations() {
2383 reset_memory_counters();
2384
2385 let value = NoCloneType::new("test".to_string());
2386 let opt = Some(Box::new(value));
2387
2388 let okp = OptionalKeyPath::new(|o: &Option<Box<NoCloneType>>| o.as_ref());
2390
2391 let _ref = okp.get(&opt);
2393
2394 let _okp_clone = okp.clone();
2396
2397 let chained = okp.then(OptionalKeyPath::new(|b: &Box<NoCloneType>| Some(b.as_ref())));
2399 let _ref2 = chained.get(&opt);
2400
2401 assert_eq!(get_alloc_count(), 1);
2402 }
2403
2404 #[test]
2405 fn test_memory_release() {
2406 reset_memory_counters();
2407
2408 {
2409 let value = NoCloneType::new("test".to_string());
2410 let boxed = Box::new(value);
2411 let kp = KeyPath::new(|b: &Box<NoCloneType>| b.as_ref());
2412
2413 let _ref = kp.get(&boxed);
2415
2416 }
2418
2419 assert_eq!(get_alloc_count(), 1);
2422 }
2425
2426 #[test]
2427 fn test_keypath_clone_does_not_clone_underlying_data() {
2428 reset_memory_counters();
2429
2430 let value = NoCloneType::new("data".to_string());
2431 let rc_value = Rc::new(value);
2432
2433 let kp = KeyPath::new(|r: &Rc<NoCloneType>| r.as_ref());
2435
2436 let kp1 = kp.clone();
2438 let kp2 = kp.clone();
2439 let kp3 = kp1.clone();
2440
2441 let _ref1 = kp.get(&rc_value);
2443 let _ref2 = kp1.get(&rc_value);
2444 let _ref3 = kp2.get(&rc_value);
2445 let _ref4 = kp3.get(&rc_value);
2446
2447 assert_eq!(get_alloc_count(), 1);
2449 }
2450
2451 #[test]
2452 fn test_optional_keypath_chaining_no_clone() {
2453 reset_memory_counters();
2454
2455 let value = NoCloneType::new("value1".to_string());
2456
2457 struct Container {
2458 inner: Option<Box<NoCloneType>>,
2459 }
2460
2461 let container = Container {
2462 inner: Some(Box::new(value)),
2463 };
2464
2465 let kp1 = OptionalKeyPath::new(|c: &Container| c.inner.as_ref());
2467 let kp2 = OptionalKeyPath::new(|b: &Box<NoCloneType>| Some(b.as_ref()));
2468
2469 let chained = kp1.then(kp2);
2471
2472 let _result = chained.get(&container);
2474
2475 assert_eq!(get_alloc_count(), 1);
2477 }
2478
2479 #[test]
2480 fn test_for_box_no_clone() {
2481 reset_memory_counters();
2482
2483 let value = NoCloneType::new("test".to_string());
2484 let boxed = Box::new(value);
2485 let opt_boxed = Some(boxed);
2486
2487 let kp = OptionalKeyPath::new(|o: &Option<Box<NoCloneType>>| o.as_ref());
2489 let unwrapped = kp.for_box();
2490
2491 let _ref = unwrapped.get(&opt_boxed);
2493
2494 assert_eq!(get_alloc_count(), 1);
2495 }
2496
2497 #[derive(Debug, PartialEq)]
2500 struct TestUser {
2501 name: String,
2502 age: u32,
2503 metadata: Option<String>,
2504 address: Option<TestAddress>,
2505 }
2506
2507 #[derive(Debug, PartialEq)]
2508 struct TestAddress {
2509 street: String,
2510 city: String,
2511 country: Option<TestCountry>,
2512 }
2513
2514 #[derive(Debug, PartialEq)]
2515 struct TestCountry {
2516 name: String,
2517 }
2518
2519 #[test]
2520 fn test_keypath_macro() {
2521 let user = TestUser {
2522 name: "Alice".to_string(),
2523 age: 30,
2524 metadata: None,
2525 address: None,
2526 };
2527
2528 let name_kp = keypath!(|u: &TestUser| &u.name);
2530 assert_eq!(name_kp.get(&user), "Alice");
2531
2532 let user_with_address = TestUser {
2534 name: "Bob".to_string(),
2535 age: 25,
2536 metadata: None,
2537 address: Some(TestAddress {
2538 street: "123 Main St".to_string(),
2539 city: "New York".to_string(),
2540 country: None,
2541 }),
2542 };
2543
2544 let street_kp = keypath!(|u: &TestUser| &u.address.as_ref().unwrap().street);
2545 assert_eq!(street_kp.get(&user_with_address), "123 Main St");
2546
2547 let user_with_country = TestUser {
2549 name: "Charlie".to_string(),
2550 age: 35,
2551 metadata: None,
2552 address: Some(TestAddress {
2553 street: "456 Oak Ave".to_string(),
2554 city: "London".to_string(),
2555 country: Some(TestCountry {
2556 name: "UK".to_string(),
2557 }),
2558 }),
2559 };
2560
2561 let country_name_kp = keypath!(|u: &TestUser| &u.address.as_ref().unwrap().country.as_ref().unwrap().name);
2562 assert_eq!(country_name_kp.get(&user_with_country), "UK");
2563
2564 let age_kp = keypath!(|u: &TestUser| &u.age);
2566 assert_eq!(age_kp.get(&user), &30);
2567 }
2568
2569 #[test]
2570 fn test_opt_keypath_macro() {
2571 let user = TestUser {
2572 name: "Alice".to_string(),
2573 age: 30,
2574 metadata: Some("admin".to_string()),
2575 address: None,
2576 };
2577
2578 let metadata_kp = opt_keypath!(|u: &TestUser| u.metadata.as_ref());
2580 assert_eq!(metadata_kp.get(&user), Some(&"admin".to_string()));
2581
2582 let user_no_metadata = TestUser {
2584 name: "Bob".to_string(),
2585 age: 25,
2586 metadata: None,
2587 address: None,
2588 };
2589 assert_eq!(metadata_kp.get(&user_no_metadata), None);
2590
2591 let user_with_address = TestUser {
2593 name: "Charlie".to_string(),
2594 age: 35,
2595 metadata: None,
2596 address: Some(TestAddress {
2597 street: "789 Pine Rd".to_string(),
2598 city: "Paris".to_string(),
2599 country: None,
2600 }),
2601 };
2602
2603 let street_kp = opt_keypath!(|u: &TestUser| u.address.as_ref().map(|a| &a.street));
2604 assert_eq!(street_kp.get(&user_with_address), Some(&"789 Pine Rd".to_string()));
2605
2606 let user_with_country = TestUser {
2608 name: "David".to_string(),
2609 age: 40,
2610 metadata: None,
2611 address: Some(TestAddress {
2612 street: "321 Elm St".to_string(),
2613 city: "Tokyo".to_string(),
2614 country: Some(TestCountry {
2615 name: "Japan".to_string(),
2616 }),
2617 }),
2618 };
2619
2620 let country_name_kp = opt_keypath!(|u: &TestUser| u.address.as_ref().and_then(|a| a.country.as_ref().map(|c| &c.name)));
2621 assert_eq!(country_name_kp.get(&user_with_country), Some(&"Japan".to_string()));
2622
2623 let metadata_kp2 = opt_keypath!(|u: &TestUser| u.metadata.as_ref());
2625 assert_eq!(metadata_kp2.get(&user), Some(&"admin".to_string()));
2626 }
2627
2628 #[test]
2629 fn test_writable_keypath_macro() {
2630 let mut user = TestUser {
2631 name: "Alice".to_string(),
2632 age: 30,
2633 metadata: None,
2634 address: None,
2635 };
2636
2637 let name_kp = writable_keypath!(|u: &mut TestUser| &mut u.name);
2639 *name_kp.get_mut(&mut user) = "Bob".to_string();
2640 assert_eq!(user.name, "Bob");
2641
2642 let mut user_with_address = TestUser {
2644 name: "Charlie".to_string(),
2645 age: 25,
2646 metadata: None,
2647 address: Some(TestAddress {
2648 street: "123 Main St".to_string(),
2649 city: "New York".to_string(),
2650 country: None,
2651 }),
2652 };
2653
2654 let street_kp = writable_keypath!(|u: &mut TestUser| &mut u.address.as_mut().unwrap().street);
2655 *street_kp.get_mut(&mut user_with_address) = "456 Oak Ave".to_string();
2656 assert_eq!(user_with_address.address.as_ref().unwrap().street, "456 Oak Ave");
2657
2658 let mut user_with_country = TestUser {
2660 name: "David".to_string(),
2661 age: 35,
2662 metadata: None,
2663 address: Some(TestAddress {
2664 street: "789 Pine Rd".to_string(),
2665 city: "London".to_string(),
2666 country: Some(TestCountry {
2667 name: "UK".to_string(),
2668 }),
2669 }),
2670 };
2671
2672 let country_name_kp = writable_keypath!(|u: &mut TestUser| &mut u.address.as_mut().unwrap().country.as_mut().unwrap().name);
2673 *country_name_kp.get_mut(&mut user_with_country) = "United Kingdom".to_string();
2674 assert_eq!(user_with_country.address.as_ref().unwrap().country.as_ref().unwrap().name, "United Kingdom");
2675
2676 let age_kp = writable_keypath!(|u: &mut TestUser| &mut u.age);
2678 *age_kp.get_mut(&mut user) = 31;
2679 assert_eq!(user.age, 31);
2680 }
2681
2682 #[test]
2683 fn test_writable_opt_keypath_macro() {
2684 let mut user = TestUser {
2685 name: "Alice".to_string(),
2686 age: 30,
2687 metadata: Some("user".to_string()),
2688 address: None,
2689 };
2690
2691 let metadata_kp = writable_opt_keypath!(|u: &mut TestUser| u.metadata.as_mut());
2693 if let Some(metadata) = metadata_kp.get_mut(&mut user) {
2694 *metadata = "admin".to_string();
2695 }
2696 assert_eq!(user.metadata, Some("admin".to_string()));
2697
2698 let mut user_no_metadata = TestUser {
2700 name: "Bob".to_string(),
2701 age: 25,
2702 metadata: None,
2703 address: None,
2704 };
2705 assert_eq!(metadata_kp.get_mut(&mut user_no_metadata), None);
2706
2707 let mut user_with_address = TestUser {
2709 name: "Charlie".to_string(),
2710 age: 35,
2711 metadata: None,
2712 address: Some(TestAddress {
2713 street: "123 Main St".to_string(),
2714 city: "New York".to_string(),
2715 country: None,
2716 }),
2717 };
2718
2719 let street_kp = writable_opt_keypath!(|u: &mut TestUser| u.address.as_mut().map(|a| &mut a.street));
2720 if let Some(street) = street_kp.get_mut(&mut user_with_address) {
2721 *street = "456 Oak Ave".to_string();
2722 }
2723 assert_eq!(user_with_address.address.as_ref().unwrap().street, "456 Oak Ave");
2724
2725 let mut user_with_country = TestUser {
2727 name: "David".to_string(),
2728 age: 40,
2729 metadata: None,
2730 address: Some(TestAddress {
2731 street: "789 Pine Rd".to_string(),
2732 city: "Tokyo".to_string(),
2733 country: Some(TestCountry {
2734 name: "Japan".to_string(),
2735 }),
2736 }),
2737 };
2738
2739 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)));
2740 if let Some(country_name) = country_name_kp.get_mut(&mut user_with_country) {
2741 *country_name = "Nippon".to_string();
2742 }
2743 assert_eq!(user_with_country.address.as_ref().unwrap().country.as_ref().unwrap().name, "Nippon");
2744
2745 let metadata_kp2 = writable_opt_keypath!(|u: &mut TestUser| u.metadata.as_mut());
2747 if let Some(metadata) = metadata_kp2.get_mut(&mut user) {
2748 *metadata = "super_admin".to_string();
2749 }
2750 assert_eq!(user.metadata, Some("super_admin".to_string()));
2751 }
2752}
2753
2754pub trait WithContainer<Root, Value> {
2760 fn with_arc<F, R>(&self, arc: &Arc<Root>, f: F) -> R
2762 where
2763 F: FnOnce(&Value) -> R;
2764
2765 fn with_box<F, R>(&self, boxed: &Box<Root>, f: F) -> R
2767 where
2768 F: FnOnce(&Value) -> R;
2769
2770 fn with_box_mut<F, R>(&self, boxed: &mut Box<Root>, f: F) -> R
2772 where
2773 F: FnOnce(&mut Value) -> R;
2774
2775 fn with_rc<F, R>(&self, rc: &Rc<Root>, f: F) -> R
2777 where
2778 F: FnOnce(&Value) -> R;
2779
2780 fn with_result<F, R, E>(&self, result: &Result<Root, E>, f: F) -> Option<R>
2782 where
2783 F: FnOnce(&Value) -> R;
2784
2785 fn with_result_mut<F, R, E>(&self, result: &mut Result<Root, E>, f: F) -> Option<R>
2787 where
2788 F: FnOnce(&mut Value) -> R;
2789
2790 fn with_option<F, R>(&self, option: &Option<Root>, f: F) -> Option<R>
2792 where
2793 F: FnOnce(&Value) -> R;
2794
2795 fn with_option_mut<F, R>(&self, option: &mut Option<Root>, f: F) -> Option<R>
2797 where
2798 F: FnOnce(&mut Value) -> R;
2799
2800 fn with_refcell<F, R>(&self, refcell: &RefCell<Root>, f: F) -> Option<R>
2802 where
2803 F: FnOnce(&Value) -> R;
2804
2805 fn with_refcell_mut<F, R>(&self, refcell: &RefCell<Root>, f: F) -> Option<R>
2807 where
2808 F: FnOnce(&mut Value) -> R;
2809
2810 #[cfg(feature = "tagged")]
2811 fn with_tagged<F, R, Tag>(&self, tagged: &Tagged<Root, Tag>, f: F) -> R
2813 where
2814 Tagged<Root, Tag>: std::ops::Deref<Target = Root>,
2815 F: FnOnce(&Value) -> R;
2816
2817 fn with_mutex<F, R>(&self, mutex: &Mutex<Root>, f: F) -> Option<R>
2819 where
2820 F: FnOnce(&Value) -> R;
2821
2822 fn with_mutex_mut<F, R>(&self, mutex: &mut Mutex<Root>, f: F) -> Option<R>
2824 where
2825 F: FnOnce(&mut Value) -> R;
2826
2827 fn with_rwlock<F, R>(&self, rwlock: &RwLock<Root>, f: F) -> Option<R>
2829 where
2830 F: FnOnce(&Value) -> R;
2831
2832 fn with_rwlock_mut<F, R>(&self, rwlock: &mut RwLock<Root>, f: F) -> Option<R>
2834 where
2835 F: FnOnce(&mut Value) -> R;
2836
2837 fn with_arc_rwlock<F, R>(&self, arc_rwlock: &Arc<RwLock<Root>>, f: F) -> Option<R>
2839 where
2840 F: FnOnce(&Value) -> R;
2841
2842 fn with_arc_rwlock_mut<F, R>(&self, arc_rwlock: &Arc<RwLock<Root>>, f: F) -> Option<R>
2844 where
2845 F: FnOnce(&mut Value) -> R;
2846}
2847
2848impl<Root, Value, F> WithContainer<Root, Value> for KeyPath<Root, Value, F>
2850where
2851 F: for<'r> Fn(&'r Root) -> &'r Value + Clone,
2852{
2853 fn with_arc<Callback, R>(&self, arc: &Arc<Root>, f: Callback) -> R
2854 where
2855 Callback: FnOnce(&Value) -> R,
2856 {
2857 self.with_arc(arc, f)
2858 }
2859
2860 fn with_box<Callback, R>(&self, boxed: &Box<Root>, f: Callback) -> R
2861 where
2862 Callback: FnOnce(&Value) -> R,
2863 {
2864 self.with_box(boxed, f)
2865 }
2866
2867 fn with_box_mut<Callback, R>(&self, _boxed: &mut Box<Root>, _f: Callback) -> R
2868 where
2869 Callback: FnOnce(&mut Value) -> R,
2870 {
2871 eprintln!("[DEBUG] KeyPath does not support mutable access - use WritableKeyPath instead");
2872 unreachable!("KeyPath does not support mutable access - use WritableKeyPath instead")
2873 }
2874
2875 fn with_rc<Callback, R>(&self, rc: &Rc<Root>, f: Callback) -> R
2876 where
2877 Callback: FnOnce(&Value) -> R,
2878 {
2879 self.with_rc(rc, f)
2880 }
2881
2882 fn with_result<Callback, R, E>(&self, result: &Result<Root, E>, f: Callback) -> Option<R>
2883 where
2884 Callback: FnOnce(&Value) -> R,
2885 {
2886 self.with_result(result, f)
2887 }
2888
2889 fn with_result_mut<Callback, R, E>(&self, _result: &mut Result<Root, E>, _f: Callback) -> Option<R>
2890 where
2891 Callback: FnOnce(&mut Value) -> R,
2892 {
2893 None
2894 }
2895
2896 fn with_option<Callback, R>(&self, option: &Option<Root>, f: Callback) -> Option<R>
2897 where
2898 Callback: FnOnce(&Value) -> R,
2899 {
2900 self.with_option(option, f)
2901 }
2902
2903 fn with_option_mut<Callback, R>(&self, _option: &mut Option<Root>, _f: Callback) -> Option<R>
2904 where
2905 Callback: FnOnce(&mut Value) -> R,
2906 {
2907 None
2908 }
2909
2910 fn with_refcell<Callback, R>(&self, refcell: &RefCell<Root>, f: Callback) -> Option<R>
2911 where
2912 Callback: FnOnce(&Value) -> R,
2913 {
2914 self.with_refcell(refcell, f)
2915 }
2916
2917 fn with_refcell_mut<Callback, R>(&self, _refcell: &RefCell<Root>, _f: Callback) -> Option<R>
2918 where
2919 Callback: FnOnce(&mut Value) -> R,
2920 {
2921 None
2922 }
2923
2924 #[cfg(feature = "tagged")]
2925 fn with_tagged<Tag, Callback, R>(&self, tagged: &Tagged<Root, Tag>, f: Callback) -> R
2926 where
2927 Tagged<Root, Tag>: std::ops::Deref<Target = Root>,
2928 Callback: FnOnce(&Value) -> R,
2929 {
2930 self.with_tagged(tagged, f)
2931 }
2932
2933 fn with_mutex<Callback, R>(&self, mutex: &Mutex<Root>, f: Callback) -> Option<R>
2934 where
2935 Callback: FnOnce(&Value) -> R,
2936 {
2937 self.with_mutex(mutex, f)
2938 }
2939
2940 fn with_mutex_mut<Callback, R>(&self, _mutex: &mut Mutex<Root>, _f: Callback) -> Option<R>
2941 where
2942 Callback: FnOnce(&mut Value) -> R,
2943 {
2944 None
2945 }
2946
2947 fn with_rwlock<Callback, R>(&self, rwlock: &RwLock<Root>, f: Callback) -> Option<R>
2948 where
2949 Callback: FnOnce(&Value) -> R,
2950 {
2951 self.with_rwlock(rwlock, f)
2952 }
2953
2954 fn with_rwlock_mut<Callback, R>(&self, _rwlock: &mut RwLock<Root>, _f: Callback) -> Option<R>
2955 where
2956 Callback: FnOnce(&mut Value) -> R,
2957 {
2958 None
2959 }
2960
2961 fn with_arc_rwlock<Callback, R>(&self, arc_rwlock: &Arc<RwLock<Root>>, f: Callback) -> Option<R>
2962 where
2963 Callback: FnOnce(&Value) -> R,
2964 {
2965 self.with_arc_rwlock(arc_rwlock, f)
2966 }
2967
2968 fn with_arc_rwlock_mut<Callback, R>(&self, _arc_rwlock: &Arc<RwLock<Root>>, _f: Callback) -> Option<R>
2969 where
2970 Callback: FnOnce(&mut Value) -> R,
2971 {
2972 None
2973 }
2974}
2975
2976impl<Root, Value, F> WithContainer<Root, Value> for OptionalKeyPath<Root, Value, F>
2978where
2979 F: for<'r> Fn(&'r Root) -> Option<&'r Value> + Clone,
2980{
2981 fn with_arc<Callback, R>(&self, arc: &Arc<Root>, f: Callback) -> R
2982 where
2983 Callback: FnOnce(&Value) -> R,
2984 {
2985 self.with_arc(arc, f)
2986 }
2987
2988 fn with_box<Callback, R>(&self, boxed: &Box<Root>, f: Callback) -> R
2989 where
2990 Callback: FnOnce(&Value) -> R,
2991 {
2992 self.with_box(boxed, f)
2993 }
2994
2995 fn with_box_mut<Callback, R>(&self, _boxed: &mut Box<Root>, _f: Callback) -> R
2996 where
2997 Callback: FnOnce(&mut Value) -> R,
2998 {
2999 eprintln!("[DEBUG] OptionalKeyPath does not support mutable access - use WritableOptionalKeyPath instead");
3000 unreachable!("OptionalKeyPath does not support mutable access - use WritableOptionalKeyPath instead")
3001 }
3002
3003 fn with_rc<Callback, R>(&self, rc: &Rc<Root>, f: Callback) -> R
3004 where
3005 Callback: FnOnce(&Value) -> R,
3006 {
3007 self.with_rc(rc, f)
3008 }
3009
3010 fn with_result<Callback, R, E>(&self, result: &Result<Root, E>, f: Callback) -> Option<R>
3011 where
3012 Callback: FnOnce(&Value) -> R,
3013 {
3014 self.with_result(result, f)
3015 }
3016
3017 fn with_result_mut<Callback, R, E>(&self, _result: &mut Result<Root, E>, _f: Callback) -> Option<R>
3018 where
3019 Callback: FnOnce(&mut Value) -> R,
3020 {
3021 None }
3023
3024 fn with_option<Callback, R>(&self, option: &Option<Root>, f: Callback) -> Option<R>
3025 where
3026 Callback: FnOnce(&Value) -> R,
3027 {
3028 self.with_option(option, f)
3029 }
3030
3031 fn with_option_mut<Callback, R>(&self, _option: &mut Option<Root>, _f: Callback) -> Option<R>
3032 where
3033 Callback: FnOnce(&mut Value) -> R,
3034 {
3035 None }
3037
3038 fn with_refcell<Callback, R>(&self, refcell: &RefCell<Root>, f: Callback) -> Option<R>
3039 where
3040 Callback: FnOnce(&Value) -> R,
3041 {
3042 self.with_refcell(refcell, f)
3043 }
3044
3045 fn with_refcell_mut<Callback, R>(&self, _refcell: &RefCell<Root>, _f: Callback) -> Option<R>
3046 where
3047 Callback: FnOnce(&mut Value) -> R,
3048 {
3049 None }
3051
3052 #[cfg(feature = "tagged")]
3053 fn with_tagged<Tag, Callback, R>(&self, tagged: &Tagged<Root, Tag>, f: Callback) -> R
3054 where
3055 Tagged<Root, Tag>: std::ops::Deref<Target = Root>,
3056 Callback: FnOnce(&Value) -> R,
3057 {
3058 self.with_tagged(tagged, f)
3059 }
3060
3061 fn with_mutex<Callback, R>(&self, mutex: &Mutex<Root>, f: Callback) -> Option<R>
3062 where
3063 Callback: FnOnce(&Value) -> R,
3064 {
3065 self.with_mutex(mutex, f)
3066 }
3067
3068 fn with_mutex_mut<Callback, R>(&self, _mutex: &mut Mutex<Root>, _f: Callback) -> Option<R>
3069 where
3070 Callback: FnOnce(&mut Value) -> R,
3071 {
3072 None }
3074
3075 fn with_rwlock<Callback, R>(&self, rwlock: &RwLock<Root>, f: Callback) -> Option<R>
3076 where
3077 Callback: FnOnce(&Value) -> R,
3078 {
3079 self.with_rwlock(rwlock, f)
3080 }
3081
3082 fn with_rwlock_mut<Callback, R>(&self, _rwlock: &mut RwLock<Root>, _f: Callback) -> Option<R>
3083 where
3084 Callback: FnOnce(&mut Value) -> R,
3085 {
3086 None }
3088
3089 fn with_arc_rwlock<Callback, R>(&self, arc_rwlock: &Arc<RwLock<Root>>, f: Callback) -> Option<R>
3090 where
3091 Callback: FnOnce(&Value) -> R,
3092 {
3093 self.with_arc_rwlock(arc_rwlock, f)
3094 }
3095
3096 fn with_arc_rwlock_mut<Callback, R>(&self, _arc_rwlock: &Arc<RwLock<Root>>, _f: Callback) -> Option<R>
3097 where
3098 Callback: FnOnce(&mut Value) -> R,
3099 {
3100 None }
3102}
3103
3104impl<Root, Value, F> WithContainer<Root, Value> for WritableKeyPath<Root, Value, F>
3106where
3107 F: for<'r> Fn(&'r mut Root) -> &'r mut Value,
3108{
3109 fn with_arc<Callback, R>(&self, _arc: &Arc<Root>, _f: Callback) -> R
3110 where
3111 Callback: FnOnce(&Value) -> R,
3112 {
3113 eprintln!("[DEBUG] WritableKeyPath::with_arc requires &mut Arc<Root> or interior mutability");
3116 unreachable!("WritableKeyPath::with_arc requires &mut Arc<Root> or interior mutability")
3117 }
3118
3119 fn with_box<Callback, R>(&self, boxed: &Box<Root>, f: Callback) -> R
3120 where
3121 Callback: FnOnce(&Value) -> R,
3122 {
3123 eprintln!("[DEBUG] WritableKeyPath::with_box requires &mut Box<Root> - use with_box_mut instead");
3126 unreachable!("WritableKeyPath::with_box requires &mut Box<Root> - use with_box_mut instead")
3127 }
3128
3129 fn with_box_mut<Callback, R>(&self, boxed: &mut Box<Root>, f: Callback) -> R
3130 where
3131 Callback: FnOnce(&mut Value) -> R,
3132 {
3133 let value = self.get_mut(boxed.as_mut());
3134 f(value)
3135 }
3136
3137 fn with_rc<Callback, R>(&self, _rc: &Rc<Root>, _f: Callback) -> R
3138 where
3139 Callback: FnOnce(&Value) -> R,
3140 {
3141 eprintln!("[DEBUG] WritableKeyPath::with_rc requires &mut Rc<Root> or interior mutability");
3144 unreachable!("WritableKeyPath::with_rc requires &mut Rc<Root> or interior mutability")
3145 }
3146
3147 fn with_result<Callback, R, E>(&self, _result: &Result<Root, E>, _f: Callback) -> Option<R>
3148 where
3149 Callback: FnOnce(&Value) -> R,
3150 {
3151 None
3154 }
3155
3156 fn with_result_mut<Callback, R, E>(&self, result: &mut Result<Root, E>, f: Callback) -> Option<R>
3157 where
3158 Callback: FnOnce(&mut Value) -> R,
3159 {
3160 result.as_mut().ok().map(|root| {
3161 let value = self.get_mut(root);
3162 f(value)
3163 })
3164 }
3165
3166 fn with_option<Callback, R>(&self, _option: &Option<Root>, _f: Callback) -> Option<R>
3167 where
3168 Callback: FnOnce(&Value) -> R,
3169 {
3170 None
3173 }
3174
3175 fn with_option_mut<Callback, R>(&self, option: &mut Option<Root>, f: Callback) -> Option<R>
3176 where
3177 Callback: FnOnce(&mut Value) -> R,
3178 {
3179 option.as_mut().map(|root| {
3180 let value = self.get_mut(root);
3181 f(value)
3182 })
3183 }
3184
3185 fn with_refcell<Callback, R>(&self, refcell: &RefCell<Root>, f: Callback) -> Option<R>
3186 where
3187 Callback: FnOnce(&Value) -> R,
3188 {
3189 None
3192 }
3193
3194 fn with_refcell_mut<Callback, R>(&self, refcell: &RefCell<Root>, f: Callback) -> Option<R>
3195 where
3196 Callback: FnOnce(&mut Value) -> R,
3197 {
3198 refcell.try_borrow_mut().ok().map(|mut borrow| {
3199 let value = self.get_mut(&mut *borrow);
3200 f(value)
3201 })
3202 }
3203
3204 #[cfg(feature = "tagged")]
3205 fn with_tagged<Tag, Callback, R>(&self, _tagged: &Tagged<Root, Tag>, _f: Callback) -> R
3206 where
3207 Tagged<Root, Tag>: std::ops::Deref<Target = Root>,
3208 Callback: FnOnce(&Value) -> R,
3209 {
3210 eprintln!("[DEBUG] WritableKeyPath::with_tagged requires &mut Tagged<Root, Tag> or interior mutability");
3213 unreachable!("WritableKeyPath::with_tagged requires &mut Tagged<Root, Tag> or interior mutability")
3214 }
3215
3216 fn with_mutex<Callback, R>(&self, mutex: &Mutex<Root>, f: Callback) -> Option<R>
3217 where
3218 Callback: FnOnce(&Value) -> R,
3219 {
3220 mutex.lock().ok().map(|mut guard| {
3221 let value = self.get_mut(&mut *guard);
3222 f(value)
3223 })
3224 }
3225
3226 fn with_mutex_mut<Callback, R>(&self, mutex: &mut Mutex<Root>, f: Callback) -> Option<R>
3227 where
3228 Callback: FnOnce(&mut Value) -> R,
3229 {
3230 mutex.get_mut().ok().map(|root| {
3232 let value = self.get_mut(root);
3233 f(value)
3234 })
3235 }
3236
3237 fn with_rwlock<Callback, R>(&self, rwlock: &RwLock<Root>, f: Callback) -> Option<R>
3238 where
3239 Callback: FnOnce(&Value) -> R,
3240 {
3241 None
3244 }
3245
3246 fn with_rwlock_mut<Callback, R>(&self, rwlock: &mut RwLock<Root>, f: Callback) -> Option<R>
3247 where
3248 Callback: FnOnce(&mut Value) -> R,
3249 {
3250 rwlock.get_mut().ok().map(|root| {
3252 let value = self.get_mut(root);
3253 f(value)
3254 })
3255 }
3256
3257 fn with_arc_rwlock<Callback, R>(&self, arc_rwlock: &Arc<RwLock<Root>>, f: Callback) -> Option<R>
3258 where
3259 Callback: FnOnce(&Value) -> R,
3260 {
3261 None
3264 }
3265
3266 fn with_arc_rwlock_mut<Callback, R>(&self, arc_rwlock: &Arc<RwLock<Root>>, f: Callback) -> Option<R>
3267 where
3268 Callback: FnOnce(&mut Value) -> R,
3269 {
3270 arc_rwlock.write().ok().map(|mut guard| {
3271 let value = self.get_mut(&mut *guard);
3272 f(value)
3273 })
3274 }
3275}
3276
3277impl<Root, Value, F> WithContainer<Root, Value> for WritableOptionalKeyPath<Root, Value, F>
3279where
3280 F: for<'r> Fn(&'r mut Root) -> Option<&'r mut Value>,
3281{
3282 fn with_arc<Callback, R>(&self, _arc: &Arc<Root>, _f: Callback) -> R
3283 where
3284 Callback: FnOnce(&Value) -> R,
3285 {
3286 eprintln!("[DEBUG] WritableOptionalKeyPath::with_arc requires &mut Arc<Root> or interior mutability");
3289 unreachable!("WritableOptionalKeyPath::with_arc requires &mut Arc<Root> or interior mutability")
3290 }
3291
3292 fn with_box<Callback, R>(&self, _boxed: &Box<Root>, _f: Callback) -> R
3293 where
3294 Callback: FnOnce(&Value) -> R,
3295 {
3296 eprintln!("[DEBUG] WritableOptionalKeyPath::with_box requires &mut Box<Root> - use with_box_mut instead");
3299 unreachable!("WritableOptionalKeyPath::with_box requires &mut Box<Root> - use with_box_mut instead")
3300 }
3301
3302 fn with_box_mut<Callback, R>(&self, boxed: &mut Box<Root>, f: Callback) -> R
3303 where
3304 Callback: FnOnce(&mut Value) -> R,
3305 {
3306 if let Some(value) = self.get_mut(boxed.as_mut()) {
3307 f(value)
3308 } else {
3309 eprintln!("[DEBUG] WritableOptionalKeyPath failed to get value from Box");
3310 unreachable!("WritableOptionalKeyPath failed to get value from Box")
3311 }
3312 }
3313
3314 fn with_rc<Callback, R>(&self, _rc: &Rc<Root>, _f: Callback) -> R
3315 where
3316 Callback: FnOnce(&Value) -> R,
3317 {
3318 eprintln!("[DEBUG] WritableOptionalKeyPath::with_rc requires &mut Rc<Root> or interior mutability");
3321 unreachable!("WritableOptionalKeyPath::with_rc requires &mut Rc<Root> or interior mutability")
3322 }
3323
3324 fn with_result<Callback, R, E>(&self, _result: &Result<Root, E>, _f: Callback) -> Option<R>
3325 where
3326 Callback: FnOnce(&Value) -> R,
3327 {
3328 None
3331 }
3332
3333 fn with_result_mut<Callback, R, E>(&self, result: &mut Result<Root, E>, f: Callback) -> Option<R>
3334 where
3335 Callback: FnOnce(&mut Value) -> R,
3336 {
3337 result.as_mut().ok().and_then(|root| {
3338 self.get_mut(root).map(|value| f(value))
3339 })
3340 }
3341
3342 fn with_option<Callback, R>(&self, _option: &Option<Root>, _f: Callback) -> Option<R>
3343 where
3344 Callback: FnOnce(&Value) -> R,
3345 {
3346 None
3349 }
3350
3351 fn with_option_mut<Callback, R>(&self, option: &mut Option<Root>, f: Callback) -> Option<R>
3352 where
3353 Callback: FnOnce(&mut Value) -> R,
3354 {
3355 option.as_mut().and_then(|root| {
3356 self.get_mut(root).map(|value| f(value))
3357 })
3358 }
3359
3360 fn with_refcell<Callback, R>(&self, _refcell: &RefCell<Root>, _f: Callback) -> Option<R>
3361 where
3362 Callback: FnOnce(&Value) -> R,
3363 {
3364 None
3367 }
3368
3369 fn with_refcell_mut<Callback, R>(&self, refcell: &RefCell<Root>, f: Callback) -> Option<R>
3370 where
3371 Callback: FnOnce(&mut Value) -> R,
3372 {
3373 refcell.try_borrow_mut().ok().and_then(|mut borrow| {
3374 self.get_mut(&mut *borrow).map(|value| f(value))
3375 })
3376 }
3377
3378 #[cfg(feature = "tagged")]
3379 fn with_tagged<Tag, Callback, R>(&self, _tagged: &Tagged<Root, Tag>, _f: Callback) -> R
3380 where
3381 Tagged<Root, Tag>: std::ops::Deref<Target = Root>,
3382 Callback: FnOnce(&Value) -> R,
3383 {
3384 eprintln!("[DEBUG] WritableOptionalKeyPath::with_tagged requires &mut Tagged<Root, Tag> or interior mutability");
3387 unreachable!("WritableOptionalKeyPath::with_tagged requires &mut Tagged<Root, Tag> or interior mutability")
3388 }
3389
3390 fn with_mutex<Callback, R>(&self, mutex: &Mutex<Root>, f: Callback) -> Option<R>
3391 where
3392 Callback: FnOnce(&Value) -> R,
3393 {
3394 mutex.lock().ok().and_then(|mut guard| {
3395 self.get_mut(&mut *guard).map(|value| f(value))
3396 })
3397 }
3398
3399 fn with_mutex_mut<Callback, R>(&self, mutex: &mut Mutex<Root>, f: Callback) -> Option<R>
3400 where
3401 Callback: FnOnce(&mut Value) -> R,
3402 {
3403 mutex.get_mut().ok().and_then(|root| {
3405 self.get_mut(root).map(|value| f(value))
3406 })
3407 }
3408
3409 fn with_rwlock<Callback, R>(&self, _rwlock: &RwLock<Root>, _f: Callback) -> Option<R>
3410 where
3411 Callback: FnOnce(&Value) -> R,
3412 {
3413 None
3416 }
3417
3418 fn with_rwlock_mut<Callback, R>(&self, rwlock: &mut RwLock<Root>, f: Callback) -> Option<R>
3419 where
3420 Callback: FnOnce(&mut Value) -> R,
3421 {
3422 rwlock.get_mut().ok().and_then(|root| {
3424 self.get_mut(root).map(|value| f(value))
3425 })
3426 }
3427
3428 fn with_arc_rwlock<Callback, R>(&self, _arc_rwlock: &Arc<RwLock<Root>>, _f: Callback) -> Option<R>
3429 where
3430 Callback: FnOnce(&Value) -> R,
3431 {
3432 None
3435 }
3436
3437 fn with_arc_rwlock_mut<Callback, R>(&self, arc_rwlock: &Arc<RwLock<Root>>, f: Callback) -> Option<R>
3438 where
3439 Callback: FnOnce(&mut Value) -> R,
3440 {
3441 arc_rwlock.write().ok().and_then(|mut guard| {
3442 self.get_mut(&mut *guard).map(|value| f(value))
3443 })
3444 }
3445}