1use 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;
11use std::fmt;
12
13#[cfg(feature = "tagged")]
14use tagged_core::Tagged;
15
16
17#[macro_export]
39macro_rules! keypath {
40 ($closure:expr) => {
42 $crate::KeyPath::new($closure)
43 };
44}
45
46#[macro_export]
66macro_rules! opt_keypath {
67 ($closure:expr) => {
69 $crate::OptionalKeyPath::new($closure)
70 };
71}
72
73#[macro_export]
93macro_rules! writable_keypath {
94 ($closure:expr) => {
96 $crate::WritableKeyPath::new($closure)
97 };
98}
99
100#[macro_export]
120macro_rules! writable_opt_keypath {
121 ($closure:expr) => {
123 $crate::WritableOptionalKeyPath::new($closure)
124 };
125}
126
127#[derive(Clone)]
131pub struct KeyPath<Root, Value, F>
132where
133 F: for<'r> Fn(&'r Root) -> &'r Value,
134{
135 getter: F,
136 _phantom: PhantomData<(Root, Value)>,
137}
138
139impl<Root, Value, F> fmt::Display for KeyPath<Root, Value, F>
140where
141 F: for<'r> Fn(&'r Root) -> &'r Value,
142{
143 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
144 let root_name = std::any::type_name::<Root>();
145 let value_name = std::any::type_name::<Value>();
146 let root_short = root_name.split("::").last().unwrap_or(root_name);
148 let value_short = value_name.split("::").last().unwrap_or(value_name);
149 write!(f, "KeyPath<{} -> {}>", root_short, value_short)
150 }
151}
152
153impl<Root, Value, F> fmt::Debug for KeyPath<Root, Value, F>
154where
155 F: for<'r> Fn(&'r Root) -> &'r Value,
156{
157 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
158 fmt::Display::fmt(self, f)
159 }
160}
161
162impl<Root, Value, F> KeyPath<Root, Value, F>
163where
164 F: for<'r> Fn(&'r Root) -> &'r Value,
165{
166 pub fn new(getter: F) -> Self {
167 Self {
168 getter,
169 _phantom: PhantomData,
170 }
171 }
172
173 pub fn get<'r>(&self, root: &'r Root) -> &'r Value {
174 (self.getter)(root)
175}
176
177 pub fn for_box<Target>(self) -> KeyPath<Root, Target, impl for<'r> Fn(&'r Root) -> &'r Target + 'static>
180 where
181 Value: std::ops::Deref<Target = Target>,
182 F: 'static,
183 Value: 'static,
184 {
185 let getter = self.getter;
186
187 KeyPath {
188 getter: move |root: &Root| {
189 getter(root).deref()
190 },
191 _phantom: PhantomData,
192 }
193 }
194
195 pub fn for_arc<Target>(self) -> KeyPath<Root, Target, impl for<'r> Fn(&'r Root) -> &'r Target + 'static>
197 where
198 Value: std::ops::Deref<Target = Target>,
199 F: 'static,
200 Value: 'static,
201 {
202 let getter = self.getter;
203
204 KeyPath {
205 getter: move |root: &Root| {
206 getter(root).deref()
207 },
208 _phantom: PhantomData,
209 }
210 }
211
212 pub fn for_rc<Target>(self) -> KeyPath<Root, Target, impl for<'r> Fn(&'r Root) -> &'r Target + 'static>
214 where
215 Value: std::ops::Deref<Target = Target>,
216 F: 'static,
217 Value: 'static,
218 {
219 let getter = self.getter;
220
221 KeyPath {
222 getter: move |root: &Root| {
223 getter(root).deref()
224 },
225 _phantom: PhantomData,
226 }
227 }
228
229 pub fn for_arc_root(self) -> OptionalKeyPath<Arc<Root>, Value, impl for<'r> Fn(&'r Arc<Root>) -> Option<&'r Value> + 'static>
231 where
232 Value: Sized,
233 F: 'static,
234 Root: 'static,
235 Value: 'static,
236 {
237 let getter = self.getter;
238
239 OptionalKeyPath {
240 getter: move |arc: &Arc<Root>| {
241 Some(getter(arc.as_ref()))
242 },
243 _phantom: PhantomData,
244 }
245 }
246
247 pub fn for_box_root(self) -> OptionalKeyPath<Box<Root>, Value, impl for<'r> Fn(&'r Box<Root>) -> Option<&'r Value> + 'static>
249 where
250 Value: Sized,
251 F: 'static,
252 Root: 'static,
253 Value: 'static,
254 {
255 let getter = self.getter;
256
257 OptionalKeyPath {
258 getter: move |boxed: &Box<Root>| {
259 Some(getter(boxed.as_ref()))
260 },
261 _phantom: PhantomData,
262 }
263 }
264
265 pub fn for_rc_root(self) -> OptionalKeyPath<Rc<Root>, Value, impl for<'r> Fn(&'r Rc<Root>) -> Option<&'r Value> + 'static>
267 where
268 Value: Sized,
269 F: 'static,
270 Root: 'static,
271 Value: 'static,
272 {
273 let getter = self.getter;
274
275 OptionalKeyPath {
276 getter: move |rc: &Rc<Root>| {
277 Some(getter(rc.as_ref()))
278 },
279 _phantom: PhantomData,
280 }
281 }
282
283 pub fn for_result<E>(self) -> OptionalKeyPath<Result<Root, E>, Value, impl for<'r> Fn(&'r Result<Root, E>) -> Option<&'r Value> + 'static>
286 where
287 F: 'static,
288 Root: 'static,
289 Value: 'static,
290 E: 'static,
291 {
292 let getter = self.getter;
293
294 OptionalKeyPath {
295 getter: move |result: &Result<Root, E>| {
296 result.as_ref().ok().map(|root| getter(root))
297 },
298 _phantom: PhantomData,
299 }
300 }
301
302 pub fn to_optional(self) -> OptionalKeyPath<Root, Value, impl for<'r> Fn(&'r Root) -> Option<&'r Value> + 'static>
305 where
306 F: 'static,
307 {
308 let getter = self.getter;
309 OptionalKeyPath::new(move |root: &Root| Some(getter(root)))
310 }
311
312 pub fn with_option<Callback, R>(&self, option: &Option<Root>, f: Callback) -> Option<R>
314 where
315 F: Clone,
316 Callback: FnOnce(&Value) -> R,
317 {
318 option.as_ref().map(|root| {
319 let value = self.get(root);
320 f(value)
321 })
322 }
323
324 pub fn with_result<Callback, R, E>(&self, result: &Result<Root, E>, f: Callback) -> Option<R>
326 where
327 F: Clone,
328 Callback: FnOnce(&Value) -> R,
329 {
330 result.as_ref().ok().map(|root| {
331 let value = self.get(root);
332 f(value)
333 })
334 }
335
336 pub fn with_box<Callback, R>(&self, boxed: &Box<Root>, f: Callback) -> R
338 where
339 F: Clone,
340 Callback: FnOnce(&Value) -> R,
341 {
342 let value = self.get(boxed);
343 f(value)
344 }
345
346 pub fn with_arc<Callback, R>(&self, arc: &Arc<Root>, f: Callback) -> R
348 where
349 F: Clone,
350 Callback: FnOnce(&Value) -> R,
351 {
352 let value = self.get(arc);
353 f(value)
354 }
355
356 pub fn with_rc<Callback, R>(&self, rc: &Rc<Root>, f: Callback) -> R
358 where
359 F: Clone,
360 Callback: FnOnce(&Value) -> R,
361 {
362 let value = self.get(rc);
363 f(value)
364 }
365
366 pub fn with_refcell<Callback, R>(&self, refcell: &RefCell<Root>, f: Callback) -> Option<R>
368 where
369 F: Clone,
370 Callback: FnOnce(&Value) -> R,
371 {
372 refcell.try_borrow().ok().map(|borrow| {
373 let value = self.get(&*borrow);
374 f(value)
375 })
376 }
377
378 pub fn with_mutex<Callback, R>(&self, mutex: &Mutex<Root>, f: Callback) -> Option<R>
380 where
381 F: Clone,
382 Callback: FnOnce(&Value) -> R,
383 {
384 mutex.lock().ok().map(|guard| {
385 let value = self.get(&*guard);
386 f(value)
387 })
388 }
389
390 pub fn with_rwlock<Callback, R>(&self, rwlock: &RwLock<Root>, f: Callback) -> Option<R>
392 where
393 F: Clone,
394 Callback: FnOnce(&Value) -> R,
395 {
396 rwlock.read().ok().map(|guard| {
397 let value = self.get(&*guard);
398 f(value)
399 })
400 }
401
402 pub fn with_arc_rwlock<Callback, R>(&self, arc_rwlock: &Arc<RwLock<Root>>, f: Callback) -> Option<R>
404 where
405 F: Clone,
406 Callback: FnOnce(&Value) -> R,
407 {
408 arc_rwlock.read().ok().map(|guard| {
409 let value = self.get(&*guard);
410 f(value)
411 })
412 }
413
414 pub fn with_arc_mutex<Callback, R>(&self, arc_mutex: &Arc<Mutex<Root>>, f: Callback) -> Option<R>
416 where
417 F: Clone,
418 Callback: FnOnce(&Value) -> R,
419 {
420 arc_mutex.lock().ok().map(|guard| {
421 let value = self.get(&*guard);
422 f(value)
423 })
424 }
425
426 #[cfg(feature = "tagged")]
427 pub fn for_tagged<Tag>(self) -> KeyPath<Tagged<Root, Tag>, Value, impl for<'r> Fn(&'r Tagged<Root, Tag>) -> &'r Value + 'static>
430 where
431 Tagged<Root, Tag>: std::ops::Deref<Target = Root>,
432 F: 'static,
433 Root: 'static,
434 Value: 'static,
435 Tag: 'static,
436 {
437 use std::ops::Deref;
438 let getter = self.getter;
439
440 KeyPath {
441 getter: move |tagged: &Tagged<Root, Tag>| {
442 getter(tagged.deref())
443 },
444 _phantom: PhantomData,
445 }
446 }
447
448 #[cfg(feature = "tagged")]
449 pub fn with_tagged<Tag, Callback, R>(&self, tagged: &Tagged<Root, Tag>, f: Callback) -> R
452 where
453 Tagged<Root, Tag>: std::ops::Deref<Target = Root>,
454 Callback: FnOnce(&Value) -> R,
455 {
456 use std::ops::Deref;
457 let value = self.get(tagged.deref());
458 f(value)
459 }
460
461 pub fn for_option(self) -> OptionalKeyPath<Option<Root>, Value, impl for<'r> Fn(&'r Option<Root>) -> Option<&'r Value> + 'static>
464 where
465 F: 'static,
466 Root: 'static,
467 Value: 'static,
468 {
469 let getter = self.getter;
470
471 OptionalKeyPath {
472 getter: move |opt: &Option<Root>| {
473 opt.as_ref().map(|root| getter(root))
474 },
475 _phantom: PhantomData,
476 }
477 }
478
479 pub fn iter<'r, T>(&self, root: &'r Root) -> Option<std::slice::Iter<'r, T>>
482 where
483 Value: AsRef<[T]> + 'r,
484 {
485 let value_ref: &'r Value = self.get(root);
486 Some(value_ref.as_ref().iter())
487 }
488
489 pub fn extract_from_slice<'r>(&self, slice: &'r [Root]) -> Vec<&'r Value> {
492 slice.iter().map(|item| self.get(item)).collect()
493 }
494
495 pub fn extract_from_ref_slice<'r>(&self, slice: &'r [&Root]) -> Vec<&'r Value> {
498 slice.iter().map(|item| self.get(item)).collect()
499 }
500
501 pub fn then<SubValue, G>(
504 self,
505 next: KeyPath<Value, SubValue, G>,
506 ) -> KeyPath<Root, SubValue, impl for<'r> Fn(&'r Root) -> &'r SubValue>
507 where
508 G: for<'r> Fn(&'r Value) -> &'r SubValue,
509 F: 'static,
510 G: 'static,
511 Value: 'static,
512 {
513 let first = self.getter;
514 let second = next.getter;
515
516 KeyPath::new(move |root: &Root| {
517 let value = first(root);
518 second(value)
519 })
520 }
521
522 pub fn then_optional<SubValue, G>(
525 self,
526 next: OptionalKeyPath<Value, SubValue, G>,
527 ) -> OptionalKeyPath<Root, SubValue, impl for<'r> Fn(&'r Root) -> Option<&'r SubValue>>
528 where
529 G: for<'r> Fn(&'r Value) -> Option<&'r SubValue>,
530 F: 'static,
531 G: 'static,
532 Value: 'static,
533 {
534 let first = self.getter;
535 let second = next.getter;
536
537 OptionalKeyPath::new(move |root: &Root| {
538 let value = first(root);
539 second(value)
540 })
541 }
542
543}
544
545impl<Root, Value, F> KeyPath<Root, Value, F>
547where
548 F: for<'r> Fn(&'r Root) -> &'r Value,
549{
550 pub fn with_arc_rwlock_direct<Callback, R>(&self, arc_rwlock: &Arc<RwLock<Root>>, f: Callback) -> Option<R>
553 where
554 Callback: FnOnce(&Value) -> R,
555 {
556 arc_rwlock.read().ok().map(|guard| {
557 let value = self.get(&*guard);
558 f(value)
559 })
560 }
561
562 pub fn with_arc_mutex_direct<Callback, R>(&self, arc_mutex: &Arc<Mutex<Root>>, f: Callback) -> Option<R>
565 where
566 Callback: FnOnce(&Value) -> R,
567 {
568 arc_mutex.lock().ok().map(|guard| {
569 let value = self.get(&*guard);
570 f(value)
571 })
572 }
573}
574
575pub fn for_slice<T>() -> impl for<'r> Fn(&'r [T], usize) -> Option<&'r T> {
577 |slice: &[T], index: usize| slice.get(index)
578}
579
580pub mod containers {
582 use super::{OptionalKeyPath, WritableOptionalKeyPath, KeyPath, WritableKeyPath};
583 use std::collections::{HashMap, BTreeMap, HashSet, BTreeSet, VecDeque, LinkedList, BinaryHeap};
584 use std::sync::{Mutex, RwLock, Weak as StdWeak, Arc};
585 use std::rc::{Weak as RcWeak, Rc};
586 use std::ops::{Deref, DerefMut};
587
588 #[cfg(feature = "parking_lot")]
589 use parking_lot::{Mutex as ParkingMutex, RwLock as ParkingRwLock};
590
591 #[cfg(feature = "tagged")]
592 use tagged_core::Tagged;
593
594 pub fn for_vec_index<T>(index: usize) -> OptionalKeyPath<Vec<T>, T, impl for<'r> Fn(&'r Vec<T>) -> Option<&'r T>> {
596 OptionalKeyPath::new(move |vec: &Vec<T>| vec.get(index))
597 }
598
599 pub fn for_vecdeque_index<T>(index: usize) -> OptionalKeyPath<VecDeque<T>, T, impl for<'r> Fn(&'r VecDeque<T>) -> Option<&'r T>> {
601 OptionalKeyPath::new(move |deque: &VecDeque<T>| deque.get(index))
602 }
603
604 pub fn for_linkedlist_index<T>(index: usize) -> OptionalKeyPath<LinkedList<T>, T, impl for<'r> Fn(&'r LinkedList<T>) -> Option<&'r T>> {
606 OptionalKeyPath::new(move |list: &LinkedList<T>| {
607 list.iter().nth(index)
608 })
609 }
610
611 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>>
613 where
614 K: std::hash::Hash + Eq + Clone + 'static,
615 V: 'static,
616 {
617 OptionalKeyPath::new(move |map: &HashMap<K, V>| map.get(&key))
618 }
619
620 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>>
622 where
623 K: Ord + Clone + 'static,
624 V: 'static,
625 {
626 OptionalKeyPath::new(move |map: &BTreeMap<K, V>| map.get(&key))
627 }
628
629 pub fn for_hashset_get<T>(value: T) -> OptionalKeyPath<HashSet<T>, T, impl for<'r> Fn(&'r HashSet<T>) -> Option<&'r T>>
631 where
632 T: std::hash::Hash + Eq + Clone + 'static,
633 {
634 OptionalKeyPath::new(move |set: &HashSet<T>| set.get(&value))
635 }
636
637 pub fn for_btreeset_get<T>(value: T) -> OptionalKeyPath<BTreeSet<T>, T, impl for<'r> Fn(&'r BTreeSet<T>) -> Option<&'r T>>
639 where
640 T: Ord + Clone + 'static,
641 {
642 OptionalKeyPath::new(move |set: &BTreeSet<T>| set.get(&value))
643 }
644
645 pub fn for_binaryheap_peek<T>() -> OptionalKeyPath<BinaryHeap<T>, T, impl for<'r> Fn(&'r BinaryHeap<T>) -> Option<&'r T>>
647 where
648 T: Ord + 'static,
649 {
650 OptionalKeyPath::new(|heap: &BinaryHeap<T>| heap.peek())
651 }
652
653 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>> {
657 WritableOptionalKeyPath::new(move |vec: &mut Vec<T>| vec.get_mut(index))
658 }
659
660 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>> {
662 WritableOptionalKeyPath::new(move |deque: &mut VecDeque<T>| deque.get_mut(index))
663 }
664
665 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>> {
667 WritableOptionalKeyPath::new(move |list: &mut LinkedList<T>| {
668 let mut iter = list.iter_mut();
670 iter.nth(index)
671 })
672 }
673
674 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>>
676 where
677 K: std::hash::Hash + Eq + Clone + 'static,
678 V: 'static,
679 {
680 WritableOptionalKeyPath::new(move |map: &mut HashMap<K, V>| map.get_mut(&key))
681 }
682
683 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>>
685 where
686 K: Ord + Clone + 'static,
687 V: 'static,
688 {
689 WritableOptionalKeyPath::new(move |map: &mut BTreeMap<K, V>| map.get_mut(&key))
690 }
691
692 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>>
695 where
696 T: std::hash::Hash + Eq + Clone + 'static,
697 {
698 WritableOptionalKeyPath::new(move |set: &mut HashSet<T>| {
699 if set.contains(&value) {
702 None
705 } else {
706 None
707 }
708 })
709 }
710
711 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>>
714 where
715 T: Ord + Clone + 'static,
716 {
717 WritableOptionalKeyPath::new(move |set: &mut BTreeSet<T>| {
718 if set.contains(&value) {
721 None
724 } else {
725 None
726 }
727 })
728 }
729
730 pub fn for_binaryheap_peek_mut<T>() -> WritableOptionalKeyPath<BinaryHeap<T>, T, impl for<'r> Fn(&'r mut BinaryHeap<T>) -> Option<&'r mut T>>
736 where
737 T: Ord + 'static,
738 {
739 WritableOptionalKeyPath::new(|_heap: &mut BinaryHeap<T>| {
743 None
744 })
745 }
746
747 pub fn lock_mutex<T>(mutex: &Mutex<T>) -> Option<std::sync::MutexGuard<'_, T>> {
756 mutex.lock().ok()
757 }
758
759 pub fn read_rwlock<T>(rwlock: &RwLock<T>) -> Option<std::sync::RwLockReadGuard<'_, T>> {
763 rwlock.read().ok()
764 }
765
766 pub fn write_rwlock<T>(rwlock: &RwLock<T>) -> Option<std::sync::RwLockWriteGuard<'_, T>> {
770 rwlock.write().ok()
771 }
772
773 pub fn lock_arc_mutex<T>(arc_mutex: &Arc<Mutex<T>>) -> Option<std::sync::MutexGuard<'_, T>> {
777 arc_mutex.lock().ok()
778 }
779
780 pub fn read_arc_rwlock<T>(arc_rwlock: &Arc<RwLock<T>>) -> Option<std::sync::RwLockReadGuard<'_, T>> {
784 arc_rwlock.read().ok()
785 }
786
787 pub fn write_arc_rwlock<T>(arc_rwlock: &Arc<RwLock<T>>) -> Option<std::sync::RwLockWriteGuard<'_, T>> {
791 arc_rwlock.write().ok()
792 }
793
794 pub fn upgrade_weak<T>(weak: &StdWeak<T>) -> Option<Arc<T>> {
798 weak.upgrade()
799 }
800
801 pub fn upgrade_rc_weak<T>(weak: &RcWeak<T>) -> Option<Rc<T>> {
805 weak.upgrade()
806 }
807
808 #[cfg(feature = "parking_lot")]
809 pub fn lock_parking_mutex<T>(mutex: &ParkingMutex<T>) -> parking_lot::MutexGuard<'_, T> {
812 mutex.lock()
813 }
814
815 #[cfg(feature = "parking_lot")]
816 pub fn read_parking_rwlock<T>(rwlock: &ParkingRwLock<T>) -> parking_lot::RwLockReadGuard<'_, T> {
819 rwlock.read()
820 }
821
822 #[cfg(feature = "parking_lot")]
823 pub fn write_parking_rwlock<T>(rwlock: &ParkingRwLock<T>) -> parking_lot::RwLockWriteGuard<'_, T> {
826 rwlock.write()
827 }
828
829 #[cfg(feature = "tagged")]
830 pub fn for_tagged<Tag, T>() -> KeyPath<Tagged<Tag, T>, T, impl for<'r> Fn(&'r Tagged<Tag, T>) -> &'r T>
833 where
834 Tagged<Tag, T>: std::ops::Deref<Target = T>,
835 Tag: 'static,
836 T: 'static,
837 {
838 KeyPath::new(|tagged: &Tagged<Tag, T>| tagged.deref())
839 }
840
841 #[cfg(feature = "tagged")]
842 pub fn for_tagged_mut<Tag, T>() -> WritableKeyPath<Tagged<Tag, T>, T, impl for<'r> Fn(&'r mut Tagged<Tag, T>) -> &'r mut T>
845 where
846 Tagged<Tag, T>: std::ops::DerefMut<Target = T>,
847 Tag: 'static,
848 T: 'static,
849 {
850 WritableKeyPath::new(|tagged: &mut Tagged<Tag, T>| tagged.deref_mut())
851 }
852}
853
854#[derive(Clone)]
856pub struct OptionalKeyPath<Root, Value, F>
857where
858 F: for<'r> Fn(&'r Root) -> Option<&'r Value>,
859{
860 getter: F,
861 _phantom: PhantomData<(Root, Value)>,
862}
863
864impl<Root, Value, F> fmt::Display for OptionalKeyPath<Root, Value, F>
865where
866 F: for<'r> Fn(&'r Root) -> Option<&'r Value>,
867{
868 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
869 let root_name = std::any::type_name::<Root>();
870 let value_name = std::any::type_name::<Value>();
871 let root_short = root_name.split("::").last().unwrap_or(root_name);
873 let value_short = value_name.split("::").last().unwrap_or(value_name);
874 write!(f, "OptionalKeyPath<{} -> Option<{}>>", root_short, value_short)
875 }
876}
877
878impl<Root, Value, F> fmt::Debug for OptionalKeyPath<Root, Value, F>
879where
880 F: for<'r> Fn(&'r Root) -> Option<&'r Value>,
881{
882 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
883 fmt::Display::fmt(self, f)
884 }
885}
886
887impl<Root, Value, F> OptionalKeyPath<Root, Value, F>
888where
889 F: for<'r> Fn(&'r Root) -> Option<&'r Value>,
890{
891 pub fn new(getter: F) -> Self {
892 Self {
893 getter,
894 _phantom: PhantomData,
895 }
896 }
897
898 pub fn get<'r>(&self, root: &'r Root) -> Option<&'r Value> {
899 (self.getter)(root)
900 }
901
902 pub fn then<SubValue, G>(
904 self,
905 next: OptionalKeyPath<Value, SubValue, G>,
906 ) -> OptionalKeyPath<Root, SubValue, impl for<'r> Fn(&'r Root) -> Option<&'r SubValue>>
907 where
908 G: for<'r> Fn(&'r Value) -> Option<&'r SubValue>,
909 F: 'static,
910 G: 'static,
911 Value: 'static,
912 {
913 let first = self.getter;
914 let second = next.getter;
915
916 OptionalKeyPath::new(move |root: &Root| {
917 first(root).and_then(|value| second(value))
918 })
919 }
920
921 pub fn for_box<Target>(self) -> OptionalKeyPath<Root, Target, impl for<'r> Fn(&'r Root) -> Option<&'r Target> + 'static>
924 where
925 Value: std::ops::Deref<Target = Target>,
926 F: 'static,
927 Value: 'static,
928 {
929 let getter = self.getter;
930
931 OptionalKeyPath {
932 getter: move |root: &Root| {
933 getter(root).map(|boxed| boxed.deref())
934 },
935 _phantom: PhantomData,
936 }
937 }
938
939 pub fn for_arc<Target>(self) -> OptionalKeyPath<Root, Target, impl for<'r> Fn(&'r Root) -> Option<&'r Target> + 'static>
941 where
942 Value: std::ops::Deref<Target = Target>,
943 F: 'static,
944 Value: 'static,
945 {
946 let getter = self.getter;
947
948 OptionalKeyPath {
949 getter: move |root: &Root| {
950 getter(root).map(|arc| arc.deref())
951 },
952 _phantom: PhantomData,
953 }
954 }
955
956 pub fn for_rc<Target>(self) -> OptionalKeyPath<Root, Target, impl for<'r> Fn(&'r Root) -> Option<&'r Target> + 'static>
958 where
959 Value: std::ops::Deref<Target = Target>,
960 F: 'static,
961 Value: 'static,
962 {
963 let getter = self.getter;
964
965 OptionalKeyPath {
966 getter: move |root: &Root| {
967 getter(root).map(|rc| rc.deref())
968 },
969 _phantom: PhantomData,
970 }
971 }
972
973 #[cfg(feature = "tagged")]
974 pub fn for_tagged<Tag>(self) -> OptionalKeyPath<Tagged<Root, Tag>, Value, impl for<'r> Fn(&'r Tagged<Root, Tag>) -> Option<&'r Value> + 'static>
977 where
978 Tagged<Root, Tag>: std::ops::Deref<Target = Root>,
979 F: 'static,
980 Root: 'static,
981 Value: 'static,
982 Tag: 'static,
983 {
984 use std::ops::Deref;
985 let getter = self.getter;
986
987 OptionalKeyPath {
988 getter: move |tagged: &Tagged<Root, Tag>| {
989 getter(tagged.deref())
990 },
991 _phantom: PhantomData,
992 }
993 }
994
995 #[cfg(feature = "tagged")]
996 pub fn with_tagged<Tag, Callback, R>(&self, tagged: &Tagged<Root, Tag>, f: Callback) -> Option<R>
999 where
1000 Tagged<Root, Tag>: std::ops::Deref<Target = Root>,
1001 F: Clone,
1002 Callback: FnOnce(&Value) -> R,
1003 {
1004 use std::ops::Deref;
1005 self.get(tagged.deref()).map(|value| f(value))
1006 }
1007
1008 pub fn for_option(self) -> OptionalKeyPath<Option<Root>, Value, impl for<'r> Fn(&'r Option<Root>) -> Option<&'r Value> + 'static>
1011 where
1012 F: 'static,
1013 Root: 'static,
1014 Value: 'static,
1015 {
1016 let getter = self.getter;
1017
1018 OptionalKeyPath {
1019 getter: move |opt: &Option<Root>| {
1020 opt.as_ref().and_then(|root| getter(root))
1021 },
1022 _phantom: PhantomData,
1023 }
1024 }
1025
1026 pub fn for_result<E>(self) -> OptionalKeyPath<Result<Root, E>, Value, impl for<'r> Fn(&'r Result<Root, E>) -> Option<&'r Value> + 'static>
1029 where
1030 F: 'static,
1031 Root: 'static,
1032 Value: 'static,
1033 E: 'static,
1034 {
1035 let getter = self.getter;
1036
1037 OptionalKeyPath {
1038 getter: move |result: &Result<Root, E>| {
1039 result.as_ref().ok().and_then(|root| getter(root))
1040 },
1041 _phantom: PhantomData,
1042 }
1043 }
1044
1045 pub fn for_arc_root(self) -> OptionalKeyPath<Arc<Root>, Value, impl for<'r> Fn(&'r Arc<Root>) -> Option<&'r Value> + 'static>
1047 where
1048 Value: Sized,
1049 F: 'static,
1050 Root: 'static,
1051 Value: 'static,
1052 {
1053 let getter = self.getter;
1054
1055 OptionalKeyPath {
1056 getter: move |arc: &Arc<Root>| {
1057 getter(arc.as_ref())
1058 },
1059 _phantom: PhantomData,
1060 }
1061 }
1062
1063 pub fn for_rc_root(self) -> OptionalKeyPath<Rc<Root>, Value, impl for<'r> Fn(&'r Rc<Root>) -> Option<&'r Value> + 'static>
1065 where
1066 Value: Sized,
1067 F: 'static,
1068 Root: 'static,
1069 Value: 'static,
1070 {
1071 let getter = self.getter;
1072
1073 OptionalKeyPath {
1074 getter: move |rc: &Rc<Root>| {
1075 getter(rc.as_ref())
1076 },
1077 _phantom: PhantomData,
1078 }
1079 }
1080
1081 pub fn with_option<Callback, R>(&self, option: &Option<Root>, f: Callback) -> Option<R>
1083 where
1084 F: Clone,
1085 Callback: FnOnce(&Value) -> R,
1086 {
1087 option.as_ref().and_then(|root| {
1088 self.get(root).map(|value| f(value))
1089 })
1090 }
1091
1092 pub fn with_mutex<Callback, R>(&self, mutex: &Mutex<Root>, f: Callback) -> Option<R>
1094 where
1095 F: Clone,
1096 Callback: FnOnce(&Value) -> R,
1097 {
1098 mutex.lock().ok().and_then(|guard| {
1099 self.get(&*guard).map(|value| f(value))
1100 })
1101 }
1102
1103 pub fn with_rwlock<Callback, R>(&self, rwlock: &RwLock<Root>, f: Callback) -> Option<R>
1105 where
1106 F: Clone,
1107 Callback: FnOnce(&Value) -> R,
1108 {
1109 rwlock.read().ok().and_then(|guard| {
1110 self.get(&*guard).map(|value| f(value))
1111 })
1112 }
1113
1114 pub fn with_arc_rwlock<Callback, R>(&self, arc_rwlock: &Arc<RwLock<Root>>, f: Callback) -> Option<R>
1116 where
1117 F: Clone,
1118 Callback: FnOnce(&Value) -> R,
1119 {
1120 arc_rwlock.read().ok().and_then(|guard| {
1121 self.get(&*guard).map(|value| f(value))
1122 })
1123 }
1124
1125 pub fn with_arc_rwlock_direct<Callback, R>(&self, arc_rwlock: &Arc<RwLock<Root>>, f: Callback) -> Option<R>
1129 where
1130 Callback: FnOnce(&Value) -> R,
1131 {
1132 arc_rwlock.read().ok().and_then(|guard| {
1133 self.get(&*guard).map(|value| f(value))
1134 })
1135 }
1136
1137 pub fn with_arc_mutex<Callback, R>(&self, arc_mutex: &Arc<Mutex<Root>>, f: Callback) -> Option<R>
1139 where
1140 F: Clone,
1141 Callback: FnOnce(&Value) -> R,
1142 {
1143 arc_mutex.lock().ok().and_then(|guard| {
1144 self.get(&*guard).map(|value| f(value))
1145 })
1146 }
1147}
1148
1149
1150#[derive(Clone)]
1152pub struct WritableKeyPath<Root, Value, F>
1153where
1154 F: for<'r> Fn(&'r mut Root) -> &'r mut Value,
1155{
1156 getter: F,
1157 _phantom: PhantomData<(Root, Value)>,
1158}
1159
1160impl<Root, Value, F> fmt::Display for WritableKeyPath<Root, Value, F>
1161where
1162 F: for<'r> Fn(&'r mut Root) -> &'r mut Value,
1163{
1164 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1165 let root_name = std::any::type_name::<Root>();
1166 let value_name = std::any::type_name::<Value>();
1167 let root_short = root_name.split("::").last().unwrap_or(root_name);
1169 let value_short = value_name.split("::").last().unwrap_or(value_name);
1170 write!(f, "WritableKeyPath<{} -> {}>", root_short, value_short)
1171 }
1172}
1173
1174impl<Root, Value, F> fmt::Debug for WritableKeyPath<Root, Value, F>
1175where
1176 F: for<'r> Fn(&'r mut Root) -> &'r mut Value,
1177{
1178 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1179 fmt::Display::fmt(self, f)
1180 }
1181}
1182
1183impl<Root, Value, F> WritableKeyPath<Root, Value, F>
1184where
1185 F: for<'r> Fn(&'r mut Root) -> &'r mut Value,
1186{
1187 pub fn new(getter: F) -> Self {
1188 Self {
1189 getter,
1190 _phantom: PhantomData,
1191 }
1192 }
1193
1194 pub fn get_mut<'r>(&self, root: &'r mut Root) -> &'r mut Value {
1195 (self.getter)(root)
1196 }
1197
1198 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>
1201 where
1202 F: 'static,
1203 Root: 'static,
1204 Value: 'static,
1205 E: 'static,
1206 {
1207 let getter = self.getter;
1208
1209 WritableOptionalKeyPath {
1210 getter: move |result: &mut Result<Root, E>| {
1211 result.as_mut().ok().map(|root| getter(root))
1212 },
1213 _phantom: PhantomData,
1214 }
1215 }
1216
1217 pub fn for_box_root(self) -> WritableKeyPath<Box<Root>, Value, impl for<'r> Fn(&'r mut Box<Root>) -> &'r mut Value + 'static>
1219 where
1220 Value: Sized,
1221 F: 'static,
1222 Root: 'static,
1223 Value: 'static,
1224 {
1225 let getter = self.getter;
1226
1227 WritableKeyPath {
1228 getter: move |boxed: &mut Box<Root>| {
1229 getter(boxed.as_mut())
1230 },
1231 _phantom: PhantomData,
1232 }
1233 }
1234
1235 pub fn for_option(self) -> WritableOptionalKeyPath<Option<Root>, Value, impl for<'r> Fn(&'r mut Option<Root>) -> Option<&'r mut Value> + 'static>
1238 where
1239 F: 'static,
1240 Root: 'static,
1241 Value: 'static,
1242 {
1243 let getter = self.getter;
1244
1245 WritableOptionalKeyPath {
1246 getter: move |option: &mut Option<Root>| {
1247 option.as_mut().map(|root| getter(root))
1248 },
1249 _phantom: PhantomData,
1250 }
1251 }
1252
1253 pub fn to_optional(self) -> WritableOptionalKeyPath<Root, Value, impl for<'r> Fn(&'r mut Root) -> Option<&'r mut Value> + 'static>
1256 where
1257 F: 'static,
1258 {
1259 let getter = self.getter;
1260 WritableOptionalKeyPath::new(move |root: &mut Root| Some(getter(root)))
1261 }
1262
1263 pub fn for_box<Target>(self) -> WritableKeyPath<Root, Target, impl for<'r> Fn(&'r mut Root) -> &'r mut Target + 'static>
1266 where
1267 Value: std::ops::DerefMut<Target = Target>,
1268 F: 'static,
1269 Value: 'static,
1270 {
1271 let getter = self.getter;
1272
1273 WritableKeyPath {
1274 getter: move |root: &mut Root| {
1275 getter(root).deref_mut()
1276 },
1277 _phantom: PhantomData,
1278 }
1279 }
1280
1281 pub fn for_arc<Target>(self) -> WritableKeyPath<Root, Target, impl for<'r> Fn(&'r mut Root) -> &'r mut Target + 'static>
1284 where
1285 Value: std::ops::DerefMut<Target = Target>,
1286 F: 'static,
1287 Value: 'static,
1288 {
1289 let getter = self.getter;
1290
1291 WritableKeyPath {
1292 getter: move |root: &mut Root| {
1293 getter(root).deref_mut()
1294 },
1295 _phantom: PhantomData,
1296 }
1297 }
1298
1299 pub fn for_rc<Target>(self) -> WritableKeyPath<Root, Target, impl for<'r> Fn(&'r mut Root) -> &'r mut Target + 'static>
1302 where
1303 Value: std::ops::DerefMut<Target = Target>,
1304 F: 'static,
1305 Value: 'static,
1306 {
1307 let getter = self.getter;
1308
1309 WritableKeyPath {
1310 getter: move |root: &mut Root| {
1311 getter(root).deref_mut()
1312 },
1313 _phantom: PhantomData,
1314 }
1315 }
1316
1317 pub fn with_box_mut<Callback, R>(&self, boxed: &mut Box<Root>, f: Callback) -> R
1319 where
1320 F: Clone,
1321 Callback: FnOnce(&mut Value) -> R,
1322 {
1323 let value = self.get_mut(boxed);
1324 f(value)
1325 }
1326
1327 pub fn with_result_mut<Callback, R, E>(&self, result: &mut Result<Root, E>, f: Callback) -> Option<R>
1329 where
1330 F: Clone,
1331 Callback: FnOnce(&mut Value) -> R,
1332 {
1333 result.as_mut().ok().map(|root| {
1334 let value = self.get_mut(root);
1335 f(value)
1336 })
1337 }
1338
1339 pub fn with_option_mut<Callback, R>(&self, option: &mut Option<Root>, f: Callback) -> Option<R>
1341 where
1342 F: Clone,
1343 Callback: FnOnce(&mut Value) -> R,
1344 {
1345 option.as_mut().map(|root| {
1346 let value = self.get_mut(root);
1347 f(value)
1348 })
1349 }
1350
1351 pub fn with_refcell_mut<Callback, R>(&self, refcell: &RefCell<Root>, f: Callback) -> Option<R>
1353 where
1354 F: Clone,
1355 Callback: FnOnce(&mut Value) -> R,
1356 {
1357 refcell.try_borrow_mut().ok().map(|mut borrow| {
1358 let value = self.get_mut(&mut *borrow);
1359 f(value)
1360 })
1361 }
1362
1363 pub fn with_mutex_mut<Callback, R>(&self, mutex: &mut Mutex<Root>, f: Callback) -> Option<R>
1365 where
1366 F: Clone,
1367 Callback: FnOnce(&mut Value) -> R,
1368 {
1369 mutex.get_mut().ok().map(|root| {
1370 let value = self.get_mut(root);
1371 f(value)
1372 })
1373 }
1374
1375 pub fn with_rwlock_mut<Callback, R>(&self, rwlock: &mut RwLock<Root>, f: Callback) -> Option<R>
1377 where
1378 F: Clone,
1379 Callback: FnOnce(&mut Value) -> R,
1380 {
1381 rwlock.write().ok().map(|mut guard| {
1382 let value = self.get_mut(&mut *guard);
1383 f(value)
1384 })
1385 }
1386
1387 pub fn iter_mut<'r, T>(&self, root: &'r mut Root) -> Option<std::slice::IterMut<'r, T>>
1390 where
1391 Value: AsMut<[T]> + 'r,
1392 {
1393 let value_ref: &'r mut Value = self.get_mut(root);
1394 Some(value_ref.as_mut().iter_mut())
1395 }
1396
1397 pub fn extract_mut_from_slice<'r>(&self, slice: &'r mut [Root]) -> Vec<&'r mut Value> {
1400 slice.iter_mut().map(|item| self.get_mut(item)).collect()
1401 }
1402
1403 pub fn extract_mut_from_ref_slice<'r>(&self, slice: &'r mut [&'r mut Root]) -> Vec<&'r mut Value> {
1406 slice.iter_mut().map(|item| self.get_mut(*item)).collect()
1407 }
1408
1409 pub fn then<SubValue, G>(
1412 self,
1413 next: WritableKeyPath<Value, SubValue, G>,
1414 ) -> WritableKeyPath<Root, SubValue, impl for<'r> Fn(&'r mut Root) -> &'r mut SubValue>
1415 where
1416 G: for<'r> Fn(&'r mut Value) -> &'r mut SubValue,
1417 F: 'static,
1418 G: 'static,
1419 Value: 'static,
1420 {
1421 let first = self.getter;
1422 let second = next.getter;
1423
1424 WritableKeyPath::new(move |root: &mut Root| {
1425 let value = first(root);
1426 second(value)
1427 })
1428 }
1429
1430 pub fn then_optional<SubValue, G>(
1433 self,
1434 next: WritableOptionalKeyPath<Value, SubValue, G>,
1435 ) -> WritableOptionalKeyPath<Root, SubValue, impl for<'r> Fn(&'r mut Root) -> Option<&'r mut SubValue>>
1436 where
1437 G: for<'r> Fn(&'r mut Value) -> Option<&'r mut SubValue>,
1438 F: 'static,
1439 G: 'static,
1440 Value: 'static,
1441 {
1442 let first = self.getter;
1443 let second = next.getter;
1444
1445 WritableOptionalKeyPath::new(move |root: &mut Root| {
1446 let value = first(root);
1447 second(value)
1448 })
1449 }
1450}
1451
1452#[derive(Clone)]
1454pub struct WritableOptionalKeyPath<Root, Value, F>
1455where
1456 F: for<'r> Fn(&'r mut Root) -> Option<&'r mut Value>,
1457{
1458 getter: F,
1459 _phantom: PhantomData<(Root, Value)>,
1460}
1461
1462impl<Root, Value, F> fmt::Display for WritableOptionalKeyPath<Root, Value, F>
1463where
1464 F: for<'r> Fn(&'r mut Root) -> Option<&'r mut Value>,
1465{
1466 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1467 let root_name = std::any::type_name::<Root>();
1468 let value_name = std::any::type_name::<Value>();
1469 let root_short = root_name.split("::").last().unwrap_or(root_name);
1471 let value_short = value_name.split("::").last().unwrap_or(value_name);
1472 write!(f, "WritableOptionalKeyPath<{} -> Option<{}>>", root_short, value_short)
1473 }
1474}
1475
1476impl<Root, Value, F> fmt::Debug for WritableOptionalKeyPath<Root, Value, F>
1477where
1478 F: for<'r> Fn(&'r mut Root) -> Option<&'r mut Value>,
1479{
1480 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1481 let root_name = std::any::type_name::<Root>();
1483 let value_name = std::any::type_name::<Value>();
1484 let root_short = root_name.split("::").last().unwrap_or(root_name);
1485 let value_short = value_name.split("::").last().unwrap_or(value_name);
1486
1487 if f.alternate() {
1489 writeln!(f, "WritableOptionalKeyPath<{} -> Option<{}>>", root_short, value_short)?;
1490 writeln!(f, " âš Chain may break if any intermediate step returns None")?;
1491 writeln!(f, " 💡 Use trace_chain() to find where the chain breaks")
1492 } else {
1493 write!(f, "WritableOptionalKeyPath<{} -> Option<{}>>", root_short, value_short)
1494 }
1495 }
1496}
1497
1498impl<Root, Value, F> WritableOptionalKeyPath<Root, Value, F>
1499where
1500 F: for<'r> Fn(&'r mut Root) -> Option<&'r mut Value>,
1501{
1502 pub fn new(getter: F) -> Self {
1503 Self {
1504 getter,
1505 _phantom: PhantomData,
1506 }
1507 }
1508
1509 pub fn get_mut<'r>(&self, root: &'r mut Root) -> Option<&'r mut Value> {
1510 (self.getter)(root)
1511 }
1512
1513 pub fn trace_chain(&self, root: &mut Root) -> Result<(), String> {
1528 match self.get_mut(root) {
1529 Some(_) => Ok(()),
1530 None => {
1531 let root_name = std::any::type_name::<Root>();
1532 let value_name = std::any::type_name::<Value>();
1533 let root_short = root_name.split("::").last().unwrap_or(root_name);
1534 let value_short = value_name.split("::").last().unwrap_or(value_name);
1535 Err(format!("{} -> Option<{}> returned None (chain broken at this step)", root_short, value_short))
1536 }
1537 }
1538 }
1539
1540 pub fn for_option(self) -> WritableOptionalKeyPath<Option<Root>, Value, impl for<'r> Fn(&'r mut Option<Root>) -> Option<&'r mut Value> + 'static>
1543 where
1544 F: 'static,
1545 Root: 'static,
1546 Value: 'static,
1547 {
1548 let getter = self.getter;
1549
1550 WritableOptionalKeyPath {
1551 getter: move |option: &mut Option<Root>| {
1552 option.as_mut().and_then(|root| getter(root))
1553 },
1554 _phantom: PhantomData,
1555 }
1556 }
1557
1558 pub fn then<SubValue, G>(
1560 self,
1561 next: WritableOptionalKeyPath<Value, SubValue, G>,
1562 ) -> WritableOptionalKeyPath<Root, SubValue, impl for<'r> Fn(&'r mut Root) -> Option<&'r mut SubValue>>
1563 where
1564 G: for<'r> Fn(&'r mut Value) -> Option<&'r mut SubValue>,
1565 F: 'static,
1566 G: 'static,
1567 Value: 'static,
1568 {
1569 let first = self.getter;
1570 let second = next.getter;
1571
1572 WritableOptionalKeyPath::new(move |root: &mut Root| {
1573 first(root).and_then(|value| second(value))
1574 })
1575 }
1576
1577 pub fn for_box<Target>(self) -> WritableOptionalKeyPath<Root, Target, impl for<'r> Fn(&'r mut Root) -> Option<&'r mut Target> + 'static>
1580 where
1581 Value: std::ops::DerefMut<Target = Target>,
1582 F: 'static,
1583 Value: 'static,
1584 {
1585 let getter = self.getter;
1586
1587 WritableOptionalKeyPath {
1588 getter: move |root: &mut Root| {
1589 getter(root).map(|boxed| boxed.deref_mut())
1590 },
1591 _phantom: PhantomData,
1592 }
1593 }
1594
1595 pub fn for_arc<Target>(self) -> WritableOptionalKeyPath<Root, Target, impl for<'r> Fn(&'r mut Root) -> Option<&'r mut Target> + 'static>
1597 where
1598 Value: std::ops::DerefMut<Target = Target>,
1599 F: 'static,
1600 Value: 'static,
1601 {
1602 let getter = self.getter;
1603
1604 WritableOptionalKeyPath {
1605 getter: move |root: &mut Root| {
1606 getter(root).map(|arc| arc.deref_mut())
1607 },
1608 _phantom: PhantomData,
1609 }
1610 }
1611
1612 pub fn for_rc<Target>(self) -> WritableOptionalKeyPath<Root, Target, impl for<'r> Fn(&'r mut Root) -> Option<&'r mut Target> + 'static>
1614 where
1615 Value: std::ops::DerefMut<Target = Target>,
1616 F: 'static,
1617 Value: 'static,
1618 {
1619 let getter = self.getter;
1620
1621 WritableOptionalKeyPath {
1622 getter: move |root: &mut Root| {
1623 getter(root).map(|rc| rc.deref_mut())
1624 },
1625 _phantom: PhantomData,
1626 }
1627 }
1628
1629 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>
1632 where
1633 F: 'static,
1634 Root: 'static,
1635 Value: 'static,
1636 E: 'static,
1637 {
1638 let getter = self.getter;
1639
1640 WritableOptionalKeyPath {
1641 getter: move |result: &mut Result<Root, E>| {
1642 result.as_mut().ok().and_then(|root| getter(root))
1643 },
1644 _phantom: PhantomData,
1645 }
1646 }
1647
1648 pub fn for_box_root(self) -> WritableOptionalKeyPath<Box<Root>, Value, impl for<'r> Fn(&'r mut Box<Root>) -> Option<&'r mut Value> + 'static>
1650 where
1651 Value: Sized,
1652 F: 'static,
1653 Root: 'static,
1654 Value: 'static,
1655 {
1656 let getter = self.getter;
1657
1658 WritableOptionalKeyPath {
1659 getter: move |boxed: &mut Box<Root>| {
1660 getter(boxed.as_mut())
1661 },
1662 _phantom: PhantomData,
1663 }
1664 }
1665
1666 pub fn for_arc_root(self) -> WritableOptionalKeyPath<Arc<Root>, Value, impl for<'r> Fn(&'r mut Arc<Root>) -> Option<&'r mut Value> + 'static>
1668 where
1669 Value: Sized,
1670 F: 'static,
1671 Root: 'static,
1672 Value: 'static,
1673 {
1674 let getter = self.getter;
1675
1676 WritableOptionalKeyPath {
1677 getter: move |arc: &mut Arc<Root>| {
1678 None
1681 },
1682 _phantom: PhantomData,
1683 }
1684 }
1685
1686 pub fn for_rc_root(self) -> WritableOptionalKeyPath<Rc<Root>, Value, impl for<'r> Fn(&'r mut Rc<Root>) -> Option<&'r mut Value> + 'static>
1688 where
1689 Value: Sized,
1690 F: 'static,
1691 Root: 'static,
1692 Value: 'static,
1693 {
1694 let getter = self.getter;
1695
1696 WritableOptionalKeyPath {
1697 getter: move |rc: &mut Rc<Root>| {
1698 None
1701 },
1702 _phantom: PhantomData,
1703 }
1704 }
1705}
1706
1707impl WritableOptionalKeyPath<(), (), fn(&mut ()) -> Option<&mut ()>> {
1709 pub fn for_option_static<T>() -> WritableOptionalKeyPath<Option<T>, T, impl for<'r> Fn(&'r mut Option<T>) -> Option<&'r mut T>> {
1712 WritableOptionalKeyPath::new(|opt: &mut Option<T>| opt.as_mut())
1713 }
1714
1715 pub fn writable_enum<Enum, Variant, EmbedFn, ReadExtractFn, WriteExtractFn>(
1736 _embedder: EmbedFn,
1737 _read_extractor: ReadExtractFn,
1738 write_extractor: WriteExtractFn,
1739 ) -> WritableOptionalKeyPath<Enum, Variant, impl for<'r> Fn(&'r mut Enum) -> Option<&'r mut Variant> + 'static>
1740 where
1741 EmbedFn: Fn(Variant) -> Enum + 'static,
1742 ReadExtractFn: for<'r> Fn(&'r Enum) -> Option<&'r Variant> + 'static,
1743 WriteExtractFn: for<'r> Fn(&'r mut Enum) -> Option<&'r mut Variant> + 'static,
1744 {
1745 WritableOptionalKeyPath::new(write_extractor)
1746 }
1747}
1748
1749pub struct EnumKeyPath<Enum = (), Variant = (), ExtractFn = fn(&()) -> Option<&()>, EmbedFn = fn(()) -> ()>
1757where
1758 ExtractFn: for<'r> Fn(&'r Enum) -> Option<&'r Variant> + 'static,
1759 EmbedFn: Fn(Variant) -> Enum + 'static,
1760{
1761 extractor: OptionalKeyPath<Enum, Variant, ExtractFn>,
1762 embedder: EmbedFn,
1763}
1764
1765impl<Enum, Variant, ExtractFn, EmbedFn> EnumKeyPath<Enum, Variant, ExtractFn, EmbedFn>
1766where
1767 ExtractFn: for<'r> Fn(&'r Enum) -> Option<&'r Variant> + 'static,
1768 EmbedFn: Fn(Variant) -> Enum + 'static,
1769{
1770 pub fn new(
1772 extractor: ExtractFn,
1773 embedder: EmbedFn,
1774 ) -> Self {
1775 Self {
1776 extractor: OptionalKeyPath::new(extractor),
1777 embedder,
1778 }
1779 }
1780
1781 pub fn get<'r>(&self, enum_value: &'r Enum) -> Option<&'r Variant> {
1783 self.extractor.get(enum_value)
1784 }
1785
1786 pub fn embed(&self, value: Variant) -> Enum {
1788 (self.embedder)(value)
1789 }
1790
1791 pub fn as_optional(&self) -> &OptionalKeyPath<Enum, Variant, ExtractFn> {
1793 &self.extractor
1794 }
1795
1796 pub fn to_optional(self) -> OptionalKeyPath<Enum, Variant, ExtractFn> {
1798 self.extractor
1799 }
1800}
1801
1802impl EnumKeyPath {
1804 pub fn readable_enum<Enum, Variant, ExtractFn, EmbedFn>(
1807 embedder: EmbedFn,
1808 extractor: ExtractFn,
1809 ) -> EnumKeyPath<Enum, Variant, ExtractFn, EmbedFn>
1810 where
1811 ExtractFn: for<'r> Fn(&'r Enum) -> Option<&'r Variant> + 'static,
1812 EmbedFn: Fn(Variant) -> Enum + 'static,
1813 {
1814 EnumKeyPath::new(extractor, embedder)
1815 }
1816
1817 pub fn for_variant<Enum, Variant, ExtractFn>(
1819 extractor: ExtractFn
1820 ) -> OptionalKeyPath<Enum, Variant, impl for<'r> Fn(&'r Enum) -> Option<&'r Variant>>
1821 where
1822 ExtractFn: Fn(&Enum) -> Option<&Variant>,
1823 {
1824 OptionalKeyPath::new(extractor)
1825 }
1826
1827 pub fn for_match<Enum, Output, MatchFn>(
1829 matcher: MatchFn
1830 ) -> KeyPath<Enum, Output, impl for<'r> Fn(&'r Enum) -> &'r Output>
1831 where
1832 MatchFn: Fn(&Enum) -> &Output,
1833 {
1834 KeyPath::new(matcher)
1835 }
1836
1837 pub fn for_ok<T, E>() -> OptionalKeyPath<Result<T, E>, T, impl for<'r> Fn(&'r Result<T, E>) -> Option<&'r T>> {
1839 OptionalKeyPath::new(|result: &Result<T, E>| result.as_ref().ok())
1840 }
1841
1842 pub fn for_err<T, E>() -> OptionalKeyPath<Result<T, E>, E, impl for<'r> Fn(&'r Result<T, E>) -> Option<&'r E>> {
1844 OptionalKeyPath::new(|result: &Result<T, E>| result.as_ref().err())
1845 }
1846
1847 pub fn for_some<T>() -> OptionalKeyPath<Option<T>, T, impl for<'r> Fn(&'r Option<T>) -> Option<&'r T>> {
1849 OptionalKeyPath::new(|opt: &Option<T>| opt.as_ref())
1850 }
1851
1852 pub fn for_option<T>() -> OptionalKeyPath<Option<T>, T, impl for<'r> Fn(&'r Option<T>) -> Option<&'r T>> {
1854 OptionalKeyPath::new(|opt: &Option<T>| opt.as_ref())
1855 }
1856
1857 pub fn for_box<T>() -> KeyPath<Box<T>, T, impl for<'r> Fn(&'r Box<T>) -> &'r T> {
1859 KeyPath::new(|b: &Box<T>| b.as_ref())
1860 }
1861
1862 pub fn for_arc<T>() -> KeyPath<Arc<T>, T, impl for<'r> Fn(&'r Arc<T>) -> &'r T> {
1864 KeyPath::new(|arc: &Arc<T>| arc.as_ref())
1865 }
1866
1867 pub fn for_rc<T>() -> KeyPath<std::rc::Rc<T>, T, impl for<'r> Fn(&'r std::rc::Rc<T>) -> &'r T> {
1869 KeyPath::new(|rc: &std::rc::Rc<T>| rc.as_ref())
1870 }
1871
1872 pub fn for_box_mut<T>() -> WritableKeyPath<Box<T>, T, impl for<'r> Fn(&'r mut Box<T>) -> &'r mut T> {
1874 WritableKeyPath::new(|b: &mut Box<T>| b.as_mut())
1875 }
1876
1877 }
1881
1882pub fn variant_of<Enum, Variant, F>(extractor: F) -> OptionalKeyPath<Enum, Variant, F>
1884where
1885 F: for<'r> Fn(&'r Enum) -> Option<&'r Variant>,
1886{
1887 OptionalKeyPath::new(extractor)
1888}
1889
1890#[derive(Clone)]
1906pub struct PartialKeyPath<Root> {
1907 getter: Rc<dyn for<'r> Fn(&'r Root) -> &'r dyn Any>,
1908 value_type_id: TypeId,
1909 _phantom: PhantomData<Root>,
1910}
1911
1912impl<Root> PartialKeyPath<Root> {
1913 pub fn new<Value>(keypath: KeyPath<Root, Value, impl for<'r> Fn(&'r Root) -> &'r Value + 'static>) -> Self
1914 where
1915 Value: Any + 'static,
1916 Root: 'static,
1917 {
1918 let value_type_id = TypeId::of::<Value>();
1919 let getter = Rc::new(keypath.getter);
1920
1921 Self {
1922 getter: Rc::new(move |root: &Root| {
1923 let value: &Value = getter(root);
1924 value as &dyn Any
1925 }),
1926 value_type_id,
1927 _phantom: PhantomData,
1928 }
1929 }
1930
1931 pub fn from<Value>(keypath: KeyPath<Root, Value, impl for<'r> Fn(&'r Root) -> &'r Value + 'static>) -> Self
1934 where
1935 Value: Any + 'static,
1936 Root: 'static,
1937 {
1938 Self::new(keypath)
1939 }
1940
1941 pub fn get<'r>(&self, root: &'r Root) -> &'r dyn Any {
1942 (self.getter)(root)
1943 }
1944
1945 pub fn value_type_id(&self) -> TypeId {
1947 self.value_type_id
1948 }
1949
1950 pub fn get_as<'a, Value: Any>(&self, root: &'a Root) -> Option<&'a Value> {
1952 if self.value_type_id == TypeId::of::<Value>() {
1953 self.get(root).downcast_ref::<Value>()
1954 } else {
1955 None
1956 }
1957 }
1958
1959 pub fn kind_name(&self) -> String {
1962 format!("{:?}", self.value_type_id)
1963 }
1964
1965 pub fn for_arc(&self) -> PartialOptionalKeyPath<Arc<Root>>
1967 where
1968 Root: 'static,
1969 {
1970 let getter = self.getter.clone();
1971 let value_type_id = self.value_type_id;
1972
1973 PartialOptionalKeyPath {
1974 getter: Rc::new(move |arc: &Arc<Root>| {
1975 Some(getter(arc.as_ref()))
1976 }),
1977 value_type_id,
1978 _phantom: PhantomData,
1979 }
1980 }
1981
1982 pub fn for_box(&self) -> PartialOptionalKeyPath<Box<Root>>
1984 where
1985 Root: 'static,
1986 {
1987 let getter = self.getter.clone();
1988 let value_type_id = self.value_type_id;
1989
1990 PartialOptionalKeyPath {
1991 getter: Rc::new(move |boxed: &Box<Root>| {
1992 Some(getter(boxed.as_ref()))
1993 }),
1994 value_type_id,
1995 _phantom: PhantomData,
1996 }
1997 }
1998
1999 pub fn for_rc(&self) -> PartialOptionalKeyPath<Rc<Root>>
2001 where
2002 Root: 'static,
2003 {
2004 let getter = self.getter.clone();
2005 let value_type_id = self.value_type_id;
2006
2007 PartialOptionalKeyPath {
2008 getter: Rc::new(move |rc: &Rc<Root>| {
2009 Some(getter(rc.as_ref()))
2010 }),
2011 value_type_id,
2012 _phantom: PhantomData,
2013 }
2014 }
2015
2016 pub fn for_option(&self) -> PartialOptionalKeyPath<Option<Root>>
2018 where
2019 Root: 'static,
2020 {
2021 let getter = self.getter.clone();
2022 let value_type_id = self.value_type_id;
2023
2024 PartialOptionalKeyPath {
2025 getter: Rc::new(move |opt: &Option<Root>| {
2026 opt.as_ref().map(|root| getter(root))
2027 }),
2028 value_type_id,
2029 _phantom: PhantomData,
2030 }
2031 }
2032
2033 pub fn for_result<E>(&self) -> PartialOptionalKeyPath<Result<Root, E>>
2035 where
2036 Root: 'static,
2037 E: 'static,
2038 {
2039 let getter = self.getter.clone();
2040 let value_type_id = self.value_type_id;
2041
2042 PartialOptionalKeyPath {
2043 getter: Rc::new(move |result: &Result<Root, E>| {
2044 result.as_ref().ok().map(|root| getter(root))
2045 }),
2046 value_type_id,
2047 _phantom: PhantomData,
2048 }
2049 }
2050
2051 pub fn for_arc_rwlock(&self) -> PartialOptionalKeyPath<Arc<RwLock<Root>>>
2055 where
2056 Root: Clone + 'static,
2057 {
2058 PartialOptionalKeyPath {
2061 getter: Rc::new(move |_arc_rwlock: &Arc<RwLock<Root>>| {
2062 None
2065 }),
2066 value_type_id: self.value_type_id,
2067 _phantom: PhantomData,
2068 }
2069 }
2070
2071 pub fn for_arc_mutex(&self) -> PartialOptionalKeyPath<Arc<Mutex<Root>>>
2075 where
2076 Root: Clone + 'static,
2077 {
2078 PartialOptionalKeyPath {
2081 getter: Rc::new(move |_arc_mutex: &Arc<Mutex<Root>>| {
2082 None
2085 }),
2086 value_type_id: self.value_type_id,
2087 _phantom: PhantomData,
2088 }
2089 }
2090}
2091
2092#[derive(Clone)]
2099pub struct PartialOptionalKeyPath<Root> {
2100 getter: Rc<dyn for<'r> Fn(&'r Root) -> Option<&'r dyn Any>>,
2101 value_type_id: TypeId,
2102 _phantom: PhantomData<Root>,
2103}
2104
2105impl<Root> PartialOptionalKeyPath<Root> {
2106 pub fn new<Value>(keypath: OptionalKeyPath<Root, Value, impl for<'r> Fn(&'r Root) -> Option<&'r Value> + 'static>) -> Self
2107 where
2108 Value: Any + 'static,
2109 Root: 'static,
2110 {
2111 let value_type_id = TypeId::of::<Value>();
2112 let getter = Rc::new(keypath.getter);
2113
2114 Self {
2115 getter: Rc::new(move |root: &Root| {
2116 getter(root).map(|value: &Value| value as &dyn Any)
2117 }),
2118 value_type_id,
2119 _phantom: PhantomData,
2120 }
2121 }
2122
2123 pub fn get<'r>(&self, root: &'r Root) -> Option<&'r dyn Any> {
2124 (self.getter)(root)
2125 }
2126
2127 pub fn value_type_id(&self) -> TypeId {
2129 self.value_type_id
2130 }
2131
2132 pub fn get_as<'a, Value: Any>(&self, root: &'a Root) -> Option<Option<&'a Value>> {
2134 if self.value_type_id == TypeId::of::<Value>() {
2135 self.get(root).map(|any| any.downcast_ref::<Value>())
2136 } else {
2137 None
2138 }
2139 }
2140
2141 pub fn then<MidValue>(
2145 self,
2146 next: PartialOptionalKeyPath<MidValue>,
2147 ) -> PartialOptionalKeyPath<Root>
2148 where
2149 MidValue: Any + 'static,
2150 Root: 'static,
2151 {
2152 let first = self.getter;
2153 let second = next.getter;
2154 let value_type_id = next.value_type_id;
2155
2156 PartialOptionalKeyPath {
2157 getter: Rc::new(move |root: &Root| {
2158 first(root).and_then(|any| {
2159 if let Some(mid_value) = any.downcast_ref::<MidValue>() {
2160 second(mid_value)
2161 } else {
2162 None
2163 }
2164 })
2165 }),
2166 value_type_id,
2167 _phantom: PhantomData,
2168 }
2169 }
2170}
2171
2172#[derive(Clone)]
2178pub struct PartialWritableKeyPath<Root> {
2179 getter: Rc<dyn for<'r> Fn(&'r mut Root) -> &'r mut dyn Any>,
2180 value_type_id: TypeId,
2181 _phantom: PhantomData<Root>,
2182}
2183
2184impl<Root> PartialWritableKeyPath<Root> {
2185 pub fn new<Value>(keypath: WritableKeyPath<Root, Value, impl for<'r> Fn(&'r mut Root) -> &'r mut Value + 'static>) -> Self
2186 where
2187 Value: Any + 'static,
2188 Root: 'static,
2189 {
2190 let value_type_id = TypeId::of::<Value>();
2191 let getter = Rc::new(keypath.getter);
2192
2193 Self {
2194 getter: Rc::new(move |root: &mut Root| {
2195 let value: &mut Value = getter(root);
2196 value as &mut dyn Any
2197 }),
2198 value_type_id,
2199 _phantom: PhantomData,
2200 }
2201 }
2202
2203 pub fn from<Value>(keypath: WritableKeyPath<Root, Value, impl for<'r> Fn(&'r mut Root) -> &'r mut Value + 'static>) -> Self
2206 where
2207 Value: Any + 'static,
2208 Root: 'static,
2209 {
2210 Self::new(keypath)
2211 }
2212
2213 pub fn get_mut<'r>(&self, root: &'r mut Root) -> &'r mut dyn Any {
2214 (self.getter)(root)
2215 }
2216
2217 pub fn value_type_id(&self) -> TypeId {
2219 self.value_type_id
2220 }
2221
2222 pub fn get_mut_as<'a, Value: Any>(&self, root: &'a mut Root) -> Option<&'a mut Value> {
2224 if self.value_type_id == TypeId::of::<Value>() {
2225 self.get_mut(root).downcast_mut::<Value>()
2226 } else {
2227 None
2228 }
2229 }
2230}
2231
2232#[derive(Clone)]
2238pub struct PartialWritableOptionalKeyPath<Root> {
2239 getter: Rc<dyn for<'r> Fn(&'r mut Root) -> Option<&'r mut dyn Any>>,
2240 value_type_id: TypeId,
2241 _phantom: PhantomData<Root>,
2242}
2243
2244impl<Root> PartialWritableOptionalKeyPath<Root> {
2245 pub fn new<Value>(keypath: WritableOptionalKeyPath<Root, Value, impl for<'r> Fn(&'r mut Root) -> Option<&'r mut Value> + 'static>) -> Self
2246 where
2247 Value: Any + 'static,
2248 Root: 'static,
2249 {
2250 let value_type_id = TypeId::of::<Value>();
2251 let getter = Rc::new(keypath.getter);
2252
2253 Self {
2254 getter: Rc::new(move |root: &mut Root| {
2255 getter(root).map(|value: &mut Value| value as &mut dyn Any)
2256 }),
2257 value_type_id,
2258 _phantom: PhantomData,
2259 }
2260 }
2261
2262 pub fn get_mut<'r>(&self, root: &'r mut Root) -> Option<&'r mut dyn Any> {
2263 (self.getter)(root)
2264 }
2265
2266 pub fn value_type_id(&self) -> TypeId {
2268 self.value_type_id
2269 }
2270
2271 pub fn get_mut_as<'a, Value: Any>(&self, root: &'a mut Root) -> Option<Option<&'a mut Value>> {
2273 if self.value_type_id == TypeId::of::<Value>() {
2274 self.get_mut(root).map(|any| any.downcast_mut::<Value>())
2275 } else {
2276 None
2277 }
2278 }
2279}
2280
2281#[derive(Clone)]
2295pub struct AnyKeyPath {
2296 getter: Rc<dyn for<'r> Fn(&'r dyn Any) -> Option<&'r dyn Any>>,
2297 root_type_id: TypeId,
2298 value_type_id: TypeId,
2299}
2300
2301impl AnyKeyPath {
2302 pub fn new<Root, Value>(keypath: OptionalKeyPath<Root, Value, impl for<'r> Fn(&'r Root) -> Option<&'r Value> + 'static>) -> Self
2303 where
2304 Root: Any + 'static,
2305 Value: Any + 'static,
2306 {
2307 let root_type_id = TypeId::of::<Root>();
2308 let value_type_id = TypeId::of::<Value>();
2309 let getter = keypath.getter;
2310
2311 Self {
2312 getter: Rc::new(move |any: &dyn Any| {
2313 if let Some(root) = any.downcast_ref::<Root>() {
2314 getter(root).map(|value: &Value| value as &dyn Any)
2315 } else {
2316 None
2317 }
2318 }),
2319 root_type_id,
2320 value_type_id,
2321 }
2322 }
2323
2324 pub fn from<Root, Value>(keypath: OptionalKeyPath<Root, Value, impl for<'r> Fn(&'r Root) -> Option<&'r Value> + 'static>) -> Self
2327 where
2328 Root: Any + 'static,
2329 Value: Any + 'static,
2330 {
2331 Self::new(keypath)
2332 }
2333
2334 pub fn get<'r>(&self, root: &'r dyn Any) -> Option<&'r dyn Any> {
2335 (self.getter)(root)
2336 }
2337
2338 pub fn root_type_id(&self) -> TypeId {
2340 self.root_type_id
2341 }
2342
2343 pub fn value_type_id(&self) -> TypeId {
2345 self.value_type_id
2346 }
2347
2348 pub fn get_as<'a, Root: Any, Value: Any>(&self, root: &'a Root) -> Option<Option<&'a Value>> {
2350 if self.root_type_id == TypeId::of::<Root>() && self.value_type_id == TypeId::of::<Value>() {
2351 self.get(root as &dyn Any).map(|any| any.downcast_ref::<Value>())
2352 } else {
2353 None
2354 }
2355 }
2356
2357 pub fn kind_name(&self) -> String {
2360 format!("{:?}", self.value_type_id)
2361 }
2362
2363 pub fn for_arc<Root>(&self) -> AnyKeyPath
2365 where
2366 Root: Any + 'static,
2367 {
2368 let root_type_id = self.root_type_id;
2369 let value_type_id = self.value_type_id;
2370 let getter = self.getter.clone();
2371
2372 AnyKeyPath {
2373 getter: Rc::new(move |any: &dyn Any| {
2374 if let Some(arc) = any.downcast_ref::<Arc<Root>>() {
2375 getter(arc.as_ref() as &dyn Any)
2376 } else {
2377 None
2378 }
2379 }),
2380 root_type_id: TypeId::of::<Arc<Root>>(),
2381 value_type_id,
2382 }
2383 }
2384
2385 pub fn for_box<Root>(&self) -> AnyKeyPath
2387 where
2388 Root: Any + 'static,
2389 {
2390 let root_type_id = self.root_type_id;
2391 let value_type_id = self.value_type_id;
2392 let getter = self.getter.clone();
2393
2394 AnyKeyPath {
2395 getter: Rc::new(move |any: &dyn Any| {
2396 if let Some(boxed) = any.downcast_ref::<Box<Root>>() {
2397 getter(boxed.as_ref() as &dyn Any)
2398 } else {
2399 None
2400 }
2401 }),
2402 root_type_id: TypeId::of::<Box<Root>>(),
2403 value_type_id,
2404 }
2405 }
2406
2407 pub fn for_rc<Root>(&self) -> AnyKeyPath
2409 where
2410 Root: Any + 'static,
2411 {
2412 let root_type_id = self.root_type_id;
2413 let value_type_id = self.value_type_id;
2414 let getter = self.getter.clone();
2415
2416 AnyKeyPath {
2417 getter: Rc::new(move |any: &dyn Any| {
2418 if let Some(rc) = any.downcast_ref::<Rc<Root>>() {
2419 getter(rc.as_ref() as &dyn Any)
2420 } else {
2421 None
2422 }
2423 }),
2424 root_type_id: TypeId::of::<Rc<Root>>(),
2425 value_type_id,
2426 }
2427 }
2428
2429 pub fn for_option<Root>(&self) -> AnyKeyPath
2431 where
2432 Root: Any + 'static,
2433 {
2434 let root_type_id = self.root_type_id;
2435 let value_type_id = self.value_type_id;
2436 let getter = self.getter.clone();
2437
2438 AnyKeyPath {
2439 getter: Rc::new(move |any: &dyn Any| {
2440 if let Some(opt) = any.downcast_ref::<Option<Root>>() {
2441 opt.as_ref().and_then(|root| getter(root as &dyn Any))
2442 } else {
2443 None
2444 }
2445 }),
2446 root_type_id: TypeId::of::<Option<Root>>(),
2447 value_type_id,
2448 }
2449 }
2450
2451 pub fn for_result<Root, E>(&self) -> AnyKeyPath
2453 where
2454 Root: Any + 'static,
2455 E: Any + 'static,
2456 {
2457 let root_type_id = self.root_type_id;
2458 let value_type_id = self.value_type_id;
2459 let getter = self.getter.clone();
2460
2461 AnyKeyPath {
2462 getter: Rc::new(move |any: &dyn Any| {
2463 if let Some(result) = any.downcast_ref::<Result<Root, E>>() {
2464 result.as_ref().ok().and_then(|root| getter(root as &dyn Any))
2465 } else {
2466 None
2467 }
2468 }),
2469 root_type_id: TypeId::of::<Result<Root, E>>(),
2470 value_type_id,
2471 }
2472 }
2473
2474 pub fn for_arc_rwlock<Root>(&self) -> AnyKeyPath
2477 where
2478 Root: Any + Clone + 'static,
2479 {
2480 AnyKeyPath {
2483 getter: Rc::new(move |_any: &dyn Any| {
2484 None
2487 }),
2488 root_type_id: TypeId::of::<Arc<RwLock<Root>>>(),
2489 value_type_id: self.value_type_id,
2490 }
2491 }
2492
2493 pub fn for_arc_mutex<Root>(&self) -> AnyKeyPath
2496 where
2497 Root: Any + Clone + 'static,
2498 {
2499 AnyKeyPath {
2502 getter: Rc::new(move |_any: &dyn Any| {
2503 None
2506 }),
2507 root_type_id: TypeId::of::<Arc<Mutex<Root>>>(),
2508 value_type_id: self.value_type_id,
2509 }
2510 }
2511}
2512
2513#[derive(Clone)]
2515pub struct AnyWritableKeyPath {
2516 getter: Rc<dyn for<'r> Fn(&'r mut dyn Any) -> Option<&'r mut dyn Any>>,
2517 root_type_id: TypeId,
2518 value_type_id: TypeId,
2519}
2520
2521#[derive(Clone)]
2526pub struct FailableCombinedKeyPath<Root, Value, ReadFn, WriteFn, OwnedFn>
2527where
2528 ReadFn: for<'r> Fn(&'r Root) -> Option<&'r Value> + 'static,
2529 WriteFn: for<'r> Fn(&'r mut Root) -> Option<&'r mut Value> + 'static,
2530 OwnedFn: Fn(Root) -> Option<Value> + 'static,
2531{
2532 readable: ReadFn,
2533 writable: WriteFn,
2534 owned: OwnedFn,
2535 _phantom: PhantomData<(Root, Value)>,
2536}
2537
2538impl<Root, Value, ReadFn, WriteFn, OwnedFn> FailableCombinedKeyPath<Root, Value, ReadFn, WriteFn, OwnedFn>
2539where
2540 ReadFn: for<'r> Fn(&'r Root) -> Option<&'r Value> + 'static,
2541 WriteFn: for<'r> Fn(&'r mut Root) -> Option<&'r mut Value> + 'static,
2542 OwnedFn: Fn(Root) -> Option<Value> + 'static,
2543{
2544 pub fn new(readable: ReadFn, writable: WriteFn, owned: OwnedFn) -> Self {
2546 Self {
2547 readable,
2548 writable,
2549 owned,
2550 _phantom: PhantomData,
2551 }
2552 }
2553
2554 pub fn get<'r>(&self, root: &'r Root) -> Option<&'r Value> {
2556 (self.readable)(root)
2557 }
2558
2559 pub fn get_mut<'r>(&self, root: &'r mut Root) -> Option<&'r mut Value> {
2561 (self.writable)(root)
2562 }
2563
2564 pub fn get_failable_owned(&self, root: Root) -> Option<Value> {
2566 (self.owned)(root)
2567 }
2568
2569 pub fn to_optional(self) -> OptionalKeyPath<Root, Value, ReadFn> {
2571 OptionalKeyPath::new(self.readable)
2572 }
2573
2574 pub fn to_writable_optional(self) -> WritableOptionalKeyPath<Root, Value, WriteFn> {
2576 WritableOptionalKeyPath::new(self.writable)
2577 }
2578
2579 pub fn then<SubValue, SubReadFn, SubWriteFn, SubOwnedFn>(
2582 self,
2583 next: FailableCombinedKeyPath<Value, SubValue, SubReadFn, SubWriteFn, SubOwnedFn>,
2584 ) -> 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>
2585 where
2586 SubReadFn: for<'r> Fn(&'r Value) -> Option<&'r SubValue> + 'static,
2587 SubWriteFn: for<'r> Fn(&'r mut Value) -> Option<&'r mut SubValue> + 'static,
2588 SubOwnedFn: Fn(Value) -> Option<SubValue> + 'static,
2589 ReadFn: 'static,
2590 WriteFn: 'static,
2591 OwnedFn: 'static,
2592 Value: 'static,
2593 Root: 'static,
2594 SubValue: 'static,
2595 {
2596 let first_read = self.readable;
2597 let first_write = self.writable;
2598 let first_owned = self.owned;
2599 let second_read = next.readable;
2600 let second_write = next.writable;
2601 let second_owned = next.owned;
2602
2603 FailableCombinedKeyPath::new(
2604 move |root: &Root| {
2605 first_read(root).and_then(|value| second_read(value))
2606 },
2607 move |root: &mut Root| {
2608 first_write(root).and_then(|value| second_write(value))
2609 },
2610 move |root: Root| {
2611 first_owned(root).and_then(|value| second_owned(value))
2612 },
2613 )
2614 }
2615
2616 pub fn then_optional<SubValue, SubReadFn>(
2620 self,
2621 next: OptionalKeyPath<Value, SubValue, SubReadFn>,
2622 ) -> 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>
2623 where
2624 SubReadFn: for<'r> Fn(&'r Value) -> Option<&'r SubValue> + 'static,
2625 ReadFn: 'static,
2626 WriteFn: 'static,
2627 OwnedFn: 'static,
2628 Value: 'static,
2629 Root: 'static,
2630 SubValue: 'static,
2631 {
2632 let first_read = self.readable;
2633 let first_write = self.writable;
2634 let first_owned = self.owned;
2635 let second_read = next.getter;
2636
2637 FailableCombinedKeyPath::new(
2638 move |root: &Root| {
2639 first_read(root).and_then(|value| second_read(value))
2640 },
2641 move |_root: &mut Root| {
2642 None },
2644 move |root: Root| {
2645 first_owned(root).and_then(|value| {
2646 None
2648 })
2649 },
2650 )
2651 }
2652}
2653
2654impl FailableCombinedKeyPath<(), (), fn(&()) -> Option<&()>, fn(&mut ()) -> Option<&mut ()>, fn(()) -> Option<()>> {
2656 pub fn failable_combined<Root, Value, ReadFn, WriteFn, OwnedFn>(
2658 readable: ReadFn,
2659 writable: WriteFn,
2660 owned: OwnedFn,
2661 ) -> FailableCombinedKeyPath<Root, Value, ReadFn, WriteFn, OwnedFn>
2662 where
2663 ReadFn: for<'r> Fn(&'r Root) -> Option<&'r Value> + 'static,
2664 WriteFn: for<'r> Fn(&'r mut Root) -> Option<&'r mut Value> + 'static,
2665 OwnedFn: Fn(Root) -> Option<Value> + 'static,
2666 {
2667 FailableCombinedKeyPath::new(readable, writable, owned)
2668 }
2669}
2670
2671impl AnyWritableKeyPath {
2672 pub fn new<Root, Value>(keypath: WritableOptionalKeyPath<Root, Value, impl for<'r> Fn(&'r mut Root) -> Option<&'r mut Value> + 'static>) -> Self
2673 where
2674 Root: Any + 'static,
2675 Value: Any + 'static,
2676 {
2677 let root_type_id = TypeId::of::<Root>();
2678 let value_type_id = TypeId::of::<Value>();
2679 let getter = keypath.getter;
2680
2681 Self {
2682 getter: Rc::new(move |any: &mut dyn Any| {
2683 if let Some(root) = any.downcast_mut::<Root>() {
2684 getter(root).map(|value: &mut Value| value as &mut dyn Any)
2685 } else {
2686 None
2687 }
2688 }),
2689 root_type_id,
2690 value_type_id,
2691 }
2692 }
2693
2694 pub fn get_mut<'r>(&self, root: &'r mut dyn Any) -> Option<&'r mut dyn Any> {
2695 (self.getter)(root)
2696 }
2697
2698 pub fn root_type_id(&self) -> TypeId {
2700 self.root_type_id
2701 }
2702
2703 pub fn value_type_id(&self) -> TypeId {
2705 self.value_type_id
2706 }
2707
2708 pub fn get_mut_as<'a, Root: Any, Value: Any>(&self, root: &'a mut Root) -> Option<Option<&'a mut Value>> {
2710 if self.root_type_id == TypeId::of::<Root>() && self.value_type_id == TypeId::of::<Value>() {
2711 self.get_mut(root as &mut dyn Any).map(|any| any.downcast_mut::<Value>())
2712 } else {
2713 None
2714 }
2715 }
2716}
2717
2718impl<Root, Value, F> KeyPath<Root, Value, F>
2720where
2721 F: for<'r> Fn(&'r Root) -> &'r Value + 'static,
2722 Root: 'static,
2723 Value: Any + 'static,
2724{
2725 pub fn to_partial(self) -> PartialKeyPath<Root> {
2727 PartialKeyPath::new(self)
2728 }
2729
2730 pub fn to(self) -> PartialKeyPath<Root> {
2732 self.to_partial()
2733 }
2734}
2735
2736impl<Root, Value, F> OptionalKeyPath<Root, Value, F>
2737where
2738 F: for<'r> Fn(&'r Root) -> Option<&'r Value> + 'static,
2739 Root: Any + 'static,
2740 Value: Any + 'static,
2741{
2742 pub fn to_partial(self) -> PartialOptionalKeyPath<Root> {
2744 PartialOptionalKeyPath::new(self)
2745 }
2746
2747 pub fn to_any(self) -> AnyKeyPath {
2749 AnyKeyPath::new(self)
2750 }
2751
2752 pub fn to(self) -> PartialOptionalKeyPath<Root> {
2754 self.to_partial()
2755 }
2756}
2757
2758impl<Root, Value, F> WritableKeyPath<Root, Value, F>
2759where
2760 F: for<'r> Fn(&'r mut Root) -> &'r mut Value + 'static,
2761 Root: 'static,
2762 Value: Any + 'static,
2763{
2764 pub fn to_partial(self) -> PartialWritableKeyPath<Root> {
2766 PartialWritableKeyPath::new(self)
2767 }
2768
2769 pub fn to(self) -> PartialWritableKeyPath<Root> {
2771 self.to_partial()
2772 }
2773}
2774
2775impl<Root, Value, F> WritableOptionalKeyPath<Root, Value, F>
2776where
2777 F: for<'r> Fn(&'r mut Root) -> Option<&'r mut Value> + 'static,
2778 Root: Any + 'static,
2779 Value: Any + 'static,
2780{
2781 pub fn to_partial(self) -> PartialWritableOptionalKeyPath<Root> {
2783 PartialWritableOptionalKeyPath::new(self)
2784 }
2785
2786 pub fn to_any(self) -> AnyWritableKeyPath {
2788 AnyWritableKeyPath::new(self)
2789 }
2790
2791 pub fn to(self) -> PartialWritableOptionalKeyPath<Root> {
2793 self.to_partial()
2794 }
2795}
2796
2797#[cfg(test)]
2915mod tests {
2916 use super::*;
2917 use std::sync::atomic::{AtomicUsize, Ordering};
2918 use std::rc::Rc;
2919
2920 static ALLOC_COUNT: AtomicUsize = AtomicUsize::new(0);
2922 static DEALLOC_COUNT: AtomicUsize = AtomicUsize::new(0);
2923
2924 #[derive(Debug)]
2926 struct NoCloneType {
2927 id: usize,
2928 data: String,
2929 }
2930
2931 impl NoCloneType {
2932 fn new(data: String) -> Self {
2933 ALLOC_COUNT.fetch_add(1, Ordering::SeqCst);
2934 Self {
2935 id: ALLOC_COUNT.load(Ordering::SeqCst),
2936 data,
2937 }
2938 }
2939 }
2940
2941 impl Clone for NoCloneType {
2942 fn clone(&self) -> Self {
2943 eprintln!("[DEBUG] NoCloneType should not be cloned! ID: {}", self.id);
2944 unreachable!("NoCloneType should not be cloned! ID: {}", self.id);
2945 }
2946 }
2947
2948 impl Drop for NoCloneType {
2949 fn drop(&mut self) {
2950 DEALLOC_COUNT.fetch_add(1, Ordering::SeqCst);
2951 }
2952 }
2953
2954 fn reset_memory_counters() {
2956 ALLOC_COUNT.store(0, Ordering::SeqCst);
2957 DEALLOC_COUNT.store(0, Ordering::SeqCst);
2958 }
2959
2960 fn get_alloc_count() -> usize {
2961 ALLOC_COUNT.load(Ordering::SeqCst)
2962 }
2963
2964 fn get_dealloc_count() -> usize {
2965 DEALLOC_COUNT.load(Ordering::SeqCst)
2966 }
2967
2968#[derive(Debug)]
2970struct User {
2971 name: String,
2972 metadata: Option<Box<UserMetadata>>,
2973 friends: Vec<Arc<User>>,
2974}
2975
2976#[derive(Debug)]
2977struct UserMetadata {
2978 created_at: String,
2979}
2980
2981fn some_fn() {
2982 let akash = User {
2983 name: "Alice".to_string(),
2984 metadata: Some(Box::new(UserMetadata {
2985 created_at: "2024-01-01".to_string(),
2986 })),
2987 friends: vec![
2988 Arc::new(User {
2989 name: "Bob".to_string(),
2990 metadata: None,
2991 friends: vec![],
2992 }),
2993 ],
2994 };
2995
2996 let name_kp = KeyPath::new(|u: &User| &u.name);
2998 let metadata_kp = OptionalKeyPath::new(|u: &User| u.metadata.as_ref());
2999 let friends_kp = KeyPath::new(|u: &User| &u.friends);
3000
3001 println!("Name: {}", name_kp.get(&akash));
3003
3004 if let Some(metadata) = metadata_kp.get(&akash) {
3005 println!("Has metadata: {:?}", metadata);
3006 }
3007
3008 if let Some(first_friend) = akash.friends.get(0) {
3010 println!("First friend: {}", name_kp.get(first_friend));
3011 }
3012
3013 let created_at_kp = KeyPath::new(|m: &UserMetadata| &m.created_at);
3015
3016 if let Some(metadata) = akash.metadata.as_ref() {
3017 let boxed_metadata: &Box<UserMetadata> = metadata;
3019 let unwrapped = boxed_metadata.as_ref();
3020 println!("Created at: {:?}", created_at_kp.get(unwrapped));
3021 }
3022 }
3023
3024 #[test]
3025 fn test_name() {
3026 some_fn();
3027 }
3028
3029 #[test]
3030 fn test_no_cloning_on_keypath_operations() {
3031 reset_memory_counters();
3032
3033 let value = NoCloneType::new("test".to_string());
3035 let boxed = Box::new(value);
3036
3037 let kp = KeyPath::new(|b: &Box<NoCloneType>| b.as_ref());
3039
3040 let _ref = kp.get(&boxed);
3042
3043 let _kp_clone = kp.clone();
3045
3046 let _ref2 = _kp_clone.get(&boxed);
3048
3049 assert_eq!(get_alloc_count(), 1);
3051 }
3052
3053 #[test]
3054 fn test_no_cloning_on_optional_keypath_operations() {
3055 reset_memory_counters();
3056
3057 let value = NoCloneType::new("test".to_string());
3058 let opt = Some(Box::new(value));
3059
3060 let okp = OptionalKeyPath::new(|o: &Option<Box<NoCloneType>>| o.as_ref());
3062
3063 let _ref = okp.get(&opt);
3065
3066 let _okp_clone = okp.clone();
3068
3069 let chained = okp.then(OptionalKeyPath::new(|b: &Box<NoCloneType>| Some(b.as_ref())));
3071 let _ref2 = chained.get(&opt);
3072
3073 assert_eq!(get_alloc_count(), 1);
3074 }
3075
3076 #[test]
3077 fn test_memory_release() {
3078 reset_memory_counters();
3079
3080 {
3081 let value = NoCloneType::new("test".to_string());
3082 let boxed = Box::new(value);
3083 let kp = KeyPath::new(|b: &Box<NoCloneType>| b.as_ref());
3084
3085 let _ref = kp.get(&boxed);
3087
3088 }
3090
3091 assert_eq!(get_alloc_count(), 1);
3094 }
3097
3098 #[test]
3099 fn test_keypath_clone_does_not_clone_underlying_data() {
3100 reset_memory_counters();
3101
3102 let value = NoCloneType::new("data".to_string());
3103 let rc_value = Rc::new(value);
3104
3105 let kp = KeyPath::new(|r: &Rc<NoCloneType>| r.as_ref());
3107
3108 let kp1 = kp.clone();
3110 let kp2 = kp.clone();
3111 let kp3 = kp1.clone();
3112
3113 let _ref1 = kp.get(&rc_value);
3115 let _ref2 = kp1.get(&rc_value);
3116 let _ref3 = kp2.get(&rc_value);
3117 let _ref4 = kp3.get(&rc_value);
3118
3119 assert_eq!(get_alloc_count(), 1);
3121 }
3122
3123 #[test]
3124 fn test_optional_keypath_chaining_no_clone() {
3125 reset_memory_counters();
3126
3127 let value = NoCloneType::new("value1".to_string());
3128
3129 struct Container {
3130 inner: Option<Box<NoCloneType>>,
3131 }
3132
3133 let container = Container {
3134 inner: Some(Box::new(value)),
3135 };
3136
3137 let kp1 = OptionalKeyPath::new(|c: &Container| c.inner.as_ref());
3139 let kp2 = OptionalKeyPath::new(|b: &Box<NoCloneType>| Some(b.as_ref()));
3140
3141 let chained = kp1.then(kp2);
3143
3144 let _result = chained.get(&container);
3146
3147 assert_eq!(get_alloc_count(), 1);
3149 }
3150
3151 #[test]
3152 fn test_for_box_no_clone() {
3153 reset_memory_counters();
3154
3155 let value = NoCloneType::new("test".to_string());
3156 let boxed = Box::new(value);
3157 let opt_boxed = Some(boxed);
3158
3159 let kp = OptionalKeyPath::new(|o: &Option<Box<NoCloneType>>| o.as_ref());
3161 let unwrapped = kp.for_box();
3162
3163 let _ref = unwrapped.get(&opt_boxed);
3165
3166 assert_eq!(get_alloc_count(), 1);
3167 }
3168
3169 #[derive(Debug, PartialEq)]
3172 struct TestUser {
3173 name: String,
3174 age: u32,
3175 metadata: Option<String>,
3176 address: Option<TestAddress>,
3177 }
3178
3179 #[derive(Debug, PartialEq)]
3180 struct TestAddress {
3181 street: String,
3182 city: String,
3183 country: Option<TestCountry>,
3184 }
3185
3186 #[derive(Debug, PartialEq)]
3187 struct TestCountry {
3188 name: String,
3189 }
3190
3191 #[test]
3192 fn test_keypath_macro() {
3193 let user = TestUser {
3194 name: "Alice".to_string(),
3195 age: 30,
3196 metadata: None,
3197 address: None,
3198 };
3199
3200 let name_kp = keypath!(|u: &TestUser| &u.name);
3202 assert_eq!(name_kp.get(&user), "Alice");
3203
3204 let user_with_address = TestUser {
3206 name: "Bob".to_string(),
3207 age: 25,
3208 metadata: None,
3209 address: Some(TestAddress {
3210 street: "123 Main St".to_string(),
3211 city: "New York".to_string(),
3212 country: None,
3213 }),
3214 };
3215
3216 let street_kp = keypath!(|u: &TestUser| &u.address.as_ref().unwrap().street);
3217 assert_eq!(street_kp.get(&user_with_address), "123 Main St");
3218
3219 let user_with_country = TestUser {
3221 name: "Charlie".to_string(),
3222 age: 35,
3223 metadata: None,
3224 address: Some(TestAddress {
3225 street: "456 Oak Ave".to_string(),
3226 city: "London".to_string(),
3227 country: Some(TestCountry {
3228 name: "UK".to_string(),
3229 }),
3230 }),
3231 };
3232
3233 let country_name_kp = keypath!(|u: &TestUser| &u.address.as_ref().unwrap().country.as_ref().unwrap().name);
3234 assert_eq!(country_name_kp.get(&user_with_country), "UK");
3235
3236 let age_kp = keypath!(|u: &TestUser| &u.age);
3238 assert_eq!(age_kp.get(&user), &30);
3239 }
3240
3241 #[test]
3242 fn test_opt_keypath_macro() {
3243 let user = TestUser {
3244 name: "Alice".to_string(),
3245 age: 30,
3246 metadata: Some("admin".to_string()),
3247 address: None,
3248 };
3249
3250 let metadata_kp = opt_keypath!(|u: &TestUser| u.metadata.as_ref());
3252 assert_eq!(metadata_kp.get(&user), Some(&"admin".to_string()));
3253
3254 let user_no_metadata = TestUser {
3256 name: "Bob".to_string(),
3257 age: 25,
3258 metadata: None,
3259 address: None,
3260 };
3261 assert_eq!(metadata_kp.get(&user_no_metadata), None);
3262
3263 let user_with_address = TestUser {
3265 name: "Charlie".to_string(),
3266 age: 35,
3267 metadata: None,
3268 address: Some(TestAddress {
3269 street: "789 Pine Rd".to_string(),
3270 city: "Paris".to_string(),
3271 country: None,
3272 }),
3273 };
3274
3275 let street_kp = opt_keypath!(|u: &TestUser| u.address.as_ref().map(|a| &a.street));
3276 assert_eq!(street_kp.get(&user_with_address), Some(&"789 Pine Rd".to_string()));
3277
3278 let user_with_country = TestUser {
3280 name: "David".to_string(),
3281 age: 40,
3282 metadata: None,
3283 address: Some(TestAddress {
3284 street: "321 Elm St".to_string(),
3285 city: "Tokyo".to_string(),
3286 country: Some(TestCountry {
3287 name: "Japan".to_string(),
3288 }),
3289 }),
3290 };
3291
3292 let country_name_kp = opt_keypath!(|u: &TestUser| u.address.as_ref().and_then(|a| a.country.as_ref().map(|c| &c.name)));
3293 assert_eq!(country_name_kp.get(&user_with_country), Some(&"Japan".to_string()));
3294
3295 let metadata_kp2 = opt_keypath!(|u: &TestUser| u.metadata.as_ref());
3297 assert_eq!(metadata_kp2.get(&user), Some(&"admin".to_string()));
3298 }
3299
3300 #[test]
3301 fn test_writable_keypath_macro() {
3302 let mut user = TestUser {
3303 name: "Alice".to_string(),
3304 age: 30,
3305 metadata: None,
3306 address: None,
3307 };
3308
3309 let name_kp = writable_keypath!(|u: &mut TestUser| &mut u.name);
3311 *name_kp.get_mut(&mut user) = "Bob".to_string();
3312 assert_eq!(user.name, "Bob");
3313
3314 let mut user_with_address = TestUser {
3316 name: "Charlie".to_string(),
3317 age: 25,
3318 metadata: None,
3319 address: Some(TestAddress {
3320 street: "123 Main St".to_string(),
3321 city: "New York".to_string(),
3322 country: None,
3323 }),
3324 };
3325
3326 let street_kp = writable_keypath!(|u: &mut TestUser| &mut u.address.as_mut().unwrap().street);
3327 *street_kp.get_mut(&mut user_with_address) = "456 Oak Ave".to_string();
3328 assert_eq!(user_with_address.address.as_ref().unwrap().street, "456 Oak Ave");
3329
3330 let mut user_with_country = TestUser {
3332 name: "David".to_string(),
3333 age: 35,
3334 metadata: None,
3335 address: Some(TestAddress {
3336 street: "789 Pine Rd".to_string(),
3337 city: "London".to_string(),
3338 country: Some(TestCountry {
3339 name: "UK".to_string(),
3340 }),
3341 }),
3342 };
3343
3344 let country_name_kp = writable_keypath!(|u: &mut TestUser| &mut u.address.as_mut().unwrap().country.as_mut().unwrap().name);
3345 *country_name_kp.get_mut(&mut user_with_country) = "United Kingdom".to_string();
3346 assert_eq!(user_with_country.address.as_ref().unwrap().country.as_ref().unwrap().name, "United Kingdom");
3347
3348 let age_kp = writable_keypath!(|u: &mut TestUser| &mut u.age);
3350 *age_kp.get_mut(&mut user) = 31;
3351 assert_eq!(user.age, 31);
3352 }
3353
3354 #[test]
3355 fn test_writable_opt_keypath_macro() {
3356 let mut user = TestUser {
3357 name: "Alice".to_string(),
3358 age: 30,
3359 metadata: Some("user".to_string()),
3360 address: None,
3361 };
3362
3363 let metadata_kp = writable_opt_keypath!(|u: &mut TestUser| u.metadata.as_mut());
3365 if let Some(metadata) = metadata_kp.get_mut(&mut user) {
3366 *metadata = "admin".to_string();
3367 }
3368 assert_eq!(user.metadata, Some("admin".to_string()));
3369
3370 let mut user_no_metadata = TestUser {
3372 name: "Bob".to_string(),
3373 age: 25,
3374 metadata: None,
3375 address: None,
3376 };
3377 assert_eq!(metadata_kp.get_mut(&mut user_no_metadata), None);
3378
3379 let mut user_with_address = TestUser {
3381 name: "Charlie".to_string(),
3382 age: 35,
3383 metadata: None,
3384 address: Some(TestAddress {
3385 street: "123 Main St".to_string(),
3386 city: "New York".to_string(),
3387 country: None,
3388 }),
3389 };
3390
3391 let street_kp = writable_opt_keypath!(|u: &mut TestUser| u.address.as_mut().map(|a| &mut a.street));
3392 if let Some(street) = street_kp.get_mut(&mut user_with_address) {
3393 *street = "456 Oak Ave".to_string();
3394 }
3395 assert_eq!(user_with_address.address.as_ref().unwrap().street, "456 Oak Ave");
3396
3397 let mut user_with_country = TestUser {
3399 name: "David".to_string(),
3400 age: 40,
3401 metadata: None,
3402 address: Some(TestAddress {
3403 street: "789 Pine Rd".to_string(),
3404 city: "Tokyo".to_string(),
3405 country: Some(TestCountry {
3406 name: "Japan".to_string(),
3407 }),
3408 }),
3409 };
3410
3411 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)));
3412 if let Some(country_name) = country_name_kp.get_mut(&mut user_with_country) {
3413 *country_name = "Nippon".to_string();
3414 }
3415 assert_eq!(user_with_country.address.as_ref().unwrap().country.as_ref().unwrap().name, "Nippon");
3416
3417 let metadata_kp2 = writable_opt_keypath!(|u: &mut TestUser| u.metadata.as_mut());
3419 if let Some(metadata) = metadata_kp2.get_mut(&mut user) {
3420 *metadata = "super_admin".to_string();
3421 }
3422 assert_eq!(user.metadata, Some("super_admin".to_string()));
3423 }
3424}
3425
3426pub trait WithContainer<Root, Value> {
3432 fn with_arc<F, R>(&self, arc: &Arc<Root>, f: F) -> R
3434 where
3435 F: FnOnce(&Value) -> R;
3436
3437 fn with_box<F, R>(&self, boxed: &Box<Root>, f: F) -> R
3439 where
3440 F: FnOnce(&Value) -> R;
3441
3442 fn with_box_mut<F, R>(&self, boxed: &mut Box<Root>, f: F) -> R
3444 where
3445 F: FnOnce(&mut Value) -> R;
3446
3447 fn with_rc<F, R>(&self, rc: &Rc<Root>, f: F) -> R
3449 where
3450 F: FnOnce(&Value) -> R;
3451
3452 fn with_result<F, R, E>(&self, result: &Result<Root, E>, f: F) -> Option<R>
3454 where
3455 F: FnOnce(&Value) -> R;
3456
3457 fn with_result_mut<F, R, E>(&self, result: &mut Result<Root, E>, f: F) -> Option<R>
3459 where
3460 F: FnOnce(&mut Value) -> R;
3461
3462 fn with_option<F, R>(&self, option: &Option<Root>, f: F) -> Option<R>
3464 where
3465 F: FnOnce(&Value) -> R;
3466
3467 fn with_option_mut<F, R>(&self, option: &mut Option<Root>, f: F) -> Option<R>
3469 where
3470 F: FnOnce(&mut Value) -> R;
3471
3472 fn with_refcell<F, R>(&self, refcell: &RefCell<Root>, f: F) -> Option<R>
3474 where
3475 F: FnOnce(&Value) -> R;
3476
3477 fn with_refcell_mut<F, R>(&self, refcell: &RefCell<Root>, f: F) -> Option<R>
3479 where
3480 F: FnOnce(&mut Value) -> R;
3481
3482 #[cfg(feature = "tagged")]
3483 fn with_tagged<F, R, Tag>(&self, tagged: &Tagged<Root, Tag>, f: F) -> R
3485 where
3486 Tagged<Root, Tag>: std::ops::Deref<Target = Root>,
3487 F: FnOnce(&Value) -> R;
3488
3489 fn with_mutex<F, R>(&self, mutex: &Mutex<Root>, f: F) -> Option<R>
3491 where
3492 F: FnOnce(&Value) -> R;
3493
3494 fn with_mutex_mut<F, R>(&self, mutex: &mut Mutex<Root>, f: F) -> Option<R>
3496 where
3497 F: FnOnce(&mut Value) -> R;
3498
3499 fn with_rwlock<F, R>(&self, rwlock: &RwLock<Root>, f: F) -> Option<R>
3501 where
3502 F: FnOnce(&Value) -> R;
3503
3504 fn with_rwlock_mut<F, R>(&self, rwlock: &mut RwLock<Root>, f: F) -> Option<R>
3506 where
3507 F: FnOnce(&mut Value) -> R;
3508
3509 fn with_arc_rwlock<F, R>(&self, arc_rwlock: &Arc<RwLock<Root>>, f: F) -> Option<R>
3511 where
3512 F: FnOnce(&Value) -> R;
3513
3514 fn with_arc_rwlock_mut<F, R>(&self, arc_rwlock: &Arc<RwLock<Root>>, f: F) -> Option<R>
3516 where
3517 F: FnOnce(&mut Value) -> R;
3518}
3519
3520impl<Root, Value, F> WithContainer<Root, Value> for KeyPath<Root, Value, F>
3522where
3523 F: for<'r> Fn(&'r Root) -> &'r Value + Clone,
3524{
3525 fn with_arc<Callback, R>(&self, arc: &Arc<Root>, f: Callback) -> R
3526 where
3527 Callback: FnOnce(&Value) -> R,
3528 {
3529 self.with_arc(arc, f)
3530 }
3531
3532 fn with_box<Callback, R>(&self, boxed: &Box<Root>, f: Callback) -> R
3533 where
3534 Callback: FnOnce(&Value) -> R,
3535 {
3536 self.with_box(boxed, f)
3537 }
3538
3539 fn with_box_mut<Callback, R>(&self, _boxed: &mut Box<Root>, _f: Callback) -> R
3540 where
3541 Callback: FnOnce(&mut Value) -> R,
3542 {
3543 eprintln!("[DEBUG] KeyPath does not support mutable access - use WritableKeyPath instead");
3544 unreachable!("KeyPath does not support mutable access - use WritableKeyPath instead")
3545 }
3546
3547 fn with_rc<Callback, R>(&self, rc: &Rc<Root>, f: Callback) -> R
3548 where
3549 Callback: FnOnce(&Value) -> R,
3550 {
3551 self.with_rc(rc, f)
3552 }
3553
3554 fn with_result<Callback, R, E>(&self, result: &Result<Root, E>, f: Callback) -> Option<R>
3555 where
3556 Callback: FnOnce(&Value) -> R,
3557 {
3558 self.with_result(result, f)
3559 }
3560
3561 fn with_result_mut<Callback, R, E>(&self, _result: &mut Result<Root, E>, _f: Callback) -> Option<R>
3562 where
3563 Callback: FnOnce(&mut Value) -> R,
3564 {
3565 None
3566 }
3567
3568 fn with_option<Callback, R>(&self, option: &Option<Root>, f: Callback) -> Option<R>
3569 where
3570 Callback: FnOnce(&Value) -> R,
3571 {
3572 self.with_option(option, f)
3573 }
3574
3575 fn with_option_mut<Callback, R>(&self, _option: &mut Option<Root>, _f: Callback) -> Option<R>
3576 where
3577 Callback: FnOnce(&mut Value) -> R,
3578 {
3579 None
3580 }
3581
3582 fn with_refcell<Callback, R>(&self, refcell: &RefCell<Root>, f: Callback) -> Option<R>
3583 where
3584 Callback: FnOnce(&Value) -> R,
3585 {
3586 self.with_refcell(refcell, f)
3587 }
3588
3589 fn with_refcell_mut<Callback, R>(&self, _refcell: &RefCell<Root>, _f: Callback) -> Option<R>
3590 where
3591 Callback: FnOnce(&mut Value) -> R,
3592 {
3593 None
3594 }
3595
3596 #[cfg(feature = "tagged")]
3597 fn with_tagged<Tag, Callback, R>(&self, tagged: &Tagged<Root, Tag>, f: Callback) -> R
3598 where
3599 Tagged<Root, Tag>: std::ops::Deref<Target = Root>,
3600 Callback: FnOnce(&Value) -> R,
3601 {
3602 self.with_tagged(tagged, f)
3603 }
3604
3605 fn with_mutex<Callback, R>(&self, mutex: &Mutex<Root>, f: Callback) -> Option<R>
3606 where
3607 Callback: FnOnce(&Value) -> R,
3608 {
3609 self.with_mutex(mutex, f)
3610 }
3611
3612 fn with_mutex_mut<Callback, R>(&self, _mutex: &mut Mutex<Root>, _f: Callback) -> Option<R>
3613 where
3614 Callback: FnOnce(&mut Value) -> R,
3615 {
3616 None
3617 }
3618
3619 fn with_rwlock<Callback, R>(&self, rwlock: &RwLock<Root>, f: Callback) -> Option<R>
3620 where
3621 Callback: FnOnce(&Value) -> R,
3622 {
3623 self.with_rwlock(rwlock, f)
3624 }
3625
3626 fn with_rwlock_mut<Callback, R>(&self, _rwlock: &mut RwLock<Root>, _f: Callback) -> Option<R>
3627 where
3628 Callback: FnOnce(&mut Value) -> R,
3629 {
3630 None
3631 }
3632
3633 fn with_arc_rwlock<Callback, R>(&self, arc_rwlock: &Arc<RwLock<Root>>, f: Callback) -> Option<R>
3634 where
3635 Callback: FnOnce(&Value) -> R,
3636 {
3637 self.with_arc_rwlock(arc_rwlock, f)
3638 }
3639
3640 fn with_arc_rwlock_mut<Callback, R>(&self, _arc_rwlock: &Arc<RwLock<Root>>, _f: Callback) -> Option<R>
3641 where
3642 Callback: FnOnce(&mut Value) -> R,
3643 {
3644 None
3645 }
3646}
3647
3648impl<Root, Value, F> WithContainer<Root, Value> for OptionalKeyPath<Root, Value, F>
3650where
3651 F: for<'r> Fn(&'r Root) -> Option<&'r Value> + Clone,
3652{
3653 fn with_arc<Callback, R>(&self, arc: &Arc<Root>, f: Callback) -> R
3654 where
3655 Callback: FnOnce(&Value) -> R,
3656 {
3657 self.with_arc(arc, f)
3658 }
3659
3660 fn with_box<Callback, R>(&self, boxed: &Box<Root>, f: Callback) -> R
3661 where
3662 Callback: FnOnce(&Value) -> R,
3663 {
3664 self.with_box(boxed, f)
3665 }
3666
3667 fn with_box_mut<Callback, R>(&self, _boxed: &mut Box<Root>, _f: Callback) -> R
3668 where
3669 Callback: FnOnce(&mut Value) -> R,
3670 {
3671 eprintln!("[DEBUG] OptionalKeyPath does not support mutable access - use WritableOptionalKeyPath instead");
3672 unreachable!("OptionalKeyPath does not support mutable access - use WritableOptionalKeyPath instead")
3673 }
3674
3675 fn with_rc<Callback, R>(&self, rc: &Rc<Root>, f: Callback) -> R
3676 where
3677 Callback: FnOnce(&Value) -> R,
3678 {
3679 self.with_rc(rc, f)
3680 }
3681
3682 fn with_result<Callback, R, E>(&self, result: &Result<Root, E>, f: Callback) -> Option<R>
3683 where
3684 Callback: FnOnce(&Value) -> R,
3685 {
3686 self.with_result(result, f)
3687 }
3688
3689 fn with_result_mut<Callback, R, E>(&self, _result: &mut Result<Root, E>, _f: Callback) -> Option<R>
3690 where
3691 Callback: FnOnce(&mut Value) -> R,
3692 {
3693 None }
3695
3696 fn with_option<Callback, R>(&self, option: &Option<Root>, f: Callback) -> Option<R>
3697 where
3698 Callback: FnOnce(&Value) -> R,
3699 {
3700 self.with_option(option, f)
3701 }
3702
3703 fn with_option_mut<Callback, R>(&self, _option: &mut Option<Root>, _f: Callback) -> Option<R>
3704 where
3705 Callback: FnOnce(&mut Value) -> R,
3706 {
3707 None }
3709
3710 fn with_refcell<Callback, R>(&self, refcell: &RefCell<Root>, f: Callback) -> Option<R>
3711 where
3712 Callback: FnOnce(&Value) -> R,
3713 {
3714 self.with_refcell(refcell, f)
3715 }
3716
3717 fn with_refcell_mut<Callback, R>(&self, _refcell: &RefCell<Root>, _f: Callback) -> Option<R>
3718 where
3719 Callback: FnOnce(&mut Value) -> R,
3720 {
3721 None }
3723
3724 #[cfg(feature = "tagged")]
3725 fn with_tagged<Tag, Callback, R>(&self, tagged: &Tagged<Root, Tag>, f: Callback) -> R
3726 where
3727 Tagged<Root, Tag>: std::ops::Deref<Target = Root>,
3728 Callback: FnOnce(&Value) -> R,
3729 {
3730 self.with_tagged(tagged, f)
3731 }
3732
3733 fn with_mutex<Callback, R>(&self, mutex: &Mutex<Root>, f: Callback) -> Option<R>
3734 where
3735 Callback: FnOnce(&Value) -> R,
3736 {
3737 self.with_mutex(mutex, f)
3738 }
3739
3740 fn with_mutex_mut<Callback, R>(&self, _mutex: &mut Mutex<Root>, _f: Callback) -> Option<R>
3741 where
3742 Callback: FnOnce(&mut Value) -> R,
3743 {
3744 None }
3746
3747 fn with_rwlock<Callback, R>(&self, rwlock: &RwLock<Root>, f: Callback) -> Option<R>
3748 where
3749 Callback: FnOnce(&Value) -> R,
3750 {
3751 self.with_rwlock(rwlock, f)
3752 }
3753
3754 fn with_rwlock_mut<Callback, R>(&self, _rwlock: &mut RwLock<Root>, _f: Callback) -> Option<R>
3755 where
3756 Callback: FnOnce(&mut Value) -> R,
3757 {
3758 None }
3760
3761 fn with_arc_rwlock<Callback, R>(&self, arc_rwlock: &Arc<RwLock<Root>>, f: Callback) -> Option<R>
3762 where
3763 Callback: FnOnce(&Value) -> R,
3764 {
3765 self.with_arc_rwlock(arc_rwlock, f)
3766 }
3767
3768 fn with_arc_rwlock_mut<Callback, R>(&self, _arc_rwlock: &Arc<RwLock<Root>>, _f: Callback) -> Option<R>
3769 where
3770 Callback: FnOnce(&mut Value) -> R,
3771 {
3772 None }
3774}
3775
3776impl<Root, Value, F> WithContainer<Root, Value> for WritableKeyPath<Root, Value, F>
3778where
3779 F: for<'r> Fn(&'r mut Root) -> &'r mut Value,
3780{
3781 fn with_arc<Callback, R>(&self, _arc: &Arc<Root>, _f: Callback) -> R
3782 where
3783 Callback: FnOnce(&Value) -> R,
3784 {
3785 eprintln!("[DEBUG] WritableKeyPath::with_arc requires &mut Arc<Root> or interior mutability");
3788 unreachable!("WritableKeyPath::with_arc requires &mut Arc<Root> or interior mutability")
3789 }
3790
3791 fn with_box<Callback, R>(&self, boxed: &Box<Root>, f: Callback) -> R
3792 where
3793 Callback: FnOnce(&Value) -> R,
3794 {
3795 eprintln!("[DEBUG] WritableKeyPath::with_box requires &mut Box<Root> - use with_box_mut instead");
3798 unreachable!("WritableKeyPath::with_box requires &mut Box<Root> - use with_box_mut instead")
3799 }
3800
3801 fn with_box_mut<Callback, R>(&self, boxed: &mut Box<Root>, f: Callback) -> R
3802 where
3803 Callback: FnOnce(&mut Value) -> R,
3804 {
3805 let value = self.get_mut(boxed.as_mut());
3806 f(value)
3807 }
3808
3809 fn with_rc<Callback, R>(&self, _rc: &Rc<Root>, _f: Callback) -> R
3810 where
3811 Callback: FnOnce(&Value) -> R,
3812 {
3813 eprintln!("[DEBUG] WritableKeyPath::with_rc requires &mut Rc<Root> or interior mutability");
3816 unreachable!("WritableKeyPath::with_rc requires &mut Rc<Root> or interior mutability")
3817 }
3818
3819 fn with_result<Callback, R, E>(&self, _result: &Result<Root, E>, _f: Callback) -> Option<R>
3820 where
3821 Callback: FnOnce(&Value) -> R,
3822 {
3823 None
3826 }
3827
3828 fn with_result_mut<Callback, R, E>(&self, result: &mut Result<Root, E>, f: Callback) -> Option<R>
3829 where
3830 Callback: FnOnce(&mut Value) -> R,
3831 {
3832 result.as_mut().ok().map(|root| {
3833 let value = self.get_mut(root);
3834 f(value)
3835 })
3836 }
3837
3838 fn with_option<Callback, R>(&self, _option: &Option<Root>, _f: Callback) -> Option<R>
3839 where
3840 Callback: FnOnce(&Value) -> R,
3841 {
3842 None
3845 }
3846
3847 fn with_option_mut<Callback, R>(&self, option: &mut Option<Root>, f: Callback) -> Option<R>
3848 where
3849 Callback: FnOnce(&mut Value) -> R,
3850 {
3851 option.as_mut().map(|root| {
3852 let value = self.get_mut(root);
3853 f(value)
3854 })
3855 }
3856
3857 fn with_refcell<Callback, R>(&self, refcell: &RefCell<Root>, f: Callback) -> Option<R>
3858 where
3859 Callback: FnOnce(&Value) -> R,
3860 {
3861 None
3864 }
3865
3866 fn with_refcell_mut<Callback, R>(&self, refcell: &RefCell<Root>, f: Callback) -> Option<R>
3867 where
3868 Callback: FnOnce(&mut Value) -> R,
3869 {
3870 refcell.try_borrow_mut().ok().map(|mut borrow| {
3871 let value = self.get_mut(&mut *borrow);
3872 f(value)
3873 })
3874 }
3875
3876 #[cfg(feature = "tagged")]
3877 fn with_tagged<Tag, Callback, R>(&self, _tagged: &Tagged<Root, Tag>, _f: Callback) -> R
3878 where
3879 Tagged<Root, Tag>: std::ops::Deref<Target = Root>,
3880 Callback: FnOnce(&Value) -> R,
3881 {
3882 eprintln!("[DEBUG] WritableKeyPath::with_tagged requires &mut Tagged<Root, Tag> or interior mutability");
3885 unreachable!("WritableKeyPath::with_tagged requires &mut Tagged<Root, Tag> or interior mutability")
3886 }
3887
3888 fn with_mutex<Callback, R>(&self, mutex: &Mutex<Root>, f: Callback) -> Option<R>
3889 where
3890 Callback: FnOnce(&Value) -> R,
3891 {
3892 mutex.lock().ok().map(|mut guard| {
3893 let value = self.get_mut(&mut *guard);
3894 f(value)
3895 })
3896 }
3897
3898 fn with_mutex_mut<Callback, R>(&self, mutex: &mut Mutex<Root>, f: Callback) -> Option<R>
3899 where
3900 Callback: FnOnce(&mut Value) -> R,
3901 {
3902 mutex.get_mut().ok().map(|root| {
3904 let value = self.get_mut(root);
3905 f(value)
3906 })
3907 }
3908
3909 fn with_rwlock<Callback, R>(&self, rwlock: &RwLock<Root>, f: Callback) -> Option<R>
3910 where
3911 Callback: FnOnce(&Value) -> R,
3912 {
3913 None
3916 }
3917
3918 fn with_rwlock_mut<Callback, R>(&self, rwlock: &mut RwLock<Root>, f: Callback) -> Option<R>
3919 where
3920 Callback: FnOnce(&mut Value) -> R,
3921 {
3922 rwlock.get_mut().ok().map(|root| {
3924 let value = self.get_mut(root);
3925 f(value)
3926 })
3927 }
3928
3929 fn with_arc_rwlock<Callback, R>(&self, arc_rwlock: &Arc<RwLock<Root>>, f: Callback) -> Option<R>
3930 where
3931 Callback: FnOnce(&Value) -> R,
3932 {
3933 None
3936 }
3937
3938 fn with_arc_rwlock_mut<Callback, R>(&self, arc_rwlock: &Arc<RwLock<Root>>, f: Callback) -> Option<R>
3939 where
3940 Callback: FnOnce(&mut Value) -> R,
3941 {
3942 arc_rwlock.write().ok().map(|mut guard| {
3943 let value = self.get_mut(&mut *guard);
3944 f(value)
3945 })
3946 }
3947}
3948
3949impl<Root, Value, F> WithContainer<Root, Value> for WritableOptionalKeyPath<Root, Value, F>
3951where
3952 F: for<'r> Fn(&'r mut Root) -> Option<&'r mut Value>,
3953{
3954 fn with_arc<Callback, R>(&self, _arc: &Arc<Root>, _f: Callback) -> R
3955 where
3956 Callback: FnOnce(&Value) -> R,
3957 {
3958 eprintln!("[DEBUG] WritableOptionalKeyPath::with_arc requires &mut Arc<Root> or interior mutability");
3961 unreachable!("WritableOptionalKeyPath::with_arc requires &mut Arc<Root> or interior mutability")
3962 }
3963
3964 fn with_box<Callback, R>(&self, _boxed: &Box<Root>, _f: Callback) -> R
3965 where
3966 Callback: FnOnce(&Value) -> R,
3967 {
3968 eprintln!("[DEBUG] WritableOptionalKeyPath::with_box requires &mut Box<Root> - use with_box_mut instead");
3971 unreachable!("WritableOptionalKeyPath::with_box requires &mut Box<Root> - use with_box_mut instead")
3972 }
3973
3974 fn with_box_mut<Callback, R>(&self, boxed: &mut Box<Root>, f: Callback) -> R
3975 where
3976 Callback: FnOnce(&mut Value) -> R,
3977 {
3978 if let Some(value) = self.get_mut(boxed.as_mut()) {
3979 f(value)
3980 } else {
3981 eprintln!("[DEBUG] WritableOptionalKeyPath failed to get value from Box");
3982 unreachable!("WritableOptionalKeyPath failed to get value from Box")
3983 }
3984 }
3985
3986 fn with_rc<Callback, R>(&self, _rc: &Rc<Root>, _f: Callback) -> R
3987 where
3988 Callback: FnOnce(&Value) -> R,
3989 {
3990 eprintln!("[DEBUG] WritableOptionalKeyPath::with_rc requires &mut Rc<Root> or interior mutability");
3993 unreachable!("WritableOptionalKeyPath::with_rc requires &mut Rc<Root> or interior mutability")
3994 }
3995
3996 fn with_result<Callback, R, E>(&self, _result: &Result<Root, E>, _f: Callback) -> Option<R>
3997 where
3998 Callback: FnOnce(&Value) -> R,
3999 {
4000 None
4003 }
4004
4005 fn with_result_mut<Callback, R, E>(&self, result: &mut Result<Root, E>, f: Callback) -> Option<R>
4006 where
4007 Callback: FnOnce(&mut Value) -> R,
4008 {
4009 result.as_mut().ok().and_then(|root| {
4010 self.get_mut(root).map(|value| f(value))
4011 })
4012 }
4013
4014 fn with_option<Callback, R>(&self, _option: &Option<Root>, _f: Callback) -> Option<R>
4015 where
4016 Callback: FnOnce(&Value) -> R,
4017 {
4018 None
4021 }
4022
4023 fn with_option_mut<Callback, R>(&self, option: &mut Option<Root>, f: Callback) -> Option<R>
4024 where
4025 Callback: FnOnce(&mut Value) -> R,
4026 {
4027 option.as_mut().and_then(|root| {
4028 self.get_mut(root).map(|value| f(value))
4029 })
4030 }
4031
4032 fn with_refcell<Callback, R>(&self, _refcell: &RefCell<Root>, _f: Callback) -> Option<R>
4033 where
4034 Callback: FnOnce(&Value) -> R,
4035 {
4036 None
4039 }
4040
4041 fn with_refcell_mut<Callback, R>(&self, refcell: &RefCell<Root>, f: Callback) -> Option<R>
4042 where
4043 Callback: FnOnce(&mut Value) -> R,
4044 {
4045 refcell.try_borrow_mut().ok().and_then(|mut borrow| {
4046 self.get_mut(&mut *borrow).map(|value| f(value))
4047 })
4048 }
4049
4050 #[cfg(feature = "tagged")]
4051 fn with_tagged<Tag, Callback, R>(&self, _tagged: &Tagged<Root, Tag>, _f: Callback) -> R
4052 where
4053 Tagged<Root, Tag>: std::ops::Deref<Target = Root>,
4054 Callback: FnOnce(&Value) -> R,
4055 {
4056 eprintln!("[DEBUG] WritableOptionalKeyPath::with_tagged requires &mut Tagged<Root, Tag> or interior mutability");
4059 unreachable!("WritableOptionalKeyPath::with_tagged requires &mut Tagged<Root, Tag> or interior mutability")
4060 }
4061
4062 fn with_mutex<Callback, R>(&self, mutex: &Mutex<Root>, f: Callback) -> Option<R>
4063 where
4064 Callback: FnOnce(&Value) -> R,
4065 {
4066 mutex.lock().ok().and_then(|mut guard| {
4067 self.get_mut(&mut *guard).map(|value| f(value))
4068 })
4069 }
4070
4071 fn with_mutex_mut<Callback, R>(&self, mutex: &mut Mutex<Root>, f: Callback) -> Option<R>
4072 where
4073 Callback: FnOnce(&mut Value) -> R,
4074 {
4075 mutex.get_mut().ok().and_then(|root| {
4077 self.get_mut(root).map(|value| f(value))
4078 })
4079 }
4080
4081 fn with_rwlock<Callback, R>(&self, _rwlock: &RwLock<Root>, _f: Callback) -> Option<R>
4082 where
4083 Callback: FnOnce(&Value) -> R,
4084 {
4085 None
4088 }
4089
4090 fn with_rwlock_mut<Callback, R>(&self, rwlock: &mut RwLock<Root>, f: Callback) -> Option<R>
4091 where
4092 Callback: FnOnce(&mut Value) -> R,
4093 {
4094 rwlock.get_mut().ok().and_then(|root| {
4096 self.get_mut(root).map(|value| f(value))
4097 })
4098 }
4099
4100 fn with_arc_rwlock<Callback, R>(&self, _arc_rwlock: &Arc<RwLock<Root>>, _f: Callback) -> Option<R>
4101 where
4102 Callback: FnOnce(&Value) -> R,
4103 {
4104 None
4107 }
4108
4109 fn with_arc_rwlock_mut<Callback, R>(&self, arc_rwlock: &Arc<RwLock<Root>>, f: Callback) -> Option<R>
4110 where
4111 Callback: FnOnce(&mut Value) -> R,
4112 {
4113 arc_rwlock.write().ok().and_then(|mut guard| {
4114 self.get_mut(&mut *guard).map(|value| f(value))
4115 })
4116 }
4117}