rust_keypaths/
lib.rs

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