1#![cfg_attr(feature = "nightly", feature(impl_trait_in_assoc_type))]
4
5use std::sync::{Arc, Mutex, RwLock};
6use std::marker::PhantomData;
7use std::any::{Any, TypeId};
8use std::rc::Rc;
9use std::cell::RefCell;
10use std::ops::Shr;
11
12#[cfg(feature = "tagged")]
13use tagged_core::Tagged;
14
15
16#[macro_export]
38macro_rules! keypath {
39 ($closure:expr) => {
41 $crate::KeyPath::new($closure)
42 };
43}
44
45#[macro_export]
65macro_rules! opt_keypath {
66 ($closure:expr) => {
68 $crate::OptionalKeyPath::new($closure)
69 };
70}
71
72#[macro_export]
92macro_rules! writable_keypath {
93 ($closure:expr) => {
95 $crate::WritableKeyPath::new($closure)
96 };
97}
98
99#[macro_export]
119macro_rules! writable_opt_keypath {
120 ($closure:expr) => {
122 $crate::WritableOptionalKeyPath::new($closure)
123 };
124}
125
126#[derive(Clone)]
130pub struct KeyPath<Root, Value, F>
131where
132 F: for<'r> Fn(&'r Root) -> &'r Value,
133{
134 getter: F,
135 _phantom: PhantomData<(Root, Value)>,
136}
137
138impl<Root, Value, F> KeyPath<Root, Value, F>
139where
140 F: for<'r> Fn(&'r Root) -> &'r Value,
141{
142 pub fn new(getter: F) -> Self {
143 Self {
144 getter,
145 _phantom: PhantomData,
146 }
147 }
148
149 pub fn get<'r>(&self, root: &'r Root) -> &'r Value {
150 (self.getter)(root)
151}
152
153 pub fn for_box<Target>(self) -> KeyPath<Root, Target, impl for<'r> Fn(&'r Root) -> &'r Target + 'static>
156 where
157 Value: std::ops::Deref<Target = Target>,
158 F: 'static,
159 Value: 'static,
160 {
161 let getter = self.getter;
162
163 KeyPath {
164 getter: move |root: &Root| {
165 getter(root).deref()
166 },
167 _phantom: PhantomData,
168 }
169 }
170
171 pub fn for_arc<Target>(self) -> KeyPath<Root, Target, impl for<'r> Fn(&'r Root) -> &'r Target + 'static>
173 where
174 Value: std::ops::Deref<Target = Target>,
175 F: 'static,
176 Value: 'static,
177 {
178 let getter = self.getter;
179
180 KeyPath {
181 getter: move |root: &Root| {
182 getter(root).deref()
183 },
184 _phantom: PhantomData,
185 }
186 }
187
188 pub fn for_rc<Target>(self) -> KeyPath<Root, Target, impl for<'r> Fn(&'r Root) -> &'r Target + 'static>
190 where
191 Value: std::ops::Deref<Target = Target>,
192 F: 'static,
193 Value: 'static,
194 {
195 let getter = self.getter;
196
197 KeyPath {
198 getter: move |root: &Root| {
199 getter(root).deref()
200 },
201 _phantom: PhantomData,
202 }
203 }
204
205 pub fn for_arc_root(self) -> OptionalKeyPath<Arc<Root>, Value, impl for<'r> Fn(&'r Arc<Root>) -> Option<&'r Value> + 'static>
207 where
208 Value: Sized,
209 F: 'static,
210 Root: 'static,
211 Value: 'static,
212 {
213 let getter = self.getter;
214
215 OptionalKeyPath {
216 getter: move |arc: &Arc<Root>| {
217 Some(getter(arc.as_ref()))
218 },
219 _phantom: PhantomData,
220 }
221 }
222
223 pub fn for_box_root(self) -> OptionalKeyPath<Box<Root>, Value, impl for<'r> Fn(&'r Box<Root>) -> Option<&'r Value> + 'static>
225 where
226 Value: Sized,
227 F: 'static,
228 Root: 'static,
229 Value: 'static,
230 {
231 let getter = self.getter;
232
233 OptionalKeyPath {
234 getter: move |boxed: &Box<Root>| {
235 Some(getter(boxed.as_ref()))
236 },
237 _phantom: PhantomData,
238 }
239 }
240
241 pub fn for_rc_root(self) -> OptionalKeyPath<Rc<Root>, Value, impl for<'r> Fn(&'r Rc<Root>) -> Option<&'r Value> + 'static>
243 where
244 Value: Sized,
245 F: 'static,
246 Root: 'static,
247 Value: 'static,
248 {
249 let getter = self.getter;
250
251 OptionalKeyPath {
252 getter: move |rc: &Rc<Root>| {
253 Some(getter(rc.as_ref()))
254 },
255 _phantom: PhantomData,
256 }
257 }
258
259 pub fn for_result<E>(self) -> OptionalKeyPath<Result<Root, E>, Value, impl for<'r> Fn(&'r Result<Root, E>) -> Option<&'r Value> + 'static>
262 where
263 F: 'static,
264 Root: 'static,
265 Value: 'static,
266 E: 'static,
267 {
268 let getter = self.getter;
269
270 OptionalKeyPath {
271 getter: move |result: &Result<Root, E>| {
272 result.as_ref().ok().map(|root| getter(root))
273 },
274 _phantom: PhantomData,
275 }
276 }
277
278 pub fn to_optional(self) -> OptionalKeyPath<Root, Value, impl for<'r> Fn(&'r Root) -> Option<&'r Value> + 'static>
281 where
282 F: 'static,
283 {
284 let getter = self.getter;
285 OptionalKeyPath::new(move |root: &Root| Some(getter(root)))
286 }
287
288 pub fn with_option<Callback, R>(&self, option: &Option<Root>, f: Callback) -> Option<R>
290 where
291 F: Clone,
292 Callback: FnOnce(&Value) -> R,
293 {
294 option.as_ref().map(|root| {
295 let value = self.get(root);
296 f(value)
297 })
298 }
299
300 pub fn with_result<Callback, R, E>(&self, result: &Result<Root, E>, f: Callback) -> Option<R>
302 where
303 F: Clone,
304 Callback: FnOnce(&Value) -> R,
305 {
306 result.as_ref().ok().map(|root| {
307 let value = self.get(root);
308 f(value)
309 })
310 }
311
312 pub fn with_box<Callback, R>(&self, boxed: &Box<Root>, f: Callback) -> R
314 where
315 F: Clone,
316 Callback: FnOnce(&Value) -> R,
317 {
318 let value = self.get(boxed);
319 f(value)
320 }
321
322 pub fn with_arc<Callback, R>(&self, arc: &Arc<Root>, f: Callback) -> R
324 where
325 F: Clone,
326 Callback: FnOnce(&Value) -> R,
327 {
328 let value = self.get(arc);
329 f(value)
330 }
331
332 pub fn with_rc<Callback, R>(&self, rc: &Rc<Root>, f: Callback) -> R
334 where
335 F: Clone,
336 Callback: FnOnce(&Value) -> R,
337 {
338 let value = self.get(rc);
339 f(value)
340 }
341
342 pub fn with_refcell<Callback, R>(&self, refcell: &RefCell<Root>, f: Callback) -> Option<R>
344 where
345 F: Clone,
346 Callback: FnOnce(&Value) -> R,
347 {
348 refcell.try_borrow().ok().map(|borrow| {
349 let value = self.get(&*borrow);
350 f(value)
351 })
352 }
353
354 pub fn with_mutex<Callback, R>(&self, mutex: &Mutex<Root>, f: Callback) -> Option<R>
356 where
357 F: Clone,
358 Callback: FnOnce(&Value) -> R,
359 {
360 mutex.lock().ok().map(|guard| {
361 let value = self.get(&*guard);
362 f(value)
363 })
364 }
365
366 pub fn with_rwlock<Callback, R>(&self, rwlock: &RwLock<Root>, f: Callback) -> Option<R>
368 where
369 F: Clone,
370 Callback: FnOnce(&Value) -> R,
371 {
372 rwlock.read().ok().map(|guard| {
373 let value = self.get(&*guard);
374 f(value)
375 })
376 }
377
378 pub fn with_arc_rwlock<Callback, R>(&self, arc_rwlock: &Arc<RwLock<Root>>, f: Callback) -> Option<R>
380 where
381 F: Clone,
382 Callback: FnOnce(&Value) -> R,
383 {
384 arc_rwlock.read().ok().map(|guard| {
385 let value = self.get(&*guard);
386 f(value)
387 })
388 }
389
390 pub fn with_arc_mutex<Callback, R>(&self, arc_mutex: &Arc<Mutex<Root>>, f: Callback) -> Option<R>
392 where
393 F: Clone,
394 Callback: FnOnce(&Value) -> R,
395 {
396 arc_mutex.lock().ok().map(|guard| {
397 let value = self.get(&*guard);
398 f(value)
399 })
400 }
401
402 #[cfg(feature = "tagged")]
403 pub fn for_tagged<Tag>(self) -> KeyPath<Tagged<Root, Tag>, Value, impl for<'r> Fn(&'r Tagged<Root, Tag>) -> &'r Value + 'static>
406 where
407 Tagged<Root, Tag>: std::ops::Deref<Target = Root>,
408 F: 'static,
409 Root: 'static,
410 Value: 'static,
411 Tag: 'static,
412 {
413 use std::ops::Deref;
414 let getter = self.getter;
415
416 KeyPath {
417 getter: move |tagged: &Tagged<Root, Tag>| {
418 getter(tagged.deref())
419 },
420 _phantom: PhantomData,
421 }
422 }
423
424 #[cfg(feature = "tagged")]
425 pub fn with_tagged<Tag, Callback, R>(&self, tagged: &Tagged<Root, Tag>, f: Callback) -> R
428 where
429 Tagged<Root, Tag>: std::ops::Deref<Target = Root>,
430 Callback: FnOnce(&Value) -> R,
431 {
432 use std::ops::Deref;
433 let value = self.get(tagged.deref());
434 f(value)
435 }
436
437 pub fn for_option(self) -> OptionalKeyPath<Option<Root>, Value, impl for<'r> Fn(&'r Option<Root>) -> Option<&'r Value> + 'static>
440 where
441 F: 'static,
442 Root: 'static,
443 Value: 'static,
444 {
445 let getter = self.getter;
446
447 OptionalKeyPath {
448 getter: move |opt: &Option<Root>| {
449 opt.as_ref().map(|root| getter(root))
450 },
451 _phantom: PhantomData,
452 }
453 }
454
455 pub fn iter<'r, T>(&self, root: &'r Root) -> Option<std::slice::Iter<'r, T>>
458 where
459 Value: AsRef<[T]> + 'r,
460 {
461 let value_ref: &'r Value = self.get(root);
462 Some(value_ref.as_ref().iter())
463 }
464
465 pub fn extract_from_slice<'r>(&self, slice: &'r [Root]) -> Vec<&'r Value> {
468 slice.iter().map(|item| self.get(item)).collect()
469 }
470
471 pub fn extract_from_ref_slice<'r>(&self, slice: &'r [&Root]) -> Vec<&'r Value> {
474 slice.iter().map(|item| self.get(item)).collect()
475 }
476
477 pub fn then<SubValue, G>(
480 self,
481 next: KeyPath<Value, SubValue, G>,
482 ) -> KeyPath<Root, SubValue, impl for<'r> Fn(&'r Root) -> &'r SubValue>
483 where
484 G: for<'r> Fn(&'r Value) -> &'r SubValue,
485 F: 'static,
486 G: 'static,
487 Value: 'static,
488 {
489 let first = self.getter;
490 let second = next.getter;
491
492 KeyPath::new(move |root: &Root| {
493 let value = first(root);
494 second(value)
495 })
496 }
497
498 pub fn then_optional<SubValue, G>(
501 self,
502 next: OptionalKeyPath<Value, SubValue, G>,
503 ) -> OptionalKeyPath<Root, SubValue, impl for<'r> Fn(&'r Root) -> Option<&'r SubValue>>
504 where
505 G: for<'r> Fn(&'r Value) -> Option<&'r SubValue>,
506 F: 'static,
507 G: 'static,
508 Value: 'static,
509 {
510 let first = self.getter;
511 let second = next.getter;
512
513 OptionalKeyPath::new(move |root: &Root| {
514 let value = first(root);
515 second(value)
516 })
517 }
518
519}
520
521impl<Root, Value, F> KeyPath<Root, Value, F>
523where
524 F: for<'r> Fn(&'r Root) -> &'r Value,
525{
526 pub fn with_arc_rwlock_direct<Callback, R>(&self, arc_rwlock: &Arc<RwLock<Root>>, f: Callback) -> Option<R>
529 where
530 Callback: FnOnce(&Value) -> R,
531 {
532 arc_rwlock.read().ok().map(|guard| {
533 let value = self.get(&*guard);
534 f(value)
535 })
536 }
537
538 pub fn with_arc_mutex_direct<Callback, R>(&self, arc_mutex: &Arc<Mutex<Root>>, f: Callback) -> Option<R>
541 where
542 Callback: FnOnce(&Value) -> R,
543 {
544 arc_mutex.lock().ok().map(|guard| {
545 let value = self.get(&*guard);
546 f(value)
547 })
548 }
549}
550
551pub fn for_slice<T>() -> impl for<'r> Fn(&'r [T], usize) -> Option<&'r T> {
553 |slice: &[T], index: usize| slice.get(index)
554}
555
556pub mod containers {
558 use super::{OptionalKeyPath, WritableOptionalKeyPath, KeyPath, WritableKeyPath};
559 use std::collections::{HashMap, BTreeMap, HashSet, BTreeSet, VecDeque, LinkedList, BinaryHeap};
560 use std::sync::{Mutex, RwLock, Weak as StdWeak, Arc};
561 use std::rc::{Weak as RcWeak, Rc};
562 use std::ops::{Deref, DerefMut};
563
564 #[cfg(feature = "parking_lot")]
565 use parking_lot::{Mutex as ParkingMutex, RwLock as ParkingRwLock};
566
567 #[cfg(feature = "tagged")]
568 use tagged_core::Tagged;
569
570 pub fn for_vec_index<T>(index: usize) -> OptionalKeyPath<Vec<T>, T, impl for<'r> Fn(&'r Vec<T>) -> Option<&'r T>> {
572 OptionalKeyPath::new(move |vec: &Vec<T>| vec.get(index))
573 }
574
575 pub fn for_vecdeque_index<T>(index: usize) -> OptionalKeyPath<VecDeque<T>, T, impl for<'r> Fn(&'r VecDeque<T>) -> Option<&'r T>> {
577 OptionalKeyPath::new(move |deque: &VecDeque<T>| deque.get(index))
578 }
579
580 pub fn for_linkedlist_index<T>(index: usize) -> OptionalKeyPath<LinkedList<T>, T, impl for<'r> Fn(&'r LinkedList<T>) -> Option<&'r T>> {
582 OptionalKeyPath::new(move |list: &LinkedList<T>| {
583 list.iter().nth(index)
584 })
585 }
586
587 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>>
589 where
590 K: std::hash::Hash + Eq + Clone + 'static,
591 V: 'static,
592 {
593 OptionalKeyPath::new(move |map: &HashMap<K, V>| map.get(&key))
594 }
595
596 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>>
598 where
599 K: Ord + Clone + 'static,
600 V: 'static,
601 {
602 OptionalKeyPath::new(move |map: &BTreeMap<K, V>| map.get(&key))
603 }
604
605 pub fn for_hashset_get<T>(value: T) -> OptionalKeyPath<HashSet<T>, T, impl for<'r> Fn(&'r HashSet<T>) -> Option<&'r T>>
607 where
608 T: std::hash::Hash + Eq + Clone + 'static,
609 {
610 OptionalKeyPath::new(move |set: &HashSet<T>| set.get(&value))
611 }
612
613 pub fn for_btreeset_get<T>(value: T) -> OptionalKeyPath<BTreeSet<T>, T, impl for<'r> Fn(&'r BTreeSet<T>) -> Option<&'r T>>
615 where
616 T: Ord + Clone + 'static,
617 {
618 OptionalKeyPath::new(move |set: &BTreeSet<T>| set.get(&value))
619 }
620
621 pub fn for_binaryheap_peek<T>() -> OptionalKeyPath<BinaryHeap<T>, T, impl for<'r> Fn(&'r BinaryHeap<T>) -> Option<&'r T>>
623 where
624 T: Ord + 'static,
625 {
626 OptionalKeyPath::new(|heap: &BinaryHeap<T>| heap.peek())
627 }
628
629 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>> {
633 WritableOptionalKeyPath::new(move |vec: &mut Vec<T>| vec.get_mut(index))
634 }
635
636 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>> {
638 WritableOptionalKeyPath::new(move |deque: &mut VecDeque<T>| deque.get_mut(index))
639 }
640
641 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>> {
643 WritableOptionalKeyPath::new(move |list: &mut LinkedList<T>| {
644 let mut iter = list.iter_mut();
646 iter.nth(index)
647 })
648 }
649
650 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>>
652 where
653 K: std::hash::Hash + Eq + Clone + 'static,
654 V: 'static,
655 {
656 WritableOptionalKeyPath::new(move |map: &mut HashMap<K, V>| map.get_mut(&key))
657 }
658
659 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>>
661 where
662 K: Ord + Clone + 'static,
663 V: 'static,
664 {
665 WritableOptionalKeyPath::new(move |map: &mut BTreeMap<K, V>| map.get_mut(&key))
666 }
667
668 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>>
671 where
672 T: std::hash::Hash + Eq + Clone + 'static,
673 {
674 WritableOptionalKeyPath::new(move |set: &mut HashSet<T>| {
675 if set.contains(&value) {
678 None
681 } else {
682 None
683 }
684 })
685 }
686
687 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>>
690 where
691 T: Ord + Clone + 'static,
692 {
693 WritableOptionalKeyPath::new(move |set: &mut BTreeSet<T>| {
694 if set.contains(&value) {
697 None
700 } else {
701 None
702 }
703 })
704 }
705
706 pub fn for_binaryheap_peek_mut<T>() -> WritableOptionalKeyPath<BinaryHeap<T>, T, impl for<'r> Fn(&'r mut BinaryHeap<T>) -> Option<&'r mut T>>
712 where
713 T: Ord + 'static,
714 {
715 WritableOptionalKeyPath::new(|_heap: &mut BinaryHeap<T>| {
719 None
720 })
721 }
722
723 pub fn lock_mutex<T>(mutex: &Mutex<T>) -> Option<std::sync::MutexGuard<'_, T>> {
732 mutex.lock().ok()
733 }
734
735 pub fn read_rwlock<T>(rwlock: &RwLock<T>) -> Option<std::sync::RwLockReadGuard<'_, T>> {
739 rwlock.read().ok()
740 }
741
742 pub fn write_rwlock<T>(rwlock: &RwLock<T>) -> Option<std::sync::RwLockWriteGuard<'_, T>> {
746 rwlock.write().ok()
747 }
748
749 pub fn lock_arc_mutex<T>(arc_mutex: &Arc<Mutex<T>>) -> Option<std::sync::MutexGuard<'_, T>> {
753 arc_mutex.lock().ok()
754 }
755
756 pub fn read_arc_rwlock<T>(arc_rwlock: &Arc<RwLock<T>>) -> Option<std::sync::RwLockReadGuard<'_, T>> {
760 arc_rwlock.read().ok()
761 }
762
763 pub fn write_arc_rwlock<T>(arc_rwlock: &Arc<RwLock<T>>) -> Option<std::sync::RwLockWriteGuard<'_, T>> {
767 arc_rwlock.write().ok()
768 }
769
770 pub fn upgrade_weak<T>(weak: &StdWeak<T>) -> Option<Arc<T>> {
774 weak.upgrade()
775 }
776
777 pub fn upgrade_rc_weak<T>(weak: &RcWeak<T>) -> Option<Rc<T>> {
781 weak.upgrade()
782 }
783
784 #[cfg(feature = "parking_lot")]
785 pub fn lock_parking_mutex<T>(mutex: &ParkingMutex<T>) -> parking_lot::MutexGuard<'_, T> {
788 mutex.lock()
789 }
790
791 #[cfg(feature = "parking_lot")]
792 pub fn read_parking_rwlock<T>(rwlock: &ParkingRwLock<T>) -> parking_lot::RwLockReadGuard<'_, T> {
795 rwlock.read()
796 }
797
798 #[cfg(feature = "parking_lot")]
799 pub fn write_parking_rwlock<T>(rwlock: &ParkingRwLock<T>) -> parking_lot::RwLockWriteGuard<'_, T> {
802 rwlock.write()
803 }
804
805 #[cfg(feature = "tagged")]
806 pub fn for_tagged<Tag, T>() -> KeyPath<Tagged<Tag, T>, T, impl for<'r> Fn(&'r Tagged<Tag, T>) -> &'r T>
809 where
810 Tagged<Tag, T>: std::ops::Deref<Target = T>,
811 Tag: 'static,
812 T: 'static,
813 {
814 KeyPath::new(|tagged: &Tagged<Tag, T>| tagged.deref())
815 }
816
817 #[cfg(feature = "tagged")]
818 pub fn for_tagged_mut<Tag, T>() -> WritableKeyPath<Tagged<Tag, T>, T, impl for<'r> Fn(&'r mut Tagged<Tag, T>) -> &'r mut T>
821 where
822 Tagged<Tag, T>: std::ops::DerefMut<Target = T>,
823 Tag: 'static,
824 T: 'static,
825 {
826 WritableKeyPath::new(|tagged: &mut Tagged<Tag, T>| tagged.deref_mut())
827 }
828}
829
830#[derive(Clone)]
832pub struct OptionalKeyPath<Root, Value, F>
833where
834 F: for<'r> Fn(&'r Root) -> Option<&'r Value>,
835{
836 getter: F,
837 _phantom: PhantomData<(Root, Value)>,
838}
839
840impl<Root, Value, F> OptionalKeyPath<Root, Value, F>
841where
842 F: for<'r> Fn(&'r Root) -> Option<&'r Value>,
843{
844 pub fn new(getter: F) -> Self {
845 Self {
846 getter,
847 _phantom: PhantomData,
848 }
849 }
850
851 pub fn get<'r>(&self, root: &'r Root) -> Option<&'r Value> {
852 (self.getter)(root)
853 }
854
855 pub fn then<SubValue, G>(
857 self,
858 next: OptionalKeyPath<Value, SubValue, G>,
859 ) -> OptionalKeyPath<Root, SubValue, impl for<'r> Fn(&'r Root) -> Option<&'r SubValue>>
860 where
861 G: for<'r> Fn(&'r Value) -> Option<&'r SubValue>,
862 F: 'static,
863 G: 'static,
864 Value: 'static,
865 {
866 let first = self.getter;
867 let second = next.getter;
868
869 OptionalKeyPath::new(move |root: &Root| {
870 first(root).and_then(|value| second(value))
871 })
872 }
873
874 pub fn for_box<Target>(self) -> OptionalKeyPath<Root, Target, impl for<'r> Fn(&'r Root) -> Option<&'r Target> + 'static>
877 where
878 Value: std::ops::Deref<Target = Target>,
879 F: 'static,
880 Value: 'static,
881 {
882 let getter = self.getter;
883
884 OptionalKeyPath {
885 getter: move |root: &Root| {
886 getter(root).map(|boxed| boxed.deref())
887 },
888 _phantom: PhantomData,
889 }
890 }
891
892 pub fn for_arc<Target>(self) -> OptionalKeyPath<Root, Target, impl for<'r> Fn(&'r Root) -> Option<&'r Target> + 'static>
894 where
895 Value: std::ops::Deref<Target = Target>,
896 F: 'static,
897 Value: 'static,
898 {
899 let getter = self.getter;
900
901 OptionalKeyPath {
902 getter: move |root: &Root| {
903 getter(root).map(|arc| arc.deref())
904 },
905 _phantom: PhantomData,
906 }
907 }
908
909 pub fn for_rc<Target>(self) -> OptionalKeyPath<Root, Target, impl for<'r> Fn(&'r Root) -> Option<&'r Target> + 'static>
911 where
912 Value: std::ops::Deref<Target = Target>,
913 F: 'static,
914 Value: 'static,
915 {
916 let getter = self.getter;
917
918 OptionalKeyPath {
919 getter: move |root: &Root| {
920 getter(root).map(|rc| rc.deref())
921 },
922 _phantom: PhantomData,
923 }
924 }
925
926 #[cfg(feature = "tagged")]
927 pub fn for_tagged<Tag>(self) -> OptionalKeyPath<Tagged<Root, Tag>, Value, impl for<'r> Fn(&'r Tagged<Root, Tag>) -> Option<&'r Value> + 'static>
930 where
931 Tagged<Root, Tag>: std::ops::Deref<Target = Root>,
932 F: 'static,
933 Root: 'static,
934 Value: 'static,
935 Tag: 'static,
936 {
937 use std::ops::Deref;
938 let getter = self.getter;
939
940 OptionalKeyPath {
941 getter: move |tagged: &Tagged<Root, Tag>| {
942 getter(tagged.deref())
943 },
944 _phantom: PhantomData,
945 }
946 }
947
948 #[cfg(feature = "tagged")]
949 pub fn with_tagged<Tag, Callback, R>(&self, tagged: &Tagged<Root, Tag>, f: Callback) -> Option<R>
952 where
953 Tagged<Root, Tag>: std::ops::Deref<Target = Root>,
954 F: Clone,
955 Callback: FnOnce(&Value) -> R,
956 {
957 use std::ops::Deref;
958 self.get(tagged.deref()).map(|value| f(value))
959 }
960
961 pub fn for_option(self) -> OptionalKeyPath<Option<Root>, Value, impl for<'r> Fn(&'r Option<Root>) -> Option<&'r Value> + 'static>
964 where
965 F: 'static,
966 Root: 'static,
967 Value: 'static,
968 {
969 let getter = self.getter;
970
971 OptionalKeyPath {
972 getter: move |opt: &Option<Root>| {
973 opt.as_ref().and_then(|root| getter(root))
974 },
975 _phantom: PhantomData,
976 }
977 }
978
979 pub fn for_result<E>(self) -> OptionalKeyPath<Result<Root, E>, Value, impl for<'r> Fn(&'r Result<Root, E>) -> Option<&'r Value> + 'static>
982 where
983 F: 'static,
984 Root: 'static,
985 Value: 'static,
986 E: 'static,
987 {
988 let getter = self.getter;
989
990 OptionalKeyPath {
991 getter: move |result: &Result<Root, E>| {
992 result.as_ref().ok().and_then(|root| getter(root))
993 },
994 _phantom: PhantomData,
995 }
996 }
997
998 pub fn for_arc_root(self) -> OptionalKeyPath<Arc<Root>, Value, impl for<'r> Fn(&'r Arc<Root>) -> Option<&'r Value> + 'static>
1000 where
1001 Value: Sized,
1002 F: 'static,
1003 Root: 'static,
1004 Value: 'static,
1005 {
1006 let getter = self.getter;
1007
1008 OptionalKeyPath {
1009 getter: move |arc: &Arc<Root>| {
1010 getter(arc.as_ref())
1011 },
1012 _phantom: PhantomData,
1013 }
1014 }
1015
1016 pub fn for_rc_root(self) -> OptionalKeyPath<Rc<Root>, Value, impl for<'r> Fn(&'r Rc<Root>) -> Option<&'r Value> + 'static>
1018 where
1019 Value: Sized,
1020 F: 'static,
1021 Root: 'static,
1022 Value: 'static,
1023 {
1024 let getter = self.getter;
1025
1026 OptionalKeyPath {
1027 getter: move |rc: &Rc<Root>| {
1028 getter(rc.as_ref())
1029 },
1030 _phantom: PhantomData,
1031 }
1032 }
1033
1034 pub fn with_option<Callback, R>(&self, option: &Option<Root>, f: Callback) -> Option<R>
1036 where
1037 F: Clone,
1038 Callback: FnOnce(&Value) -> R,
1039 {
1040 option.as_ref().and_then(|root| {
1041 self.get(root).map(|value| f(value))
1042 })
1043 }
1044
1045 pub fn with_mutex<Callback, R>(&self, mutex: &Mutex<Root>, f: Callback) -> Option<R>
1047 where
1048 F: Clone,
1049 Callback: FnOnce(&Value) -> R,
1050 {
1051 mutex.lock().ok().and_then(|guard| {
1052 self.get(&*guard).map(|value| f(value))
1053 })
1054 }
1055
1056 pub fn with_rwlock<Callback, R>(&self, rwlock: &RwLock<Root>, f: Callback) -> Option<R>
1058 where
1059 F: Clone,
1060 Callback: FnOnce(&Value) -> R,
1061 {
1062 rwlock.read().ok().and_then(|guard| {
1063 self.get(&*guard).map(|value| f(value))
1064 })
1065 }
1066
1067 pub fn with_arc_rwlock<Callback, R>(&self, arc_rwlock: &Arc<RwLock<Root>>, f: Callback) -> Option<R>
1069 where
1070 F: Clone,
1071 Callback: FnOnce(&Value) -> R,
1072 {
1073 arc_rwlock.read().ok().and_then(|guard| {
1074 self.get(&*guard).map(|value| f(value))
1075 })
1076 }
1077
1078 pub fn with_arc_rwlock_direct<Callback, R>(&self, arc_rwlock: &Arc<RwLock<Root>>, f: Callback) -> Option<R>
1082 where
1083 Callback: FnOnce(&Value) -> R,
1084 {
1085 arc_rwlock.read().ok().and_then(|guard| {
1086 self.get(&*guard).map(|value| f(value))
1087 })
1088 }
1089
1090 pub fn with_arc_mutex<Callback, R>(&self, arc_mutex: &Arc<Mutex<Root>>, f: Callback) -> Option<R>
1092 where
1093 F: Clone,
1094 Callback: FnOnce(&Value) -> R,
1095 {
1096 arc_mutex.lock().ok().and_then(|guard| {
1097 self.get(&*guard).map(|value| f(value))
1098 })
1099 }
1100}
1101
1102
1103#[derive(Clone)]
1105pub struct WritableKeyPath<Root, Value, F>
1106where
1107 F: for<'r> Fn(&'r mut Root) -> &'r mut Value,
1108{
1109 getter: F,
1110 _phantom: PhantomData<(Root, Value)>,
1111}
1112
1113impl<Root, Value, F> WritableKeyPath<Root, Value, F>
1114where
1115 F: for<'r> Fn(&'r mut Root) -> &'r mut Value,
1116{
1117 pub fn new(getter: F) -> Self {
1118 Self {
1119 getter,
1120 _phantom: PhantomData,
1121 }
1122 }
1123
1124 pub fn get_mut<'r>(&self, root: &'r mut Root) -> &'r mut Value {
1125 (self.getter)(root)
1126 }
1127
1128 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>
1131 where
1132 F: 'static,
1133 Root: 'static,
1134 Value: 'static,
1135 E: 'static,
1136 {
1137 let getter = self.getter;
1138
1139 WritableOptionalKeyPath {
1140 getter: move |result: &mut Result<Root, E>| {
1141 result.as_mut().ok().map(|root| getter(root))
1142 },
1143 _phantom: PhantomData,
1144 }
1145 }
1146
1147 pub fn for_box_root(self) -> WritableKeyPath<Box<Root>, Value, impl for<'r> Fn(&'r mut Box<Root>) -> &'r mut Value + 'static>
1149 where
1150 Value: Sized,
1151 F: 'static,
1152 Root: 'static,
1153 Value: 'static,
1154 {
1155 let getter = self.getter;
1156
1157 WritableKeyPath {
1158 getter: move |boxed: &mut Box<Root>| {
1159 getter(boxed.as_mut())
1160 },
1161 _phantom: PhantomData,
1162 }
1163 }
1164
1165 pub fn for_option(self) -> WritableOptionalKeyPath<Option<Root>, Value, impl for<'r> Fn(&'r mut Option<Root>) -> Option<&'r mut Value> + 'static>
1168 where
1169 F: 'static,
1170 Root: 'static,
1171 Value: 'static,
1172 {
1173 let getter = self.getter;
1174
1175 WritableOptionalKeyPath {
1176 getter: move |option: &mut Option<Root>| {
1177 option.as_mut().map(|root| getter(root))
1178 },
1179 _phantom: PhantomData,
1180 }
1181 }
1182
1183 pub fn to_optional(self) -> WritableOptionalKeyPath<Root, Value, impl for<'r> Fn(&'r mut Root) -> Option<&'r mut Value> + 'static>
1186 where
1187 F: 'static,
1188 {
1189 let getter = self.getter;
1190 WritableOptionalKeyPath::new(move |root: &mut Root| Some(getter(root)))
1191 }
1192
1193 pub fn for_box<Target>(self) -> WritableKeyPath<Root, Target, impl for<'r> Fn(&'r mut Root) -> &'r mut Target + 'static>
1196 where
1197 Value: std::ops::DerefMut<Target = Target>,
1198 F: 'static,
1199 Value: 'static,
1200 {
1201 let getter = self.getter;
1202
1203 WritableKeyPath {
1204 getter: move |root: &mut Root| {
1205 getter(root).deref_mut()
1206 },
1207 _phantom: PhantomData,
1208 }
1209 }
1210
1211 pub fn for_arc<Target>(self) -> WritableKeyPath<Root, Target, impl for<'r> Fn(&'r mut Root) -> &'r mut Target + 'static>
1214 where
1215 Value: std::ops::DerefMut<Target = Target>,
1216 F: 'static,
1217 Value: 'static,
1218 {
1219 let getter = self.getter;
1220
1221 WritableKeyPath {
1222 getter: move |root: &mut Root| {
1223 getter(root).deref_mut()
1224 },
1225 _phantom: PhantomData,
1226 }
1227 }
1228
1229 pub fn for_rc<Target>(self) -> WritableKeyPath<Root, Target, impl for<'r> Fn(&'r mut Root) -> &'r mut Target + 'static>
1232 where
1233 Value: std::ops::DerefMut<Target = Target>,
1234 F: 'static,
1235 Value: 'static,
1236 {
1237 let getter = self.getter;
1238
1239 WritableKeyPath {
1240 getter: move |root: &mut Root| {
1241 getter(root).deref_mut()
1242 },
1243 _phantom: PhantomData,
1244 }
1245 }
1246
1247 pub fn with_box_mut<Callback, R>(&self, boxed: &mut Box<Root>, f: Callback) -> R
1249 where
1250 F: Clone,
1251 Callback: FnOnce(&mut Value) -> R,
1252 {
1253 let value = self.get_mut(boxed);
1254 f(value)
1255 }
1256
1257 pub fn with_result_mut<Callback, R, E>(&self, result: &mut Result<Root, E>, f: Callback) -> Option<R>
1259 where
1260 F: Clone,
1261 Callback: FnOnce(&mut Value) -> R,
1262 {
1263 result.as_mut().ok().map(|root| {
1264 let value = self.get_mut(root);
1265 f(value)
1266 })
1267 }
1268
1269 pub fn with_option_mut<Callback, R>(&self, option: &mut Option<Root>, f: Callback) -> Option<R>
1271 where
1272 F: Clone,
1273 Callback: FnOnce(&mut Value) -> R,
1274 {
1275 option.as_mut().map(|root| {
1276 let value = self.get_mut(root);
1277 f(value)
1278 })
1279 }
1280
1281 pub fn with_refcell_mut<Callback, R>(&self, refcell: &RefCell<Root>, f: Callback) -> Option<R>
1283 where
1284 F: Clone,
1285 Callback: FnOnce(&mut Value) -> R,
1286 {
1287 refcell.try_borrow_mut().ok().map(|mut borrow| {
1288 let value = self.get_mut(&mut *borrow);
1289 f(value)
1290 })
1291 }
1292
1293 pub fn with_mutex_mut<Callback, R>(&self, mutex: &mut Mutex<Root>, f: Callback) -> Option<R>
1295 where
1296 F: Clone,
1297 Callback: FnOnce(&mut Value) -> R,
1298 {
1299 mutex.get_mut().ok().map(|root| {
1300 let value = self.get_mut(root);
1301 f(value)
1302 })
1303 }
1304
1305 pub fn with_rwlock_mut<Callback, R>(&self, rwlock: &mut RwLock<Root>, f: Callback) -> Option<R>
1307 where
1308 F: Clone,
1309 Callback: FnOnce(&mut Value) -> R,
1310 {
1311 rwlock.write().ok().map(|mut guard| {
1312 let value = self.get_mut(&mut *guard);
1313 f(value)
1314 })
1315 }
1316
1317 pub fn iter_mut<'r, T>(&self, root: &'r mut Root) -> Option<std::slice::IterMut<'r, T>>
1320 where
1321 Value: AsMut<[T]> + 'r,
1322 {
1323 let value_ref: &'r mut Value = self.get_mut(root);
1324 Some(value_ref.as_mut().iter_mut())
1325 }
1326
1327 pub fn extract_mut_from_slice<'r>(&self, slice: &'r mut [Root]) -> Vec<&'r mut Value> {
1330 slice.iter_mut().map(|item| self.get_mut(item)).collect()
1331 }
1332
1333 pub fn extract_mut_from_ref_slice<'r>(&self, slice: &'r mut [&'r mut Root]) -> Vec<&'r mut Value> {
1336 slice.iter_mut().map(|item| self.get_mut(*item)).collect()
1337 }
1338
1339 pub fn then<SubValue, G>(
1342 self,
1343 next: WritableKeyPath<Value, SubValue, G>,
1344 ) -> WritableKeyPath<Root, SubValue, impl for<'r> Fn(&'r mut Root) -> &'r mut SubValue>
1345 where
1346 G: for<'r> Fn(&'r mut Value) -> &'r mut SubValue,
1347 F: 'static,
1348 G: 'static,
1349 Value: 'static,
1350 {
1351 let first = self.getter;
1352 let second = next.getter;
1353
1354 WritableKeyPath::new(move |root: &mut Root| {
1355 let value = first(root);
1356 second(value)
1357 })
1358 }
1359
1360 pub fn then_optional<SubValue, G>(
1363 self,
1364 next: WritableOptionalKeyPath<Value, SubValue, G>,
1365 ) -> WritableOptionalKeyPath<Root, SubValue, impl for<'r> Fn(&'r mut Root) -> Option<&'r mut SubValue>>
1366 where
1367 G: for<'r> Fn(&'r mut Value) -> Option<&'r mut SubValue>,
1368 F: 'static,
1369 G: 'static,
1370 Value: 'static,
1371 {
1372 let first = self.getter;
1373 let second = next.getter;
1374
1375 WritableOptionalKeyPath::new(move |root: &mut Root| {
1376 let value = first(root);
1377 second(value)
1378 })
1379 }
1380}
1381
1382#[derive(Clone)]
1384pub struct WritableOptionalKeyPath<Root, Value, F>
1385where
1386 F: for<'r> Fn(&'r mut Root) -> Option<&'r mut Value>,
1387{
1388 getter: F,
1389 _phantom: PhantomData<(Root, Value)>,
1390}
1391
1392impl<Root, Value, F> WritableOptionalKeyPath<Root, Value, F>
1393where
1394 F: for<'r> Fn(&'r mut Root) -> Option<&'r mut Value>,
1395{
1396 pub fn new(getter: F) -> Self {
1397 Self {
1398 getter,
1399 _phantom: PhantomData,
1400 }
1401 }
1402
1403 pub fn get_mut<'r>(&self, root: &'r mut Root) -> Option<&'r mut Value> {
1404 (self.getter)(root)
1405 }
1406
1407 pub fn for_option(self) -> WritableOptionalKeyPath<Option<Root>, Value, impl for<'r> Fn(&'r mut Option<Root>) -> Option<&'r mut Value> + 'static>
1410 where
1411 F: 'static,
1412 Root: 'static,
1413 Value: 'static,
1414 {
1415 let getter = self.getter;
1416
1417 WritableOptionalKeyPath {
1418 getter: move |option: &mut Option<Root>| {
1419 option.as_mut().and_then(|root| getter(root))
1420 },
1421 _phantom: PhantomData,
1422 }
1423 }
1424
1425 pub fn then<SubValue, G>(
1427 self,
1428 next: WritableOptionalKeyPath<Value, SubValue, G>,
1429 ) -> WritableOptionalKeyPath<Root, SubValue, impl for<'r> Fn(&'r mut Root) -> Option<&'r mut SubValue>>
1430 where
1431 G: for<'r> Fn(&'r mut Value) -> Option<&'r mut SubValue>,
1432 F: 'static,
1433 G: 'static,
1434 Value: 'static,
1435 {
1436 let first = self.getter;
1437 let second = next.getter;
1438
1439 WritableOptionalKeyPath::new(move |root: &mut Root| {
1440 first(root).and_then(|value| second(value))
1441 })
1442 }
1443
1444 pub fn for_box<Target>(self) -> WritableOptionalKeyPath<Root, Target, impl for<'r> Fn(&'r mut Root) -> Option<&'r mut Target> + 'static>
1447 where
1448 Value: std::ops::DerefMut<Target = Target>,
1449 F: 'static,
1450 Value: 'static,
1451 {
1452 let getter = self.getter;
1453
1454 WritableOptionalKeyPath {
1455 getter: move |root: &mut Root| {
1456 getter(root).map(|boxed| boxed.deref_mut())
1457 },
1458 _phantom: PhantomData,
1459 }
1460 }
1461
1462 pub fn for_arc<Target>(self) -> WritableOptionalKeyPath<Root, Target, impl for<'r> Fn(&'r mut Root) -> Option<&'r mut Target> + 'static>
1464 where
1465 Value: std::ops::DerefMut<Target = Target>,
1466 F: 'static,
1467 Value: 'static,
1468 {
1469 let getter = self.getter;
1470
1471 WritableOptionalKeyPath {
1472 getter: move |root: &mut Root| {
1473 getter(root).map(|arc| arc.deref_mut())
1474 },
1475 _phantom: PhantomData,
1476 }
1477 }
1478
1479 pub fn for_rc<Target>(self) -> WritableOptionalKeyPath<Root, Target, impl for<'r> Fn(&'r mut Root) -> Option<&'r mut Target> + 'static>
1481 where
1482 Value: std::ops::DerefMut<Target = Target>,
1483 F: 'static,
1484 Value: 'static,
1485 {
1486 let getter = self.getter;
1487
1488 WritableOptionalKeyPath {
1489 getter: move |root: &mut Root| {
1490 getter(root).map(|rc| rc.deref_mut())
1491 },
1492 _phantom: PhantomData,
1493 }
1494 }
1495
1496 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>
1499 where
1500 F: 'static,
1501 Root: 'static,
1502 Value: 'static,
1503 E: 'static,
1504 {
1505 let getter = self.getter;
1506
1507 WritableOptionalKeyPath {
1508 getter: move |result: &mut Result<Root, E>| {
1509 result.as_mut().ok().and_then(|root| getter(root))
1510 },
1511 _phantom: PhantomData,
1512 }
1513 }
1514
1515 pub fn for_box_root(self) -> WritableOptionalKeyPath<Box<Root>, Value, impl for<'r> Fn(&'r mut Box<Root>) -> Option<&'r mut Value> + 'static>
1517 where
1518 Value: Sized,
1519 F: 'static,
1520 Root: 'static,
1521 Value: 'static,
1522 {
1523 let getter = self.getter;
1524
1525 WritableOptionalKeyPath {
1526 getter: move |boxed: &mut Box<Root>| {
1527 getter(boxed.as_mut())
1528 },
1529 _phantom: PhantomData,
1530 }
1531 }
1532
1533 pub fn for_arc_root(self) -> WritableOptionalKeyPath<Arc<Root>, Value, impl for<'r> Fn(&'r mut Arc<Root>) -> Option<&'r mut Value> + 'static>
1535 where
1536 Value: Sized,
1537 F: 'static,
1538 Root: 'static,
1539 Value: 'static,
1540 {
1541 let getter = self.getter;
1542
1543 WritableOptionalKeyPath {
1544 getter: move |arc: &mut Arc<Root>| {
1545 None
1548 },
1549 _phantom: PhantomData,
1550 }
1551 }
1552
1553 pub fn for_rc_root(self) -> WritableOptionalKeyPath<Rc<Root>, Value, impl for<'r> Fn(&'r mut Rc<Root>) -> Option<&'r mut Value> + 'static>
1555 where
1556 Value: Sized,
1557 F: 'static,
1558 Root: 'static,
1559 Value: 'static,
1560 {
1561 let getter = self.getter;
1562
1563 WritableOptionalKeyPath {
1564 getter: move |rc: &mut Rc<Root>| {
1565 None
1568 },
1569 _phantom: PhantomData,
1570 }
1571 }
1572}
1573
1574impl WritableOptionalKeyPath<(), (), fn(&mut ()) -> Option<&mut ()>> {
1576 pub fn for_option_static<T>() -> WritableOptionalKeyPath<Option<T>, T, impl for<'r> Fn(&'r mut Option<T>) -> Option<&'r mut T>> {
1579 WritableOptionalKeyPath::new(|opt: &mut Option<T>| opt.as_mut())
1580 }
1581
1582 pub fn writable_enum<Enum, Variant, EmbedFn, ReadExtractFn, WriteExtractFn>(
1603 _embedder: EmbedFn,
1604 _read_extractor: ReadExtractFn,
1605 write_extractor: WriteExtractFn,
1606 ) -> WritableOptionalKeyPath<Enum, Variant, impl for<'r> Fn(&'r mut Enum) -> Option<&'r mut Variant> + 'static>
1607 where
1608 EmbedFn: Fn(Variant) -> Enum + 'static,
1609 ReadExtractFn: for<'r> Fn(&'r Enum) -> Option<&'r Variant> + 'static,
1610 WriteExtractFn: for<'r> Fn(&'r mut Enum) -> Option<&'r mut Variant> + 'static,
1611 {
1612 WritableOptionalKeyPath::new(write_extractor)
1613 }
1614}
1615
1616pub struct EnumKeyPath<Enum = (), Variant = (), ExtractFn = fn(&()) -> Option<&()>, EmbedFn = fn(()) -> ()>
1624where
1625 ExtractFn: for<'r> Fn(&'r Enum) -> Option<&'r Variant> + 'static,
1626 EmbedFn: Fn(Variant) -> Enum + 'static,
1627{
1628 extractor: OptionalKeyPath<Enum, Variant, ExtractFn>,
1629 embedder: EmbedFn,
1630}
1631
1632impl<Enum, Variant, ExtractFn, EmbedFn> EnumKeyPath<Enum, Variant, ExtractFn, EmbedFn>
1633where
1634 ExtractFn: for<'r> Fn(&'r Enum) -> Option<&'r Variant> + 'static,
1635 EmbedFn: Fn(Variant) -> Enum + 'static,
1636{
1637 pub fn new(
1639 extractor: ExtractFn,
1640 embedder: EmbedFn,
1641 ) -> Self {
1642 Self {
1643 extractor: OptionalKeyPath::new(extractor),
1644 embedder,
1645 }
1646 }
1647
1648 pub fn get<'r>(&self, enum_value: &'r Enum) -> Option<&'r Variant> {
1650 self.extractor.get(enum_value)
1651 }
1652
1653 pub fn embed(&self, value: Variant) -> Enum {
1655 (self.embedder)(value)
1656 }
1657
1658 pub fn as_optional(&self) -> &OptionalKeyPath<Enum, Variant, ExtractFn> {
1660 &self.extractor
1661 }
1662
1663 pub fn to_optional(self) -> OptionalKeyPath<Enum, Variant, ExtractFn> {
1665 self.extractor
1666 }
1667}
1668
1669impl EnumKeyPath {
1671 pub fn readable_enum<Enum, Variant, ExtractFn, EmbedFn>(
1674 embedder: EmbedFn,
1675 extractor: ExtractFn,
1676 ) -> EnumKeyPath<Enum, Variant, ExtractFn, EmbedFn>
1677 where
1678 ExtractFn: for<'r> Fn(&'r Enum) -> Option<&'r Variant> + 'static,
1679 EmbedFn: Fn(Variant) -> Enum + 'static,
1680 {
1681 EnumKeyPath::new(extractor, embedder)
1682 }
1683
1684 pub fn for_variant<Enum, Variant, ExtractFn>(
1686 extractor: ExtractFn
1687 ) -> OptionalKeyPath<Enum, Variant, impl for<'r> Fn(&'r Enum) -> Option<&'r Variant>>
1688 where
1689 ExtractFn: Fn(&Enum) -> Option<&Variant>,
1690 {
1691 OptionalKeyPath::new(extractor)
1692 }
1693
1694 pub fn for_match<Enum, Output, MatchFn>(
1696 matcher: MatchFn
1697 ) -> KeyPath<Enum, Output, impl for<'r> Fn(&'r Enum) -> &'r Output>
1698 where
1699 MatchFn: Fn(&Enum) -> &Output,
1700 {
1701 KeyPath::new(matcher)
1702 }
1703
1704 pub fn for_ok<T, E>() -> OptionalKeyPath<Result<T, E>, T, impl for<'r> Fn(&'r Result<T, E>) -> Option<&'r T>> {
1706 OptionalKeyPath::new(|result: &Result<T, E>| result.as_ref().ok())
1707 }
1708
1709 pub fn for_err<T, E>() -> OptionalKeyPath<Result<T, E>, E, impl for<'r> Fn(&'r Result<T, E>) -> Option<&'r E>> {
1711 OptionalKeyPath::new(|result: &Result<T, E>| result.as_ref().err())
1712 }
1713
1714 pub fn for_some<T>() -> OptionalKeyPath<Option<T>, T, impl for<'r> Fn(&'r Option<T>) -> Option<&'r T>> {
1716 OptionalKeyPath::new(|opt: &Option<T>| opt.as_ref())
1717 }
1718
1719 pub fn for_option<T>() -> OptionalKeyPath<Option<T>, T, impl for<'r> Fn(&'r Option<T>) -> Option<&'r T>> {
1721 OptionalKeyPath::new(|opt: &Option<T>| opt.as_ref())
1722 }
1723
1724 pub fn for_box<T>() -> KeyPath<Box<T>, T, impl for<'r> Fn(&'r Box<T>) -> &'r T> {
1726 KeyPath::new(|b: &Box<T>| b.as_ref())
1727 }
1728
1729 pub fn for_arc<T>() -> KeyPath<Arc<T>, T, impl for<'r> Fn(&'r Arc<T>) -> &'r T> {
1731 KeyPath::new(|arc: &Arc<T>| arc.as_ref())
1732 }
1733
1734 pub fn for_rc<T>() -> KeyPath<std::rc::Rc<T>, T, impl for<'r> Fn(&'r std::rc::Rc<T>) -> &'r T> {
1736 KeyPath::new(|rc: &std::rc::Rc<T>| rc.as_ref())
1737 }
1738
1739 pub fn for_box_mut<T>() -> WritableKeyPath<Box<T>, T, impl for<'r> Fn(&'r mut Box<T>) -> &'r mut T> {
1741 WritableKeyPath::new(|b: &mut Box<T>| b.as_mut())
1742 }
1743
1744 }
1748
1749pub fn variant_of<Enum, Variant, F>(extractor: F) -> OptionalKeyPath<Enum, Variant, F>
1751where
1752 F: for<'r> Fn(&'r Enum) -> Option<&'r Variant>,
1753{
1754 OptionalKeyPath::new(extractor)
1755}
1756
1757#[derive(Clone)]
1773pub struct PartialKeyPath<Root> {
1774 getter: Rc<dyn for<'r> Fn(&'r Root) -> &'r dyn Any>,
1775 value_type_id: TypeId,
1776 _phantom: PhantomData<Root>,
1777}
1778
1779impl<Root> PartialKeyPath<Root> {
1780 pub fn new<Value>(keypath: KeyPath<Root, Value, impl for<'r> Fn(&'r Root) -> &'r Value + 'static>) -> Self
1781 where
1782 Value: Any + 'static,
1783 Root: 'static,
1784 {
1785 let value_type_id = TypeId::of::<Value>();
1786 let getter = Rc::new(keypath.getter);
1787
1788 Self {
1789 getter: Rc::new(move |root: &Root| {
1790 let value: &Value = getter(root);
1791 value as &dyn Any
1792 }),
1793 value_type_id,
1794 _phantom: PhantomData,
1795 }
1796 }
1797
1798 pub fn from<Value>(keypath: KeyPath<Root, Value, impl for<'r> Fn(&'r Root) -> &'r Value + 'static>) -> Self
1801 where
1802 Value: Any + 'static,
1803 Root: 'static,
1804 {
1805 Self::new(keypath)
1806 }
1807
1808 pub fn get<'r>(&self, root: &'r Root) -> &'r dyn Any {
1809 (self.getter)(root)
1810 }
1811
1812 pub fn value_type_id(&self) -> TypeId {
1814 self.value_type_id
1815 }
1816
1817 pub fn get_as<'a, Value: Any>(&self, root: &'a Root) -> Option<&'a Value> {
1819 if self.value_type_id == TypeId::of::<Value>() {
1820 self.get(root).downcast_ref::<Value>()
1821 } else {
1822 None
1823 }
1824 }
1825
1826 pub fn kind_name(&self) -> String {
1829 format!("{:?}", self.value_type_id)
1830 }
1831
1832 pub fn for_arc(&self) -> PartialOptionalKeyPath<Arc<Root>>
1834 where
1835 Root: 'static,
1836 {
1837 let getter = self.getter.clone();
1838 let value_type_id = self.value_type_id;
1839
1840 PartialOptionalKeyPath {
1841 getter: Rc::new(move |arc: &Arc<Root>| {
1842 Some(getter(arc.as_ref()))
1843 }),
1844 value_type_id,
1845 _phantom: PhantomData,
1846 }
1847 }
1848
1849 pub fn for_box(&self) -> PartialOptionalKeyPath<Box<Root>>
1851 where
1852 Root: 'static,
1853 {
1854 let getter = self.getter.clone();
1855 let value_type_id = self.value_type_id;
1856
1857 PartialOptionalKeyPath {
1858 getter: Rc::new(move |boxed: &Box<Root>| {
1859 Some(getter(boxed.as_ref()))
1860 }),
1861 value_type_id,
1862 _phantom: PhantomData,
1863 }
1864 }
1865
1866 pub fn for_rc(&self) -> PartialOptionalKeyPath<Rc<Root>>
1868 where
1869 Root: 'static,
1870 {
1871 let getter = self.getter.clone();
1872 let value_type_id = self.value_type_id;
1873
1874 PartialOptionalKeyPath {
1875 getter: Rc::new(move |rc: &Rc<Root>| {
1876 Some(getter(rc.as_ref()))
1877 }),
1878 value_type_id,
1879 _phantom: PhantomData,
1880 }
1881 }
1882
1883 pub fn for_option(&self) -> PartialOptionalKeyPath<Option<Root>>
1885 where
1886 Root: 'static,
1887 {
1888 let getter = self.getter.clone();
1889 let value_type_id = self.value_type_id;
1890
1891 PartialOptionalKeyPath {
1892 getter: Rc::new(move |opt: &Option<Root>| {
1893 opt.as_ref().map(|root| getter(root))
1894 }),
1895 value_type_id,
1896 _phantom: PhantomData,
1897 }
1898 }
1899
1900 pub fn for_result<E>(&self) -> PartialOptionalKeyPath<Result<Root, E>>
1902 where
1903 Root: 'static,
1904 E: 'static,
1905 {
1906 let getter = self.getter.clone();
1907 let value_type_id = self.value_type_id;
1908
1909 PartialOptionalKeyPath {
1910 getter: Rc::new(move |result: &Result<Root, E>| {
1911 result.as_ref().ok().map(|root| getter(root))
1912 }),
1913 value_type_id,
1914 _phantom: PhantomData,
1915 }
1916 }
1917
1918 pub fn for_arc_rwlock(&self) -> PartialOptionalKeyPath<Arc<RwLock<Root>>>
1922 where
1923 Root: Clone + 'static,
1924 {
1925 PartialOptionalKeyPath {
1928 getter: Rc::new(move |_arc_rwlock: &Arc<RwLock<Root>>| {
1929 None
1932 }),
1933 value_type_id: self.value_type_id,
1934 _phantom: PhantomData,
1935 }
1936 }
1937
1938 pub fn for_arc_mutex(&self) -> PartialOptionalKeyPath<Arc<Mutex<Root>>>
1942 where
1943 Root: Clone + 'static,
1944 {
1945 PartialOptionalKeyPath {
1948 getter: Rc::new(move |_arc_mutex: &Arc<Mutex<Root>>| {
1949 None
1952 }),
1953 value_type_id: self.value_type_id,
1954 _phantom: PhantomData,
1955 }
1956 }
1957}
1958
1959#[derive(Clone)]
1966pub struct PartialOptionalKeyPath<Root> {
1967 getter: Rc<dyn for<'r> Fn(&'r Root) -> Option<&'r dyn Any>>,
1968 value_type_id: TypeId,
1969 _phantom: PhantomData<Root>,
1970}
1971
1972impl<Root> PartialOptionalKeyPath<Root> {
1973 pub fn new<Value>(keypath: OptionalKeyPath<Root, Value, impl for<'r> Fn(&'r Root) -> Option<&'r Value> + 'static>) -> Self
1974 where
1975 Value: Any + 'static,
1976 Root: 'static,
1977 {
1978 let value_type_id = TypeId::of::<Value>();
1979 let getter = Rc::new(keypath.getter);
1980
1981 Self {
1982 getter: Rc::new(move |root: &Root| {
1983 getter(root).map(|value: &Value| value as &dyn Any)
1984 }),
1985 value_type_id,
1986 _phantom: PhantomData,
1987 }
1988 }
1989
1990 pub fn get<'r>(&self, root: &'r Root) -> Option<&'r dyn Any> {
1991 (self.getter)(root)
1992 }
1993
1994 pub fn value_type_id(&self) -> TypeId {
1996 self.value_type_id
1997 }
1998
1999 pub fn get_as<'a, Value: Any>(&self, root: &'a Root) -> Option<Option<&'a Value>> {
2001 if self.value_type_id == TypeId::of::<Value>() {
2002 self.get(root).map(|any| any.downcast_ref::<Value>())
2003 } else {
2004 None
2005 }
2006 }
2007
2008 pub fn then<MidValue>(
2012 self,
2013 next: PartialOptionalKeyPath<MidValue>,
2014 ) -> PartialOptionalKeyPath<Root>
2015 where
2016 MidValue: Any + 'static,
2017 Root: 'static,
2018 {
2019 let first = self.getter;
2020 let second = next.getter;
2021 let value_type_id = next.value_type_id;
2022
2023 PartialOptionalKeyPath {
2024 getter: Rc::new(move |root: &Root| {
2025 first(root).and_then(|any| {
2026 if let Some(mid_value) = any.downcast_ref::<MidValue>() {
2027 second(mid_value)
2028 } else {
2029 None
2030 }
2031 })
2032 }),
2033 value_type_id,
2034 _phantom: PhantomData,
2035 }
2036 }
2037}
2038
2039#[derive(Clone)]
2045pub struct PartialWritableKeyPath<Root> {
2046 getter: Rc<dyn for<'r> Fn(&'r mut Root) -> &'r mut dyn Any>,
2047 value_type_id: TypeId,
2048 _phantom: PhantomData<Root>,
2049}
2050
2051impl<Root> PartialWritableKeyPath<Root> {
2052 pub fn new<Value>(keypath: WritableKeyPath<Root, Value, impl for<'r> Fn(&'r mut Root) -> &'r mut Value + 'static>) -> Self
2053 where
2054 Value: Any + 'static,
2055 Root: 'static,
2056 {
2057 let value_type_id = TypeId::of::<Value>();
2058 let getter = Rc::new(keypath.getter);
2059
2060 Self {
2061 getter: Rc::new(move |root: &mut Root| {
2062 let value: &mut Value = getter(root);
2063 value as &mut dyn Any
2064 }),
2065 value_type_id,
2066 _phantom: PhantomData,
2067 }
2068 }
2069
2070 pub fn from<Value>(keypath: WritableKeyPath<Root, Value, impl for<'r> Fn(&'r mut Root) -> &'r mut Value + 'static>) -> Self
2073 where
2074 Value: Any + 'static,
2075 Root: 'static,
2076 {
2077 Self::new(keypath)
2078 }
2079
2080 pub fn get_mut<'r>(&self, root: &'r mut Root) -> &'r mut dyn Any {
2081 (self.getter)(root)
2082 }
2083
2084 pub fn value_type_id(&self) -> TypeId {
2086 self.value_type_id
2087 }
2088
2089 pub fn get_mut_as<'a, Value: Any>(&self, root: &'a mut Root) -> Option<&'a mut Value> {
2091 if self.value_type_id == TypeId::of::<Value>() {
2092 self.get_mut(root).downcast_mut::<Value>()
2093 } else {
2094 None
2095 }
2096 }
2097}
2098
2099#[derive(Clone)]
2105pub struct PartialWritableOptionalKeyPath<Root> {
2106 getter: Rc<dyn for<'r> Fn(&'r mut Root) -> Option<&'r mut dyn Any>>,
2107 value_type_id: TypeId,
2108 _phantom: PhantomData<Root>,
2109}
2110
2111impl<Root> PartialWritableOptionalKeyPath<Root> {
2112 pub fn new<Value>(keypath: WritableOptionalKeyPath<Root, Value, impl for<'r> Fn(&'r mut Root) -> Option<&'r mut Value> + 'static>) -> Self
2113 where
2114 Value: Any + 'static,
2115 Root: 'static,
2116 {
2117 let value_type_id = TypeId::of::<Value>();
2118 let getter = Rc::new(keypath.getter);
2119
2120 Self {
2121 getter: Rc::new(move |root: &mut Root| {
2122 getter(root).map(|value: &mut Value| value as &mut dyn Any)
2123 }),
2124 value_type_id,
2125 _phantom: PhantomData,
2126 }
2127 }
2128
2129 pub fn get_mut<'r>(&self, root: &'r mut Root) -> Option<&'r mut dyn Any> {
2130 (self.getter)(root)
2131 }
2132
2133 pub fn value_type_id(&self) -> TypeId {
2135 self.value_type_id
2136 }
2137
2138 pub fn get_mut_as<'a, Value: Any>(&self, root: &'a mut Root) -> Option<Option<&'a mut Value>> {
2140 if self.value_type_id == TypeId::of::<Value>() {
2141 self.get_mut(root).map(|any| any.downcast_mut::<Value>())
2142 } else {
2143 None
2144 }
2145 }
2146}
2147
2148#[derive(Clone)]
2162pub struct AnyKeyPath {
2163 getter: Rc<dyn for<'r> Fn(&'r dyn Any) -> Option<&'r dyn Any>>,
2164 root_type_id: TypeId,
2165 value_type_id: TypeId,
2166}
2167
2168impl AnyKeyPath {
2169 pub fn new<Root, Value>(keypath: OptionalKeyPath<Root, Value, impl for<'r> Fn(&'r Root) -> Option<&'r Value> + 'static>) -> Self
2170 where
2171 Root: Any + 'static,
2172 Value: Any + 'static,
2173 {
2174 let root_type_id = TypeId::of::<Root>();
2175 let value_type_id = TypeId::of::<Value>();
2176 let getter = keypath.getter;
2177
2178 Self {
2179 getter: Rc::new(move |any: &dyn Any| {
2180 if let Some(root) = any.downcast_ref::<Root>() {
2181 getter(root).map(|value: &Value| value as &dyn Any)
2182 } else {
2183 None
2184 }
2185 }),
2186 root_type_id,
2187 value_type_id,
2188 }
2189 }
2190
2191 pub fn from<Root, Value>(keypath: OptionalKeyPath<Root, Value, impl for<'r> Fn(&'r Root) -> Option<&'r Value> + 'static>) -> Self
2194 where
2195 Root: Any + 'static,
2196 Value: Any + 'static,
2197 {
2198 Self::new(keypath)
2199 }
2200
2201 pub fn get<'r>(&self, root: &'r dyn Any) -> Option<&'r dyn Any> {
2202 (self.getter)(root)
2203 }
2204
2205 pub fn root_type_id(&self) -> TypeId {
2207 self.root_type_id
2208 }
2209
2210 pub fn value_type_id(&self) -> TypeId {
2212 self.value_type_id
2213 }
2214
2215 pub fn get_as<'a, Root: Any, Value: Any>(&self, root: &'a Root) -> Option<Option<&'a Value>> {
2217 if self.root_type_id == TypeId::of::<Root>() && self.value_type_id == TypeId::of::<Value>() {
2218 self.get(root as &dyn Any).map(|any| any.downcast_ref::<Value>())
2219 } else {
2220 None
2221 }
2222 }
2223
2224 pub fn kind_name(&self) -> String {
2227 format!("{:?}", self.value_type_id)
2228 }
2229
2230 pub fn for_arc<Root>(&self) -> AnyKeyPath
2232 where
2233 Root: Any + 'static,
2234 {
2235 let root_type_id = self.root_type_id;
2236 let value_type_id = self.value_type_id;
2237 let getter = self.getter.clone();
2238
2239 AnyKeyPath {
2240 getter: Rc::new(move |any: &dyn Any| {
2241 if let Some(arc) = any.downcast_ref::<Arc<Root>>() {
2242 getter(arc.as_ref() as &dyn Any)
2243 } else {
2244 None
2245 }
2246 }),
2247 root_type_id: TypeId::of::<Arc<Root>>(),
2248 value_type_id,
2249 }
2250 }
2251
2252 pub fn for_box<Root>(&self) -> AnyKeyPath
2254 where
2255 Root: Any + 'static,
2256 {
2257 let root_type_id = self.root_type_id;
2258 let value_type_id = self.value_type_id;
2259 let getter = self.getter.clone();
2260
2261 AnyKeyPath {
2262 getter: Rc::new(move |any: &dyn Any| {
2263 if let Some(boxed) = any.downcast_ref::<Box<Root>>() {
2264 getter(boxed.as_ref() as &dyn Any)
2265 } else {
2266 None
2267 }
2268 }),
2269 root_type_id: TypeId::of::<Box<Root>>(),
2270 value_type_id,
2271 }
2272 }
2273
2274 pub fn for_rc<Root>(&self) -> AnyKeyPath
2276 where
2277 Root: Any + 'static,
2278 {
2279 let root_type_id = self.root_type_id;
2280 let value_type_id = self.value_type_id;
2281 let getter = self.getter.clone();
2282
2283 AnyKeyPath {
2284 getter: Rc::new(move |any: &dyn Any| {
2285 if let Some(rc) = any.downcast_ref::<Rc<Root>>() {
2286 getter(rc.as_ref() as &dyn Any)
2287 } else {
2288 None
2289 }
2290 }),
2291 root_type_id: TypeId::of::<Rc<Root>>(),
2292 value_type_id,
2293 }
2294 }
2295
2296 pub fn for_option<Root>(&self) -> AnyKeyPath
2298 where
2299 Root: Any + 'static,
2300 {
2301 let root_type_id = self.root_type_id;
2302 let value_type_id = self.value_type_id;
2303 let getter = self.getter.clone();
2304
2305 AnyKeyPath {
2306 getter: Rc::new(move |any: &dyn Any| {
2307 if let Some(opt) = any.downcast_ref::<Option<Root>>() {
2308 opt.as_ref().and_then(|root| getter(root as &dyn Any))
2309 } else {
2310 None
2311 }
2312 }),
2313 root_type_id: TypeId::of::<Option<Root>>(),
2314 value_type_id,
2315 }
2316 }
2317
2318 pub fn for_result<Root, E>(&self) -> AnyKeyPath
2320 where
2321 Root: Any + 'static,
2322 E: Any + 'static,
2323 {
2324 let root_type_id = self.root_type_id;
2325 let value_type_id = self.value_type_id;
2326 let getter = self.getter.clone();
2327
2328 AnyKeyPath {
2329 getter: Rc::new(move |any: &dyn Any| {
2330 if let Some(result) = any.downcast_ref::<Result<Root, E>>() {
2331 result.as_ref().ok().and_then(|root| getter(root as &dyn Any))
2332 } else {
2333 None
2334 }
2335 }),
2336 root_type_id: TypeId::of::<Result<Root, E>>(),
2337 value_type_id,
2338 }
2339 }
2340
2341 pub fn for_arc_rwlock<Root>(&self) -> AnyKeyPath
2344 where
2345 Root: Any + Clone + 'static,
2346 {
2347 AnyKeyPath {
2350 getter: Rc::new(move |_any: &dyn Any| {
2351 None
2354 }),
2355 root_type_id: TypeId::of::<Arc<RwLock<Root>>>(),
2356 value_type_id: self.value_type_id,
2357 }
2358 }
2359
2360 pub fn for_arc_mutex<Root>(&self) -> AnyKeyPath
2363 where
2364 Root: Any + Clone + 'static,
2365 {
2366 AnyKeyPath {
2369 getter: Rc::new(move |_any: &dyn Any| {
2370 None
2373 }),
2374 root_type_id: TypeId::of::<Arc<Mutex<Root>>>(),
2375 value_type_id: self.value_type_id,
2376 }
2377 }
2378}
2379
2380#[derive(Clone)]
2382pub struct AnyWritableKeyPath {
2383 getter: Rc<dyn for<'r> Fn(&'r mut dyn Any) -> Option<&'r mut dyn Any>>,
2384 root_type_id: TypeId,
2385 value_type_id: TypeId,
2386}
2387
2388#[derive(Clone)]
2393pub struct FailableCombinedKeyPath<Root, Value, ReadFn, WriteFn, OwnedFn>
2394where
2395 ReadFn: for<'r> Fn(&'r Root) -> Option<&'r Value> + 'static,
2396 WriteFn: for<'r> Fn(&'r mut Root) -> Option<&'r mut Value> + 'static,
2397 OwnedFn: Fn(Root) -> Option<Value> + 'static,
2398{
2399 readable: ReadFn,
2400 writable: WriteFn,
2401 owned: OwnedFn,
2402 _phantom: PhantomData<(Root, Value)>,
2403}
2404
2405impl<Root, Value, ReadFn, WriteFn, OwnedFn> FailableCombinedKeyPath<Root, Value, ReadFn, WriteFn, OwnedFn>
2406where
2407 ReadFn: for<'r> Fn(&'r Root) -> Option<&'r Value> + 'static,
2408 WriteFn: for<'r> Fn(&'r mut Root) -> Option<&'r mut Value> + 'static,
2409 OwnedFn: Fn(Root) -> Option<Value> + 'static,
2410{
2411 pub fn new(readable: ReadFn, writable: WriteFn, owned: OwnedFn) -> Self {
2413 Self {
2414 readable,
2415 writable,
2416 owned,
2417 _phantom: PhantomData,
2418 }
2419 }
2420
2421 pub fn get<'r>(&self, root: &'r Root) -> Option<&'r Value> {
2423 (self.readable)(root)
2424 }
2425
2426 pub fn get_mut<'r>(&self, root: &'r mut Root) -> Option<&'r mut Value> {
2428 (self.writable)(root)
2429 }
2430
2431 pub fn get_failable_owned(&self, root: Root) -> Option<Value> {
2433 (self.owned)(root)
2434 }
2435
2436 pub fn to_optional(self) -> OptionalKeyPath<Root, Value, ReadFn> {
2438 OptionalKeyPath::new(self.readable)
2439 }
2440
2441 pub fn to_writable_optional(self) -> WritableOptionalKeyPath<Root, Value, WriteFn> {
2443 WritableOptionalKeyPath::new(self.writable)
2444 }
2445
2446 pub fn then<SubValue, SubReadFn, SubWriteFn, SubOwnedFn>(
2449 self,
2450 next: FailableCombinedKeyPath<Value, SubValue, SubReadFn, SubWriteFn, SubOwnedFn>,
2451 ) -> 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>
2452 where
2453 SubReadFn: for<'r> Fn(&'r Value) -> Option<&'r SubValue> + 'static,
2454 SubWriteFn: for<'r> Fn(&'r mut Value) -> Option<&'r mut SubValue> + 'static,
2455 SubOwnedFn: Fn(Value) -> Option<SubValue> + 'static,
2456 ReadFn: 'static,
2457 WriteFn: 'static,
2458 OwnedFn: 'static,
2459 Value: 'static,
2460 Root: 'static,
2461 SubValue: 'static,
2462 {
2463 let first_read = self.readable;
2464 let first_write = self.writable;
2465 let first_owned = self.owned;
2466 let second_read = next.readable;
2467 let second_write = next.writable;
2468 let second_owned = next.owned;
2469
2470 FailableCombinedKeyPath::new(
2471 move |root: &Root| {
2472 first_read(root).and_then(|value| second_read(value))
2473 },
2474 move |root: &mut Root| {
2475 first_write(root).and_then(|value| second_write(value))
2476 },
2477 move |root: Root| {
2478 first_owned(root).and_then(|value| second_owned(value))
2479 },
2480 )
2481 }
2482
2483 pub fn then_optional<SubValue, SubReadFn>(
2487 self,
2488 next: OptionalKeyPath<Value, SubValue, SubReadFn>,
2489 ) -> 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>
2490 where
2491 SubReadFn: for<'r> Fn(&'r Value) -> Option<&'r SubValue> + 'static,
2492 ReadFn: 'static,
2493 WriteFn: 'static,
2494 OwnedFn: 'static,
2495 Value: 'static,
2496 Root: 'static,
2497 SubValue: 'static,
2498 {
2499 let first_read = self.readable;
2500 let first_write = self.writable;
2501 let first_owned = self.owned;
2502 let second_read = next.getter;
2503
2504 FailableCombinedKeyPath::new(
2505 move |root: &Root| {
2506 first_read(root).and_then(|value| second_read(value))
2507 },
2508 move |_root: &mut Root| {
2509 None },
2511 move |root: Root| {
2512 first_owned(root).and_then(|value| {
2513 None
2515 })
2516 },
2517 )
2518 }
2519}
2520
2521impl FailableCombinedKeyPath<(), (), fn(&()) -> Option<&()>, fn(&mut ()) -> Option<&mut ()>, fn(()) -> Option<()>> {
2523 pub fn failable_combined<Root, Value, ReadFn, WriteFn, OwnedFn>(
2525 readable: ReadFn,
2526 writable: WriteFn,
2527 owned: OwnedFn,
2528 ) -> FailableCombinedKeyPath<Root, Value, ReadFn, WriteFn, OwnedFn>
2529 where
2530 ReadFn: for<'r> Fn(&'r Root) -> Option<&'r Value> + 'static,
2531 WriteFn: for<'r> Fn(&'r mut Root) -> Option<&'r mut Value> + 'static,
2532 OwnedFn: Fn(Root) -> Option<Value> + 'static,
2533 {
2534 FailableCombinedKeyPath::new(readable, writable, owned)
2535 }
2536}
2537
2538impl AnyWritableKeyPath {
2539 pub fn new<Root, Value>(keypath: WritableOptionalKeyPath<Root, Value, impl for<'r> Fn(&'r mut Root) -> Option<&'r mut Value> + 'static>) -> Self
2540 where
2541 Root: Any + 'static,
2542 Value: Any + 'static,
2543 {
2544 let root_type_id = TypeId::of::<Root>();
2545 let value_type_id = TypeId::of::<Value>();
2546 let getter = keypath.getter;
2547
2548 Self {
2549 getter: Rc::new(move |any: &mut dyn Any| {
2550 if let Some(root) = any.downcast_mut::<Root>() {
2551 getter(root).map(|value: &mut Value| value as &mut dyn Any)
2552 } else {
2553 None
2554 }
2555 }),
2556 root_type_id,
2557 value_type_id,
2558 }
2559 }
2560
2561 pub fn get_mut<'r>(&self, root: &'r mut dyn Any) -> Option<&'r mut dyn Any> {
2562 (self.getter)(root)
2563 }
2564
2565 pub fn root_type_id(&self) -> TypeId {
2567 self.root_type_id
2568 }
2569
2570 pub fn value_type_id(&self) -> TypeId {
2572 self.value_type_id
2573 }
2574
2575 pub fn get_mut_as<'a, Root: Any, Value: Any>(&self, root: &'a mut Root) -> Option<Option<&'a mut Value>> {
2577 if self.root_type_id == TypeId::of::<Root>() && self.value_type_id == TypeId::of::<Value>() {
2578 self.get_mut(root as &mut dyn Any).map(|any| any.downcast_mut::<Value>())
2579 } else {
2580 None
2581 }
2582 }
2583}
2584
2585impl<Root, Value, F> KeyPath<Root, Value, F>
2587where
2588 F: for<'r> Fn(&'r Root) -> &'r Value + 'static,
2589 Root: 'static,
2590 Value: Any + 'static,
2591{
2592 pub fn to_partial(self) -> PartialKeyPath<Root> {
2594 PartialKeyPath::new(self)
2595 }
2596
2597 pub fn to(self) -> PartialKeyPath<Root> {
2599 self.to_partial()
2600 }
2601}
2602
2603impl<Root, Value, F> OptionalKeyPath<Root, Value, F>
2604where
2605 F: for<'r> Fn(&'r Root) -> Option<&'r Value> + 'static,
2606 Root: Any + 'static,
2607 Value: Any + 'static,
2608{
2609 pub fn to_partial(self) -> PartialOptionalKeyPath<Root> {
2611 PartialOptionalKeyPath::new(self)
2612 }
2613
2614 pub fn to_any(self) -> AnyKeyPath {
2616 AnyKeyPath::new(self)
2617 }
2618
2619 pub fn to(self) -> PartialOptionalKeyPath<Root> {
2621 self.to_partial()
2622 }
2623}
2624
2625impl<Root, Value, F> WritableKeyPath<Root, Value, F>
2626where
2627 F: for<'r> Fn(&'r mut Root) -> &'r mut Value + 'static,
2628 Root: 'static,
2629 Value: Any + 'static,
2630{
2631 pub fn to_partial(self) -> PartialWritableKeyPath<Root> {
2633 PartialWritableKeyPath::new(self)
2634 }
2635
2636 pub fn to(self) -> PartialWritableKeyPath<Root> {
2638 self.to_partial()
2639 }
2640}
2641
2642impl<Root, Value, F> WritableOptionalKeyPath<Root, Value, F>
2643where
2644 F: for<'r> Fn(&'r mut Root) -> Option<&'r mut Value> + 'static,
2645 Root: Any + 'static,
2646 Value: Any + 'static,
2647{
2648 pub fn to_partial(self) -> PartialWritableOptionalKeyPath<Root> {
2650 PartialWritableOptionalKeyPath::new(self)
2651 }
2652
2653 pub fn to_any(self) -> AnyWritableKeyPath {
2655 AnyWritableKeyPath::new(self)
2656 }
2657
2658 pub fn to(self) -> PartialWritableOptionalKeyPath<Root> {
2660 self.to_partial()
2661 }
2662}
2663
2664#[cfg(feature = "nightly")]
2693mod shr_impls {
2694 use super::*;
2695
2696 impl<Root, Value, F, SubValue, G> Shr<KeyPath<Value, SubValue, G>> for KeyPath<Root, Value, F>
2698 where
2699 F: for<'r> Fn(&'r Root) -> &'r Value + 'static,
2700 G: for<'r> Fn(&'r Value) -> &'r SubValue + 'static,
2701 Value: 'static,
2702 {
2703 type Output = KeyPath<Root, SubValue, impl for<'r> Fn(&'r Root) -> &'r SubValue>;
2704
2705 fn shr(self, rhs: KeyPath<Value, SubValue, G>) -> Self::Output {
2706 self.then(rhs)
2707 }
2708 }
2709
2710 impl<Root, Value, F, SubValue, G> Shr<OptionalKeyPath<Value, SubValue, G>> for KeyPath<Root, Value, F>
2712 where
2713 F: for<'r> Fn(&'r Root) -> &'r Value + 'static,
2714 G: for<'r> Fn(&'r Value) -> Option<&'r SubValue> + 'static,
2715 Value: 'static,
2716 {
2717 type Output = OptionalKeyPath<Root, SubValue, impl for<'r> Fn(&'r Root) -> Option<&'r SubValue>>;
2718
2719 fn shr(self, rhs: OptionalKeyPath<Value, SubValue, G>) -> Self::Output {
2720 self.then_optional(rhs)
2721 }
2722 }
2723
2724 impl<Root, Value, F, SubValue, G> Shr<OptionalKeyPath<Value, SubValue, G>> for OptionalKeyPath<Root, Value, F>
2726 where
2727 F: for<'r> Fn(&'r Root) -> Option<&'r Value> + 'static,
2728 G: for<'r> Fn(&'r Value) -> Option<&'r SubValue> + 'static,
2729 Value: 'static,
2730 {
2731 type Output = OptionalKeyPath<Root, SubValue, impl for<'r> Fn(&'r Root) -> Option<&'r SubValue>>;
2732
2733 fn shr(self, rhs: OptionalKeyPath<Value, SubValue, G>) -> Self::Output {
2734 self.then(rhs)
2735 }
2736 }
2737
2738 impl<Root, Value, F, SubValue, G> Shr<WritableKeyPath<Value, SubValue, G>> for WritableKeyPath<Root, Value, F>
2740 where
2741 F: for<'r> Fn(&'r mut Root) -> &'r mut Value + 'static,
2742 G: for<'r> Fn(&'r mut Value) -> &'r mut SubValue + 'static,
2743 Value: 'static,
2744 {
2745 type Output = WritableKeyPath<Root, SubValue, impl for<'r> Fn(&'r mut Root) -> &'r mut SubValue>;
2746
2747 fn shr(self, rhs: WritableKeyPath<Value, SubValue, G>) -> Self::Output {
2748 self.then(rhs)
2749 }
2750 }
2751
2752 impl<Root, Value, F, SubValue, G> Shr<WritableOptionalKeyPath<Value, SubValue, G>> for WritableKeyPath<Root, Value, F>
2754 where
2755 F: for<'r> Fn(&'r mut Root) -> &'r mut Value + 'static,
2756 G: for<'r> Fn(&'r mut Value) -> Option<&'r mut SubValue> + 'static,
2757 Value: 'static,
2758 {
2759 type Output = WritableOptionalKeyPath<Root, SubValue, impl for<'r> Fn(&'r mut Root) -> Option<&'r mut SubValue>>;
2760
2761 fn shr(self, rhs: WritableOptionalKeyPath<Value, SubValue, G>) -> Self::Output {
2762 self.then_optional(rhs)
2763 }
2764 }
2765
2766 impl<Root, Value, F, SubValue, G> Shr<WritableOptionalKeyPath<Value, SubValue, G>> for WritableOptionalKeyPath<Root, Value, F>
2768 where
2769 F: for<'r> Fn(&'r mut Root) -> Option<&'r mut Value> + 'static,
2770 G: for<'r> Fn(&'r mut Value) -> Option<&'r mut SubValue> + 'static,
2771 Value: 'static,
2772 {
2773 type Output = WritableOptionalKeyPath<Root, SubValue, impl for<'r> Fn(&'r mut Root) -> Option<&'r mut SubValue>>;
2774
2775 fn shr(self, rhs: WritableOptionalKeyPath<Value, SubValue, G>) -> Self::Output {
2776 self.then(rhs)
2777 }
2778 }
2779}
2780
2781#[cfg(test)]
2782mod tests {
2783 use super::*;
2784 use std::sync::atomic::{AtomicUsize, Ordering};
2785 use std::rc::Rc;
2786
2787 static ALLOC_COUNT: AtomicUsize = AtomicUsize::new(0);
2789 static DEALLOC_COUNT: AtomicUsize = AtomicUsize::new(0);
2790
2791 #[derive(Debug)]
2793 struct NoCloneType {
2794 id: usize,
2795 data: String,
2796 }
2797
2798 impl NoCloneType {
2799 fn new(data: String) -> Self {
2800 ALLOC_COUNT.fetch_add(1, Ordering::SeqCst);
2801 Self {
2802 id: ALLOC_COUNT.load(Ordering::SeqCst),
2803 data,
2804 }
2805 }
2806 }
2807
2808 impl Clone for NoCloneType {
2809 fn clone(&self) -> Self {
2810 eprintln!("[DEBUG] NoCloneType should not be cloned! ID: {}", self.id);
2811 unreachable!("NoCloneType should not be cloned! ID: {}", self.id);
2812 }
2813 }
2814
2815 impl Drop for NoCloneType {
2816 fn drop(&mut self) {
2817 DEALLOC_COUNT.fetch_add(1, Ordering::SeqCst);
2818 }
2819 }
2820
2821 fn reset_memory_counters() {
2823 ALLOC_COUNT.store(0, Ordering::SeqCst);
2824 DEALLOC_COUNT.store(0, Ordering::SeqCst);
2825 }
2826
2827 fn get_alloc_count() -> usize {
2828 ALLOC_COUNT.load(Ordering::SeqCst)
2829 }
2830
2831 fn get_dealloc_count() -> usize {
2832 DEALLOC_COUNT.load(Ordering::SeqCst)
2833 }
2834
2835#[derive(Debug)]
2837struct User {
2838 name: String,
2839 metadata: Option<Box<UserMetadata>>,
2840 friends: Vec<Arc<User>>,
2841}
2842
2843#[derive(Debug)]
2844struct UserMetadata {
2845 created_at: String,
2846}
2847
2848fn some_fn() {
2849 let akash = User {
2850 name: "Alice".to_string(),
2851 metadata: Some(Box::new(UserMetadata {
2852 created_at: "2024-01-01".to_string(),
2853 })),
2854 friends: vec![
2855 Arc::new(User {
2856 name: "Bob".to_string(),
2857 metadata: None,
2858 friends: vec![],
2859 }),
2860 ],
2861 };
2862
2863 let name_kp = KeyPath::new(|u: &User| &u.name);
2865 let metadata_kp = OptionalKeyPath::new(|u: &User| u.metadata.as_ref());
2866 let friends_kp = KeyPath::new(|u: &User| &u.friends);
2867
2868 println!("Name: {}", name_kp.get(&akash));
2870
2871 if let Some(metadata) = metadata_kp.get(&akash) {
2872 println!("Has metadata: {:?}", metadata);
2873 }
2874
2875 if let Some(first_friend) = akash.friends.get(0) {
2877 println!("First friend: {}", name_kp.get(first_friend));
2878 }
2879
2880 let created_at_kp = KeyPath::new(|m: &UserMetadata| &m.created_at);
2882
2883 if let Some(metadata) = akash.metadata.as_ref() {
2884 let boxed_metadata: &Box<UserMetadata> = metadata;
2886 let unwrapped = boxed_metadata.as_ref();
2887 println!("Created at: {:?}", created_at_kp.get(unwrapped));
2888 }
2889 }
2890
2891 #[test]
2892 fn test_name() {
2893 some_fn();
2894 }
2895
2896 #[test]
2897 fn test_no_cloning_on_keypath_operations() {
2898 reset_memory_counters();
2899
2900 let value = NoCloneType::new("test".to_string());
2902 let boxed = Box::new(value);
2903
2904 let kp = KeyPath::new(|b: &Box<NoCloneType>| b.as_ref());
2906
2907 let _ref = kp.get(&boxed);
2909
2910 let _kp_clone = kp.clone();
2912
2913 let _ref2 = _kp_clone.get(&boxed);
2915
2916 assert_eq!(get_alloc_count(), 1);
2918 }
2919
2920 #[test]
2921 fn test_no_cloning_on_optional_keypath_operations() {
2922 reset_memory_counters();
2923
2924 let value = NoCloneType::new("test".to_string());
2925 let opt = Some(Box::new(value));
2926
2927 let okp = OptionalKeyPath::new(|o: &Option<Box<NoCloneType>>| o.as_ref());
2929
2930 let _ref = okp.get(&opt);
2932
2933 let _okp_clone = okp.clone();
2935
2936 let chained = okp.then(OptionalKeyPath::new(|b: &Box<NoCloneType>| Some(b.as_ref())));
2938 let _ref2 = chained.get(&opt);
2939
2940 assert_eq!(get_alloc_count(), 1);
2941 }
2942
2943 #[test]
2944 fn test_memory_release() {
2945 reset_memory_counters();
2946
2947 {
2948 let value = NoCloneType::new("test".to_string());
2949 let boxed = Box::new(value);
2950 let kp = KeyPath::new(|b: &Box<NoCloneType>| b.as_ref());
2951
2952 let _ref = kp.get(&boxed);
2954
2955 }
2957
2958 assert_eq!(get_alloc_count(), 1);
2961 }
2964
2965 #[test]
2966 fn test_keypath_clone_does_not_clone_underlying_data() {
2967 reset_memory_counters();
2968
2969 let value = NoCloneType::new("data".to_string());
2970 let rc_value = Rc::new(value);
2971
2972 let kp = KeyPath::new(|r: &Rc<NoCloneType>| r.as_ref());
2974
2975 let kp1 = kp.clone();
2977 let kp2 = kp.clone();
2978 let kp3 = kp1.clone();
2979
2980 let _ref1 = kp.get(&rc_value);
2982 let _ref2 = kp1.get(&rc_value);
2983 let _ref3 = kp2.get(&rc_value);
2984 let _ref4 = kp3.get(&rc_value);
2985
2986 assert_eq!(get_alloc_count(), 1);
2988 }
2989
2990 #[test]
2991 fn test_optional_keypath_chaining_no_clone() {
2992 reset_memory_counters();
2993
2994 let value = NoCloneType::new("value1".to_string());
2995
2996 struct Container {
2997 inner: Option<Box<NoCloneType>>,
2998 }
2999
3000 let container = Container {
3001 inner: Some(Box::new(value)),
3002 };
3003
3004 let kp1 = OptionalKeyPath::new(|c: &Container| c.inner.as_ref());
3006 let kp2 = OptionalKeyPath::new(|b: &Box<NoCloneType>| Some(b.as_ref()));
3007
3008 let chained = kp1.then(kp2);
3010
3011 let _result = chained.get(&container);
3013
3014 assert_eq!(get_alloc_count(), 1);
3016 }
3017
3018 #[test]
3019 fn test_for_box_no_clone() {
3020 reset_memory_counters();
3021
3022 let value = NoCloneType::new("test".to_string());
3023 let boxed = Box::new(value);
3024 let opt_boxed = Some(boxed);
3025
3026 let kp = OptionalKeyPath::new(|o: &Option<Box<NoCloneType>>| o.as_ref());
3028 let unwrapped = kp.for_box();
3029
3030 let _ref = unwrapped.get(&opt_boxed);
3032
3033 assert_eq!(get_alloc_count(), 1);
3034 }
3035
3036 #[derive(Debug, PartialEq)]
3039 struct TestUser {
3040 name: String,
3041 age: u32,
3042 metadata: Option<String>,
3043 address: Option<TestAddress>,
3044 }
3045
3046 #[derive(Debug, PartialEq)]
3047 struct TestAddress {
3048 street: String,
3049 city: String,
3050 country: Option<TestCountry>,
3051 }
3052
3053 #[derive(Debug, PartialEq)]
3054 struct TestCountry {
3055 name: String,
3056 }
3057
3058 #[test]
3059 fn test_keypath_macro() {
3060 let user = TestUser {
3061 name: "Alice".to_string(),
3062 age: 30,
3063 metadata: None,
3064 address: None,
3065 };
3066
3067 let name_kp = keypath!(|u: &TestUser| &u.name);
3069 assert_eq!(name_kp.get(&user), "Alice");
3070
3071 let user_with_address = TestUser {
3073 name: "Bob".to_string(),
3074 age: 25,
3075 metadata: None,
3076 address: Some(TestAddress {
3077 street: "123 Main St".to_string(),
3078 city: "New York".to_string(),
3079 country: None,
3080 }),
3081 };
3082
3083 let street_kp = keypath!(|u: &TestUser| &u.address.as_ref().unwrap().street);
3084 assert_eq!(street_kp.get(&user_with_address), "123 Main St");
3085
3086 let user_with_country = TestUser {
3088 name: "Charlie".to_string(),
3089 age: 35,
3090 metadata: None,
3091 address: Some(TestAddress {
3092 street: "456 Oak Ave".to_string(),
3093 city: "London".to_string(),
3094 country: Some(TestCountry {
3095 name: "UK".to_string(),
3096 }),
3097 }),
3098 };
3099
3100 let country_name_kp = keypath!(|u: &TestUser| &u.address.as_ref().unwrap().country.as_ref().unwrap().name);
3101 assert_eq!(country_name_kp.get(&user_with_country), "UK");
3102
3103 let age_kp = keypath!(|u: &TestUser| &u.age);
3105 assert_eq!(age_kp.get(&user), &30);
3106 }
3107
3108 #[test]
3109 fn test_opt_keypath_macro() {
3110 let user = TestUser {
3111 name: "Alice".to_string(),
3112 age: 30,
3113 metadata: Some("admin".to_string()),
3114 address: None,
3115 };
3116
3117 let metadata_kp = opt_keypath!(|u: &TestUser| u.metadata.as_ref());
3119 assert_eq!(metadata_kp.get(&user), Some(&"admin".to_string()));
3120
3121 let user_no_metadata = TestUser {
3123 name: "Bob".to_string(),
3124 age: 25,
3125 metadata: None,
3126 address: None,
3127 };
3128 assert_eq!(metadata_kp.get(&user_no_metadata), None);
3129
3130 let user_with_address = TestUser {
3132 name: "Charlie".to_string(),
3133 age: 35,
3134 metadata: None,
3135 address: Some(TestAddress {
3136 street: "789 Pine Rd".to_string(),
3137 city: "Paris".to_string(),
3138 country: None,
3139 }),
3140 };
3141
3142 let street_kp = opt_keypath!(|u: &TestUser| u.address.as_ref().map(|a| &a.street));
3143 assert_eq!(street_kp.get(&user_with_address), Some(&"789 Pine Rd".to_string()));
3144
3145 let user_with_country = TestUser {
3147 name: "David".to_string(),
3148 age: 40,
3149 metadata: None,
3150 address: Some(TestAddress {
3151 street: "321 Elm St".to_string(),
3152 city: "Tokyo".to_string(),
3153 country: Some(TestCountry {
3154 name: "Japan".to_string(),
3155 }),
3156 }),
3157 };
3158
3159 let country_name_kp = opt_keypath!(|u: &TestUser| u.address.as_ref().and_then(|a| a.country.as_ref().map(|c| &c.name)));
3160 assert_eq!(country_name_kp.get(&user_with_country), Some(&"Japan".to_string()));
3161
3162 let metadata_kp2 = opt_keypath!(|u: &TestUser| u.metadata.as_ref());
3164 assert_eq!(metadata_kp2.get(&user), Some(&"admin".to_string()));
3165 }
3166
3167 #[test]
3168 fn test_writable_keypath_macro() {
3169 let mut user = TestUser {
3170 name: "Alice".to_string(),
3171 age: 30,
3172 metadata: None,
3173 address: None,
3174 };
3175
3176 let name_kp = writable_keypath!(|u: &mut TestUser| &mut u.name);
3178 *name_kp.get_mut(&mut user) = "Bob".to_string();
3179 assert_eq!(user.name, "Bob");
3180
3181 let mut user_with_address = TestUser {
3183 name: "Charlie".to_string(),
3184 age: 25,
3185 metadata: None,
3186 address: Some(TestAddress {
3187 street: "123 Main St".to_string(),
3188 city: "New York".to_string(),
3189 country: None,
3190 }),
3191 };
3192
3193 let street_kp = writable_keypath!(|u: &mut TestUser| &mut u.address.as_mut().unwrap().street);
3194 *street_kp.get_mut(&mut user_with_address) = "456 Oak Ave".to_string();
3195 assert_eq!(user_with_address.address.as_ref().unwrap().street, "456 Oak Ave");
3196
3197 let mut user_with_country = TestUser {
3199 name: "David".to_string(),
3200 age: 35,
3201 metadata: None,
3202 address: Some(TestAddress {
3203 street: "789 Pine Rd".to_string(),
3204 city: "London".to_string(),
3205 country: Some(TestCountry {
3206 name: "UK".to_string(),
3207 }),
3208 }),
3209 };
3210
3211 let country_name_kp = writable_keypath!(|u: &mut TestUser| &mut u.address.as_mut().unwrap().country.as_mut().unwrap().name);
3212 *country_name_kp.get_mut(&mut user_with_country) = "United Kingdom".to_string();
3213 assert_eq!(user_with_country.address.as_ref().unwrap().country.as_ref().unwrap().name, "United Kingdom");
3214
3215 let age_kp = writable_keypath!(|u: &mut TestUser| &mut u.age);
3217 *age_kp.get_mut(&mut user) = 31;
3218 assert_eq!(user.age, 31);
3219 }
3220
3221 #[test]
3222 fn test_writable_opt_keypath_macro() {
3223 let mut user = TestUser {
3224 name: "Alice".to_string(),
3225 age: 30,
3226 metadata: Some("user".to_string()),
3227 address: None,
3228 };
3229
3230 let metadata_kp = writable_opt_keypath!(|u: &mut TestUser| u.metadata.as_mut());
3232 if let Some(metadata) = metadata_kp.get_mut(&mut user) {
3233 *metadata = "admin".to_string();
3234 }
3235 assert_eq!(user.metadata, Some("admin".to_string()));
3236
3237 let mut user_no_metadata = TestUser {
3239 name: "Bob".to_string(),
3240 age: 25,
3241 metadata: None,
3242 address: None,
3243 };
3244 assert_eq!(metadata_kp.get_mut(&mut user_no_metadata), None);
3245
3246 let mut user_with_address = TestUser {
3248 name: "Charlie".to_string(),
3249 age: 35,
3250 metadata: None,
3251 address: Some(TestAddress {
3252 street: "123 Main St".to_string(),
3253 city: "New York".to_string(),
3254 country: None,
3255 }),
3256 };
3257
3258 let street_kp = writable_opt_keypath!(|u: &mut TestUser| u.address.as_mut().map(|a| &mut a.street));
3259 if let Some(street) = street_kp.get_mut(&mut user_with_address) {
3260 *street = "456 Oak Ave".to_string();
3261 }
3262 assert_eq!(user_with_address.address.as_ref().unwrap().street, "456 Oak Ave");
3263
3264 let mut user_with_country = TestUser {
3266 name: "David".to_string(),
3267 age: 40,
3268 metadata: None,
3269 address: Some(TestAddress {
3270 street: "789 Pine Rd".to_string(),
3271 city: "Tokyo".to_string(),
3272 country: Some(TestCountry {
3273 name: "Japan".to_string(),
3274 }),
3275 }),
3276 };
3277
3278 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)));
3279 if let Some(country_name) = country_name_kp.get_mut(&mut user_with_country) {
3280 *country_name = "Nippon".to_string();
3281 }
3282 assert_eq!(user_with_country.address.as_ref().unwrap().country.as_ref().unwrap().name, "Nippon");
3283
3284 let metadata_kp2 = writable_opt_keypath!(|u: &mut TestUser| u.metadata.as_mut());
3286 if let Some(metadata) = metadata_kp2.get_mut(&mut user) {
3287 *metadata = "super_admin".to_string();
3288 }
3289 assert_eq!(user.metadata, Some("super_admin".to_string()));
3290 }
3291}
3292
3293pub trait WithContainer<Root, Value> {
3299 fn with_arc<F, R>(&self, arc: &Arc<Root>, f: F) -> R
3301 where
3302 F: FnOnce(&Value) -> R;
3303
3304 fn with_box<F, R>(&self, boxed: &Box<Root>, f: F) -> R
3306 where
3307 F: FnOnce(&Value) -> R;
3308
3309 fn with_box_mut<F, R>(&self, boxed: &mut Box<Root>, f: F) -> R
3311 where
3312 F: FnOnce(&mut Value) -> R;
3313
3314 fn with_rc<F, R>(&self, rc: &Rc<Root>, f: F) -> R
3316 where
3317 F: FnOnce(&Value) -> R;
3318
3319 fn with_result<F, R, E>(&self, result: &Result<Root, E>, f: F) -> Option<R>
3321 where
3322 F: FnOnce(&Value) -> R;
3323
3324 fn with_result_mut<F, R, E>(&self, result: &mut Result<Root, E>, f: F) -> Option<R>
3326 where
3327 F: FnOnce(&mut Value) -> R;
3328
3329 fn with_option<F, R>(&self, option: &Option<Root>, f: F) -> Option<R>
3331 where
3332 F: FnOnce(&Value) -> R;
3333
3334 fn with_option_mut<F, R>(&self, option: &mut Option<Root>, f: F) -> Option<R>
3336 where
3337 F: FnOnce(&mut Value) -> R;
3338
3339 fn with_refcell<F, R>(&self, refcell: &RefCell<Root>, f: F) -> Option<R>
3341 where
3342 F: FnOnce(&Value) -> R;
3343
3344 fn with_refcell_mut<F, R>(&self, refcell: &RefCell<Root>, f: F) -> Option<R>
3346 where
3347 F: FnOnce(&mut Value) -> R;
3348
3349 #[cfg(feature = "tagged")]
3350 fn with_tagged<F, R, Tag>(&self, tagged: &Tagged<Root, Tag>, f: F) -> R
3352 where
3353 Tagged<Root, Tag>: std::ops::Deref<Target = Root>,
3354 F: FnOnce(&Value) -> R;
3355
3356 fn with_mutex<F, R>(&self, mutex: &Mutex<Root>, f: F) -> Option<R>
3358 where
3359 F: FnOnce(&Value) -> R;
3360
3361 fn with_mutex_mut<F, R>(&self, mutex: &mut Mutex<Root>, f: F) -> Option<R>
3363 where
3364 F: FnOnce(&mut Value) -> R;
3365
3366 fn with_rwlock<F, R>(&self, rwlock: &RwLock<Root>, f: F) -> Option<R>
3368 where
3369 F: FnOnce(&Value) -> R;
3370
3371 fn with_rwlock_mut<F, R>(&self, rwlock: &mut RwLock<Root>, f: F) -> Option<R>
3373 where
3374 F: FnOnce(&mut Value) -> R;
3375
3376 fn with_arc_rwlock<F, R>(&self, arc_rwlock: &Arc<RwLock<Root>>, f: F) -> Option<R>
3378 where
3379 F: FnOnce(&Value) -> R;
3380
3381 fn with_arc_rwlock_mut<F, R>(&self, arc_rwlock: &Arc<RwLock<Root>>, f: F) -> Option<R>
3383 where
3384 F: FnOnce(&mut Value) -> R;
3385}
3386
3387impl<Root, Value, F> WithContainer<Root, Value> for KeyPath<Root, Value, F>
3389where
3390 F: for<'r> Fn(&'r Root) -> &'r Value + Clone,
3391{
3392 fn with_arc<Callback, R>(&self, arc: &Arc<Root>, f: Callback) -> R
3393 where
3394 Callback: FnOnce(&Value) -> R,
3395 {
3396 self.with_arc(arc, f)
3397 }
3398
3399 fn with_box<Callback, R>(&self, boxed: &Box<Root>, f: Callback) -> R
3400 where
3401 Callback: FnOnce(&Value) -> R,
3402 {
3403 self.with_box(boxed, f)
3404 }
3405
3406 fn with_box_mut<Callback, R>(&self, _boxed: &mut Box<Root>, _f: Callback) -> R
3407 where
3408 Callback: FnOnce(&mut Value) -> R,
3409 {
3410 eprintln!("[DEBUG] KeyPath does not support mutable access - use WritableKeyPath instead");
3411 unreachable!("KeyPath does not support mutable access - use WritableKeyPath instead")
3412 }
3413
3414 fn with_rc<Callback, R>(&self, rc: &Rc<Root>, f: Callback) -> R
3415 where
3416 Callback: FnOnce(&Value) -> R,
3417 {
3418 self.with_rc(rc, f)
3419 }
3420
3421 fn with_result<Callback, R, E>(&self, result: &Result<Root, E>, f: Callback) -> Option<R>
3422 where
3423 Callback: FnOnce(&Value) -> R,
3424 {
3425 self.with_result(result, f)
3426 }
3427
3428 fn with_result_mut<Callback, R, E>(&self, _result: &mut Result<Root, E>, _f: Callback) -> Option<R>
3429 where
3430 Callback: FnOnce(&mut Value) -> R,
3431 {
3432 None
3433 }
3434
3435 fn with_option<Callback, R>(&self, option: &Option<Root>, f: Callback) -> Option<R>
3436 where
3437 Callback: FnOnce(&Value) -> R,
3438 {
3439 self.with_option(option, f)
3440 }
3441
3442 fn with_option_mut<Callback, R>(&self, _option: &mut Option<Root>, _f: Callback) -> Option<R>
3443 where
3444 Callback: FnOnce(&mut Value) -> R,
3445 {
3446 None
3447 }
3448
3449 fn with_refcell<Callback, R>(&self, refcell: &RefCell<Root>, f: Callback) -> Option<R>
3450 where
3451 Callback: FnOnce(&Value) -> R,
3452 {
3453 self.with_refcell(refcell, f)
3454 }
3455
3456 fn with_refcell_mut<Callback, R>(&self, _refcell: &RefCell<Root>, _f: Callback) -> Option<R>
3457 where
3458 Callback: FnOnce(&mut Value) -> R,
3459 {
3460 None
3461 }
3462
3463 #[cfg(feature = "tagged")]
3464 fn with_tagged<Tag, Callback, R>(&self, tagged: &Tagged<Root, Tag>, f: Callback) -> R
3465 where
3466 Tagged<Root, Tag>: std::ops::Deref<Target = Root>,
3467 Callback: FnOnce(&Value) -> R,
3468 {
3469 self.with_tagged(tagged, f)
3470 }
3471
3472 fn with_mutex<Callback, R>(&self, mutex: &Mutex<Root>, f: Callback) -> Option<R>
3473 where
3474 Callback: FnOnce(&Value) -> R,
3475 {
3476 self.with_mutex(mutex, f)
3477 }
3478
3479 fn with_mutex_mut<Callback, R>(&self, _mutex: &mut Mutex<Root>, _f: Callback) -> Option<R>
3480 where
3481 Callback: FnOnce(&mut Value) -> R,
3482 {
3483 None
3484 }
3485
3486 fn with_rwlock<Callback, R>(&self, rwlock: &RwLock<Root>, f: Callback) -> Option<R>
3487 where
3488 Callback: FnOnce(&Value) -> R,
3489 {
3490 self.with_rwlock(rwlock, f)
3491 }
3492
3493 fn with_rwlock_mut<Callback, R>(&self, _rwlock: &mut RwLock<Root>, _f: Callback) -> Option<R>
3494 where
3495 Callback: FnOnce(&mut Value) -> R,
3496 {
3497 None
3498 }
3499
3500 fn with_arc_rwlock<Callback, R>(&self, arc_rwlock: &Arc<RwLock<Root>>, f: Callback) -> Option<R>
3501 where
3502 Callback: FnOnce(&Value) -> R,
3503 {
3504 self.with_arc_rwlock(arc_rwlock, f)
3505 }
3506
3507 fn with_arc_rwlock_mut<Callback, R>(&self, _arc_rwlock: &Arc<RwLock<Root>>, _f: Callback) -> Option<R>
3508 where
3509 Callback: FnOnce(&mut Value) -> R,
3510 {
3511 None
3512 }
3513}
3514
3515impl<Root, Value, F> WithContainer<Root, Value> for OptionalKeyPath<Root, Value, F>
3517where
3518 F: for<'r> Fn(&'r Root) -> Option<&'r Value> + Clone,
3519{
3520 fn with_arc<Callback, R>(&self, arc: &Arc<Root>, f: Callback) -> R
3521 where
3522 Callback: FnOnce(&Value) -> R,
3523 {
3524 self.with_arc(arc, f)
3525 }
3526
3527 fn with_box<Callback, R>(&self, boxed: &Box<Root>, f: Callback) -> R
3528 where
3529 Callback: FnOnce(&Value) -> R,
3530 {
3531 self.with_box(boxed, f)
3532 }
3533
3534 fn with_box_mut<Callback, R>(&self, _boxed: &mut Box<Root>, _f: Callback) -> R
3535 where
3536 Callback: FnOnce(&mut Value) -> R,
3537 {
3538 eprintln!("[DEBUG] OptionalKeyPath does not support mutable access - use WritableOptionalKeyPath instead");
3539 unreachable!("OptionalKeyPath does not support mutable access - use WritableOptionalKeyPath instead")
3540 }
3541
3542 fn with_rc<Callback, R>(&self, rc: &Rc<Root>, f: Callback) -> R
3543 where
3544 Callback: FnOnce(&Value) -> R,
3545 {
3546 self.with_rc(rc, f)
3547 }
3548
3549 fn with_result<Callback, R, E>(&self, result: &Result<Root, E>, f: Callback) -> Option<R>
3550 where
3551 Callback: FnOnce(&Value) -> R,
3552 {
3553 self.with_result(result, f)
3554 }
3555
3556 fn with_result_mut<Callback, R, E>(&self, _result: &mut Result<Root, E>, _f: Callback) -> Option<R>
3557 where
3558 Callback: FnOnce(&mut Value) -> R,
3559 {
3560 None }
3562
3563 fn with_option<Callback, R>(&self, option: &Option<Root>, f: Callback) -> Option<R>
3564 where
3565 Callback: FnOnce(&Value) -> R,
3566 {
3567 self.with_option(option, f)
3568 }
3569
3570 fn with_option_mut<Callback, R>(&self, _option: &mut Option<Root>, _f: Callback) -> Option<R>
3571 where
3572 Callback: FnOnce(&mut Value) -> R,
3573 {
3574 None }
3576
3577 fn with_refcell<Callback, R>(&self, refcell: &RefCell<Root>, f: Callback) -> Option<R>
3578 where
3579 Callback: FnOnce(&Value) -> R,
3580 {
3581 self.with_refcell(refcell, f)
3582 }
3583
3584 fn with_refcell_mut<Callback, R>(&self, _refcell: &RefCell<Root>, _f: Callback) -> Option<R>
3585 where
3586 Callback: FnOnce(&mut Value) -> R,
3587 {
3588 None }
3590
3591 #[cfg(feature = "tagged")]
3592 fn with_tagged<Tag, Callback, R>(&self, tagged: &Tagged<Root, Tag>, f: Callback) -> R
3593 where
3594 Tagged<Root, Tag>: std::ops::Deref<Target = Root>,
3595 Callback: FnOnce(&Value) -> R,
3596 {
3597 self.with_tagged(tagged, f)
3598 }
3599
3600 fn with_mutex<Callback, R>(&self, mutex: &Mutex<Root>, f: Callback) -> Option<R>
3601 where
3602 Callback: FnOnce(&Value) -> R,
3603 {
3604 self.with_mutex(mutex, f)
3605 }
3606
3607 fn with_mutex_mut<Callback, R>(&self, _mutex: &mut Mutex<Root>, _f: Callback) -> Option<R>
3608 where
3609 Callback: FnOnce(&mut Value) -> R,
3610 {
3611 None }
3613
3614 fn with_rwlock<Callback, R>(&self, rwlock: &RwLock<Root>, f: Callback) -> Option<R>
3615 where
3616 Callback: FnOnce(&Value) -> R,
3617 {
3618 self.with_rwlock(rwlock, f)
3619 }
3620
3621 fn with_rwlock_mut<Callback, R>(&self, _rwlock: &mut RwLock<Root>, _f: Callback) -> Option<R>
3622 where
3623 Callback: FnOnce(&mut Value) -> R,
3624 {
3625 None }
3627
3628 fn with_arc_rwlock<Callback, R>(&self, arc_rwlock: &Arc<RwLock<Root>>, f: Callback) -> Option<R>
3629 where
3630 Callback: FnOnce(&Value) -> R,
3631 {
3632 self.with_arc_rwlock(arc_rwlock, f)
3633 }
3634
3635 fn with_arc_rwlock_mut<Callback, R>(&self, _arc_rwlock: &Arc<RwLock<Root>>, _f: Callback) -> Option<R>
3636 where
3637 Callback: FnOnce(&mut Value) -> R,
3638 {
3639 None }
3641}
3642
3643impl<Root, Value, F> WithContainer<Root, Value> for WritableKeyPath<Root, Value, F>
3645where
3646 F: for<'r> Fn(&'r mut Root) -> &'r mut Value,
3647{
3648 fn with_arc<Callback, R>(&self, _arc: &Arc<Root>, _f: Callback) -> R
3649 where
3650 Callback: FnOnce(&Value) -> R,
3651 {
3652 eprintln!("[DEBUG] WritableKeyPath::with_arc requires &mut Arc<Root> or interior mutability");
3655 unreachable!("WritableKeyPath::with_arc requires &mut Arc<Root> or interior mutability")
3656 }
3657
3658 fn with_box<Callback, R>(&self, boxed: &Box<Root>, f: Callback) -> R
3659 where
3660 Callback: FnOnce(&Value) -> R,
3661 {
3662 eprintln!("[DEBUG] WritableKeyPath::with_box requires &mut Box<Root> - use with_box_mut instead");
3665 unreachable!("WritableKeyPath::with_box requires &mut Box<Root> - use with_box_mut instead")
3666 }
3667
3668 fn with_box_mut<Callback, R>(&self, boxed: &mut Box<Root>, f: Callback) -> R
3669 where
3670 Callback: FnOnce(&mut Value) -> R,
3671 {
3672 let value = self.get_mut(boxed.as_mut());
3673 f(value)
3674 }
3675
3676 fn with_rc<Callback, R>(&self, _rc: &Rc<Root>, _f: Callback) -> R
3677 where
3678 Callback: FnOnce(&Value) -> R,
3679 {
3680 eprintln!("[DEBUG] WritableKeyPath::with_rc requires &mut Rc<Root> or interior mutability");
3683 unreachable!("WritableKeyPath::with_rc requires &mut Rc<Root> or interior mutability")
3684 }
3685
3686 fn with_result<Callback, R, E>(&self, _result: &Result<Root, E>, _f: Callback) -> Option<R>
3687 where
3688 Callback: FnOnce(&Value) -> R,
3689 {
3690 None
3693 }
3694
3695 fn with_result_mut<Callback, R, E>(&self, result: &mut Result<Root, E>, f: Callback) -> Option<R>
3696 where
3697 Callback: FnOnce(&mut Value) -> R,
3698 {
3699 result.as_mut().ok().map(|root| {
3700 let value = self.get_mut(root);
3701 f(value)
3702 })
3703 }
3704
3705 fn with_option<Callback, R>(&self, _option: &Option<Root>, _f: Callback) -> Option<R>
3706 where
3707 Callback: FnOnce(&Value) -> R,
3708 {
3709 None
3712 }
3713
3714 fn with_option_mut<Callback, R>(&self, option: &mut Option<Root>, f: Callback) -> Option<R>
3715 where
3716 Callback: FnOnce(&mut Value) -> R,
3717 {
3718 option.as_mut().map(|root| {
3719 let value = self.get_mut(root);
3720 f(value)
3721 })
3722 }
3723
3724 fn with_refcell<Callback, R>(&self, refcell: &RefCell<Root>, f: Callback) -> Option<R>
3725 where
3726 Callback: FnOnce(&Value) -> R,
3727 {
3728 None
3731 }
3732
3733 fn with_refcell_mut<Callback, R>(&self, refcell: &RefCell<Root>, f: Callback) -> Option<R>
3734 where
3735 Callback: FnOnce(&mut Value) -> R,
3736 {
3737 refcell.try_borrow_mut().ok().map(|mut borrow| {
3738 let value = self.get_mut(&mut *borrow);
3739 f(value)
3740 })
3741 }
3742
3743 #[cfg(feature = "tagged")]
3744 fn with_tagged<Tag, Callback, R>(&self, _tagged: &Tagged<Root, Tag>, _f: Callback) -> R
3745 where
3746 Tagged<Root, Tag>: std::ops::Deref<Target = Root>,
3747 Callback: FnOnce(&Value) -> R,
3748 {
3749 eprintln!("[DEBUG] WritableKeyPath::with_tagged requires &mut Tagged<Root, Tag> or interior mutability");
3752 unreachable!("WritableKeyPath::with_tagged requires &mut Tagged<Root, Tag> or interior mutability")
3753 }
3754
3755 fn with_mutex<Callback, R>(&self, mutex: &Mutex<Root>, f: Callback) -> Option<R>
3756 where
3757 Callback: FnOnce(&Value) -> R,
3758 {
3759 mutex.lock().ok().map(|mut guard| {
3760 let value = self.get_mut(&mut *guard);
3761 f(value)
3762 })
3763 }
3764
3765 fn with_mutex_mut<Callback, R>(&self, mutex: &mut Mutex<Root>, f: Callback) -> Option<R>
3766 where
3767 Callback: FnOnce(&mut Value) -> R,
3768 {
3769 mutex.get_mut().ok().map(|root| {
3771 let value = self.get_mut(root);
3772 f(value)
3773 })
3774 }
3775
3776 fn with_rwlock<Callback, R>(&self, rwlock: &RwLock<Root>, f: Callback) -> Option<R>
3777 where
3778 Callback: FnOnce(&Value) -> R,
3779 {
3780 None
3783 }
3784
3785 fn with_rwlock_mut<Callback, R>(&self, rwlock: &mut RwLock<Root>, f: Callback) -> Option<R>
3786 where
3787 Callback: FnOnce(&mut Value) -> R,
3788 {
3789 rwlock.get_mut().ok().map(|root| {
3791 let value = self.get_mut(root);
3792 f(value)
3793 })
3794 }
3795
3796 fn with_arc_rwlock<Callback, R>(&self, arc_rwlock: &Arc<RwLock<Root>>, f: Callback) -> Option<R>
3797 where
3798 Callback: FnOnce(&Value) -> R,
3799 {
3800 None
3803 }
3804
3805 fn with_arc_rwlock_mut<Callback, R>(&self, arc_rwlock: &Arc<RwLock<Root>>, f: Callback) -> Option<R>
3806 where
3807 Callback: FnOnce(&mut Value) -> R,
3808 {
3809 arc_rwlock.write().ok().map(|mut guard| {
3810 let value = self.get_mut(&mut *guard);
3811 f(value)
3812 })
3813 }
3814}
3815
3816impl<Root, Value, F> WithContainer<Root, Value> for WritableOptionalKeyPath<Root, Value, F>
3818where
3819 F: for<'r> Fn(&'r mut Root) -> Option<&'r mut Value>,
3820{
3821 fn with_arc<Callback, R>(&self, _arc: &Arc<Root>, _f: Callback) -> R
3822 where
3823 Callback: FnOnce(&Value) -> R,
3824 {
3825 eprintln!("[DEBUG] WritableOptionalKeyPath::with_arc requires &mut Arc<Root> or interior mutability");
3828 unreachable!("WritableOptionalKeyPath::with_arc requires &mut Arc<Root> or interior mutability")
3829 }
3830
3831 fn with_box<Callback, R>(&self, _boxed: &Box<Root>, _f: Callback) -> R
3832 where
3833 Callback: FnOnce(&Value) -> R,
3834 {
3835 eprintln!("[DEBUG] WritableOptionalKeyPath::with_box requires &mut Box<Root> - use with_box_mut instead");
3838 unreachable!("WritableOptionalKeyPath::with_box requires &mut Box<Root> - use with_box_mut instead")
3839 }
3840
3841 fn with_box_mut<Callback, R>(&self, boxed: &mut Box<Root>, f: Callback) -> R
3842 where
3843 Callback: FnOnce(&mut Value) -> R,
3844 {
3845 if let Some(value) = self.get_mut(boxed.as_mut()) {
3846 f(value)
3847 } else {
3848 eprintln!("[DEBUG] WritableOptionalKeyPath failed to get value from Box");
3849 unreachable!("WritableOptionalKeyPath failed to get value from Box")
3850 }
3851 }
3852
3853 fn with_rc<Callback, R>(&self, _rc: &Rc<Root>, _f: Callback) -> R
3854 where
3855 Callback: FnOnce(&Value) -> R,
3856 {
3857 eprintln!("[DEBUG] WritableOptionalKeyPath::with_rc requires &mut Rc<Root> or interior mutability");
3860 unreachable!("WritableOptionalKeyPath::with_rc requires &mut Rc<Root> or interior mutability")
3861 }
3862
3863 fn with_result<Callback, R, E>(&self, _result: &Result<Root, E>, _f: Callback) -> Option<R>
3864 where
3865 Callback: FnOnce(&Value) -> R,
3866 {
3867 None
3870 }
3871
3872 fn with_result_mut<Callback, R, E>(&self, result: &mut Result<Root, E>, f: Callback) -> Option<R>
3873 where
3874 Callback: FnOnce(&mut Value) -> R,
3875 {
3876 result.as_mut().ok().and_then(|root| {
3877 self.get_mut(root).map(|value| f(value))
3878 })
3879 }
3880
3881 fn with_option<Callback, R>(&self, _option: &Option<Root>, _f: Callback) -> Option<R>
3882 where
3883 Callback: FnOnce(&Value) -> R,
3884 {
3885 None
3888 }
3889
3890 fn with_option_mut<Callback, R>(&self, option: &mut Option<Root>, f: Callback) -> Option<R>
3891 where
3892 Callback: FnOnce(&mut Value) -> R,
3893 {
3894 option.as_mut().and_then(|root| {
3895 self.get_mut(root).map(|value| f(value))
3896 })
3897 }
3898
3899 fn with_refcell<Callback, R>(&self, _refcell: &RefCell<Root>, _f: Callback) -> Option<R>
3900 where
3901 Callback: FnOnce(&Value) -> R,
3902 {
3903 None
3906 }
3907
3908 fn with_refcell_mut<Callback, R>(&self, refcell: &RefCell<Root>, f: Callback) -> Option<R>
3909 where
3910 Callback: FnOnce(&mut Value) -> R,
3911 {
3912 refcell.try_borrow_mut().ok().and_then(|mut borrow| {
3913 self.get_mut(&mut *borrow).map(|value| f(value))
3914 })
3915 }
3916
3917 #[cfg(feature = "tagged")]
3918 fn with_tagged<Tag, Callback, R>(&self, _tagged: &Tagged<Root, Tag>, _f: Callback) -> R
3919 where
3920 Tagged<Root, Tag>: std::ops::Deref<Target = Root>,
3921 Callback: FnOnce(&Value) -> R,
3922 {
3923 eprintln!("[DEBUG] WritableOptionalKeyPath::with_tagged requires &mut Tagged<Root, Tag> or interior mutability");
3926 unreachable!("WritableOptionalKeyPath::with_tagged requires &mut Tagged<Root, Tag> or interior mutability")
3927 }
3928
3929 fn with_mutex<Callback, R>(&self, mutex: &Mutex<Root>, f: Callback) -> Option<R>
3930 where
3931 Callback: FnOnce(&Value) -> R,
3932 {
3933 mutex.lock().ok().and_then(|mut guard| {
3934 self.get_mut(&mut *guard).map(|value| f(value))
3935 })
3936 }
3937
3938 fn with_mutex_mut<Callback, R>(&self, mutex: &mut Mutex<Root>, f: Callback) -> Option<R>
3939 where
3940 Callback: FnOnce(&mut Value) -> R,
3941 {
3942 mutex.get_mut().ok().and_then(|root| {
3944 self.get_mut(root).map(|value| f(value))
3945 })
3946 }
3947
3948 fn with_rwlock<Callback, R>(&self, _rwlock: &RwLock<Root>, _f: Callback) -> Option<R>
3949 where
3950 Callback: FnOnce(&Value) -> R,
3951 {
3952 None
3955 }
3956
3957 fn with_rwlock_mut<Callback, R>(&self, rwlock: &mut RwLock<Root>, f: Callback) -> Option<R>
3958 where
3959 Callback: FnOnce(&mut Value) -> R,
3960 {
3961 rwlock.get_mut().ok().and_then(|root| {
3963 self.get_mut(root).map(|value| f(value))
3964 })
3965 }
3966
3967 fn with_arc_rwlock<Callback, R>(&self, _arc_rwlock: &Arc<RwLock<Root>>, _f: Callback) -> Option<R>
3968 where
3969 Callback: FnOnce(&Value) -> R,
3970 {
3971 None
3974 }
3975
3976 fn with_arc_rwlock_mut<Callback, R>(&self, arc_rwlock: &Arc<RwLock<Root>>, f: Callback) -> Option<R>
3977 where
3978 Callback: FnOnce(&mut Value) -> R,
3979 {
3980 arc_rwlock.write().ok().and_then(|mut guard| {
3981 self.get_mut(&mut *guard).map(|value| f(value))
3982 })
3983 }
3984}