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