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