rust_keypaths/
lib.rs

1// Enable feature gate when nightly feature is enabled
2// NOTE: This will only work with nightly Rust toolchain
3#![cfg_attr(feature = "nightly", feature(impl_trait_in_assoc_type))]
4
5use std::sync::{Arc, Mutex, RwLock};
6use std::marker::PhantomData;
7use std::any::{Any, TypeId};
8use std::rc::Rc;
9use std::cell::RefCell;
10use std::ops::Shr;
11
12#[cfg(feature = "tagged")]
13use tagged_core::Tagged;
14
15
16// ========== HELPER MACROS FOR KEYPATH CREATION ==========
17
18/// Macro to create a `KeyPath` (readable, non-optional)
19/// 
20/// # Examples
21/// 
22/// ```rust
23/// use rust_keypaths::keypath;
24/// 
25/// struct User { name: String, address: Address }
26/// struct Address { street: String }
27/// 
28/// // Using a closure with type annotation
29/// let kp = keypath!(|u: &User| &u.name);
30/// 
31/// // Nested field access
32/// let kp = keypath!(|u: &User| &u.address.street);
33/// 
34/// // Or with automatic type inference
35/// let kp = keypath!(|u| &u.name);
36/// ```
37#[macro_export]
38macro_rules! keypath {
39    // Accept a closure directly
40    ($closure:expr) => {
41        $crate::KeyPath::new($closure)
42    };
43}
44
45/// Macro to create an `OptionalKeyPath` (readable, optional)
46/// 
47/// # Examples
48/// 
49/// ```rust
50/// use rust_keypaths::opt_keypath;
51/// 
52/// struct User { metadata: Option<String>, address: Option<Address> }
53/// struct Address { street: String }
54/// 
55/// // Using a closure with type annotation
56/// let kp = opt_keypath!(|u: &User| u.metadata.as_ref());
57/// 
58/// // Nested field access through Option
59/// let kp = opt_keypath!(|u: &User| u.address.as_ref().map(|a| &a.street));
60/// 
61/// // Or with automatic type inference
62/// let kp = opt_keypath!(|u| u.metadata.as_ref());
63/// ```
64#[macro_export]
65macro_rules! opt_keypath {
66    // Accept a closure directly
67    ($closure:expr) => {
68        $crate::OptionalKeyPath::new($closure)
69    };
70}
71
72/// Macro to create a `WritableKeyPath` (writable, non-optional)
73/// 
74/// # Examples
75/// 
76/// ```rust
77/// use rust_keypaths::writable_keypath;
78/// 
79/// struct User { name: String, address: Address }
80/// struct Address { street: String }
81/// 
82/// // Using a closure with type annotation
83/// let kp = writable_keypath!(|u: &mut User| &mut u.name);
84/// 
85/// // Nested field access
86/// let kp = writable_keypath!(|u: &mut User| &mut u.address.street);
87/// 
88/// // Or with automatic type inference
89/// let kp = writable_keypath!(|u| &mut u.name);
90/// ```
91#[macro_export]
92macro_rules! writable_keypath {
93    // Accept a closure directly
94    ($closure:expr) => {
95        $crate::WritableKeyPath::new($closure)
96    };
97}
98
99/// Macro to create a `WritableOptionalKeyPath` (writable, optional)
100/// 
101/// # Examples
102/// 
103/// ```rust
104/// use rust_keypaths::writable_opt_keypath;
105/// 
106/// struct User { metadata: Option<String>, address: Option<Address> }
107/// struct Address { street: String }
108/// 
109/// // Using a closure with type annotation
110/// let kp = writable_opt_keypath!(|u: &mut User| u.metadata.as_mut());
111/// 
112/// // Nested field access through Option
113/// let kp = writable_opt_keypath!(|u: &mut User| u.address.as_mut().map(|a| &mut a.street));
114/// 
115/// // Or with automatic type inference
116/// let kp = writable_opt_keypath!(|u| u.metadata.as_mut());
117/// ```
118#[macro_export]
119macro_rules! writable_opt_keypath {
120    // Accept a closure directly
121    ($closure:expr) => {
122        $crate::WritableOptionalKeyPath::new($closure)
123    };
124}
125
126// ========== BASE KEYPATH TYPES ==========
127
128// Base KeyPath
129#[derive(Clone)]
130pub struct KeyPath<Root, Value, F>
131where
132    F: for<'r> Fn(&'r Root) -> &'r Value,
133{
134    getter: F,
135    _phantom: PhantomData<(Root, Value)>,
136}
137
138impl<Root, Value, F> KeyPath<Root, Value, F>
139where
140    F: for<'r> Fn(&'r Root) -> &'r Value,
141{
142    pub fn new(getter: F) -> Self {
143        Self {
144            getter,
145            _phantom: PhantomData,
146        }
147    }
148    
149    pub fn get<'r>(&self, root: &'r Root) -> &'r Value {
150        (self.getter)(root)
151}
152
153    // Instance methods for unwrapping containers (automatically infers Target from Value::Target)
154    // Box<T> -> T
155    pub fn for_box<Target>(self) -> KeyPath<Root, Target, impl for<'r> Fn(&'r Root) -> &'r Target + 'static>
156    where
157        Value: std::ops::Deref<Target = Target>,
158        F: 'static,
159        Value: 'static,
160    {
161        let getter = self.getter;
162        
163        KeyPath {
164            getter: move |root: &Root| {
165                getter(root).deref()
166            },
167            _phantom: PhantomData,
168        }
169    }
170    
171    // Arc<T> -> T
172    pub fn for_arc<Target>(self) -> KeyPath<Root, Target, impl for<'r> Fn(&'r Root) -> &'r Target + 'static>
173    where
174        Value: std::ops::Deref<Target = Target>,
175        F: 'static,
176        Value: 'static,
177    {
178        let getter = self.getter;
179        
180        KeyPath {
181            getter: move |root: &Root| {
182                getter(root).deref()
183            },
184            _phantom: PhantomData,
185        }
186    }
187    
188    // Rc<T> -> T
189    pub fn for_rc<Target>(self) -> KeyPath<Root, Target, impl for<'r> Fn(&'r Root) -> &'r Target + 'static>
190    where
191        Value: std::ops::Deref<Target = Target>,
192        F: 'static,
193        Value: 'static,
194    {
195        let getter = self.getter;
196        
197        KeyPath {
198            getter: move |root: &Root| {
199                getter(root).deref()
200            },
201            _phantom: PhantomData,
202        }
203    }
204    
205    // Overload: Adapt root type to Arc<Root> when Value is Sized (not a container)
206    pub fn for_arc_root(self) -> OptionalKeyPath<Arc<Root>, Value, impl for<'r> Fn(&'r Arc<Root>) -> Option<&'r Value> + 'static>
207    where
208        Value: Sized,
209        F: 'static,
210        Root: 'static,
211        Value: 'static,
212    {
213        let getter = self.getter;
214        
215        OptionalKeyPath {
216            getter: move |arc: &Arc<Root>| {
217                Some(getter(arc.as_ref()))
218            },
219            _phantom: PhantomData,
220        }
221    }
222    
223    // Overload: Adapt root type to Box<Root> when Value is Sized (not a container)
224    pub fn for_box_root(self) -> OptionalKeyPath<Box<Root>, Value, impl for<'r> Fn(&'r Box<Root>) -> Option<&'r Value> + 'static>
225    where
226        Value: Sized,
227        F: 'static,
228        Root: 'static,
229        Value: 'static,
230    {
231        let getter = self.getter;
232        
233        OptionalKeyPath {
234            getter: move |boxed: &Box<Root>| {
235                Some(getter(boxed.as_ref()))
236            },
237            _phantom: PhantomData,
238        }
239    }
240    
241    // Overload: Adapt root type to Rc<Root> when Value is Sized (not a container)
242    pub fn for_rc_root(self) -> OptionalKeyPath<Rc<Root>, Value, impl for<'r> Fn(&'r Rc<Root>) -> Option<&'r Value> + 'static>
243    where
244        Value: Sized,
245        F: 'static,
246        Root: 'static,
247        Value: 'static,
248    {
249        let getter = self.getter;
250        
251        OptionalKeyPath {
252            getter: move |rc: &Rc<Root>| {
253                Some(getter(rc.as_ref()))
254            },
255            _phantom: PhantomData,
256        }
257    }
258    
259    /// Adapt this keypath to work with Result<Root, E> instead of Root
260    /// This unwraps the Result and applies the keypath to the Ok value
261    pub fn for_result<E>(self) -> OptionalKeyPath<Result<Root, E>, Value, impl for<'r> Fn(&'r Result<Root, E>) -> Option<&'r Value> + 'static>
262    where
263        F: 'static,
264        Root: 'static,
265        Value: 'static,
266        E: 'static,
267    {
268        let getter = self.getter;
269        
270        OptionalKeyPath {
271            getter: move |result: &Result<Root, E>| {
272                result.as_ref().ok().map(|root| getter(root))
273            },
274            _phantom: PhantomData,
275        }
276    }
277    
278    /// Convert a KeyPath to OptionalKeyPath for chaining
279    /// This allows non-optional keypaths to be chained with then()
280    pub fn to_optional(self) -> OptionalKeyPath<Root, Value, impl for<'r> Fn(&'r Root) -> Option<&'r Value> + 'static>
281    where
282        F: 'static,
283    {
284        let getter = self.getter;
285        OptionalKeyPath::new(move |root: &Root| Some(getter(root)))
286    }
287    
288    /// Execute a closure with a reference to the value inside an Option
289    pub fn with_option<Callback, R>(&self, option: &Option<Root>, f: Callback) -> Option<R>
290    where
291        F: Clone,
292        Callback: FnOnce(&Value) -> R,
293    {
294        option.as_ref().map(|root| {
295            let value = self.get(root);
296            f(value)
297        })
298    }
299    
300    /// Execute a closure with a reference to the value inside a Result
301    pub fn with_result<Callback, R, E>(&self, result: &Result<Root, E>, f: Callback) -> Option<R>
302    where
303        F: Clone,
304        Callback: FnOnce(&Value) -> R,
305    {
306        result.as_ref().ok().map(|root| {
307            let value = self.get(root);
308            f(value)
309        })
310    }
311    
312    /// Execute a closure with a reference to the value inside a Box
313    pub fn with_box<Callback, R>(&self, boxed: &Box<Root>, f: Callback) -> R
314    where
315        F: Clone,
316        Callback: FnOnce(&Value) -> R,
317    {
318        let value = self.get(boxed);
319        f(value)
320    }
321    
322    /// Execute a closure with a reference to the value inside an Arc
323    pub fn with_arc<Callback, R>(&self, arc: &Arc<Root>, f: Callback) -> R
324    where
325        F: Clone,
326        Callback: FnOnce(&Value) -> R,
327    {
328        let value = self.get(arc);
329        f(value)
330    }
331    
332    /// Execute a closure with a reference to the value inside an Rc
333    pub fn with_rc<Callback, R>(&self, rc: &Rc<Root>, f: Callback) -> R
334    where
335        F: Clone,
336        Callback: FnOnce(&Value) -> R,
337    {
338        let value = self.get(rc);
339        f(value)
340    }
341    
342    /// Execute a closure with a reference to the value inside a RefCell
343    pub fn with_refcell<Callback, R>(&self, refcell: &RefCell<Root>, f: Callback) -> Option<R>
344    where
345        F: Clone,
346        Callback: FnOnce(&Value) -> R,
347    {
348        refcell.try_borrow().ok().map(|borrow| {
349            let value = self.get(&*borrow);
350            f(value)
351        })
352    }
353    
354    /// Execute a closure with a reference to the value inside a Mutex
355    pub fn with_mutex<Callback, R>(&self, mutex: &Mutex<Root>, f: Callback) -> Option<R>
356    where
357        F: Clone,
358        Callback: FnOnce(&Value) -> R,
359    {
360        mutex.lock().ok().map(|guard| {
361            let value = self.get(&*guard);
362            f(value)
363        })
364    }
365    
366    /// Execute a closure with a reference to the value inside an RwLock
367    pub fn with_rwlock<Callback, R>(&self, rwlock: &RwLock<Root>, f: Callback) -> Option<R>
368    where
369        F: Clone,
370        Callback: FnOnce(&Value) -> R,
371    {
372        rwlock.read().ok().map(|guard| {
373            let value = self.get(&*guard);
374            f(value)
375        })
376    }
377    
378    /// Execute a closure with a reference to the value inside an Arc<RwLock<Root>>
379    pub fn with_arc_rwlock<Callback, R>(&self, arc_rwlock: &Arc<RwLock<Root>>, f: Callback) -> Option<R>
380    where
381        F: Clone,
382        Callback: FnOnce(&Value) -> R,
383    {
384        arc_rwlock.read().ok().map(|guard| {
385            let value = self.get(&*guard);
386            f(value)
387        })
388    }
389    
390    /// Execute a closure with a reference to the value inside an Arc<Mutex<Root>>
391    pub fn with_arc_mutex<Callback, R>(&self, arc_mutex: &Arc<Mutex<Root>>, f: Callback) -> Option<R>
392    where
393        F: Clone,
394        Callback: FnOnce(&Value) -> R,
395    {
396        arc_mutex.lock().ok().map(|guard| {
397            let value = self.get(&*guard);
398            f(value)
399        })
400    }
401    
402    #[cfg(feature = "tagged")]
403    /// Adapt this keypath to work with Tagged<Root, Tag> instead of Root
404    /// This unwraps the Tagged wrapper and applies the keypath to the inner value
405    pub fn for_tagged<Tag>(self) -> KeyPath<Tagged<Root, Tag>, Value, impl for<'r> Fn(&'r Tagged<Root, Tag>) -> &'r Value + 'static>
406    where
407        Tagged<Root, Tag>: std::ops::Deref<Target = Root>,
408        F: 'static,
409        Root: 'static,
410        Value: 'static,
411        Tag: 'static,
412    {
413        use std::ops::Deref;
414        let getter = self.getter;
415        
416        KeyPath {
417            getter: move |tagged: &Tagged<Root, Tag>| {
418                getter(tagged.deref())
419            },
420            _phantom: PhantomData,
421        }
422    }
423    
424    #[cfg(feature = "tagged")]
425    /// Execute a closure with a reference to the value inside a Tagged
426    /// This avoids cloning by working with references directly
427    pub fn with_tagged<Tag, Callback, R>(&self, tagged: &Tagged<Root, Tag>, f: Callback) -> R
428    where
429        Tagged<Root, Tag>: std::ops::Deref<Target = Root>,
430        Callback: FnOnce(&Value) -> R,
431    {
432        use std::ops::Deref;
433        let value = self.get(tagged.deref());
434        f(value)
435    }
436    
437    /// Adapt this keypath to work with Option<Root> instead of Root
438    /// This converts the KeyPath to an OptionalKeyPath and unwraps the Option
439    pub fn for_option(self) -> OptionalKeyPath<Option<Root>, Value, impl for<'r> Fn(&'r Option<Root>) -> Option<&'r Value> + 'static>
440    where
441        F: 'static,
442        Root: 'static,
443        Value: 'static,
444    {
445        let getter = self.getter;
446        
447        OptionalKeyPath {
448            getter: move |opt: &Option<Root>| {
449                opt.as_ref().map(|root| getter(root))
450            },
451            _phantom: PhantomData,
452        }
453    }
454    
455    /// Get an iterator over a Vec when Value is Vec<T>
456    /// Returns Some(iterator) if the value is a Vec, None otherwise
457    pub fn iter<'r, T>(&self, root: &'r Root) -> Option<std::slice::Iter<'r, T>>
458    where
459        Value: AsRef<[T]> + 'r,
460    {
461        let value_ref: &'r Value = self.get(root);
462        Some(value_ref.as_ref().iter())
463    }
464    
465    /// Extract values from a slice of owned values
466    /// Returns a Vec of references to the extracted values
467    pub fn extract_from_slice<'r>(&self, slice: &'r [Root]) -> Vec<&'r Value> {
468        slice.iter().map(|item| self.get(item)).collect()
469    }
470    
471    /// Extract values from a slice of references
472    /// Returns a Vec of references to the extracted values
473    pub fn extract_from_ref_slice<'r>(&self, slice: &'r [&Root]) -> Vec<&'r Value> {
474        slice.iter().map(|item| self.get(item)).collect()
475    }
476    
477    /// Chain this keypath with another keypath
478    /// Returns a KeyPath that chains both keypaths
479    pub fn then<SubValue, G>(
480        self,
481        next: KeyPath<Value, SubValue, G>,
482    ) -> KeyPath<Root, SubValue, impl for<'r> Fn(&'r Root) -> &'r SubValue>
483    where
484        G: for<'r> Fn(&'r Value) -> &'r SubValue,
485        F: 'static,
486        G: 'static,
487        Value: 'static,
488    {
489        let first = self.getter;
490        let second = next.getter;
491        
492        KeyPath::new(move |root: &Root| {
493            let value = first(root);
494            second(value)
495        })
496    }
497    
498    /// Chain this keypath with an optional keypath
499    /// Returns an OptionalKeyPath that chains both keypaths
500    pub fn then_optional<SubValue, G>(
501        self,
502        next: OptionalKeyPath<Value, SubValue, G>,
503    ) -> OptionalKeyPath<Root, SubValue, impl for<'r> Fn(&'r Root) -> Option<&'r SubValue>>
504    where
505        G: for<'r> Fn(&'r Value) -> Option<&'r SubValue>,
506        F: 'static,
507        G: 'static,
508        Value: 'static,
509    {
510        let first = self.getter;
511        let second = next.getter;
512        
513        OptionalKeyPath::new(move |root: &Root| {
514            let value = first(root);
515            second(value)
516        })
517    }
518    
519}
520
521// Extension methods for KeyPath to support Arc<RwLock> and Arc<Mutex> directly
522impl<Root, Value, F> KeyPath<Root, Value, F>
523where
524    F: for<'r> Fn(&'r Root) -> &'r Value,
525{
526    /// Execute a closure with a reference to the value inside an Arc<RwLock<Root>>
527    /// This is a convenience method that works directly with Arc<RwLock<T>>
528    pub fn with_arc_rwlock_direct<Callback, R>(&self, arc_rwlock: &Arc<RwLock<Root>>, f: Callback) -> Option<R>
529    where
530        Callback: FnOnce(&Value) -> R,
531    {
532        arc_rwlock.read().ok().map(|guard| {
533            let value = self.get(&*guard);
534            f(value)
535        })
536    }
537    
538    /// Execute a closure with a reference to the value inside an Arc<Mutex<Root>>
539    /// This is a convenience method that works directly with Arc<Mutex<T>>
540    pub fn with_arc_mutex_direct<Callback, R>(&self, arc_mutex: &Arc<Mutex<Root>>, f: Callback) -> Option<R>
541    where
542        Callback: FnOnce(&Value) -> R,
543    {
544        arc_mutex.lock().ok().map(|guard| {
545            let value = self.get(&*guard);
546            f(value)
547        })
548    }
549}
550
551// Utility function for slice access (kept as standalone function)
552pub fn for_slice<T>() -> impl for<'r> Fn(&'r [T], usize) -> Option<&'r T> {
553    |slice: &[T], index: usize| slice.get(index)
554}
555
556// Container access utilities
557pub mod containers {
558    use super::{OptionalKeyPath, WritableOptionalKeyPath, KeyPath, WritableKeyPath};
559    use std::collections::{HashMap, BTreeMap, HashSet, BTreeSet, VecDeque, LinkedList, BinaryHeap};
560    use std::sync::{Mutex, RwLock, Weak as StdWeak, Arc};
561    use std::rc::{Weak as RcWeak, Rc};
562    use std::ops::{Deref, DerefMut};
563
564    #[cfg(feature = "parking_lot")]
565    use parking_lot::{Mutex as ParkingMutex, RwLock as ParkingRwLock};
566
567    #[cfg(feature = "tagged")]
568    use tagged_core::Tagged;
569
570    /// Create a keypath for indexed access in Vec<T>
571    pub fn for_vec_index<T>(index: usize) -> OptionalKeyPath<Vec<T>, T, impl for<'r> Fn(&'r Vec<T>) -> Option<&'r T>> {
572        OptionalKeyPath::new(move |vec: &Vec<T>| vec.get(index))
573    }
574
575    /// Create a keypath for indexed access in VecDeque<T>
576    pub fn for_vecdeque_index<T>(index: usize) -> OptionalKeyPath<VecDeque<T>, T, impl for<'r> Fn(&'r VecDeque<T>) -> Option<&'r T>> {
577        OptionalKeyPath::new(move |deque: &VecDeque<T>| deque.get(index))
578    }
579
580    /// Create a keypath for indexed access in LinkedList<T>
581    pub fn for_linkedlist_index<T>(index: usize) -> OptionalKeyPath<LinkedList<T>, T, impl for<'r> Fn(&'r LinkedList<T>) -> Option<&'r T>> {
582        OptionalKeyPath::new(move |list: &LinkedList<T>| {
583            list.iter().nth(index)
584        })
585    }
586
587    /// Create a keypath for key-based access in HashMap<K, V>
588    pub fn for_hashmap_key<K, V>(key: K) -> OptionalKeyPath<HashMap<K, V>, V, impl for<'r> Fn(&'r HashMap<K, V>) -> Option<&'r V>>
589    where
590        K: std::hash::Hash + Eq + Clone + 'static,
591        V: 'static,
592    {
593        OptionalKeyPath::new(move |map: &HashMap<K, V>| map.get(&key))
594    }
595
596    /// Create a keypath for key-based access in BTreeMap<K, V>
597    pub fn for_btreemap_key<K, V>(key: K) -> OptionalKeyPath<BTreeMap<K, V>, V, impl for<'r> Fn(&'r BTreeMap<K, V>) -> Option<&'r V>>
598    where
599        K: Ord + Clone + 'static,
600        V: 'static,
601    {
602        OptionalKeyPath::new(move |map: &BTreeMap<K, V>| map.get(&key))
603    }
604
605    /// Create a keypath for getting a value from HashSet<T> (returns Option<&T>)
606    pub fn for_hashset_get<T>(value: T) -> OptionalKeyPath<HashSet<T>, T, impl for<'r> Fn(&'r HashSet<T>) -> Option<&'r T>>
607    where
608        T: std::hash::Hash + Eq + Clone + 'static,
609    {
610        OptionalKeyPath::new(move |set: &HashSet<T>| set.get(&value))
611    }
612
613    /// Create a keypath for checking membership in BTreeSet<T>
614    pub fn for_btreeset_get<T>(value: T) -> OptionalKeyPath<BTreeSet<T>, T, impl for<'r> Fn(&'r BTreeSet<T>) -> Option<&'r T>>
615    where
616        T: Ord + Clone + 'static,
617    {
618        OptionalKeyPath::new(move |set: &BTreeSet<T>| set.get(&value))
619    }
620
621    /// Create a keypath for peeking at the top of BinaryHeap<T>
622    pub fn for_binaryheap_peek<T>() -> OptionalKeyPath<BinaryHeap<T>, T, impl for<'r> Fn(&'r BinaryHeap<T>) -> Option<&'r T>>
623    where
624        T: Ord + 'static,
625    {
626        OptionalKeyPath::new(|heap: &BinaryHeap<T>| heap.peek())
627    }
628
629    // ========== WRITABLE VERSIONS ==========
630
631    /// Create a writable keypath for indexed access in Vec<T>
632    pub fn for_vec_index_mut<T>(index: usize) -> WritableOptionalKeyPath<Vec<T>, T, impl for<'r> Fn(&'r mut Vec<T>) -> Option<&'r mut T>> {
633        WritableOptionalKeyPath::new(move |vec: &mut Vec<T>| vec.get_mut(index))
634    }
635
636    /// Create a writable keypath for indexed access in VecDeque<T>
637    pub fn for_vecdeque_index_mut<T>(index: usize) -> WritableOptionalKeyPath<VecDeque<T>, T, impl for<'r> Fn(&'r mut VecDeque<T>) -> Option<&'r mut T>> {
638        WritableOptionalKeyPath::new(move |deque: &mut VecDeque<T>| deque.get_mut(index))
639    }
640
641    /// Create a writable keypath for indexed access in LinkedList<T>
642    pub fn for_linkedlist_index_mut<T>(index: usize) -> WritableOptionalKeyPath<LinkedList<T>, T, impl for<'r> Fn(&'r mut LinkedList<T>) -> Option<&'r mut T>> {
643        WritableOptionalKeyPath::new(move |list: &mut LinkedList<T>| {
644            // LinkedList doesn't have get_mut, so we need to iterate
645            let mut iter = list.iter_mut();
646            iter.nth(index)
647        })
648    }
649
650    /// Create a writable keypath for key-based access in HashMap<K, V>
651    pub fn for_hashmap_key_mut<K, V>(key: K) -> WritableOptionalKeyPath<HashMap<K, V>, V, impl for<'r> Fn(&'r mut HashMap<K, V>) -> Option<&'r mut V>>
652    where
653        K: std::hash::Hash + Eq + Clone + 'static,
654        V: 'static,
655    {
656        WritableOptionalKeyPath::new(move |map: &mut HashMap<K, V>| map.get_mut(&key))
657    }
658
659    /// Create a writable keypath for key-based access in BTreeMap<K, V>
660    pub fn for_btreemap_key_mut<K, V>(key: K) -> WritableOptionalKeyPath<BTreeMap<K, V>, V, impl for<'r> Fn(&'r mut BTreeMap<K, V>) -> Option<&'r mut V>>
661    where
662        K: Ord + Clone + 'static,
663        V: 'static,
664    {
665        WritableOptionalKeyPath::new(move |map: &mut BTreeMap<K, V>| map.get_mut(&key))
666    }
667
668    /// Create a writable keypath for getting a mutable value from HashSet<T>
669    /// Note: HashSet doesn't support mutable access to elements, but we provide it for consistency
670    pub fn for_hashset_get_mut<T>(value: T) -> WritableOptionalKeyPath<HashSet<T>, T, impl for<'r> Fn(&'r mut HashSet<T>) -> Option<&'r mut T>>
671    where
672        T: std::hash::Hash + Eq + Clone + 'static,
673    {
674        WritableOptionalKeyPath::new(move |set: &mut HashSet<T>| {
675            // HashSet doesn't have get_mut, so we need to check and return None
676            // This is a limitation of HashSet's design
677            if set.contains(&value) {
678                // We can't return a mutable reference to the value in the set
679                // This is a fundamental limitation of HashSet
680                None
681            } else {
682                None
683            }
684        })
685    }
686
687    /// Create a writable keypath for getting a mutable value from BTreeSet<T>
688    /// Note: BTreeSet doesn't support mutable access to elements, but we provide it for consistency
689    pub fn for_btreeset_get_mut<T>(value: T) -> WritableOptionalKeyPath<BTreeSet<T>, T, impl for<'r> Fn(&'r mut BTreeSet<T>) -> Option<&'r mut T>>
690    where
691        T: Ord + Clone + 'static,
692    {
693        WritableOptionalKeyPath::new(move |set: &mut BTreeSet<T>| {
694            // BTreeSet doesn't have get_mut, so we need to check and return None
695            // This is a limitation of BTreeSet's design
696            if set.contains(&value) {
697                // We can't return a mutable reference to the value in the set
698                // This is a fundamental limitation of BTreeSet
699                None
700            } else {
701                None
702            }
703        })
704    }
705
706    /// Create a writable keypath for peeking at the top of BinaryHeap<T>
707    /// Note: BinaryHeap.peek_mut() returns PeekMut which is a guard type.
708    /// Due to Rust's borrowing rules, we cannot return &mut T directly from PeekMut.
709    /// This function returns None as BinaryHeap doesn't support direct mutable access
710    /// through keypaths. Use heap.peek_mut() directly for mutable access.
711    pub fn for_binaryheap_peek_mut<T>() -> WritableOptionalKeyPath<BinaryHeap<T>, T, impl for<'r> Fn(&'r mut BinaryHeap<T>) -> Option<&'r mut T>>
712    where
713        T: Ord + 'static,
714    {
715        // BinaryHeap.peek_mut() returns PeekMut which is a guard type that owns the mutable reference.
716        // We cannot return &mut T from it due to lifetime constraints.
717        // This is a fundamental limitation - use heap.peek_mut() directly instead.
718        WritableOptionalKeyPath::new(|_heap: &mut BinaryHeap<T>| {
719            None
720        })
721    }
722
723    // ========== SYNCHRONIZATION PRIMITIVES ==========
724    // Note: Mutex and RwLock return guards that own the lock, not references.
725    // We cannot create keypaths that return references from guards due to lifetime constraints.
726    // These helper functions are provided for convenience, but direct lock()/read()/write() calls are recommended.
727
728    /// Helper function to lock a Mutex<T> and access its value
729    /// Returns None if the mutex is poisoned
730    /// Note: This returns a guard, not a reference, so it cannot be used in keypaths directly
731    pub fn lock_mutex<T>(mutex: &Mutex<T>) -> Option<std::sync::MutexGuard<'_, T>> {
732        mutex.lock().ok()
733    }
734
735    /// Helper function to read-lock an RwLock<T> and access its value
736    /// Returns None if the lock is poisoned
737    /// Note: This returns a guard, not a reference, so it cannot be used in keypaths directly
738    pub fn read_rwlock<T>(rwlock: &RwLock<T>) -> Option<std::sync::RwLockReadGuard<'_, T>> {
739        rwlock.read().ok()
740    }
741
742    /// Helper function to write-lock an RwLock<T> and access its value
743    /// Returns None if the lock is poisoned
744    /// Note: This returns a guard, not a reference, so it cannot be used in keypaths directly
745    pub fn write_rwlock<T>(rwlock: &RwLock<T>) -> Option<std::sync::RwLockWriteGuard<'_, T>> {
746        rwlock.write().ok()
747    }
748
749    /// Helper function to lock an Arc<Mutex<T>> and access its value
750    /// Returns None if the mutex is poisoned
751    /// Note: This returns a guard, not a reference, so it cannot be used in keypaths directly
752    pub fn lock_arc_mutex<T>(arc_mutex: &Arc<Mutex<T>>) -> Option<std::sync::MutexGuard<'_, T>> {
753        arc_mutex.lock().ok()
754    }
755
756    /// Helper function to read-lock an Arc<RwLock<T>> and access its value
757    /// Returns None if the lock is poisoned
758    /// Note: This returns a guard, not a reference, so it cannot be used in keypaths directly
759    pub fn read_arc_rwlock<T>(arc_rwlock: &Arc<RwLock<T>>) -> Option<std::sync::RwLockReadGuard<'_, T>> {
760        arc_rwlock.read().ok()
761    }
762
763    /// Helper function to write-lock an Arc<RwLock<T>> and access its value
764    /// Returns None if the lock is poisoned
765    /// Note: This returns a guard, not a reference, so it cannot be used in keypaths directly
766    pub fn write_arc_rwlock<T>(arc_rwlock: &Arc<RwLock<T>>) -> Option<std::sync::RwLockWriteGuard<'_, T>> {
767        arc_rwlock.write().ok()
768    }
769
770    /// Helper function to upgrade a Weak<T> to Arc<T>
771    /// Returns None if the Arc has been dropped
772    /// Note: This returns an owned Arc, not a reference, so it cannot be used in keypaths directly
773    pub fn upgrade_weak<T>(weak: &StdWeak<T>) -> Option<Arc<T>> {
774        weak.upgrade()
775    }
776
777    /// Helper function to upgrade an Rc::Weak<T> to Rc<T>
778    /// Returns None if the Rc has been dropped
779    /// Note: This returns an owned Rc, not a reference, so it cannot be used in keypaths directly
780    pub fn upgrade_rc_weak<T>(weak: &RcWeak<T>) -> Option<Rc<T>> {
781        weak.upgrade()
782    }
783
784    #[cfg(feature = "parking_lot")]
785    /// Helper function to lock a parking_lot::Mutex<T> and access its value
786    /// Note: This returns a guard, not a reference, so it cannot be used in keypaths directly
787    pub fn lock_parking_mutex<T>(mutex: &ParkingMutex<T>) -> parking_lot::MutexGuard<'_, T> {
788        mutex.lock()
789    }
790
791    #[cfg(feature = "parking_lot")]
792    /// Helper function to read-lock a parking_lot::RwLock<T> and access its value
793    /// Note: This returns a guard, not a reference, so it cannot be used in keypaths directly
794    pub fn read_parking_rwlock<T>(rwlock: &ParkingRwLock<T>) -> parking_lot::RwLockReadGuard<'_, T> {
795        rwlock.read()
796    }
797
798    #[cfg(feature = "parking_lot")]
799    /// Helper function to write-lock a parking_lot::RwLock<T> and access its value
800    /// Note: This returns a guard, not a reference, so it cannot be used in keypaths directly
801    pub fn write_parking_rwlock<T>(rwlock: &ParkingRwLock<T>) -> parking_lot::RwLockWriteGuard<'_, T> {
802        rwlock.write()
803    }
804
805    #[cfg(feature = "tagged")]
806    /// Create a keypath for accessing the inner value of Tagged<Tag, T>
807    /// Tagged implements Deref, so we can access the inner value directly
808    pub fn for_tagged<Tag, T>() -> KeyPath<Tagged<Tag, T>, T, impl for<'r> Fn(&'r Tagged<Tag, T>) -> &'r T>
809    where
810        Tagged<Tag, T>: std::ops::Deref<Target = T>,
811        Tag: 'static,
812        T: 'static,
813    {
814        KeyPath::new(|tagged: &Tagged<Tag, T>| tagged.deref())
815    }
816
817    #[cfg(feature = "tagged")]
818    /// Create a writable keypath for accessing the inner value of Tagged<Tag, T>
819    /// Tagged implements DerefMut, so we can access the inner value directly
820    pub fn for_tagged_mut<Tag, T>() -> WritableKeyPath<Tagged<Tag, T>, T, impl for<'r> Fn(&'r mut Tagged<Tag, T>) -> &'r mut T>
821    where
822        Tagged<Tag, T>: std::ops::DerefMut<Target = T>,
823        Tag: 'static,
824        T: 'static,
825    {
826        WritableKeyPath::new(|tagged: &mut Tagged<Tag, T>| tagged.deref_mut())
827    }
828}
829
830// OptionalKeyPath for Option<T>
831#[derive(Clone)]
832pub struct OptionalKeyPath<Root, Value, F>
833where
834    F: for<'r> Fn(&'r Root) -> Option<&'r Value>,
835{
836    getter: F,
837    _phantom: PhantomData<(Root, Value)>,
838}
839
840impl<Root, Value, F> OptionalKeyPath<Root, Value, F>
841where
842    F: for<'r> Fn(&'r Root) -> Option<&'r Value>,
843{
844    pub fn new(getter: F) -> Self {
845        Self {
846            getter,
847            _phantom: PhantomData,
848        }
849    }
850    
851    pub fn get<'r>(&self, root: &'r Root) -> Option<&'r Value> {
852        (self.getter)(root)
853    }
854    
855    // Swift-like operator for chaining OptionalKeyPath
856    pub fn then<SubValue, G>(
857        self,
858        next: OptionalKeyPath<Value, SubValue, G>,
859    ) -> OptionalKeyPath<Root, SubValue, impl for<'r> Fn(&'r Root) -> Option<&'r SubValue>>
860    where
861        G: for<'r> Fn(&'r Value) -> Option<&'r SubValue>,
862        F: 'static,
863        G: 'static,
864        Value: 'static,
865    {
866        let first = self.getter;
867        let second = next.getter;
868        
869        OptionalKeyPath::new(move |root: &Root| {
870            first(root).and_then(|value| second(value))
871        })
872    }
873    
874    // Instance methods for unwrapping containers from Option<Container<T>>
875    // Option<Box<T>> -> Option<&T> (type automatically inferred from Value::Target)
876    pub fn for_box<Target>(self) -> OptionalKeyPath<Root, Target, impl for<'r> Fn(&'r Root) -> Option<&'r Target> + 'static>
877    where
878        Value: std::ops::Deref<Target = Target>,
879        F: 'static,
880        Value: 'static,
881    {
882        let getter = self.getter;
883        
884        OptionalKeyPath {
885            getter: move |root: &Root| {
886                getter(root).map(|boxed| boxed.deref())
887            },
888            _phantom: PhantomData,
889        }
890    }
891    
892    // Option<Arc<T>> -> Option<&T> (type automatically inferred from Value::Target)
893    pub fn for_arc<Target>(self) -> OptionalKeyPath<Root, Target, impl for<'r> Fn(&'r Root) -> Option<&'r Target> + 'static>
894    where
895        Value: std::ops::Deref<Target = Target>,
896        F: 'static,
897        Value: 'static,
898    {
899        let getter = self.getter;
900        
901        OptionalKeyPath {
902            getter: move |root: &Root| {
903                getter(root).map(|arc| arc.deref())
904            },
905            _phantom: PhantomData,
906        }
907    }
908    
909    // Option<Rc<T>> -> Option<&T> (type automatically inferred from Value::Target)
910    pub fn for_rc<Target>(self) -> OptionalKeyPath<Root, Target, impl for<'r> Fn(&'r Root) -> Option<&'r Target> + 'static>
911    where
912        Value: std::ops::Deref<Target = Target>,
913        F: 'static,
914        Value: 'static,
915    {
916        let getter = self.getter;
917        
918        OptionalKeyPath {
919            getter: move |root: &Root| {
920                getter(root).map(|rc| rc.deref())
921            },
922            _phantom: PhantomData,
923        }
924    }
925    
926    #[cfg(feature = "tagged")]
927    /// Adapt this keypath to work with Tagged<Root, Tag> instead of Root
928    /// This unwraps the Tagged wrapper and applies the keypath to the inner value
929    pub fn for_tagged<Tag>(self) -> OptionalKeyPath<Tagged<Root, Tag>, Value, impl for<'r> Fn(&'r Tagged<Root, Tag>) -> Option<&'r Value> + 'static>
930    where
931        Tagged<Root, Tag>: std::ops::Deref<Target = Root>,
932        F: 'static,
933        Root: 'static,
934        Value: 'static,
935        Tag: 'static,
936    {
937        use std::ops::Deref;
938        let getter = self.getter;
939        
940        OptionalKeyPath {
941            getter: move |tagged: &Tagged<Root, Tag>| {
942                getter(tagged.deref())
943            },
944            _phantom: PhantomData,
945        }
946    }
947    
948    #[cfg(feature = "tagged")]
949    /// Execute a closure with a reference to the value inside a Tagged
950    /// This avoids cloning by working with references directly
951    pub fn with_tagged<Tag, Callback, R>(&self, tagged: &Tagged<Root, Tag>, f: Callback) -> Option<R>
952    where
953        Tagged<Root, Tag>: std::ops::Deref<Target = Root>,
954        F: Clone,
955        Callback: FnOnce(&Value) -> R,
956    {
957        use std::ops::Deref;
958        self.get(tagged.deref()).map(|value| f(value))
959    }
960    
961    /// Adapt this keypath to work with Option<Root> instead of Root
962    /// This unwraps the Option and applies the keypath to the inner value
963    pub fn for_option(self) -> OptionalKeyPath<Option<Root>, Value, impl for<'r> Fn(&'r Option<Root>) -> Option<&'r Value> + 'static>
964    where
965        F: 'static,
966        Root: 'static,
967        Value: 'static,
968    {
969        let getter = self.getter;
970        
971        OptionalKeyPath {
972            getter: move |opt: &Option<Root>| {
973                opt.as_ref().and_then(|root| getter(root))
974            },
975            _phantom: PhantomData,
976        }
977    }
978    
979    /// Adapt this keypath to work with Result<Root, E> instead of Root
980    /// This unwraps the Result and applies the keypath to the Ok value
981    pub fn for_result<E>(self) -> OptionalKeyPath<Result<Root, E>, Value, impl for<'r> Fn(&'r Result<Root, E>) -> Option<&'r Value> + 'static>
982    where
983        F: 'static,
984        Root: 'static,
985        Value: 'static,
986        E: 'static,
987    {
988        let getter = self.getter;
989        
990        OptionalKeyPath {
991            getter: move |result: &Result<Root, E>| {
992                result.as_ref().ok().and_then(|root| getter(root))
993            },
994            _phantom: PhantomData,
995        }
996    }
997    
998    // Overload: Adapt root type to Arc<Root> when Value is Sized (not a container)
999    pub fn for_arc_root(self) -> OptionalKeyPath<Arc<Root>, Value, impl for<'r> Fn(&'r Arc<Root>) -> Option<&'r Value> + 'static>
1000    where
1001        Value: Sized,
1002        F: 'static,
1003        Root: 'static,
1004        Value: 'static,
1005    {
1006        let getter = self.getter;
1007        
1008        OptionalKeyPath {
1009            getter: move |arc: &Arc<Root>| {
1010                getter(arc.as_ref())
1011            },
1012            _phantom: PhantomData,
1013        }
1014    }
1015    
1016    // Overload: Adapt root type to Rc<Root> when Value is Sized (not a container)
1017    pub fn for_rc_root(self) -> OptionalKeyPath<Rc<Root>, Value, impl for<'r> Fn(&'r Rc<Root>) -> Option<&'r Value> + 'static>
1018    where
1019        Value: Sized,
1020        F: 'static,
1021        Root: 'static,
1022        Value: 'static,
1023    {
1024        let getter = self.getter;
1025        
1026        OptionalKeyPath {
1027            getter: move |rc: &Rc<Root>| {
1028                getter(rc.as_ref())
1029            },
1030            _phantom: PhantomData,
1031        }
1032    }
1033    
1034    /// Execute a closure with a reference to the value inside an Option
1035    pub fn with_option<Callback, R>(&self, option: &Option<Root>, f: Callback) -> Option<R>
1036    where
1037        F: Clone,
1038        Callback: FnOnce(&Value) -> R,
1039    {
1040        option.as_ref().and_then(|root| {
1041            self.get(root).map(|value| f(value))
1042        })
1043    }
1044    
1045    /// Execute a closure with a reference to the value inside a Mutex
1046    pub fn with_mutex<Callback, R>(&self, mutex: &Mutex<Root>, f: Callback) -> Option<R>
1047    where
1048        F: Clone,
1049        Callback: FnOnce(&Value) -> R,
1050    {
1051        mutex.lock().ok().and_then(|guard| {
1052            self.get(&*guard).map(|value| f(value))
1053        })
1054    }
1055    
1056    /// Execute a closure with a reference to the value inside an RwLock
1057    pub fn with_rwlock<Callback, R>(&self, rwlock: &RwLock<Root>, f: Callback) -> Option<R>
1058    where
1059        F: Clone,
1060        Callback: FnOnce(&Value) -> R,
1061    {
1062        rwlock.read().ok().and_then(|guard| {
1063            self.get(&*guard).map(|value| f(value))
1064        })
1065    }
1066    
1067    /// Execute a closure with a reference to the value inside an Arc<RwLock<Root>>
1068    pub fn with_arc_rwlock<Callback, R>(&self, arc_rwlock: &Arc<RwLock<Root>>, f: Callback) -> Option<R>
1069    where
1070        F: Clone,
1071        Callback: FnOnce(&Value) -> R,
1072    {
1073        arc_rwlock.read().ok().and_then(|guard| {
1074            self.get(&*guard).map(|value| f(value))
1075        })
1076    }
1077    
1078    /// Execute a closure with a reference to the value inside an Arc<RwLock<Root>>
1079    /// This is a convenience method that works directly with Arc<RwLock<T>>
1080    /// Unlike with_arc_rwlock, this doesn't require F: Clone
1081    pub fn with_arc_rwlock_direct<Callback, R>(&self, arc_rwlock: &Arc<RwLock<Root>>, f: Callback) -> Option<R>
1082    where
1083        Callback: FnOnce(&Value) -> R,
1084    {
1085        arc_rwlock.read().ok().and_then(|guard| {
1086            self.get(&*guard).map(|value| f(value))
1087        })
1088    }
1089    
1090    /// Execute a closure with a reference to the value inside an Arc<Mutex<Root>>
1091    pub fn with_arc_mutex<Callback, R>(&self, arc_mutex: &Arc<Mutex<Root>>, f: Callback) -> Option<R>
1092    where
1093        F: Clone,
1094        Callback: FnOnce(&Value) -> R,
1095    {
1096        arc_mutex.lock().ok().and_then(|guard| {
1097            self.get(&*guard).map(|value| f(value))
1098        })
1099    }
1100}
1101
1102
1103// WritableKeyPath for mutable access
1104#[derive(Clone)]
1105pub struct WritableKeyPath<Root, Value, F>
1106where
1107    F: for<'r> Fn(&'r mut Root) -> &'r mut Value,
1108{
1109    getter: F,
1110    _phantom: PhantomData<(Root, Value)>,
1111}
1112
1113impl<Root, Value, F> WritableKeyPath<Root, Value, F>
1114where
1115    F: for<'r> Fn(&'r mut Root) -> &'r mut Value,
1116{
1117    pub fn new(getter: F) -> Self {
1118        Self {
1119            getter,
1120            _phantom: PhantomData,
1121        }
1122    }
1123    
1124    pub fn get_mut<'r>(&self, root: &'r mut Root) -> &'r mut Value {
1125        (self.getter)(root)
1126    }
1127    
1128    /// Adapt this keypath to work with Result<Root, E> instead of Root
1129    /// This unwraps the Result and applies the keypath to the Ok value
1130    pub fn for_result<E>(self) -> WritableOptionalKeyPath<Result<Root, E>, Value, impl for<'r> Fn(&'r mut Result<Root, E>) -> Option<&'r mut Value> + 'static>
1131    where
1132        F: 'static,
1133        Root: 'static,
1134        Value: 'static,
1135        E: 'static,
1136    {
1137        let getter = self.getter;
1138        
1139        WritableOptionalKeyPath {
1140            getter: move |result: &mut Result<Root, E>| {
1141                result.as_mut().ok().map(|root| getter(root))
1142            },
1143            _phantom: PhantomData,
1144        }
1145    }
1146    
1147    // Overload: Adapt root type to Box<Root> when Value is Sized (not a container)
1148    pub fn for_box_root(self) -> WritableKeyPath<Box<Root>, Value, impl for<'r> Fn(&'r mut Box<Root>) -> &'r mut Value + 'static>
1149    where
1150        Value: Sized,
1151        F: 'static,
1152        Root: 'static,
1153        Value: 'static,
1154    {
1155        let getter = self.getter;
1156        
1157        WritableKeyPath {
1158            getter: move |boxed: &mut Box<Root>| {
1159                getter(boxed.as_mut())
1160            },
1161            _phantom: PhantomData,
1162        }
1163    }
1164    
1165    /// Adapt this keypath to work with Option<Root> instead of Root
1166    /// This unwraps the Option and applies the keypath to the Some value
1167    pub fn for_option(self) -> WritableOptionalKeyPath<Option<Root>, Value, impl for<'r> Fn(&'r mut Option<Root>) -> Option<&'r mut Value> + 'static>
1168    where
1169        F: 'static,
1170        Root: 'static,
1171        Value: 'static,
1172    {
1173        let getter = self.getter;
1174        
1175        WritableOptionalKeyPath {
1176            getter: move |option: &mut Option<Root>| {
1177                option.as_mut().map(|root| getter(root))
1178            },
1179            _phantom: PhantomData,
1180        }
1181    }
1182    
1183    /// Convert a WritableKeyPath to WritableOptionalKeyPath for chaining
1184    /// This allows non-optional writable keypaths to be chained with then()
1185    pub fn to_optional(self) -> WritableOptionalKeyPath<Root, Value, impl for<'r> Fn(&'r mut Root) -> Option<&'r mut Value> + 'static>
1186    where
1187        F: 'static,
1188    {
1189        let getter = self.getter;
1190        WritableOptionalKeyPath::new(move |root: &mut Root| Some(getter(root)))
1191    }
1192    
1193    // Instance methods for unwrapping containers (automatically infers Target from Value::Target)
1194    // Box<T> -> T
1195    pub fn for_box<Target>(self) -> WritableKeyPath<Root, Target, impl for<'r> Fn(&'r mut Root) -> &'r mut Target + 'static>
1196    where
1197        Value: std::ops::DerefMut<Target = Target>,
1198        F: 'static,
1199        Value: 'static,
1200    {
1201        let getter = self.getter;
1202        
1203        WritableKeyPath {
1204            getter: move |root: &mut Root| {
1205                getter(root).deref_mut()
1206            },
1207            _phantom: PhantomData,
1208        }
1209    }
1210    
1211    // Arc<T> -> T (Note: Arc doesn't support mutable access, but we provide it for consistency)
1212    // This will require interior mutability patterns
1213    pub fn for_arc<Target>(self) -> WritableKeyPath<Root, Target, impl for<'r> Fn(&'r mut Root) -> &'r mut Target + 'static>
1214    where
1215        Value: std::ops::DerefMut<Target = Target>,
1216        F: 'static,
1217        Value: 'static,
1218    {
1219        let getter = self.getter;
1220        
1221        WritableKeyPath {
1222            getter: move |root: &mut Root| {
1223                getter(root).deref_mut()
1224            },
1225            _phantom: PhantomData,
1226        }
1227    }
1228    
1229    // Rc<T> -> T (Note: Rc doesn't support mutable access, but we provide it for consistency)
1230    // This will require interior mutability patterns
1231    pub fn for_rc<Target>(self) -> WritableKeyPath<Root, Target, impl for<'r> Fn(&'r mut Root) -> &'r mut Target + 'static>
1232    where
1233        Value: std::ops::DerefMut<Target = Target>,
1234        F: 'static,
1235        Value: 'static,
1236    {
1237        let getter = self.getter;
1238        
1239        WritableKeyPath {
1240            getter: move |root: &mut Root| {
1241                getter(root).deref_mut()
1242            },
1243            _phantom: PhantomData,
1244        }
1245    }
1246    
1247    /// Execute a closure with a mutable reference to the value inside a Box
1248    pub fn with_box_mut<Callback, R>(&self, boxed: &mut Box<Root>, f: Callback) -> R
1249    where
1250        F: Clone,
1251        Callback: FnOnce(&mut Value) -> R,
1252    {
1253        let value = self.get_mut(boxed);
1254        f(value)
1255    }
1256    
1257    /// Execute a closure with a mutable reference to the value inside a Result
1258    pub fn with_result_mut<Callback, R, E>(&self, result: &mut Result<Root, E>, f: Callback) -> Option<R>
1259    where
1260        F: Clone,
1261        Callback: FnOnce(&mut Value) -> R,
1262    {
1263        result.as_mut().ok().map(|root| {
1264            let value = self.get_mut(root);
1265            f(value)
1266        })
1267    }
1268    
1269    /// Execute a closure with a mutable reference to the value inside an Option
1270    pub fn with_option_mut<Callback, R>(&self, option: &mut Option<Root>, f: Callback) -> Option<R>
1271    where
1272        F: Clone,
1273        Callback: FnOnce(&mut Value) -> R,
1274    {
1275        option.as_mut().map(|root| {
1276            let value = self.get_mut(root);
1277            f(value)
1278        })
1279    }
1280    
1281    /// Execute a closure with a mutable reference to the value inside a RefCell
1282    pub fn with_refcell_mut<Callback, R>(&self, refcell: &RefCell<Root>, f: Callback) -> Option<R>
1283    where
1284        F: Clone,
1285        Callback: FnOnce(&mut Value) -> R,
1286    {
1287        refcell.try_borrow_mut().ok().map(|mut borrow| {
1288            let value = self.get_mut(&mut *borrow);
1289            f(value)
1290        })
1291    }
1292    
1293    /// Execute a closure with a mutable reference to the value inside a Mutex
1294    pub fn with_mutex_mut<Callback, R>(&self, mutex: &mut Mutex<Root>, f: Callback) -> Option<R>
1295    where
1296        F: Clone,
1297        Callback: FnOnce(&mut Value) -> R,
1298    {
1299        mutex.get_mut().ok().map(|root| {
1300            let value = self.get_mut(root);
1301            f(value)
1302        })
1303    }
1304    
1305    /// Execute a closure with a mutable reference to the value inside an RwLock
1306    pub fn with_rwlock_mut<Callback, R>(&self, rwlock: &mut RwLock<Root>, f: Callback) -> Option<R>
1307    where
1308        F: Clone,
1309        Callback: FnOnce(&mut Value) -> R,
1310    {
1311        rwlock.write().ok().map(|mut guard| {
1312            let value = self.get_mut(&mut *guard);
1313            f(value)
1314        })
1315    }
1316    
1317    /// Get a mutable iterator over a Vec when Value is Vec<T>
1318    /// Returns Some(iterator) if the value is a Vec, None otherwise
1319    pub fn iter_mut<'r, T>(&self, root: &'r mut Root) -> Option<std::slice::IterMut<'r, T>>
1320    where
1321        Value: AsMut<[T]> + 'r,
1322    {
1323        let value_ref: &'r mut Value = self.get_mut(root);
1324        Some(value_ref.as_mut().iter_mut())
1325    }
1326    
1327    /// Extract mutable values from a slice of owned mutable values
1328    /// Returns a Vec of mutable references to the extracted values
1329    pub fn extract_mut_from_slice<'r>(&self, slice: &'r mut [Root]) -> Vec<&'r mut Value> {
1330        slice.iter_mut().map(|item| self.get_mut(item)).collect()
1331    }
1332    
1333    /// Extract mutable values from a slice of mutable references
1334    /// Returns a Vec of mutable references to the extracted values
1335    pub fn extract_mut_from_ref_slice<'r>(&self, slice: &'r mut [&'r mut Root]) -> Vec<&'r mut Value> {
1336        slice.iter_mut().map(|item| self.get_mut(*item)).collect()
1337    }
1338    
1339    /// Chain this keypath with another writable keypath
1340    /// Returns a WritableKeyPath that chains both keypaths
1341    pub fn then<SubValue, G>(
1342        self,
1343        next: WritableKeyPath<Value, SubValue, G>,
1344    ) -> WritableKeyPath<Root, SubValue, impl for<'r> Fn(&'r mut Root) -> &'r mut SubValue>
1345    where
1346        G: for<'r> Fn(&'r mut Value) -> &'r mut SubValue,
1347        F: 'static,
1348        G: 'static,
1349        Value: 'static,
1350    {
1351        let first = self.getter;
1352        let second = next.getter;
1353        
1354        WritableKeyPath::new(move |root: &mut Root| {
1355            let value = first(root);
1356            second(value)
1357        })
1358    }
1359    
1360    /// Chain this keypath with a writable optional keypath
1361    /// Returns a WritableOptionalKeyPath that chains both keypaths
1362    pub fn then_optional<SubValue, G>(
1363        self,
1364        next: WritableOptionalKeyPath<Value, SubValue, G>,
1365    ) -> WritableOptionalKeyPath<Root, SubValue, impl for<'r> Fn(&'r mut Root) -> Option<&'r mut SubValue>>
1366    where
1367        G: for<'r> Fn(&'r mut Value) -> Option<&'r mut SubValue>,
1368        F: 'static,
1369        G: 'static,
1370        Value: 'static,
1371    {
1372        let first = self.getter;
1373        let second = next.getter;
1374        
1375        WritableOptionalKeyPath::new(move |root: &mut Root| {
1376            let value = first(root);
1377            second(value)
1378        })
1379    }
1380}
1381
1382// WritableOptionalKeyPath for failable mutable access
1383#[derive(Clone)]
1384pub struct WritableOptionalKeyPath<Root, Value, F>
1385where
1386    F: for<'r> Fn(&'r mut Root) -> Option<&'r mut Value>,
1387{
1388    getter: F,
1389    _phantom: PhantomData<(Root, Value)>,
1390}
1391
1392impl<Root, Value, F> WritableOptionalKeyPath<Root, Value, F>
1393where
1394    F: for<'r> Fn(&'r mut Root) -> Option<&'r mut Value>,
1395{
1396    pub fn new(getter: F) -> Self {
1397        Self {
1398            getter,
1399            _phantom: PhantomData,
1400        }
1401    }
1402    
1403    pub fn get_mut<'r>(&self, root: &'r mut Root) -> Option<&'r mut Value> {
1404        (self.getter)(root)
1405    }
1406    
1407    /// Adapt this keypath to work with Option<Root> instead of Root
1408    /// This unwraps the Option and applies the keypath to the Some value
1409    pub fn for_option(self) -> WritableOptionalKeyPath<Option<Root>, Value, impl for<'r> Fn(&'r mut Option<Root>) -> Option<&'r mut Value> + 'static>
1410    where
1411        F: 'static,
1412        Root: 'static,
1413        Value: 'static,
1414    {
1415        let getter = self.getter;
1416        
1417        WritableOptionalKeyPath {
1418            getter: move |option: &mut Option<Root>| {
1419                option.as_mut().and_then(|root| getter(root))
1420            },
1421            _phantom: PhantomData,
1422        }
1423    }
1424    
1425    // Swift-like operator for chaining WritableOptionalKeyPath
1426    pub fn then<SubValue, G>(
1427        self,
1428        next: WritableOptionalKeyPath<Value, SubValue, G>,
1429    ) -> WritableOptionalKeyPath<Root, SubValue, impl for<'r> Fn(&'r mut Root) -> Option<&'r mut SubValue>>
1430    where
1431        G: for<'r> Fn(&'r mut Value) -> Option<&'r mut SubValue>,
1432        F: 'static,
1433        G: 'static,
1434        Value: 'static,
1435    {
1436        let first = self.getter;
1437        let second = next.getter;
1438        
1439        WritableOptionalKeyPath::new(move |root: &mut Root| {
1440            first(root).and_then(|value| second(value))
1441        })
1442    }
1443    
1444    // Instance methods for unwrapping containers from Option<Container<T>>
1445    // Option<Box<T>> -> Option<&mut T> (type automatically inferred from Value::Target)
1446    pub fn for_box<Target>(self) -> WritableOptionalKeyPath<Root, Target, impl for<'r> Fn(&'r mut Root) -> Option<&'r mut Target> + 'static>
1447    where
1448        Value: std::ops::DerefMut<Target = Target>,
1449        F: 'static,
1450        Value: 'static,
1451    {
1452        let getter = self.getter;
1453        
1454        WritableOptionalKeyPath {
1455            getter: move |root: &mut Root| {
1456                getter(root).map(|boxed| boxed.deref_mut())
1457            },
1458            _phantom: PhantomData,
1459        }
1460    }
1461    
1462    // Option<Arc<T>> -> Option<&mut T> (type automatically inferred from Value::Target)
1463    pub fn for_arc<Target>(self) -> WritableOptionalKeyPath<Root, Target, impl for<'r> Fn(&'r mut Root) -> Option<&'r mut Target> + 'static>
1464    where
1465        Value: std::ops::DerefMut<Target = Target>,
1466        F: 'static,
1467        Value: 'static,
1468    {
1469        let getter = self.getter;
1470        
1471        WritableOptionalKeyPath {
1472            getter: move |root: &mut Root| {
1473                getter(root).map(|arc| arc.deref_mut())
1474            },
1475            _phantom: PhantomData,
1476        }
1477    }
1478    
1479    // Option<Rc<T>> -> Option<&mut T> (type automatically inferred from Value::Target)
1480    pub fn for_rc<Target>(self) -> WritableOptionalKeyPath<Root, Target, impl for<'r> Fn(&'r mut Root) -> Option<&'r mut Target> + 'static>
1481    where
1482        Value: std::ops::DerefMut<Target = Target>,
1483        F: 'static,
1484        Value: 'static,
1485    {
1486        let getter = self.getter;
1487        
1488        WritableOptionalKeyPath {
1489            getter: move |root: &mut Root| {
1490                getter(root).map(|rc| rc.deref_mut())
1491            },
1492            _phantom: PhantomData,
1493        }
1494    }
1495    
1496    /// Adapt this keypath to work with Result<Root, E> instead of Root
1497    /// This unwraps the Result and applies the keypath to the Ok value
1498    pub fn for_result<E>(self) -> WritableOptionalKeyPath<Result<Root, E>, Value, impl for<'r> Fn(&'r mut Result<Root, E>) -> Option<&'r mut Value> + 'static>
1499    where
1500        F: 'static,
1501        Root: 'static,
1502        Value: 'static,
1503        E: 'static,
1504    {
1505        let getter = self.getter;
1506        
1507        WritableOptionalKeyPath {
1508            getter: move |result: &mut Result<Root, E>| {
1509                result.as_mut().ok().and_then(|root| getter(root))
1510            },
1511            _phantom: PhantomData,
1512        }
1513    }
1514    
1515    // Overload: Adapt root type to Box<Root> when Value is Sized (not a container)
1516    pub fn for_box_root(self) -> WritableOptionalKeyPath<Box<Root>, Value, impl for<'r> Fn(&'r mut Box<Root>) -> Option<&'r mut Value> + 'static>
1517    where
1518        Value: Sized,
1519        F: 'static,
1520        Root: 'static,
1521        Value: 'static,
1522    {
1523        let getter = self.getter;
1524        
1525        WritableOptionalKeyPath {
1526            getter: move |boxed: &mut Box<Root>| {
1527                getter(boxed.as_mut())
1528            },
1529            _phantom: PhantomData,
1530        }
1531    }
1532    
1533    // Overload: Adapt root type to Arc<Root> when Value is Sized (not a container)
1534    pub fn for_arc_root(self) -> WritableOptionalKeyPath<Arc<Root>, Value, impl for<'r> Fn(&'r mut Arc<Root>) -> Option<&'r mut Value> + 'static>
1535    where
1536        Value: Sized,
1537        F: 'static,
1538        Root: 'static,
1539        Value: 'static,
1540    {
1541        let getter = self.getter;
1542        
1543        WritableOptionalKeyPath {
1544            getter: move |arc: &mut Arc<Root>| {
1545                // Arc doesn't support mutable access without interior mutability
1546                // This will always return None, but we provide it for API consistency
1547                None
1548            },
1549            _phantom: PhantomData,
1550        }
1551    }
1552    
1553    // Overload: Adapt root type to Rc<Root> when Value is Sized (not a container)
1554    pub fn for_rc_root(self) -> WritableOptionalKeyPath<Rc<Root>, Value, impl for<'r> Fn(&'r mut Rc<Root>) -> Option<&'r mut Value> + 'static>
1555    where
1556        Value: Sized,
1557        F: 'static,
1558        Root: 'static,
1559        Value: 'static,
1560    {
1561        let getter = self.getter;
1562        
1563        WritableOptionalKeyPath {
1564            getter: move |rc: &mut Rc<Root>| {
1565                // Rc doesn't support mutable access without interior mutability
1566                // This will always return None, but we provide it for API consistency
1567                None
1568            },
1569            _phantom: PhantomData,
1570        }
1571    }
1572}
1573
1574// Static factory methods for WritableOptionalKeyPath
1575impl WritableOptionalKeyPath<(), (), fn(&mut ()) -> Option<&mut ()>> {
1576    // Static method for Option<T> -> Option<&mut T>
1577    // Note: This is a factory method. Use instance method `for_option()` to adapt existing keypaths.
1578    pub fn for_option_static<T>() -> WritableOptionalKeyPath<Option<T>, T, impl for<'r> Fn(&'r mut Option<T>) -> Option<&'r mut T>> {
1579        WritableOptionalKeyPath::new(|opt: &mut Option<T>| opt.as_mut())
1580    }
1581    
1582    /// Backword compatibility method for writable enum keypath
1583    // Create a writable enum keypath for enum variants
1584    /// This allows both reading and writing to enum variant fields
1585    /// 
1586    /// # Arguments
1587    /// * `embedder` - Function to embed a value into the enum variant (for API consistency, not used)
1588    /// * `read_extractor` - Function to extract a read reference from the enum (for API consistency, not used)
1589    /// * `write_extractor` - Function to extract a mutable reference from the enum
1590    /// 
1591    /// # Example
1592    /// ```rust
1593    /// enum Color { Other(RGBU8) }
1594    /// struct RGBU8(u8, u8, u8);
1595    /// 
1596    /// let case_path = WritableOptionalKeyPath::writable_enum(
1597    ///     |v| Color::Other(v),
1598    ///     |p: &Color| match p { Color::Other(rgb) => Some(rgb), _ => None },
1599    ///     |p: &mut Color| match p { Color::Other(rgb) => Some(rgb), _ => None },
1600    /// );
1601    /// ```
1602    pub fn writable_enum<Enum, Variant, EmbedFn, ReadExtractFn, WriteExtractFn>(
1603        _embedder: EmbedFn,
1604        _read_extractor: ReadExtractFn,
1605        write_extractor: WriteExtractFn,
1606    ) -> WritableOptionalKeyPath<Enum, Variant, impl for<'r> Fn(&'r mut Enum) -> Option<&'r mut Variant> + 'static>
1607    where
1608        EmbedFn: Fn(Variant) -> Enum + 'static,
1609        ReadExtractFn: for<'r> Fn(&'r Enum) -> Option<&'r Variant> + 'static,
1610        WriteExtractFn: for<'r> Fn(&'r mut Enum) -> Option<&'r mut Variant> + 'static,
1611    {
1612        WritableOptionalKeyPath::new(write_extractor)
1613    }
1614}
1615
1616// Enum-specific keypaths
1617/// EnumKeyPath - A keypath for enum variants that supports both extraction and embedding
1618/// Uses generic type parameters instead of dynamic dispatch for zero-cost abstraction
1619/// 
1620/// This struct serves dual purpose:
1621/// 1. As a concrete keypath instance: `EnumKeyPath<Enum, Variant, ExtractFn, EmbedFn>`
1622/// 2. As a namespace for static factory methods: `EnumKeyPath::readable_enum(...)`
1623pub struct EnumKeyPath<Enum = (), Variant = (), ExtractFn = fn(&()) -> Option<&()>, EmbedFn = fn(()) -> ()> 
1624where
1625    ExtractFn: for<'r> Fn(&'r Enum) -> Option<&'r Variant> + 'static,
1626    EmbedFn: Fn(Variant) -> Enum + 'static,
1627{
1628    extractor: OptionalKeyPath<Enum, Variant, ExtractFn>,
1629    embedder: EmbedFn,
1630}
1631
1632impl<Enum, Variant, ExtractFn, EmbedFn> EnumKeyPath<Enum, Variant, ExtractFn, EmbedFn>
1633where
1634    ExtractFn: for<'r> Fn(&'r Enum) -> Option<&'r Variant> + 'static,
1635    EmbedFn: Fn(Variant) -> Enum + 'static,
1636{
1637    /// Create a new EnumKeyPath with extractor and embedder functions
1638    pub fn new(
1639        extractor: ExtractFn,
1640        embedder: EmbedFn,
1641    ) -> Self {
1642        Self {
1643            extractor: OptionalKeyPath::new(extractor),
1644            embedder,
1645        }
1646    }
1647    
1648    /// Extract the value from an enum variant
1649    pub fn get<'r>(&self, enum_value: &'r Enum) -> Option<&'r Variant> {
1650        self.extractor.get(enum_value)
1651    }
1652    
1653    /// Embed a value into the enum variant
1654    pub fn embed(&self, value: Variant) -> Enum {
1655        (self.embedder)(value)
1656    }
1657    
1658    /// Get the underlying OptionalKeyPath for composition
1659    pub fn as_optional(&self) -> &OptionalKeyPath<Enum, Variant, ExtractFn> {
1660        &self.extractor
1661    }
1662    
1663    /// Convert to OptionalKeyPath (loses embedding capability but gains composition)
1664    pub fn to_optional(self) -> OptionalKeyPath<Enum, Variant, ExtractFn> {
1665        self.extractor
1666    }
1667}
1668
1669// Static factory methods for EnumKeyPath
1670impl EnumKeyPath {
1671    /// Create a readable enum keypath with both extraction and embedding
1672    /// Returns an EnumKeyPath that supports both get() and embed() operations
1673    pub fn readable_enum<Enum, Variant, ExtractFn, EmbedFn>(
1674        embedder: EmbedFn,
1675        extractor: ExtractFn,
1676    ) -> EnumKeyPath<Enum, Variant, ExtractFn, EmbedFn>
1677    where
1678        ExtractFn: for<'r> Fn(&'r Enum) -> Option<&'r Variant> + 'static,
1679        EmbedFn: Fn(Variant) -> Enum + 'static,
1680    {
1681        EnumKeyPath::new(extractor, embedder)
1682    }
1683    
1684    /// Extract from a specific enum variant
1685    pub fn for_variant<Enum, Variant, ExtractFn>(
1686        extractor: ExtractFn
1687    ) -> OptionalKeyPath<Enum, Variant, impl for<'r> Fn(&'r Enum) -> Option<&'r Variant>>
1688    where
1689        ExtractFn: Fn(&Enum) -> Option<&Variant>,
1690    {
1691        OptionalKeyPath::new(extractor)
1692    }
1693    
1694    /// Match against multiple variants (returns a tagged union)
1695    pub fn for_match<Enum, Output, MatchFn>(
1696        matcher: MatchFn
1697    ) -> KeyPath<Enum, Output, impl for<'r> Fn(&'r Enum) -> &'r Output>
1698    where
1699        MatchFn: Fn(&Enum) -> &Output,
1700    {
1701        KeyPath::new(matcher)
1702    }
1703    
1704    /// Extract from Result<T, E> - Ok variant
1705    pub fn for_ok<T, E>() -> OptionalKeyPath<Result<T, E>, T, impl for<'r> Fn(&'r Result<T, E>) -> Option<&'r T>> {
1706        OptionalKeyPath::new(|result: &Result<T, E>| result.as_ref().ok())
1707    }
1708    
1709    /// Extract from Result<T, E> - Err variant
1710    pub fn for_err<T, E>() -> OptionalKeyPath<Result<T, E>, E, impl for<'r> Fn(&'r Result<T, E>) -> Option<&'r E>> {
1711        OptionalKeyPath::new(|result: &Result<T, E>| result.as_ref().err())
1712    }
1713    
1714    /// Extract from Option<T> - Some variant
1715    pub fn for_some<T>() -> OptionalKeyPath<Option<T>, T, impl for<'r> Fn(&'r Option<T>) -> Option<&'r T>> {
1716        OptionalKeyPath::new(|opt: &Option<T>| opt.as_ref())
1717    }
1718    
1719    /// Extract from Option<T> - Some variant (alias for for_some for consistency)
1720    pub fn for_option<T>() -> OptionalKeyPath<Option<T>, T, impl for<'r> Fn(&'r Option<T>) -> Option<&'r T>> {
1721        OptionalKeyPath::new(|opt: &Option<T>| opt.as_ref())
1722    }
1723    
1724    /// Unwrap Box<T> -> T
1725    pub fn for_box<T>() -> KeyPath<Box<T>, T, impl for<'r> Fn(&'r Box<T>) -> &'r T> {
1726        KeyPath::new(|b: &Box<T>| b.as_ref())
1727    }
1728    
1729    /// Unwrap Arc<T> -> T
1730    pub fn for_arc<T>() -> KeyPath<Arc<T>, T, impl for<'r> Fn(&'r Arc<T>) -> &'r T> {
1731        KeyPath::new(|arc: &Arc<T>| arc.as_ref())
1732    }
1733    
1734    /// Unwrap Rc<T> -> T
1735    pub fn for_rc<T>() -> KeyPath<std::rc::Rc<T>, T, impl for<'r> Fn(&'r std::rc::Rc<T>) -> &'r T> {
1736        KeyPath::new(|rc: &std::rc::Rc<T>| rc.as_ref())
1737    }
1738
1739    /// Unwrap Box<T> -> T (mutable)
1740    pub fn for_box_mut<T>() -> WritableKeyPath<Box<T>, T, impl for<'r> Fn(&'r mut Box<T>) -> &'r mut T> {
1741        WritableKeyPath::new(|b: &mut Box<T>| b.as_mut())
1742    }
1743
1744    // Note: Arc<T> and Rc<T> don't support direct mutable access without interior mutability
1745    // (e.g., Arc<Mutex<T>> or Rc<RefCell<T>>). These methods are not provided as they
1746    // would require unsafe code or interior mutability patterns.
1747}
1748
1749// Helper to create enum variant keypaths with type inference
1750pub fn variant_of<Enum, Variant, F>(extractor: F) -> OptionalKeyPath<Enum, Variant, F>
1751where
1752    F: for<'r> Fn(&'r Enum) -> Option<&'r Variant>,
1753{
1754    OptionalKeyPath::new(extractor)
1755}
1756
1757// ========== PARTIAL KEYPATHS (Hide Value Type) ==========
1758
1759/// PartialKeyPath - Hides the Value type but keeps Root visible
1760/// Useful for storing keypaths in collections without knowing the exact Value type
1761/// 
1762/// # Why PhantomData<Root>?
1763/// 
1764/// `PhantomData<Root>` is needed because:
1765/// 1. The `Root` type parameter is not actually stored in the struct (only used in the closure)
1766/// 2. Rust needs to know the generic type parameter for:
1767///    - Type checking at compile time
1768///    - Ensuring correct usage (e.g., `PartialKeyPath<User>` can only be used with `&User`)
1769///    - Preventing mixing different Root types
1770/// 3. Without `PhantomData`, Rust would complain that `Root` is unused
1771/// 4. `PhantomData` is zero-sized - it adds no runtime overhead
1772#[derive(Clone)]
1773pub struct PartialKeyPath<Root> {
1774    getter: Rc<dyn for<'r> Fn(&'r Root) -> &'r dyn Any>,
1775    value_type_id: TypeId,
1776    _phantom: PhantomData<Root>,
1777}
1778
1779impl<Root> PartialKeyPath<Root> {
1780    pub fn new<Value>(keypath: KeyPath<Root, Value, impl for<'r> Fn(&'r Root) -> &'r Value + 'static>) -> Self
1781    where
1782        Value: Any + 'static,
1783        Root: 'static,
1784    {
1785        let value_type_id = TypeId::of::<Value>();
1786        let getter = Rc::new(keypath.getter);
1787        
1788        Self {
1789            getter: Rc::new(move |root: &Root| {
1790                let value: &Value = getter(root);
1791                value as &dyn Any
1792            }),
1793            value_type_id,
1794            _phantom: PhantomData,
1795        }
1796    }
1797    
1798    /// Create a PartialKeyPath from a concrete KeyPath
1799    /// Alias for `new()` for consistency with `from()` pattern
1800    pub fn from<Value>(keypath: KeyPath<Root, Value, impl for<'r> Fn(&'r Root) -> &'r Value + 'static>) -> Self
1801    where
1802        Value: Any + 'static,
1803        Root: 'static,
1804    {
1805        Self::new(keypath)
1806    }
1807    
1808    pub fn get<'r>(&self, root: &'r Root) -> &'r dyn Any {
1809        (self.getter)(root)
1810    }
1811    
1812    /// Get the TypeId of the Value type
1813    pub fn value_type_id(&self) -> TypeId {
1814        self.value_type_id
1815    }
1816    
1817    /// Try to downcast the result to a specific type
1818    pub fn get_as<'a, Value: Any>(&self, root: &'a Root) -> Option<&'a Value> {
1819        if self.value_type_id == TypeId::of::<Value>() {
1820            self.get(root).downcast_ref::<Value>()
1821        } else {
1822            None
1823        }
1824    }
1825    
1826    /// Get a human-readable name for the value type
1827    /// Returns a string representation of the TypeId
1828    pub fn kind_name(&self) -> String {
1829        format!("{:?}", self.value_type_id)
1830    }
1831    
1832    /// Adapt this keypath to work with Arc<Root> instead of Root
1833    pub fn for_arc(&self) -> PartialOptionalKeyPath<Arc<Root>>
1834    where
1835        Root: 'static,
1836    {
1837        let getter = self.getter.clone();
1838        let value_type_id = self.value_type_id;
1839        
1840        PartialOptionalKeyPath {
1841            getter: Rc::new(move |arc: &Arc<Root>| {
1842                Some(getter(arc.as_ref()))
1843            }),
1844            value_type_id,
1845            _phantom: PhantomData,
1846        }
1847    }
1848    
1849    /// Adapt this keypath to work with Box<Root> instead of Root
1850    pub fn for_box(&self) -> PartialOptionalKeyPath<Box<Root>>
1851    where
1852        Root: 'static,
1853    {
1854        let getter = self.getter.clone();
1855        let value_type_id = self.value_type_id;
1856        
1857        PartialOptionalKeyPath {
1858            getter: Rc::new(move |boxed: &Box<Root>| {
1859                Some(getter(boxed.as_ref()))
1860            }),
1861            value_type_id,
1862            _phantom: PhantomData,
1863        }
1864    }
1865    
1866    /// Adapt this keypath to work with Rc<Root> instead of Root
1867    pub fn for_rc(&self) -> PartialOptionalKeyPath<Rc<Root>>
1868    where
1869        Root: 'static,
1870    {
1871        let getter = self.getter.clone();
1872        let value_type_id = self.value_type_id;
1873        
1874        PartialOptionalKeyPath {
1875            getter: Rc::new(move |rc: &Rc<Root>| {
1876                Some(getter(rc.as_ref()))
1877            }),
1878            value_type_id,
1879            _phantom: PhantomData,
1880        }
1881    }
1882    
1883    /// Adapt this keypath to work with Option<Root> instead of Root
1884    pub fn for_option(&self) -> PartialOptionalKeyPath<Option<Root>>
1885    where
1886        Root: 'static,
1887    {
1888        let getter = self.getter.clone();
1889        let value_type_id = self.value_type_id;
1890        
1891        PartialOptionalKeyPath {
1892            getter: Rc::new(move |opt: &Option<Root>| {
1893                opt.as_ref().map(|root| getter(root))
1894            }),
1895            value_type_id,
1896            _phantom: PhantomData,
1897        }
1898    }
1899    
1900    /// Adapt this keypath to work with Result<Root, E> instead of Root
1901    pub fn for_result<E>(&self) -> PartialOptionalKeyPath<Result<Root, E>>
1902    where
1903        Root: 'static,
1904        E: 'static,
1905    {
1906        let getter = self.getter.clone();
1907        let value_type_id = self.value_type_id;
1908        
1909        PartialOptionalKeyPath {
1910            getter: Rc::new(move |result: &Result<Root, E>| {
1911                result.as_ref().ok().map(|root| getter(root))
1912            }),
1913            value_type_id,
1914            _phantom: PhantomData,
1915        }
1916    }
1917    
1918    /// Adapt this keypath to work with Arc<RwLock<Root>> instead of Root
1919    /// Note: This requires the Root to be cloned first, then use the keypath on the cloned value
1920    /// Example: `keypath.get_as::<Value>(&arc_rwlock.read().unwrap().clone())`
1921    pub fn for_arc_rwlock(&self) -> PartialOptionalKeyPath<Arc<RwLock<Root>>>
1922    where
1923        Root: Clone + 'static,
1924    {
1925        // We can't return a reference from a guard, so we return None
1926        // Users should clone the root first: arc_rwlock.read().unwrap().clone()
1927        PartialOptionalKeyPath {
1928            getter: Rc::new(move |_arc_rwlock: &Arc<RwLock<Root>>| {
1929                // Cannot return reference from temporary guard
1930                // User should clone the root first and use the keypath on the cloned value
1931                None
1932            }),
1933            value_type_id: self.value_type_id,
1934            _phantom: PhantomData,
1935        }
1936    }
1937    
1938    /// Adapt this keypath to work with Arc<Mutex<Root>> instead of Root
1939    /// Note: This requires the Root to be cloned first, then use the keypath on the cloned value
1940    /// Example: `keypath.get_as::<Value>(&arc_mutex.lock().unwrap().clone())`
1941    pub fn for_arc_mutex(&self) -> PartialOptionalKeyPath<Arc<Mutex<Root>>>
1942    where
1943        Root: Clone + 'static,
1944    {
1945        // We can't return a reference from a guard, so we return None
1946        // Users should clone the root first: arc_mutex.lock().unwrap().clone()
1947        PartialOptionalKeyPath {
1948            getter: Rc::new(move |_arc_mutex: &Arc<Mutex<Root>>| {
1949                // Cannot return reference from temporary guard
1950                // User should clone the root first and use the keypath on the cloned value
1951                None
1952            }),
1953            value_type_id: self.value_type_id,
1954            _phantom: PhantomData,
1955        }
1956    }
1957}
1958
1959/// PartialOptionalKeyPath - Hides the Value type but keeps Root visible
1960/// Useful for storing optional keypaths in collections without knowing the exact Value type
1961/// 
1962/// # Why PhantomData<Root>?
1963/// 
1964/// See `PartialKeyPath` documentation for explanation of why `PhantomData` is needed.
1965#[derive(Clone)]
1966pub struct PartialOptionalKeyPath<Root> {
1967    getter: Rc<dyn for<'r> Fn(&'r Root) -> Option<&'r dyn Any>>,
1968    value_type_id: TypeId,
1969    _phantom: PhantomData<Root>,
1970}
1971
1972impl<Root> PartialOptionalKeyPath<Root> {
1973    pub fn new<Value>(keypath: OptionalKeyPath<Root, Value, impl for<'r> Fn(&'r Root) -> Option<&'r Value> + 'static>) -> Self
1974    where
1975        Value: Any + 'static,
1976        Root: 'static,
1977    {
1978        let value_type_id = TypeId::of::<Value>();
1979        let getter = Rc::new(keypath.getter);
1980        
1981        Self {
1982            getter: Rc::new(move |root: &Root| {
1983                getter(root).map(|value: &Value| value as &dyn Any)
1984            }),
1985            value_type_id,
1986            _phantom: PhantomData,
1987        }
1988    }
1989    
1990    pub fn get<'r>(&self, root: &'r Root) -> Option<&'r dyn Any> {
1991        (self.getter)(root)
1992    }
1993    
1994    /// Get the TypeId of the Value type
1995    pub fn value_type_id(&self) -> TypeId {
1996        self.value_type_id
1997    }
1998    
1999    /// Try to downcast the result to a specific type
2000    pub fn get_as<'a, Value: Any>(&self, root: &'a Root) -> Option<Option<&'a Value>> {
2001        if self.value_type_id == TypeId::of::<Value>() {
2002            self.get(root).map(|any| any.downcast_ref::<Value>())
2003        } else {
2004            None
2005        }
2006    }
2007    
2008    /// Chain with another PartialOptionalKeyPath
2009    /// Note: This requires the Value type of the first keypath to match the Root type of the second
2010    /// For type-erased chaining, consider using AnyKeyPath instead
2011    pub fn then<MidValue>(
2012        self,
2013        next: PartialOptionalKeyPath<MidValue>,
2014    ) -> PartialOptionalKeyPath<Root>
2015    where
2016        MidValue: Any + 'static,
2017        Root: 'static,
2018    {
2019        let first = self.getter;
2020        let second = next.getter;
2021        let value_type_id = next.value_type_id;
2022        
2023        PartialOptionalKeyPath {
2024            getter: Rc::new(move |root: &Root| {
2025                first(root).and_then(|any| {
2026                    if let Some(mid_value) = any.downcast_ref::<MidValue>() {
2027                        second(mid_value)
2028                    } else {
2029                        None
2030                    }
2031                })
2032            }),
2033            value_type_id,
2034            _phantom: PhantomData,
2035        }
2036    }
2037}
2038
2039/// PartialWritableKeyPath - Hides the Value type but keeps Root visible (writable)
2040/// 
2041/// # Why PhantomData<Root>?
2042/// 
2043/// See `PartialKeyPath` documentation for explanation of why `PhantomData` is needed.
2044#[derive(Clone)]
2045pub struct PartialWritableKeyPath<Root> {
2046    getter: Rc<dyn for<'r> Fn(&'r mut Root) -> &'r mut dyn Any>,
2047    value_type_id: TypeId,
2048    _phantom: PhantomData<Root>,
2049}
2050
2051impl<Root> PartialWritableKeyPath<Root> {
2052    pub fn new<Value>(keypath: WritableKeyPath<Root, Value, impl for<'r> Fn(&'r mut Root) -> &'r mut Value + 'static>) -> Self
2053    where
2054        Value: Any + 'static,
2055        Root: 'static,
2056    {
2057        let value_type_id = TypeId::of::<Value>();
2058        let getter = Rc::new(keypath.getter);
2059        
2060        Self {
2061            getter: Rc::new(move |root: &mut Root| {
2062                let value: &mut Value = getter(root);
2063                value as &mut dyn Any
2064            }),
2065            value_type_id,
2066            _phantom: PhantomData,
2067        }
2068    }
2069    
2070    /// Create a PartialWritableKeyPath from a concrete WritableKeyPath
2071    /// Alias for `new()` for consistency with `from()` pattern
2072    pub fn from<Value>(keypath: WritableKeyPath<Root, Value, impl for<'r> Fn(&'r mut Root) -> &'r mut Value + 'static>) -> Self
2073    where
2074        Value: Any + 'static,
2075        Root: 'static,
2076    {
2077        Self::new(keypath)
2078    }
2079    
2080    pub fn get_mut<'r>(&self, root: &'r mut Root) -> &'r mut dyn Any {
2081        (self.getter)(root)
2082    }
2083    
2084    /// Get the TypeId of the Value type
2085    pub fn value_type_id(&self) -> TypeId {
2086        self.value_type_id
2087    }
2088    
2089    /// Try to downcast the result to a specific type
2090    pub fn get_mut_as<'a, Value: Any>(&self, root: &'a mut Root) -> Option<&'a mut Value> {
2091        if self.value_type_id == TypeId::of::<Value>() {
2092            self.get_mut(root).downcast_mut::<Value>()
2093        } else {
2094            None
2095        }
2096    }
2097}
2098
2099/// PartialWritableOptionalKeyPath - Hides the Value type but keeps Root visible (writable optional)
2100/// 
2101/// # Why PhantomData<Root>?
2102/// 
2103/// See `PartialKeyPath` documentation for explanation of why `PhantomData` is needed.
2104#[derive(Clone)]
2105pub struct PartialWritableOptionalKeyPath<Root> {
2106    getter: Rc<dyn for<'r> Fn(&'r mut Root) -> Option<&'r mut dyn Any>>,
2107    value_type_id: TypeId,
2108    _phantom: PhantomData<Root>,
2109}
2110
2111impl<Root> PartialWritableOptionalKeyPath<Root> {
2112    pub fn new<Value>(keypath: WritableOptionalKeyPath<Root, Value, impl for<'r> Fn(&'r mut Root) -> Option<&'r mut Value> + 'static>) -> Self
2113    where
2114        Value: Any + 'static,
2115        Root: 'static,
2116    {
2117        let value_type_id = TypeId::of::<Value>();
2118        let getter = Rc::new(keypath.getter);
2119        
2120        Self {
2121            getter: Rc::new(move |root: &mut Root| {
2122                getter(root).map(|value: &mut Value| value as &mut dyn Any)
2123            }),
2124            value_type_id,
2125            _phantom: PhantomData,
2126        }
2127    }
2128    
2129    pub fn get_mut<'r>(&self, root: &'r mut Root) -> Option<&'r mut dyn Any> {
2130        (self.getter)(root)
2131    }
2132    
2133    /// Get the TypeId of the Value type
2134    pub fn value_type_id(&self) -> TypeId {
2135        self.value_type_id
2136    }
2137    
2138    /// Try to downcast the result to a specific type
2139    pub fn get_mut_as<'a, Value: Any>(&self, root: &'a mut Root) -> Option<Option<&'a mut Value>> {
2140        if self.value_type_id == TypeId::of::<Value>() {
2141            self.get_mut(root).map(|any| any.downcast_mut::<Value>())
2142        } else {
2143            None
2144        }
2145    }
2146}
2147
2148// ========== ANY KEYPATHS (Hide Both Root and Value Types) ==========
2149
2150/// AnyKeyPath - Hides both Root and Value types
2151/// Equivalent to Swift's AnyKeyPath
2152/// Useful for storing keypaths in collections without knowing either type
2153/// 
2154/// # Why No PhantomData?
2155/// 
2156/// Unlike `PartialKeyPath`, `AnyKeyPath` doesn't need `PhantomData` because:
2157/// - Both `Root` and `Value` types are completely erased
2158/// - We store `TypeId` instead for runtime type checking
2159/// - The type information is encoded in the closure's behavior, not the struct
2160/// - There's no generic type parameter to track at compile time
2161#[derive(Clone)]
2162pub struct AnyKeyPath {
2163    getter: Rc<dyn for<'r> Fn(&'r dyn Any) -> Option<&'r dyn Any>>,
2164    root_type_id: TypeId,
2165    value_type_id: TypeId,
2166}
2167
2168impl AnyKeyPath {
2169    pub fn new<Root, Value>(keypath: OptionalKeyPath<Root, Value, impl for<'r> Fn(&'r Root) -> Option<&'r Value> + 'static>) -> Self
2170    where
2171        Root: Any + 'static,
2172        Value: Any + 'static,
2173    {
2174        let root_type_id = TypeId::of::<Root>();
2175        let value_type_id = TypeId::of::<Value>();
2176        let getter = keypath.getter;
2177        
2178        Self {
2179            getter: Rc::new(move |any: &dyn Any| {
2180                if let Some(root) = any.downcast_ref::<Root>() {
2181                    getter(root).map(|value: &Value| value as &dyn Any)
2182                } else {
2183                    None
2184                }
2185            }),
2186            root_type_id,
2187            value_type_id,
2188        }
2189    }
2190    
2191    /// Create an AnyKeyPath from a concrete OptionalKeyPath
2192    /// Alias for `new()` for consistency with `from()` pattern
2193    pub fn from<Root, Value>(keypath: OptionalKeyPath<Root, Value, impl for<'r> Fn(&'r Root) -> Option<&'r Value> + 'static>) -> Self
2194    where
2195        Root: Any + 'static,
2196        Value: Any + 'static,
2197    {
2198        Self::new(keypath)
2199    }
2200    
2201    pub fn get<'r>(&self, root: &'r dyn Any) -> Option<&'r dyn Any> {
2202        (self.getter)(root)
2203    }
2204    
2205    /// Get the TypeId of the Root type
2206    pub fn root_type_id(&self) -> TypeId {
2207        self.root_type_id
2208    }
2209    
2210    /// Get the TypeId of the Value type
2211    pub fn value_type_id(&self) -> TypeId {
2212        self.value_type_id
2213    }
2214    
2215    /// Try to get the value with type checking
2216    pub fn get_as<'a, Root: Any, Value: Any>(&self, root: &'a Root) -> Option<Option<&'a Value>> {
2217        if self.root_type_id == TypeId::of::<Root>() && self.value_type_id == TypeId::of::<Value>() {
2218            self.get(root as &dyn Any).map(|any| any.downcast_ref::<Value>())
2219        } else {
2220            None
2221        }
2222    }
2223    
2224    /// Get a human-readable name for the value type
2225    /// Returns a string representation of the TypeId
2226    pub fn kind_name(&self) -> String {
2227        format!("{:?}", self.value_type_id)
2228    }
2229    
2230    /// Adapt this keypath to work with Arc<Root> instead of Root
2231    pub fn for_arc<Root>(&self) -> AnyKeyPath
2232    where
2233        Root: Any + 'static,
2234    {
2235        let root_type_id = self.root_type_id;
2236        let value_type_id = self.value_type_id;
2237        let getter = self.getter.clone();
2238        
2239        AnyKeyPath {
2240            getter: Rc::new(move |any: &dyn Any| {
2241                if let Some(arc) = any.downcast_ref::<Arc<Root>>() {
2242                    getter(arc.as_ref() as &dyn Any)
2243                } else {
2244                    None
2245                }
2246            }),
2247            root_type_id: TypeId::of::<Arc<Root>>(),
2248            value_type_id,
2249        }
2250    }
2251    
2252    /// Adapt this keypath to work with Box<Root> instead of Root
2253    pub fn for_box<Root>(&self) -> AnyKeyPath
2254    where
2255        Root: Any + 'static,
2256    {
2257        let root_type_id = self.root_type_id;
2258        let value_type_id = self.value_type_id;
2259        let getter = self.getter.clone();
2260        
2261        AnyKeyPath {
2262            getter: Rc::new(move |any: &dyn Any| {
2263                if let Some(boxed) = any.downcast_ref::<Box<Root>>() {
2264                    getter(boxed.as_ref() as &dyn Any)
2265                } else {
2266                    None
2267                }
2268            }),
2269            root_type_id: TypeId::of::<Box<Root>>(),
2270            value_type_id,
2271        }
2272    }
2273    
2274    /// Adapt this keypath to work with Rc<Root> instead of Root
2275    pub fn for_rc<Root>(&self) -> AnyKeyPath
2276    where
2277        Root: Any + 'static,
2278    {
2279        let root_type_id = self.root_type_id;
2280        let value_type_id = self.value_type_id;
2281        let getter = self.getter.clone();
2282        
2283        AnyKeyPath {
2284            getter: Rc::new(move |any: &dyn Any| {
2285                if let Some(rc) = any.downcast_ref::<Rc<Root>>() {
2286                    getter(rc.as_ref() as &dyn Any)
2287                } else {
2288                    None
2289                }
2290            }),
2291            root_type_id: TypeId::of::<Rc<Root>>(),
2292            value_type_id,
2293        }
2294    }
2295    
2296    /// Adapt this keypath to work with Option<Root> instead of Root
2297    pub fn for_option<Root>(&self) -> AnyKeyPath
2298    where
2299        Root: Any + 'static,
2300    {
2301        let root_type_id = self.root_type_id;
2302        let value_type_id = self.value_type_id;
2303        let getter = self.getter.clone();
2304        
2305        AnyKeyPath {
2306            getter: Rc::new(move |any: &dyn Any| {
2307                if let Some(opt) = any.downcast_ref::<Option<Root>>() {
2308                    opt.as_ref().and_then(|root| getter(root as &dyn Any))
2309                } else {
2310                    None
2311                }
2312            }),
2313            root_type_id: TypeId::of::<Option<Root>>(),
2314            value_type_id,
2315        }
2316    }
2317    
2318    /// Adapt this keypath to work with Result<Root, E> instead of Root
2319    pub fn for_result<Root, E>(&self) -> AnyKeyPath
2320    where
2321        Root: Any + 'static,
2322        E: Any + 'static,
2323    {
2324        let root_type_id = self.root_type_id;
2325        let value_type_id = self.value_type_id;
2326        let getter = self.getter.clone();
2327        
2328        AnyKeyPath {
2329            getter: Rc::new(move |any: &dyn Any| {
2330                if let Some(result) = any.downcast_ref::<Result<Root, E>>() {
2331                    result.as_ref().ok().and_then(|root| getter(root as &dyn Any))
2332                } else {
2333                    None
2334                }
2335            }),
2336            root_type_id: TypeId::of::<Result<Root, E>>(),
2337            value_type_id,
2338        }
2339    }
2340    
2341    /// Adapt this keypath to work with Arc<RwLock<Root>> instead of Root
2342    /// Note: This requires the Root to be cloned first, then use the keypath on the cloned value
2343    pub fn for_arc_rwlock<Root>(&self) -> AnyKeyPath
2344    where
2345        Root: Any + Clone + 'static,
2346    {
2347        // We can't return a reference from a guard, so we return None
2348        // Users should clone the root first
2349        AnyKeyPath {
2350            getter: Rc::new(move |_any: &dyn Any| {
2351                // Cannot return reference from temporary guard
2352                // User should clone the root first and use the keypath on the cloned value
2353                None
2354            }),
2355            root_type_id: TypeId::of::<Arc<RwLock<Root>>>(),
2356            value_type_id: self.value_type_id,
2357        }
2358    }
2359    
2360    /// Adapt this keypath to work with Arc<Mutex<Root>> instead of Root
2361    /// Note: This requires the Root to be cloned first, then use the keypath on the cloned value
2362    pub fn for_arc_mutex<Root>(&self) -> AnyKeyPath
2363    where
2364        Root: Any + Clone + 'static,
2365    {
2366        // We can't return a reference from a guard, so we return None
2367        // Users should clone the root first
2368        AnyKeyPath {
2369            getter: Rc::new(move |_any: &dyn Any| {
2370                // Cannot return reference from temporary guard
2371                // User should clone the root first and use the keypath on the cloned value
2372                None
2373            }),
2374            root_type_id: TypeId::of::<Arc<Mutex<Root>>>(),
2375            value_type_id: self.value_type_id,
2376        }
2377    }
2378}
2379
2380/// AnyWritableKeyPath - Hides both Root and Value types (writable)
2381#[derive(Clone)]
2382pub struct AnyWritableKeyPath {
2383    getter: Rc<dyn for<'r> Fn(&'r mut dyn Any) -> Option<&'r mut dyn Any>>,
2384    root_type_id: TypeId,
2385    value_type_id: TypeId,
2386}
2387
2388/// FailableCombinedKeyPath - A keypath that supports readable, writable, and owned access patterns
2389/// 
2390/// This keypath type combines the functionality of OptionalKeyPath, WritableOptionalKeyPath,
2391/// and adds owned access. It's useful when you need all three access patterns for the same field.
2392#[derive(Clone)]
2393pub struct FailableCombinedKeyPath<Root, Value, ReadFn, WriteFn, OwnedFn>
2394where
2395    ReadFn: for<'r> Fn(&'r Root) -> Option<&'r Value> + 'static,
2396    WriteFn: for<'r> Fn(&'r mut Root) -> Option<&'r mut Value> + 'static,
2397    OwnedFn: Fn(Root) -> Option<Value> + 'static,
2398{
2399    readable: ReadFn,
2400    writable: WriteFn,
2401    owned: OwnedFn,
2402    _phantom: PhantomData<(Root, Value)>,
2403}
2404
2405impl<Root, Value, ReadFn, WriteFn, OwnedFn> FailableCombinedKeyPath<Root, Value, ReadFn, WriteFn, OwnedFn>
2406where
2407    ReadFn: for<'r> Fn(&'r Root) -> Option<&'r Value> + 'static,
2408    WriteFn: for<'r> Fn(&'r mut Root) -> Option<&'r mut Value> + 'static,
2409    OwnedFn: Fn(Root) -> Option<Value> + 'static,
2410{
2411    /// Create a new FailableCombinedKeyPath with all three access patterns
2412    pub fn new(readable: ReadFn, writable: WriteFn, owned: OwnedFn) -> Self {
2413        Self {
2414            readable,
2415            writable,
2416            owned,
2417            _phantom: PhantomData,
2418        }
2419    }
2420    
2421    /// Get an immutable reference to the value (readable access)
2422    pub fn get<'r>(&self, root: &'r Root) -> Option<&'r Value> {
2423        (self.readable)(root)
2424    }
2425    
2426    /// Get a mutable reference to the value (writable access)
2427    pub fn get_mut<'r>(&self, root: &'r mut Root) -> Option<&'r mut Value> {
2428        (self.writable)(root)
2429    }
2430    
2431    /// Get an owned value (owned access) - consumes the root
2432    pub fn get_failable_owned(&self, root: Root) -> Option<Value> {
2433        (self.owned)(root)
2434    }
2435    
2436    /// Convert to OptionalKeyPath (loses writable and owned capabilities)
2437    pub fn to_optional(self) -> OptionalKeyPath<Root, Value, ReadFn> {
2438        OptionalKeyPath::new(self.readable)
2439    }
2440    
2441    /// Convert to WritableOptionalKeyPath (loses owned capability)
2442    pub fn to_writable_optional(self) -> WritableOptionalKeyPath<Root, Value, WriteFn> {
2443        WritableOptionalKeyPath::new(self.writable)
2444    }
2445    
2446    /// Compose this keypath with another FailableCombinedKeyPath
2447    /// Returns a new FailableCombinedKeyPath that chains both keypaths
2448    pub fn then<SubValue, SubReadFn, SubWriteFn, SubOwnedFn>(
2449        self,
2450        next: FailableCombinedKeyPath<Value, SubValue, SubReadFn, SubWriteFn, SubOwnedFn>,
2451    ) -> FailableCombinedKeyPath<Root, SubValue, impl for<'r> Fn(&'r Root) -> Option<&'r SubValue> + 'static, impl for<'r> Fn(&'r mut Root) -> Option<&'r mut SubValue> + 'static, impl Fn(Root) -> Option<SubValue> + 'static>
2452    where
2453        SubReadFn: for<'r> Fn(&'r Value) -> Option<&'r SubValue> + 'static,
2454        SubWriteFn: for<'r> Fn(&'r mut Value) -> Option<&'r mut SubValue> + 'static,
2455        SubOwnedFn: Fn(Value) -> Option<SubValue> + 'static,
2456        ReadFn: 'static,
2457        WriteFn: 'static,
2458        OwnedFn: 'static,
2459        Value: 'static,
2460        Root: 'static,
2461        SubValue: 'static,
2462    {
2463        let first_read = self.readable;
2464        let first_write = self.writable;
2465        let first_owned = self.owned;
2466        let second_read = next.readable;
2467        let second_write = next.writable;
2468        let second_owned = next.owned;
2469        
2470        FailableCombinedKeyPath::new(
2471            move |root: &Root| {
2472                first_read(root).and_then(|value| second_read(value))
2473            },
2474            move |root: &mut Root| {
2475                first_write(root).and_then(|value| second_write(value))
2476            },
2477            move |root: Root| {
2478                first_owned(root).and_then(|value| second_owned(value))
2479            },
2480        )
2481    }
2482    
2483    /// Compose with OptionalKeyPath (readable only)
2484    /// Returns a FailableCombinedKeyPath that uses the readable from OptionalKeyPath
2485    /// and creates dummy writable/owned closures that return None
2486    pub fn then_optional<SubValue, SubReadFn>(
2487        self,
2488        next: OptionalKeyPath<Value, SubValue, SubReadFn>,
2489    ) -> FailableCombinedKeyPath<Root, SubValue, impl for<'r> Fn(&'r Root) -> Option<&'r SubValue> + 'static, impl for<'r> Fn(&'r mut Root) -> Option<&'r mut SubValue> + 'static, impl Fn(Root) -> Option<SubValue> + 'static>
2490    where
2491        SubReadFn: for<'r> Fn(&'r Value) -> Option<&'r SubValue> + 'static,
2492        ReadFn: 'static,
2493        WriteFn: 'static,
2494        OwnedFn: 'static,
2495        Value: 'static,
2496        Root: 'static,
2497        SubValue: 'static,
2498    {
2499        let first_read = self.readable;
2500        let first_write = self.writable;
2501        let first_owned = self.owned;
2502        let second_read = next.getter;
2503        
2504        FailableCombinedKeyPath::new(
2505            move |root: &Root| {
2506                first_read(root).and_then(|value| second_read(value))
2507            },
2508            move |_root: &mut Root| {
2509                None // Writable not supported when composing with OptionalKeyPath
2510            },
2511            move |root: Root| {
2512                first_owned(root).and_then(|value| {
2513                    // Try to get owned value, but OptionalKeyPath doesn't support owned
2514                    None
2515                })
2516            },
2517        )
2518    }
2519}
2520
2521// Factory function for FailableCombinedKeyPath
2522impl FailableCombinedKeyPath<(), (), fn(&()) -> Option<&()>, fn(&mut ()) -> Option<&mut ()>, fn(()) -> Option<()>> {
2523    /// Create a FailableCombinedKeyPath with all three access patterns
2524    pub fn failable_combined<Root, Value, ReadFn, WriteFn, OwnedFn>(
2525        readable: ReadFn,
2526        writable: WriteFn,
2527        owned: OwnedFn,
2528    ) -> FailableCombinedKeyPath<Root, Value, ReadFn, WriteFn, OwnedFn>
2529    where
2530        ReadFn: for<'r> Fn(&'r Root) -> Option<&'r Value> + 'static,
2531        WriteFn: for<'r> Fn(&'r mut Root) -> Option<&'r mut Value> + 'static,
2532        OwnedFn: Fn(Root) -> Option<Value> + 'static,
2533    {
2534        FailableCombinedKeyPath::new(readable, writable, owned)
2535    }
2536}
2537
2538impl AnyWritableKeyPath {
2539    pub fn new<Root, Value>(keypath: WritableOptionalKeyPath<Root, Value, impl for<'r> Fn(&'r mut Root) -> Option<&'r mut Value> + 'static>) -> Self
2540    where
2541        Root: Any + 'static,
2542        Value: Any + 'static,
2543    {
2544        let root_type_id = TypeId::of::<Root>();
2545        let value_type_id = TypeId::of::<Value>();
2546        let getter = keypath.getter;
2547        
2548        Self {
2549            getter: Rc::new(move |any: &mut dyn Any| {
2550                if let Some(root) = any.downcast_mut::<Root>() {
2551                    getter(root).map(|value: &mut Value| value as &mut dyn Any)
2552                } else {
2553                    None
2554                }
2555            }),
2556            root_type_id,
2557            value_type_id,
2558        }
2559    }
2560    
2561    pub fn get_mut<'r>(&self, root: &'r mut dyn Any) -> Option<&'r mut dyn Any> {
2562        (self.getter)(root)
2563    }
2564    
2565    /// Get the TypeId of the Root type
2566    pub fn root_type_id(&self) -> TypeId {
2567        self.root_type_id
2568    }
2569    
2570    /// Get the TypeId of the Value type
2571    pub fn value_type_id(&self) -> TypeId {
2572        self.value_type_id
2573    }
2574    
2575    /// Try to get the value with type checking
2576    pub fn get_mut_as<'a, Root: Any, Value: Any>(&self, root: &'a mut Root) -> Option<Option<&'a mut Value>> {
2577        if self.root_type_id == TypeId::of::<Root>() && self.value_type_id == TypeId::of::<Value>() {
2578            self.get_mut(root as &mut dyn Any).map(|any| any.downcast_mut::<Value>())
2579        } else {
2580            None
2581        }
2582    }
2583}
2584
2585// Conversion methods from concrete keypaths to partial/any keypaths
2586impl<Root, Value, F> KeyPath<Root, Value, F>
2587where
2588    F: for<'r> Fn(&'r Root) -> &'r Value + 'static,
2589    Root: 'static,
2590    Value: Any + 'static,
2591{
2592    /// Convert to PartialKeyPath (hides Value type)
2593    pub fn to_partial(self) -> PartialKeyPath<Root> {
2594        PartialKeyPath::new(self)
2595    }
2596    
2597    /// Alias for `to_partial()` - converts to PartialKeyPath
2598    pub fn to(self) -> PartialKeyPath<Root> {
2599        self.to_partial()
2600    }
2601}
2602
2603impl<Root, Value, F> OptionalKeyPath<Root, Value, F>
2604where
2605    F: for<'r> Fn(&'r Root) -> Option<&'r Value> + 'static,
2606    Root: Any + 'static,
2607    Value: Any + 'static,
2608{
2609    /// Convert to PartialOptionalKeyPath (hides Value type)
2610    pub fn to_partial(self) -> PartialOptionalKeyPath<Root> {
2611        PartialOptionalKeyPath::new(self)
2612    }
2613    
2614    /// Convert to AnyKeyPath (hides both Root and Value types)
2615    pub fn to_any(self) -> AnyKeyPath {
2616        AnyKeyPath::new(self)
2617    }
2618    
2619    /// Convert to PartialOptionalKeyPath (alias for `to_partial()`)
2620    pub fn to(self) -> PartialOptionalKeyPath<Root> {
2621        self.to_partial()
2622    }
2623}
2624
2625impl<Root, Value, F> WritableKeyPath<Root, Value, F>
2626where
2627    F: for<'r> Fn(&'r mut Root) -> &'r mut Value + 'static,
2628    Root: 'static,
2629    Value: Any + 'static,
2630{
2631    /// Convert to PartialWritableKeyPath (hides Value type)
2632    pub fn to_partial(self) -> PartialWritableKeyPath<Root> {
2633        PartialWritableKeyPath::new(self)
2634    }
2635    
2636    /// Alias for `to_partial()` - converts to PartialWritableKeyPath
2637    pub fn to(self) -> PartialWritableKeyPath<Root> {
2638        self.to_partial()
2639    }
2640}
2641
2642impl<Root, Value, F> WritableOptionalKeyPath<Root, Value, F>
2643where
2644    F: for<'r> Fn(&'r mut Root) -> Option<&'r mut Value> + 'static,
2645    Root: Any + 'static,
2646    Value: Any + 'static,
2647{
2648    /// Convert to PartialWritableOptionalKeyPath (hides Value type)
2649    pub fn to_partial(self) -> PartialWritableOptionalKeyPath<Root> {
2650        PartialWritableOptionalKeyPath::new(self)
2651    }
2652    
2653    /// Convert to AnyWritableKeyPath (hides both Root and Value types)
2654    pub fn to_any(self) -> AnyWritableKeyPath {
2655        AnyWritableKeyPath::new(self)
2656    }
2657    
2658    /// Convert to PartialWritableOptionalKeyPath (alias for `to_partial()`)
2659    pub fn to(self) -> PartialWritableOptionalKeyPath<Root> {
2660        self.to_partial()
2661    }
2662}
2663
2664// ========== SHR OPERATOR IMPLEMENTATIONS (>> operator) ==========
2665// 
2666// The `>>` operator provides the same functionality as `then()` methods.
2667// It requires nightly Rust with the `nightly` feature enabled.
2668//
2669// Usage example (requires nightly):
2670// ```rust
2671// #![feature(impl_trait_in_assoc_type)]  // Must be in YOUR code
2672// use rust_keypaths::{keypath, KeyPath};
2673// 
2674// struct User { address: Address }
2675// struct Address { street: String }
2676// 
2677// let kp1 = keypath!(|u: &User| &u.address);
2678// let kp2 = keypath!(|a: &Address| &a.street);
2679// let chained = kp1 >> kp2; // Works with nightly feature
2680// ```
2681//
2682// On stable Rust, use `keypath1.then(keypath2)` instead.
2683//
2684// Supported combinations (same as `then()` methods):
2685// - `KeyPath >> KeyPath` → `KeyPath`
2686// - `KeyPath >> OptionalKeyPath` → `OptionalKeyPath`
2687// - `OptionalKeyPath >> OptionalKeyPath` → `OptionalKeyPath`
2688// - `WritableKeyPath >> WritableKeyPath` → `WritableKeyPath`
2689// - `WritableKeyPath >> WritableOptionalKeyPath` → `WritableOptionalKeyPath`
2690// - `WritableOptionalKeyPath >> WritableOptionalKeyPath` → `WritableOptionalKeyPath`
2691
2692#[cfg(feature = "nightly")]
2693mod shr_impls {
2694    use super::*;
2695    
2696    // Implement Shr for KeyPath >> KeyPath: returns KeyPath
2697    impl<Root, Value, F, SubValue, G> Shr<KeyPath<Value, SubValue, G>> for KeyPath<Root, Value, F>
2698    where
2699        F: for<'r> Fn(&'r Root) -> &'r Value + 'static,
2700        G: for<'r> Fn(&'r Value) -> &'r SubValue + 'static,
2701        Value: 'static,
2702    {
2703        type Output = KeyPath<Root, SubValue, impl for<'r> Fn(&'r Root) -> &'r SubValue>;
2704        
2705        fn shr(self, rhs: KeyPath<Value, SubValue, G>) -> Self::Output {
2706            self.then(rhs)
2707        }
2708    }
2709    
2710    // Implement Shr for KeyPath >> OptionalKeyPath: returns OptionalKeyPath  
2711    impl<Root, Value, F, SubValue, G> Shr<OptionalKeyPath<Value, SubValue, G>> for KeyPath<Root, Value, F>
2712    where
2713        F: for<'r> Fn(&'r Root) -> &'r Value + 'static,
2714        G: for<'r> Fn(&'r Value) -> Option<&'r SubValue> + 'static,
2715        Value: 'static,
2716    {
2717        type Output = OptionalKeyPath<Root, SubValue, impl for<'r> Fn(&'r Root) -> Option<&'r SubValue>>;
2718        
2719        fn shr(self, rhs: OptionalKeyPath<Value, SubValue, G>) -> Self::Output {
2720            self.then_optional(rhs)
2721        }
2722    }
2723    
2724    // Implement Shr for OptionalKeyPath >> OptionalKeyPath: returns OptionalKeyPath
2725    impl<Root, Value, F, SubValue, G> Shr<OptionalKeyPath<Value, SubValue, G>> for OptionalKeyPath<Root, Value, F>
2726    where
2727        F: for<'r> Fn(&'r Root) -> Option<&'r Value> + 'static,
2728        G: for<'r> Fn(&'r Value) -> Option<&'r SubValue> + 'static,
2729        Value: 'static,
2730    {
2731        type Output = OptionalKeyPath<Root, SubValue, impl for<'r> Fn(&'r Root) -> Option<&'r SubValue>>;
2732        
2733        fn shr(self, rhs: OptionalKeyPath<Value, SubValue, G>) -> Self::Output {
2734            self.then(rhs)
2735        }
2736    }
2737    
2738    // Implement Shr for WritableKeyPath >> WritableKeyPath: returns WritableKeyPath
2739    impl<Root, Value, F, SubValue, G> Shr<WritableKeyPath<Value, SubValue, G>> for WritableKeyPath<Root, Value, F>
2740    where
2741        F: for<'r> Fn(&'r mut Root) -> &'r mut Value + 'static,
2742        G: for<'r> Fn(&'r mut Value) -> &'r mut SubValue + 'static,
2743        Value: 'static,
2744    {
2745        type Output = WritableKeyPath<Root, SubValue, impl for<'r> Fn(&'r mut Root) -> &'r mut SubValue>;
2746        
2747        fn shr(self, rhs: WritableKeyPath<Value, SubValue, G>) -> Self::Output {
2748            self.then(rhs)
2749        }
2750    }
2751    
2752    // Implement Shr for WritableKeyPath >> WritableOptionalKeyPath: returns WritableOptionalKeyPath
2753    impl<Root, Value, F, SubValue, G> Shr<WritableOptionalKeyPath<Value, SubValue, G>> for WritableKeyPath<Root, Value, F>
2754    where
2755        F: for<'r> Fn(&'r mut Root) -> &'r mut Value + 'static,
2756        G: for<'r> Fn(&'r mut Value) -> Option<&'r mut SubValue> + 'static,
2757        Value: 'static,
2758    {
2759        type Output = WritableOptionalKeyPath<Root, SubValue, impl for<'r> Fn(&'r mut Root) -> Option<&'r mut SubValue>>;
2760        
2761        fn shr(self, rhs: WritableOptionalKeyPath<Value, SubValue, G>) -> Self::Output {
2762            self.then_optional(rhs)
2763        }
2764    }
2765    
2766    // Implement Shr for WritableOptionalKeyPath >> WritableOptionalKeyPath: returns WritableOptionalKeyPath
2767    impl<Root, Value, F, SubValue, G> Shr<WritableOptionalKeyPath<Value, SubValue, G>> for WritableOptionalKeyPath<Root, Value, F>
2768    where
2769        F: for<'r> Fn(&'r mut Root) -> Option<&'r mut Value> + 'static,
2770        G: for<'r> Fn(&'r mut Value) -> Option<&'r mut SubValue> + 'static,
2771        Value: 'static,
2772    {
2773        type Output = WritableOptionalKeyPath<Root, SubValue, impl for<'r> Fn(&'r mut Root) -> Option<&'r mut SubValue>>;
2774        
2775        fn shr(self, rhs: WritableOptionalKeyPath<Value, SubValue, G>) -> Self::Output {
2776            self.then(rhs)
2777        }
2778    }
2779}
2780
2781#[cfg(test)]
2782mod tests {
2783    use super::*;
2784    use std::sync::atomic::{AtomicUsize, Ordering};
2785    use std::rc::Rc;
2786
2787    // Global counter to track memory allocations/deallocations
2788    static ALLOC_COUNT: AtomicUsize = AtomicUsize::new(0);
2789    static DEALLOC_COUNT: AtomicUsize = AtomicUsize::new(0);
2790
2791    // Type that panics on clone to detect unwanted cloning
2792    #[derive(Debug)]
2793    struct NoCloneType {
2794        id: usize,
2795        data: String,
2796    }
2797
2798    impl NoCloneType {
2799        fn new(data: String) -> Self {
2800            ALLOC_COUNT.fetch_add(1, Ordering::SeqCst);
2801            Self {
2802                id: ALLOC_COUNT.load(Ordering::SeqCst),
2803                data,
2804            }
2805        }
2806    }
2807
2808    impl Clone for NoCloneType {
2809        fn clone(&self) -> Self {
2810            eprintln!("[DEBUG] NoCloneType should not be cloned! ID: {}", self.id);
2811            unreachable!("NoCloneType should not be cloned! ID: {}", self.id);
2812        }
2813    }
2814
2815    impl Drop for NoCloneType {
2816        fn drop(&mut self) {
2817            DEALLOC_COUNT.fetch_add(1, Ordering::SeqCst);
2818        }
2819    }
2820
2821    // Helper functions for testing memory management
2822    fn reset_memory_counters() {
2823        ALLOC_COUNT.store(0, Ordering::SeqCst);
2824        DEALLOC_COUNT.store(0, Ordering::SeqCst);
2825    }
2826
2827    fn get_alloc_count() -> usize {
2828        ALLOC_COUNT.load(Ordering::SeqCst)
2829    }
2830
2831    fn get_dealloc_count() -> usize {
2832        DEALLOC_COUNT.load(Ordering::SeqCst)
2833    }
2834
2835// Usage example
2836#[derive(Debug)]
2837struct User {
2838    name: String,
2839    metadata: Option<Box<UserMetadata>>,
2840    friends: Vec<Arc<User>>,
2841}
2842
2843#[derive(Debug)]
2844struct UserMetadata {
2845    created_at: String,
2846}
2847
2848fn some_fn() {
2849        let akash = User {
2850        name: "Alice".to_string(),
2851        metadata: Some(Box::new(UserMetadata {
2852            created_at: "2024-01-01".to_string(),
2853        })),
2854        friends: vec![
2855            Arc::new(User {
2856                name: "Bob".to_string(),
2857                metadata: None,
2858                friends: vec![],
2859            }),
2860        ],
2861    };
2862    
2863    // Create keypaths
2864    let name_kp = KeyPath::new(|u: &User| &u.name);
2865    let metadata_kp = OptionalKeyPath::new(|u: &User| u.metadata.as_ref());
2866    let friends_kp = KeyPath::new(|u: &User| &u.friends);
2867    
2868    // Use them
2869        println!("Name: {}", name_kp.get(&akash));
2870    
2871        if let Some(metadata) = metadata_kp.get(&akash) {
2872        println!("Has metadata: {:?}", metadata);
2873    }
2874    
2875    // Access first friend's name
2876        if let Some(first_friend) = akash.friends.get(0) {
2877        println!("First friend: {}", name_kp.get(first_friend));
2878    }
2879    
2880        // Access metadata through Box using for_box()
2881    let created_at_kp = KeyPath::new(|m: &UserMetadata| &m.created_at);
2882    
2883        if let Some(metadata) = akash.metadata.as_ref() {
2884            // Use for_box() to unwrap Box<UserMetadata> to &UserMetadata
2885            let boxed_metadata: &Box<UserMetadata> = metadata;
2886            let unwrapped = boxed_metadata.as_ref();
2887            println!("Created at: {:?}", created_at_kp.get(unwrapped));
2888        }
2889    }
2890
2891    #[test]
2892    fn test_name() {
2893        some_fn();
2894    }
2895    
2896    #[test]
2897    fn test_no_cloning_on_keypath_operations() {
2898        reset_memory_counters();
2899        
2900        // Create a value that panics on clone
2901        let value = NoCloneType::new("test".to_string());
2902        let boxed = Box::new(value);
2903        
2904        // Create keypath - should not clone
2905        let kp = KeyPath::new(|b: &Box<NoCloneType>| b.as_ref());
2906        
2907        // Access value - should not clone
2908        let _ref = kp.get(&boxed);
2909        
2910        // Clone the keypath itself (this is allowed)
2911        let _kp_clone = kp.clone();
2912        
2913        // Access again - should not clone the value
2914        let _ref2 = _kp_clone.get(&boxed);
2915        
2916        // Verify no panics occurred (if we got here, no cloning happened)
2917        assert_eq!(get_alloc_count(), 1);
2918    }
2919    
2920    #[test]
2921    fn test_no_cloning_on_optional_keypath_operations() {
2922        reset_memory_counters();
2923        
2924        let value = NoCloneType::new("test".to_string());
2925        let opt = Some(Box::new(value));
2926        
2927        // Create optional keypath
2928        let okp = OptionalKeyPath::new(|o: &Option<Box<NoCloneType>>| o.as_ref());
2929        
2930        // Access - should not clone
2931        let _ref = okp.get(&opt);
2932        
2933        // Clone keypath (allowed)
2934        let _okp_clone = okp.clone();
2935        
2936        // Chain operations - should not clone values
2937        let chained = okp.then(OptionalKeyPath::new(|b: &Box<NoCloneType>| Some(b.as_ref())));
2938        let _ref2 = chained.get(&opt);
2939        
2940        assert_eq!(get_alloc_count(), 1);
2941    }
2942    
2943    #[test]
2944    fn test_memory_release() {
2945        reset_memory_counters();
2946        
2947        {
2948            let value = NoCloneType::new("test".to_string());
2949            let boxed = Box::new(value);
2950            let kp = KeyPath::new(|b: &Box<NoCloneType>| b.as_ref());
2951            
2952            // Use the keypath
2953            let _ref = kp.get(&boxed);
2954            
2955            // boxed goes out of scope here
2956        }
2957        
2958        // After drop, memory should be released
2959        // Note: This is a best-effort check since drop timing can vary
2960        assert_eq!(get_alloc_count(), 1);
2961        // Deallocation happens when the value is dropped
2962        // We can't reliably test exact timing, but we verify the counter exists
2963    }
2964    
2965    #[test]
2966    fn test_keypath_clone_does_not_clone_underlying_data() {
2967        reset_memory_counters();
2968        
2969        let value = NoCloneType::new("data".to_string());
2970        let rc_value = Rc::new(value);
2971        
2972        // Create keypath
2973        let kp = KeyPath::new(|r: &Rc<NoCloneType>| r.as_ref());
2974        
2975        // Clone keypath multiple times
2976        let kp1 = kp.clone();
2977        let kp2 = kp.clone();
2978        let kp3 = kp1.clone();
2979        
2980        // All should work without cloning the underlying data
2981        let _ref1 = kp.get(&rc_value);
2982        let _ref2 = kp1.get(&rc_value);
2983        let _ref3 = kp2.get(&rc_value);
2984        let _ref4 = kp3.get(&rc_value);
2985        
2986        // Only one allocation should have happened
2987        assert_eq!(get_alloc_count(), 1);
2988    }
2989    
2990    #[test]
2991    fn test_optional_keypath_chaining_no_clone() {
2992        reset_memory_counters();
2993        
2994        let value = NoCloneType::new("value1".to_string());
2995        
2996        struct Container {
2997            inner: Option<Box<NoCloneType>>,
2998        }
2999        
3000        let container = Container {
3001            inner: Some(Box::new(value)),
3002        };
3003        
3004        // Create chained keypath
3005        let kp1 = OptionalKeyPath::new(|c: &Container| c.inner.as_ref());
3006        let kp2 = OptionalKeyPath::new(|b: &Box<NoCloneType>| Some(b.as_ref()));
3007        
3008        // Chain them - should not clone
3009        let chained = kp1.then(kp2);
3010        
3011        // Use chained keypath
3012        let _result = chained.get(&container);
3013        
3014        // Should only have one allocation
3015        assert_eq!(get_alloc_count(), 1);
3016    }
3017    
3018    #[test]
3019    fn test_for_box_no_clone() {
3020        reset_memory_counters();
3021        
3022        let value = NoCloneType::new("test".to_string());
3023        let boxed = Box::new(value);
3024        let opt_boxed = Some(boxed);
3025        
3026        // Create keypath with for_box
3027        let kp = OptionalKeyPath::new(|o: &Option<Box<NoCloneType>>| o.as_ref());
3028        let unwrapped = kp.for_box();
3029        
3030        // Access - should not clone
3031        let _ref = unwrapped.get(&opt_boxed);
3032        
3033        assert_eq!(get_alloc_count(), 1);
3034    }
3035    
3036    // ========== MACRO USAGE EXAMPLES ==========
3037    
3038    #[derive(Debug, PartialEq)]
3039    struct TestUser {
3040        name: String,
3041        age: u32,
3042        metadata: Option<String>,
3043        address: Option<TestAddress>,
3044    }
3045    
3046    #[derive(Debug, PartialEq)]
3047    struct TestAddress {
3048        street: String,
3049        city: String,
3050        country: Option<TestCountry>,
3051    }
3052    
3053    #[derive(Debug, PartialEq)]
3054    struct TestCountry {
3055        name: String,
3056    }
3057    
3058    #[test]
3059    fn test_keypath_macro() {
3060        let user = TestUser {
3061            name: "Alice".to_string(),
3062            age: 30,
3063            metadata: None,
3064            address: None,
3065        };
3066        
3067        // Simple field access using closure
3068        let name_kp = keypath!(|u: &TestUser| &u.name);
3069        assert_eq!(name_kp.get(&user), "Alice");
3070        
3071        // Nested field access
3072        let user_with_address = TestUser {
3073            name: "Bob".to_string(),
3074            age: 25,
3075            metadata: None,
3076            address: Some(TestAddress {
3077                street: "123 Main St".to_string(),
3078                city: "New York".to_string(),
3079                country: None,
3080            }),
3081        };
3082        
3083        let street_kp = keypath!(|u: &TestUser| &u.address.as_ref().unwrap().street);
3084        assert_eq!(street_kp.get(&user_with_address), "123 Main St");
3085        
3086        // Deeper nesting
3087        let user_with_country = TestUser {
3088            name: "Charlie".to_string(),
3089            age: 35,
3090            metadata: None,
3091            address: Some(TestAddress {
3092                street: "456 Oak Ave".to_string(),
3093                city: "London".to_string(),
3094                country: Some(TestCountry {
3095                    name: "UK".to_string(),
3096                }),
3097            }),
3098        };
3099        
3100        let country_name_kp = keypath!(|u: &TestUser| &u.address.as_ref().unwrap().country.as_ref().unwrap().name);
3101        assert_eq!(country_name_kp.get(&user_with_country), "UK");
3102        
3103        // Fallback: using closure
3104        let age_kp = keypath!(|u: &TestUser| &u.age);
3105        assert_eq!(age_kp.get(&user), &30);
3106    }
3107    
3108    #[test]
3109    fn test_opt_keypath_macro() {
3110        let user = TestUser {
3111            name: "Alice".to_string(),
3112            age: 30,
3113            metadata: Some("admin".to_string()),
3114            address: None,
3115        };
3116        
3117        // Simple Option field access using closure
3118        let metadata_kp = opt_keypath!(|u: &TestUser| u.metadata.as_ref());
3119        assert_eq!(metadata_kp.get(&user), Some(&"admin".to_string()));
3120        
3121        // None case
3122        let user_no_metadata = TestUser {
3123            name: "Bob".to_string(),
3124            age: 25,
3125            metadata: None,
3126            address: None,
3127        };
3128        assert_eq!(metadata_kp.get(&user_no_metadata), None);
3129        
3130        // Nested Option access
3131        let user_with_address = TestUser {
3132            name: "Charlie".to_string(),
3133            age: 35,
3134            metadata: None,
3135            address: Some(TestAddress {
3136                street: "789 Pine Rd".to_string(),
3137                city: "Paris".to_string(),
3138                country: None,
3139            }),
3140        };
3141        
3142        let street_kp = opt_keypath!(|u: &TestUser| u.address.as_ref().map(|a| &a.street));
3143        assert_eq!(street_kp.get(&user_with_address), Some(&"789 Pine Rd".to_string()));
3144        
3145        // Deeper nesting through Options
3146        let user_with_country = TestUser {
3147            name: "David".to_string(),
3148            age: 40,
3149            metadata: None,
3150            address: Some(TestAddress {
3151                street: "321 Elm St".to_string(),
3152                city: "Tokyo".to_string(),
3153                country: Some(TestCountry {
3154                    name: "Japan".to_string(),
3155                }),
3156            }),
3157        };
3158        
3159        let country_name_kp = opt_keypath!(|u: &TestUser| u.address.as_ref().and_then(|a| a.country.as_ref().map(|c| &c.name)));
3160        assert_eq!(country_name_kp.get(&user_with_country), Some(&"Japan".to_string()));
3161        
3162        // Fallback: using closure
3163        let metadata_kp2 = opt_keypath!(|u: &TestUser| u.metadata.as_ref());
3164        assert_eq!(metadata_kp2.get(&user), Some(&"admin".to_string()));
3165    }
3166    
3167    #[test]
3168    fn test_writable_keypath_macro() {
3169        let mut user = TestUser {
3170            name: "Alice".to_string(),
3171            age: 30,
3172            metadata: None,
3173            address: None,
3174        };
3175        
3176        // Simple field mutation using closure
3177        let name_kp = writable_keypath!(|u: &mut TestUser| &mut u.name);
3178        *name_kp.get_mut(&mut user) = "Bob".to_string();
3179        assert_eq!(user.name, "Bob");
3180        
3181        // Nested field mutation
3182        let mut user_with_address = TestUser {
3183            name: "Charlie".to_string(),
3184            age: 25,
3185            metadata: None,
3186            address: Some(TestAddress {
3187                street: "123 Main St".to_string(),
3188                city: "New York".to_string(),
3189                country: None,
3190            }),
3191        };
3192        
3193        let street_kp = writable_keypath!(|u: &mut TestUser| &mut u.address.as_mut().unwrap().street);
3194        *street_kp.get_mut(&mut user_with_address) = "456 Oak Ave".to_string();
3195        assert_eq!(user_with_address.address.as_ref().unwrap().street, "456 Oak Ave");
3196        
3197        // Deeper nesting
3198        let mut user_with_country = TestUser {
3199            name: "David".to_string(),
3200            age: 35,
3201            metadata: None,
3202            address: Some(TestAddress {
3203                street: "789 Pine Rd".to_string(),
3204                city: "London".to_string(),
3205                country: Some(TestCountry {
3206                    name: "UK".to_string(),
3207                }),
3208            }),
3209        };
3210        
3211        let country_name_kp = writable_keypath!(|u: &mut TestUser| &mut u.address.as_mut().unwrap().country.as_mut().unwrap().name);
3212        *country_name_kp.get_mut(&mut user_with_country) = "United Kingdom".to_string();
3213        assert_eq!(user_with_country.address.as_ref().unwrap().country.as_ref().unwrap().name, "United Kingdom");
3214        
3215        // Fallback: using closure
3216        let age_kp = writable_keypath!(|u: &mut TestUser| &mut u.age);
3217        *age_kp.get_mut(&mut user) = 31;
3218        assert_eq!(user.age, 31);
3219    }
3220    
3221    #[test]
3222    fn test_writable_opt_keypath_macro() {
3223        let mut user = TestUser {
3224            name: "Alice".to_string(),
3225            age: 30,
3226            metadata: Some("user".to_string()),
3227            address: None,
3228        };
3229        
3230        // Simple Option field mutation using closure
3231        let metadata_kp = writable_opt_keypath!(|u: &mut TestUser| u.metadata.as_mut());
3232        if let Some(metadata) = metadata_kp.get_mut(&mut user) {
3233            *metadata = "admin".to_string();
3234        }
3235        assert_eq!(user.metadata, Some("admin".to_string()));
3236        
3237        // None case - should return None
3238        let mut user_no_metadata = TestUser {
3239            name: "Bob".to_string(),
3240            age: 25,
3241            metadata: None,
3242            address: None,
3243        };
3244        assert_eq!(metadata_kp.get_mut(&mut user_no_metadata), None);
3245        
3246        // Nested Option access
3247        let mut user_with_address = TestUser {
3248            name: "Charlie".to_string(),
3249            age: 35,
3250            metadata: None,
3251            address: Some(TestAddress {
3252                street: "123 Main St".to_string(),
3253                city: "New York".to_string(),
3254                country: None,
3255            }),
3256        };
3257        
3258        let street_kp = writable_opt_keypath!(|u: &mut TestUser| u.address.as_mut().map(|a| &mut a.street));
3259        if let Some(street) = street_kp.get_mut(&mut user_with_address) {
3260            *street = "456 Oak Ave".to_string();
3261        }
3262        assert_eq!(user_with_address.address.as_ref().unwrap().street, "456 Oak Ave");
3263        
3264        // Deeper nesting through Options
3265        let mut user_with_country = TestUser {
3266            name: "David".to_string(),
3267            age: 40,
3268            metadata: None,
3269            address: Some(TestAddress {
3270                street: "789 Pine Rd".to_string(),
3271                city: "Tokyo".to_string(),
3272                country: Some(TestCountry {
3273                    name: "Japan".to_string(),
3274                }),
3275            }),
3276        };
3277        
3278        let country_name_kp = writable_opt_keypath!(|u: &mut TestUser| u.address.as_mut().and_then(|a| a.country.as_mut().map(|c| &mut c.name)));
3279        if let Some(country_name) = country_name_kp.get_mut(&mut user_with_country) {
3280            *country_name = "Nippon".to_string();
3281        }
3282        assert_eq!(user_with_country.address.as_ref().unwrap().country.as_ref().unwrap().name, "Nippon");
3283        
3284        // Fallback: using closure
3285        let metadata_kp2 = writable_opt_keypath!(|u: &mut TestUser| u.metadata.as_mut());
3286        if let Some(metadata) = metadata_kp2.get_mut(&mut user) {
3287            *metadata = "super_admin".to_string();
3288        }
3289        assert_eq!(user.metadata, Some("super_admin".to_string()));
3290    }
3291}
3292
3293// ========== WithContainer Trait ==========
3294
3295/// Trait for no-clone callback-based access to container types
3296/// Provides methods to execute closures with references to values inside containers
3297/// without requiring cloning of the values
3298pub trait WithContainer<Root, Value> {
3299    /// Execute a closure with a reference to the value inside an Arc
3300    fn with_arc<F, R>(&self, arc: &Arc<Root>, f: F) -> R
3301    where
3302        F: FnOnce(&Value) -> R;
3303
3304    /// Execute a closure with a reference to the value inside a Box
3305    fn with_box<F, R>(&self, boxed: &Box<Root>, f: F) -> R
3306    where
3307        F: FnOnce(&Value) -> R;
3308
3309    /// Execute a closure with a mutable reference to the value inside a Box
3310    fn with_box_mut<F, R>(&self, boxed: &mut Box<Root>, f: F) -> R
3311    where
3312        F: FnOnce(&mut Value) -> R;
3313
3314    /// Execute a closure with a reference to the value inside an Rc
3315    fn with_rc<F, R>(&self, rc: &Rc<Root>, f: F) -> R
3316    where
3317        F: FnOnce(&Value) -> R;
3318
3319    /// Execute a closure with a reference to the value inside a Result
3320    fn with_result<F, R, E>(&self, result: &Result<Root, E>, f: F) -> Option<R>
3321    where
3322        F: FnOnce(&Value) -> R;
3323
3324    /// Execute a closure with a mutable reference to the value inside a Result
3325    fn with_result_mut<F, R, E>(&self, result: &mut Result<Root, E>, f: F) -> Option<R>
3326    where
3327        F: FnOnce(&mut Value) -> R;
3328
3329    /// Execute a closure with a reference to the value inside an Option
3330    fn with_option<F, R>(&self, option: &Option<Root>, f: F) -> Option<R>
3331    where
3332        F: FnOnce(&Value) -> R;
3333
3334    /// Execute a closure with a mutable reference to the value inside an Option
3335    fn with_option_mut<F, R>(&self, option: &mut Option<Root>, f: F) -> Option<R>
3336    where
3337        F: FnOnce(&mut Value) -> R;
3338
3339    /// Execute a closure with a reference to the value inside a RefCell
3340    fn with_refcell<F, R>(&self, refcell: &RefCell<Root>, f: F) -> Option<R>
3341    where
3342        F: FnOnce(&Value) -> R;
3343
3344    /// Execute a closure with a mutable reference to the value inside a RefCell
3345    fn with_refcell_mut<F, R>(&self, refcell: &RefCell<Root>, f: F) -> Option<R>
3346    where
3347        F: FnOnce(&mut Value) -> R;
3348
3349    #[cfg(feature = "tagged")]
3350    /// Execute a closure with a reference to the value inside a Tagged
3351    fn with_tagged<F, R, Tag>(&self, tagged: &Tagged<Root, Tag>, f: F) -> R
3352    where
3353        Tagged<Root, Tag>: std::ops::Deref<Target = Root>,
3354        F: FnOnce(&Value) -> R;
3355
3356    /// Execute a closure with a reference to the value inside a Mutex
3357    fn with_mutex<F, R>(&self, mutex: &Mutex<Root>, f: F) -> Option<R>
3358    where
3359        F: FnOnce(&Value) -> R;
3360
3361    /// Execute a closure with a mutable reference to the value inside a Mutex
3362    fn with_mutex_mut<F, R>(&self, mutex: &mut Mutex<Root>, f: F) -> Option<R>
3363    where
3364        F: FnOnce(&mut Value) -> R;
3365
3366    /// Execute a closure with a reference to the value inside an RwLock
3367    fn with_rwlock<F, R>(&self, rwlock: &RwLock<Root>, f: F) -> Option<R>
3368    where
3369        F: FnOnce(&Value) -> R;
3370
3371    /// Execute a closure with a mutable reference to the value inside an RwLock
3372    fn with_rwlock_mut<F, R>(&self, rwlock: &mut RwLock<Root>, f: F) -> Option<R>
3373    where
3374        F: FnOnce(&mut Value) -> R;
3375
3376    /// Execute a closure with a reference to the value inside an Arc<RwLock<Root>>
3377    fn with_arc_rwlock<F, R>(&self, arc_rwlock: &Arc<RwLock<Root>>, f: F) -> Option<R>
3378    where
3379        F: FnOnce(&Value) -> R;
3380
3381    /// Execute a closure with a mutable reference to the value inside an Arc<RwLock<Root>>
3382    fn with_arc_rwlock_mut<F, R>(&self, arc_rwlock: &Arc<RwLock<Root>>, f: F) -> Option<R>
3383    where
3384        F: FnOnce(&mut Value) -> R;
3385}
3386
3387// Implement WithContainer for KeyPath
3388impl<Root, Value, F> WithContainer<Root, Value> for KeyPath<Root, Value, F>
3389where
3390    F: for<'r> Fn(&'r Root) -> &'r Value + Clone,
3391{
3392    fn with_arc<Callback, R>(&self, arc: &Arc<Root>, f: Callback) -> R
3393    where
3394        Callback: FnOnce(&Value) -> R,
3395    {
3396        self.with_arc(arc, f)
3397    }
3398
3399    fn with_box<Callback, R>(&self, boxed: &Box<Root>, f: Callback) -> R
3400    where
3401        Callback: FnOnce(&Value) -> R,
3402    {
3403        self.with_box(boxed, f)
3404    }
3405
3406    fn with_box_mut<Callback, R>(&self, _boxed: &mut Box<Root>, _f: Callback) -> R
3407    where
3408        Callback: FnOnce(&mut Value) -> R,
3409    {
3410        eprintln!("[DEBUG] KeyPath does not support mutable access - use WritableKeyPath instead");
3411        unreachable!("KeyPath does not support mutable access - use WritableKeyPath instead")
3412    }
3413
3414    fn with_rc<Callback, R>(&self, rc: &Rc<Root>, f: Callback) -> R
3415    where
3416        Callback: FnOnce(&Value) -> R,
3417    {
3418        self.with_rc(rc, f)
3419    }
3420
3421    fn with_result<Callback, R, E>(&self, result: &Result<Root, E>, f: Callback) -> Option<R>
3422    where
3423        Callback: FnOnce(&Value) -> R,
3424    {
3425        self.with_result(result, f)
3426    }
3427
3428    fn with_result_mut<Callback, R, E>(&self, _result: &mut Result<Root, E>, _f: Callback) -> Option<R>
3429    where
3430        Callback: FnOnce(&mut Value) -> R,
3431    {
3432        None
3433    }
3434
3435    fn with_option<Callback, R>(&self, option: &Option<Root>, f: Callback) -> Option<R>
3436    where
3437        Callback: FnOnce(&Value) -> R,
3438    {
3439        self.with_option(option, f)
3440    }
3441
3442    fn with_option_mut<Callback, R>(&self, _option: &mut Option<Root>, _f: Callback) -> Option<R>
3443    where
3444        Callback: FnOnce(&mut Value) -> R,
3445    {
3446        None
3447    }
3448
3449    fn with_refcell<Callback, R>(&self, refcell: &RefCell<Root>, f: Callback) -> Option<R>
3450    where
3451        Callback: FnOnce(&Value) -> R,
3452    {
3453        self.with_refcell(refcell, f)
3454    }
3455
3456    fn with_refcell_mut<Callback, R>(&self, _refcell: &RefCell<Root>, _f: Callback) -> Option<R>
3457    where
3458        Callback: FnOnce(&mut Value) -> R,
3459    {
3460        None
3461    }
3462
3463    #[cfg(feature = "tagged")]
3464    fn with_tagged<Tag, Callback, R>(&self, tagged: &Tagged<Root, Tag>, f: Callback) -> R
3465    where
3466        Tagged<Root, Tag>: std::ops::Deref<Target = Root>,
3467        Callback: FnOnce(&Value) -> R,
3468    {
3469        self.with_tagged(tagged, f)
3470    }
3471
3472    fn with_mutex<Callback, R>(&self, mutex: &Mutex<Root>, f: Callback) -> Option<R>
3473    where
3474        Callback: FnOnce(&Value) -> R,
3475    {
3476        self.with_mutex(mutex, f)
3477    }
3478
3479    fn with_mutex_mut<Callback, R>(&self, _mutex: &mut Mutex<Root>, _f: Callback) -> Option<R>
3480    where
3481        Callback: FnOnce(&mut Value) -> R,
3482    {
3483        None
3484    }
3485
3486    fn with_rwlock<Callback, R>(&self, rwlock: &RwLock<Root>, f: Callback) -> Option<R>
3487    where
3488        Callback: FnOnce(&Value) -> R,
3489    {
3490        self.with_rwlock(rwlock, f)
3491    }
3492
3493    fn with_rwlock_mut<Callback, R>(&self, _rwlock: &mut RwLock<Root>, _f: Callback) -> Option<R>
3494    where
3495        Callback: FnOnce(&mut Value) -> R,
3496    {
3497        None
3498    }
3499
3500    fn with_arc_rwlock<Callback, R>(&self, arc_rwlock: &Arc<RwLock<Root>>, f: Callback) -> Option<R>
3501    where
3502        Callback: FnOnce(&Value) -> R,
3503    {
3504        self.with_arc_rwlock(arc_rwlock, f)
3505    }
3506
3507    fn with_arc_rwlock_mut<Callback, R>(&self, _arc_rwlock: &Arc<RwLock<Root>>, _f: Callback) -> Option<R>
3508    where
3509        Callback: FnOnce(&mut Value) -> R,
3510    {
3511        None
3512    }
3513}
3514
3515// Implement WithContainer for OptionalKeyPath - read-only operations only
3516impl<Root, Value, F> WithContainer<Root, Value> for OptionalKeyPath<Root, Value, F>
3517where
3518    F: for<'r> Fn(&'r Root) -> Option<&'r Value> + Clone,
3519{
3520    fn with_arc<Callback, R>(&self, arc: &Arc<Root>, f: Callback) -> R
3521    where
3522        Callback: FnOnce(&Value) -> R,
3523    {
3524        self.with_arc(arc, f)
3525    }
3526
3527    fn with_box<Callback, R>(&self, boxed: &Box<Root>, f: Callback) -> R
3528    where
3529        Callback: FnOnce(&Value) -> R,
3530    {
3531        self.with_box(boxed, f)
3532    }
3533
3534    fn with_box_mut<Callback, R>(&self, _boxed: &mut Box<Root>, _f: Callback) -> R
3535    where
3536        Callback: FnOnce(&mut Value) -> R,
3537    {
3538        eprintln!("[DEBUG] OptionalKeyPath does not support mutable access - use WritableOptionalKeyPath instead");
3539        unreachable!("OptionalKeyPath does not support mutable access - use WritableOptionalKeyPath instead")
3540    }
3541
3542    fn with_rc<Callback, R>(&self, rc: &Rc<Root>, f: Callback) -> R
3543    where
3544        Callback: FnOnce(&Value) -> R,
3545    {
3546        self.with_rc(rc, f)
3547    }
3548
3549    fn with_result<Callback, R, E>(&self, result: &Result<Root, E>, f: Callback) -> Option<R>
3550    where
3551        Callback: FnOnce(&Value) -> R,
3552    {
3553        self.with_result(result, f)
3554    }
3555
3556    fn with_result_mut<Callback, R, E>(&self, _result: &mut Result<Root, E>, _f: Callback) -> Option<R>
3557    where
3558        Callback: FnOnce(&mut Value) -> R,
3559    {
3560        None // OptionalKeyPath doesn't support mutable access
3561    }
3562
3563    fn with_option<Callback, R>(&self, option: &Option<Root>, f: Callback) -> Option<R>
3564    where
3565        Callback: FnOnce(&Value) -> R,
3566    {
3567        self.with_option(option, f)
3568    }
3569
3570    fn with_option_mut<Callback, R>(&self, _option: &mut Option<Root>, _f: Callback) -> Option<R>
3571    where
3572        Callback: FnOnce(&mut Value) -> R,
3573    {
3574        None // OptionalKeyPath doesn't support mutable access
3575    }
3576
3577    fn with_refcell<Callback, R>(&self, refcell: &RefCell<Root>, f: Callback) -> Option<R>
3578    where
3579        Callback: FnOnce(&Value) -> R,
3580    {
3581        self.with_refcell(refcell, f)
3582    }
3583
3584    fn with_refcell_mut<Callback, R>(&self, _refcell: &RefCell<Root>, _f: Callback) -> Option<R>
3585    where
3586        Callback: FnOnce(&mut Value) -> R,
3587    {
3588        None // OptionalKeyPath doesn't support mutable access
3589    }
3590
3591    #[cfg(feature = "tagged")]
3592    fn with_tagged<Tag, Callback, R>(&self, tagged: &Tagged<Root, Tag>, f: Callback) -> R
3593    where
3594        Tagged<Root, Tag>: std::ops::Deref<Target = Root>,
3595        Callback: FnOnce(&Value) -> R,
3596    {
3597        self.with_tagged(tagged, f)
3598    }
3599
3600    fn with_mutex<Callback, R>(&self, mutex: &Mutex<Root>, f: Callback) -> Option<R>
3601    where
3602        Callback: FnOnce(&Value) -> R,
3603    {
3604        self.with_mutex(mutex, f)
3605    }
3606
3607    fn with_mutex_mut<Callback, R>(&self, _mutex: &mut Mutex<Root>, _f: Callback) -> Option<R>
3608    where
3609        Callback: FnOnce(&mut Value) -> R,
3610    {
3611        None // OptionalKeyPath doesn't support mutable access
3612    }
3613
3614    fn with_rwlock<Callback, R>(&self, rwlock: &RwLock<Root>, f: Callback) -> Option<R>
3615    where
3616        Callback: FnOnce(&Value) -> R,
3617    {
3618        self.with_rwlock(rwlock, f)
3619    }
3620
3621    fn with_rwlock_mut<Callback, R>(&self, _rwlock: &mut RwLock<Root>, _f: Callback) -> Option<R>
3622    where
3623        Callback: FnOnce(&mut Value) -> R,
3624    {
3625        None // OptionalKeyPath doesn't support mutable access
3626    }
3627
3628    fn with_arc_rwlock<Callback, R>(&self, arc_rwlock: &Arc<RwLock<Root>>, f: Callback) -> Option<R>
3629    where
3630        Callback: FnOnce(&Value) -> R,
3631    {
3632        self.with_arc_rwlock(arc_rwlock, f)
3633    }
3634
3635    fn with_arc_rwlock_mut<Callback, R>(&self, _arc_rwlock: &Arc<RwLock<Root>>, _f: Callback) -> Option<R>
3636    where
3637        Callback: FnOnce(&mut Value) -> R,
3638    {
3639        None // OptionalKeyPath doesn't support mutable access - use WritableOptionalKeyPath instead
3640    }
3641}
3642
3643// Implement WithContainer for WritableKeyPath - supports all mutable operations
3644impl<Root, Value, F> WithContainer<Root, Value> for WritableKeyPath<Root, Value, F>
3645where
3646    F: for<'r> Fn(&'r mut Root) -> &'r mut Value,
3647{
3648    fn with_arc<Callback, R>(&self, _arc: &Arc<Root>, _f: Callback) -> R
3649    where
3650        Callback: FnOnce(&Value) -> R,
3651    {
3652        // Arc doesn't support mutable access without interior mutability
3653        // This method requires &mut Arc<Root> which we don't have
3654        eprintln!("[DEBUG] WritableKeyPath::with_arc requires &mut Arc<Root> or interior mutability");
3655        unreachable!("WritableKeyPath::with_arc requires &mut Arc<Root> or interior mutability")
3656    }
3657
3658    fn with_box<Callback, R>(&self, boxed: &Box<Root>, f: Callback) -> R
3659    where
3660        Callback: FnOnce(&Value) -> R,
3661    {
3662        // Box doesn't support getting mutable reference from immutable reference
3663        // This is a limitation - we'd need &mut Box<Root> for mutable access
3664        eprintln!("[DEBUG] WritableKeyPath::with_box requires &mut Box<Root> - use with_box_mut instead");
3665        unreachable!("WritableKeyPath::with_box requires &mut Box<Root> - use with_box_mut instead")
3666    }
3667
3668    fn with_box_mut<Callback, R>(&self, boxed: &mut Box<Root>, f: Callback) -> R
3669    where
3670        Callback: FnOnce(&mut Value) -> R,
3671    {
3672        let value = self.get_mut(boxed.as_mut());
3673        f(value)
3674    }
3675
3676    fn with_rc<Callback, R>(&self, _rc: &Rc<Root>, _f: Callback) -> R
3677    where
3678        Callback: FnOnce(&Value) -> R,
3679    {
3680        // Rc doesn't support mutable access without interior mutability
3681        // This method requires &mut Rc<Root> which we don't have
3682        eprintln!("[DEBUG] WritableKeyPath::with_rc requires &mut Rc<Root> or interior mutability");
3683        unreachable!("WritableKeyPath::with_rc requires &mut Rc<Root> or interior mutability")
3684    }
3685
3686    fn with_result<Callback, R, E>(&self, _result: &Result<Root, E>, _f: Callback) -> Option<R>
3687    where
3688        Callback: FnOnce(&Value) -> R,
3689    {
3690        // WritableKeyPath requires &mut Root, but we only have &Result<Root, E>
3691        // This is a limitation - use with_result_mut for mutable access
3692        None
3693    }
3694
3695    fn with_result_mut<Callback, R, E>(&self, result: &mut Result<Root, E>, f: Callback) -> Option<R>
3696    where
3697        Callback: FnOnce(&mut Value) -> R,
3698    {
3699        result.as_mut().ok().map(|root| {
3700            let value = self.get_mut(root);
3701            f(value)
3702        })
3703    }
3704
3705    fn with_option<Callback, R>(&self, _option: &Option<Root>, _f: Callback) -> Option<R>
3706    where
3707        Callback: FnOnce(&Value) -> R,
3708    {
3709        // WritableKeyPath requires &mut Root, but we only have &Option<Root>
3710        // This is a limitation - use with_option_mut for mutable access
3711        None
3712    }
3713
3714    fn with_option_mut<Callback, R>(&self, option: &mut Option<Root>, f: Callback) -> Option<R>
3715    where
3716        Callback: FnOnce(&mut Value) -> R,
3717    {
3718        option.as_mut().map(|root| {
3719            let value = self.get_mut(root);
3720            f(value)
3721        })
3722    }
3723
3724    fn with_refcell<Callback, R>(&self, refcell: &RefCell<Root>, f: Callback) -> Option<R>
3725    where
3726        Callback: FnOnce(&Value) -> R,
3727    {
3728        // RefCell doesn't allow getting mutable reference from immutable borrow
3729        // This is a limitation - we'd need try_borrow_mut for mutable access
3730        None
3731    }
3732
3733    fn with_refcell_mut<Callback, R>(&self, refcell: &RefCell<Root>, f: Callback) -> Option<R>
3734    where
3735        Callback: FnOnce(&mut Value) -> R,
3736    {
3737        refcell.try_borrow_mut().ok().map(|mut borrow| {
3738            let value = self.get_mut(&mut *borrow);
3739            f(value)
3740        })
3741    }
3742
3743    #[cfg(feature = "tagged")]
3744    fn with_tagged<Tag, Callback, R>(&self, _tagged: &Tagged<Root, Tag>, _f: Callback) -> R
3745    where
3746        Tagged<Root, Tag>: std::ops::Deref<Target = Root>,
3747        Callback: FnOnce(&Value) -> R,
3748    {
3749        // WritableKeyPath requires &mut Root, but we only have &Tagged<Root, Tag>
3750        // This is a limitation - Tagged doesn't support mutable access without interior mutability
3751        eprintln!("[DEBUG] WritableKeyPath::with_tagged requires &mut Tagged<Root, Tag> or interior mutability");
3752        unreachable!("WritableKeyPath::with_tagged requires &mut Tagged<Root, Tag> or interior mutability")
3753    }
3754
3755    fn with_mutex<Callback, R>(&self, mutex: &Mutex<Root>, f: Callback) -> Option<R>
3756    where
3757        Callback: FnOnce(&Value) -> R,
3758    {
3759        mutex.lock().ok().map(|mut guard| {
3760            let value = self.get_mut(&mut *guard);
3761            f(value)
3762        })
3763    }
3764
3765    fn with_mutex_mut<Callback, R>(&self, mutex: &mut Mutex<Root>, f: Callback) -> Option<R>
3766    where
3767        Callback: FnOnce(&mut Value) -> R,
3768    {
3769        // Mutex::get_mut returns Result<&mut Root, PoisonError>
3770        mutex.get_mut().ok().map(|root| {
3771            let value = self.get_mut(root);
3772            f(value)
3773        })
3774    }
3775
3776    fn with_rwlock<Callback, R>(&self, rwlock: &RwLock<Root>, f: Callback) -> Option<R>
3777    where
3778        Callback: FnOnce(&Value) -> R,
3779    {
3780        // RwLock read guard doesn't allow mutable access
3781        // This is a limitation - we'd need write() for mutable access
3782        None
3783    }
3784
3785    fn with_rwlock_mut<Callback, R>(&self, rwlock: &mut RwLock<Root>, f: Callback) -> Option<R>
3786    where
3787        Callback: FnOnce(&mut Value) -> R,
3788    {
3789        // RwLock::get_mut returns Result<&mut Root, PoisonError>
3790        rwlock.get_mut().ok().map(|root| {
3791            let value = self.get_mut(root);
3792            f(value)
3793        })
3794    }
3795
3796    fn with_arc_rwlock<Callback, R>(&self, arc_rwlock: &Arc<RwLock<Root>>, f: Callback) -> Option<R>
3797    where
3798        Callback: FnOnce(&Value) -> R,
3799    {
3800        // Arc<RwLock> read guard doesn't allow mutable access
3801        // This is a limitation - we'd need write() for mutable access
3802        None
3803    }
3804
3805    fn with_arc_rwlock_mut<Callback, R>(&self, arc_rwlock: &Arc<RwLock<Root>>, f: Callback) -> Option<R>
3806    where
3807        Callback: FnOnce(&mut Value) -> R,
3808    {
3809        arc_rwlock.write().ok().map(|mut guard| {
3810            let value = self.get_mut(&mut *guard);
3811            f(value)
3812        })
3813    }
3814}
3815
3816// Implement WithContainer for WritableOptionalKeyPath - supports all mutable operations
3817impl<Root, Value, F> WithContainer<Root, Value> for WritableOptionalKeyPath<Root, Value, F>
3818where
3819    F: for<'r> Fn(&'r mut Root) -> Option<&'r mut Value>,
3820{
3821    fn with_arc<Callback, R>(&self, _arc: &Arc<Root>, _f: Callback) -> R
3822    where
3823        Callback: FnOnce(&Value) -> R,
3824    {
3825        // Arc doesn't support mutable access without interior mutability
3826        // This method requires &mut Arc<Root> which we don't have
3827        eprintln!("[DEBUG] WritableOptionalKeyPath::with_arc requires &mut Arc<Root> or interior mutability");
3828        unreachable!("WritableOptionalKeyPath::with_arc requires &mut Arc<Root> or interior mutability")
3829    }
3830
3831    fn with_box<Callback, R>(&self, _boxed: &Box<Root>, _f: Callback) -> R
3832    where
3833        Callback: FnOnce(&Value) -> R,
3834    {
3835        // WritableOptionalKeyPath requires &mut Root, but we only have &Box<Root>
3836        // This is a limitation - use with_box_mut for mutable access
3837        eprintln!("[DEBUG] WritableOptionalKeyPath::with_box requires &mut Box<Root> - use with_box_mut instead");
3838        unreachable!("WritableOptionalKeyPath::with_box requires &mut Box<Root> - use with_box_mut instead")
3839    }
3840
3841    fn with_box_mut<Callback, R>(&self, boxed: &mut Box<Root>, f: Callback) -> R
3842    where
3843        Callback: FnOnce(&mut Value) -> R,
3844    {
3845        if let Some(value) = self.get_mut(boxed.as_mut()) {
3846            f(value)
3847        } else {
3848            eprintln!("[DEBUG] WritableOptionalKeyPath failed to get value from Box");
3849            unreachable!("WritableOptionalKeyPath failed to get value from Box")
3850        }
3851    }
3852
3853    fn with_rc<Callback, R>(&self, _rc: &Rc<Root>, _f: Callback) -> R
3854    where
3855        Callback: FnOnce(&Value) -> R,
3856    {
3857        // Rc doesn't support mutable access without interior mutability
3858        // This method requires &mut Rc<Root> which we don't have
3859        eprintln!("[DEBUG] WritableOptionalKeyPath::with_rc requires &mut Rc<Root> or interior mutability");
3860        unreachable!("WritableOptionalKeyPath::with_rc requires &mut Rc<Root> or interior mutability")
3861    }
3862
3863    fn with_result<Callback, R, E>(&self, _result: &Result<Root, E>, _f: Callback) -> Option<R>
3864    where
3865        Callback: FnOnce(&Value) -> R,
3866    {
3867        // WritableOptionalKeyPath requires &mut Root, but we only have &Result<Root, E>
3868        // This is a limitation - use with_result_mut for mutable access
3869        None
3870    }
3871
3872    fn with_result_mut<Callback, R, E>(&self, result: &mut Result<Root, E>, f: Callback) -> Option<R>
3873    where
3874        Callback: FnOnce(&mut Value) -> R,
3875    {
3876        result.as_mut().ok().and_then(|root| {
3877            self.get_mut(root).map(|value| f(value))
3878        })
3879    }
3880
3881    fn with_option<Callback, R>(&self, _option: &Option<Root>, _f: Callback) -> Option<R>
3882    where
3883        Callback: FnOnce(&Value) -> R,
3884    {
3885        // WritableOptionalKeyPath requires &mut Root, but we only have &Option<Root>
3886        // This is a limitation - use with_option_mut for mutable access
3887        None
3888    }
3889
3890    fn with_option_mut<Callback, R>(&self, option: &mut Option<Root>, f: Callback) -> Option<R>
3891    where
3892        Callback: FnOnce(&mut Value) -> R,
3893    {
3894        option.as_mut().and_then(|root| {
3895            self.get_mut(root).map(|value| f(value))
3896        })
3897    }
3898
3899    fn with_refcell<Callback, R>(&self, _refcell: &RefCell<Root>, _f: Callback) -> Option<R>
3900    where
3901        Callback: FnOnce(&Value) -> R,
3902    {
3903        // RefCell doesn't allow getting mutable reference from immutable borrow
3904        // This is a limitation - we'd need try_borrow_mut for mutable access
3905        None
3906    }
3907
3908    fn with_refcell_mut<Callback, R>(&self, refcell: &RefCell<Root>, f: Callback) -> Option<R>
3909    where
3910        Callback: FnOnce(&mut Value) -> R,
3911    {
3912        refcell.try_borrow_mut().ok().and_then(|mut borrow| {
3913            self.get_mut(&mut *borrow).map(|value| f(value))
3914        })
3915    }
3916
3917    #[cfg(feature = "tagged")]
3918    fn with_tagged<Tag, Callback, R>(&self, _tagged: &Tagged<Root, Tag>, _f: Callback) -> R
3919    where
3920        Tagged<Root, Tag>: std::ops::Deref<Target = Root>,
3921        Callback: FnOnce(&Value) -> R,
3922    {
3923        // WritableOptionalKeyPath requires &mut Root, but we only have &Tagged<Root, Tag>
3924        // This is a limitation - Tagged doesn't support mutable access without interior mutability
3925        eprintln!("[DEBUG] WritableOptionalKeyPath::with_tagged requires &mut Tagged<Root, Tag> or interior mutability");
3926        unreachable!("WritableOptionalKeyPath::with_tagged requires &mut Tagged<Root, Tag> or interior mutability")
3927    }
3928
3929    fn with_mutex<Callback, R>(&self, mutex: &Mutex<Root>, f: Callback) -> Option<R>
3930    where
3931        Callback: FnOnce(&Value) -> R,
3932    {
3933        mutex.lock().ok().and_then(|mut guard| {
3934            self.get_mut(&mut *guard).map(|value| f(value))
3935        })
3936    }
3937
3938    fn with_mutex_mut<Callback, R>(&self, mutex: &mut Mutex<Root>, f: Callback) -> Option<R>
3939    where
3940        Callback: FnOnce(&mut Value) -> R,
3941    {
3942        // Mutex::get_mut returns Result<&mut Root, PoisonError>
3943        mutex.get_mut().ok().and_then(|root| {
3944            self.get_mut(root).map(|value| f(value))
3945        })
3946    }
3947
3948    fn with_rwlock<Callback, R>(&self, _rwlock: &RwLock<Root>, _f: Callback) -> Option<R>
3949    where
3950        Callback: FnOnce(&Value) -> R,
3951    {
3952        // RwLock read guard doesn't allow mutable access
3953        // This is a limitation - we'd need write() for mutable access
3954        None
3955    }
3956
3957    fn with_rwlock_mut<Callback, R>(&self, rwlock: &mut RwLock<Root>, f: Callback) -> Option<R>
3958    where
3959        Callback: FnOnce(&mut Value) -> R,
3960    {
3961        // RwLock::get_mut returns Result<&mut Root, PoisonError>
3962        rwlock.get_mut().ok().and_then(|root| {
3963            self.get_mut(root).map(|value| f(value))
3964        })
3965    }
3966
3967    fn with_arc_rwlock<Callback, R>(&self, _arc_rwlock: &Arc<RwLock<Root>>, _f: Callback) -> Option<R>
3968    where
3969        Callback: FnOnce(&Value) -> R,
3970    {
3971        // Arc<RwLock> read guard doesn't allow mutable access
3972        // This is a limitation - we'd need write() for mutable access
3973        None
3974    }
3975
3976    fn with_arc_rwlock_mut<Callback, R>(&self, arc_rwlock: &Arc<RwLock<Root>>, f: Callback) -> Option<R>
3977    where
3978        Callback: FnOnce(&mut Value) -> R,
3979    {
3980        arc_rwlock.write().ok().and_then(|mut guard| {
3981            self.get_mut(&mut *guard).map(|value| f(value))
3982        })
3983    }
3984}