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    /// Adapt this keypath to work with Option<Root> instead of Root
1106    /// This unwraps the Option and applies the keypath to the Some value
1107    pub fn for_option(self) -> WritableOptionalKeyPath<Option<Root>, Value, impl for<'r> Fn(&'r mut Option<Root>) -> Option<&'r mut Value> + 'static>
1108    where
1109        F: 'static,
1110        Root: 'static,
1111        Value: 'static,
1112    {
1113        let getter = self.getter;
1114        
1115        WritableOptionalKeyPath {
1116            getter: move |option: &mut Option<Root>| {
1117                option.as_mut().map(|root| getter(root))
1118            },
1119            _phantom: PhantomData,
1120        }
1121    }
1122    
1123    /// Convert a WritableKeyPath to WritableOptionalKeyPath for chaining
1124    /// This allows non-optional writable keypaths to be chained with then()
1125    pub fn to_optional(self) -> WritableOptionalKeyPath<Root, Value, impl for<'r> Fn(&'r mut Root) -> Option<&'r mut Value> + 'static>
1126    where
1127        F: 'static,
1128    {
1129        let getter = self.getter;
1130        WritableOptionalKeyPath::new(move |root: &mut Root| Some(getter(root)))
1131    }
1132    
1133    // Instance methods for unwrapping containers (automatically infers Target from Value::Target)
1134    // Box<T> -> T
1135    pub fn for_box<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    // Arc<T> -> T (Note: Arc doesn't support mutable access, but we provide it for consistency)
1152    // This will require interior mutability patterns
1153    pub fn for_arc<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    // Rc<T> -> T (Note: Rc doesn't support mutable access, but we provide it for consistency)
1170    // This will require interior mutability patterns
1171    pub fn for_rc<Target>(self) -> WritableKeyPath<Root, Target, impl for<'r> Fn(&'r mut Root) -> &'r mut Target + 'static>
1172    where
1173        Value: std::ops::DerefMut<Target = Target>,
1174        F: 'static,
1175        Value: 'static,
1176    {
1177        let getter = self.getter;
1178        
1179        WritableKeyPath {
1180            getter: move |root: &mut Root| {
1181                getter(root).deref_mut()
1182            },
1183            _phantom: PhantomData,
1184        }
1185    }
1186    
1187    /// Execute a closure with a mutable reference to the value inside a Box
1188    pub fn with_box_mut<Callback, R>(&self, boxed: &mut Box<Root>, f: Callback) -> R
1189    where
1190        F: Clone,
1191        Callback: FnOnce(&mut Value) -> R,
1192    {
1193        let value = self.get_mut(boxed);
1194        f(value)
1195    }
1196    
1197    /// Execute a closure with a mutable reference to the value inside a Result
1198    pub fn with_result_mut<Callback, R, E>(&self, result: &mut Result<Root, E>, f: Callback) -> Option<R>
1199    where
1200        F: Clone,
1201        Callback: FnOnce(&mut Value) -> R,
1202    {
1203        result.as_mut().ok().map(|root| {
1204            let value = self.get_mut(root);
1205            f(value)
1206        })
1207    }
1208    
1209    /// Execute a closure with a mutable reference to the value inside an Option
1210    pub fn with_option_mut<Callback, R>(&self, option: &mut Option<Root>, f: Callback) -> Option<R>
1211    where
1212        F: Clone,
1213        Callback: FnOnce(&mut Value) -> R,
1214    {
1215        option.as_mut().map(|root| {
1216            let value = self.get_mut(root);
1217            f(value)
1218        })
1219    }
1220    
1221    /// Execute a closure with a mutable reference to the value inside a RefCell
1222    pub fn with_refcell_mut<Callback, R>(&self, refcell: &RefCell<Root>, f: Callback) -> Option<R>
1223    where
1224        F: Clone,
1225        Callback: FnOnce(&mut Value) -> R,
1226    {
1227        refcell.try_borrow_mut().ok().map(|mut borrow| {
1228            let value = self.get_mut(&mut *borrow);
1229            f(value)
1230        })
1231    }
1232    
1233    /// Execute a closure with a mutable reference to the value inside a Mutex
1234    pub fn with_mutex_mut<Callback, R>(&self, mutex: &mut Mutex<Root>, f: Callback) -> Option<R>
1235    where
1236        F: Clone,
1237        Callback: FnOnce(&mut Value) -> R,
1238    {
1239        mutex.get_mut().ok().map(|root| {
1240            let value = self.get_mut(root);
1241            f(value)
1242        })
1243    }
1244    
1245    /// Execute a closure with a mutable reference to the value inside an RwLock
1246    pub fn with_rwlock_mut<Callback, R>(&self, rwlock: &mut RwLock<Root>, f: Callback) -> Option<R>
1247    where
1248        F: Clone,
1249        Callback: FnOnce(&mut Value) -> R,
1250    {
1251        rwlock.write().ok().map(|mut guard| {
1252            let value = self.get_mut(&mut *guard);
1253            f(value)
1254        })
1255    }
1256    
1257    /// Get a mutable iterator over a Vec when Value is Vec<T>
1258    /// Returns Some(iterator) if the value is a Vec, None otherwise
1259    pub fn iter_mut<'r, T>(&self, root: &'r mut Root) -> Option<std::slice::IterMut<'r, T>>
1260    where
1261        Value: AsMut<[T]> + 'r,
1262    {
1263        let value_ref: &'r mut Value = self.get_mut(root);
1264        Some(value_ref.as_mut().iter_mut())
1265    }
1266}
1267
1268// WritableOptionalKeyPath for failable mutable access
1269#[derive(Clone)]
1270pub struct WritableOptionalKeyPath<Root, Value, F>
1271where
1272    F: for<'r> Fn(&'r mut Root) -> Option<&'r mut Value>,
1273{
1274    getter: F,
1275    _phantom: PhantomData<(Root, Value)>,
1276}
1277
1278impl<Root, Value, F> WritableOptionalKeyPath<Root, Value, F>
1279where
1280    F: for<'r> Fn(&'r mut Root) -> Option<&'r mut Value>,
1281{
1282    pub fn new(getter: F) -> Self {
1283        Self {
1284            getter,
1285            _phantom: PhantomData,
1286        }
1287    }
1288    
1289    pub fn get_mut<'r>(&self, root: &'r mut Root) -> Option<&'r mut Value> {
1290        (self.getter)(root)
1291    }
1292    
1293    /// Adapt this keypath to work with Option<Root> instead of Root
1294    /// This unwraps the Option and applies the keypath to the Some value
1295    pub fn for_option(self) -> WritableOptionalKeyPath<Option<Root>, Value, impl for<'r> Fn(&'r mut Option<Root>) -> Option<&'r mut Value> + 'static>
1296    where
1297        F: 'static,
1298        Root: 'static,
1299        Value: 'static,
1300    {
1301        let getter = self.getter;
1302        
1303        WritableOptionalKeyPath {
1304            getter: move |option: &mut Option<Root>| {
1305                option.as_mut().and_then(|root| getter(root))
1306            },
1307            _phantom: PhantomData,
1308        }
1309    }
1310    
1311    // Swift-like operator for chaining WritableOptionalKeyPath
1312    pub fn then<SubValue, G>(
1313        self,
1314        next: WritableOptionalKeyPath<Value, SubValue, G>,
1315    ) -> WritableOptionalKeyPath<Root, SubValue, impl for<'r> Fn(&'r mut Root) -> Option<&'r mut SubValue>>
1316    where
1317        G: for<'r> Fn(&'r mut Value) -> Option<&'r mut SubValue>,
1318        F: 'static,
1319        G: 'static,
1320        Value: 'static,
1321    {
1322        let first = self.getter;
1323        let second = next.getter;
1324        
1325        WritableOptionalKeyPath::new(move |root: &mut Root| {
1326            first(root).and_then(|value| second(value))
1327        })
1328    }
1329    
1330    // Instance methods for unwrapping containers from Option<Container<T>>
1331    // Option<Box<T>> -> Option<&mut T> (type automatically inferred from Value::Target)
1332    pub fn for_box<Target>(self) -> WritableOptionalKeyPath<Root, Target, impl for<'r> Fn(&'r mut Root) -> Option<&'r mut Target> + 'static>
1333    where
1334        Value: std::ops::DerefMut<Target = Target>,
1335        F: 'static,
1336        Value: 'static,
1337    {
1338        let getter = self.getter;
1339        
1340        WritableOptionalKeyPath {
1341            getter: move |root: &mut Root| {
1342                getter(root).map(|boxed| boxed.deref_mut())
1343            },
1344            _phantom: PhantomData,
1345        }
1346    }
1347    
1348    // Option<Arc<T>> -> Option<&mut T> (type automatically inferred from Value::Target)
1349    pub fn for_arc<Target>(self) -> WritableOptionalKeyPath<Root, Target, impl for<'r> Fn(&'r mut Root) -> Option<&'r mut Target> + 'static>
1350    where
1351        Value: std::ops::DerefMut<Target = Target>,
1352        F: 'static,
1353        Value: 'static,
1354    {
1355        let getter = self.getter;
1356        
1357        WritableOptionalKeyPath {
1358            getter: move |root: &mut Root| {
1359                getter(root).map(|arc| arc.deref_mut())
1360            },
1361            _phantom: PhantomData,
1362        }
1363    }
1364    
1365    // Option<Rc<T>> -> Option<&mut T> (type automatically inferred from Value::Target)
1366    pub fn for_rc<Target>(self) -> WritableOptionalKeyPath<Root, Target, impl for<'r> Fn(&'r mut Root) -> Option<&'r mut Target> + 'static>
1367    where
1368        Value: std::ops::DerefMut<Target = Target>,
1369        F: 'static,
1370        Value: 'static,
1371    {
1372        let getter = self.getter;
1373        
1374        WritableOptionalKeyPath {
1375            getter: move |root: &mut Root| {
1376                getter(root).map(|rc| rc.deref_mut())
1377            },
1378            _phantom: PhantomData,
1379        }
1380    }
1381    
1382    /// Adapt this keypath to work with Result<Root, E> instead of Root
1383    /// This unwraps the Result and applies the keypath to the Ok value
1384    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>
1385    where
1386        F: 'static,
1387        Root: 'static,
1388        Value: 'static,
1389        E: 'static,
1390    {
1391        let getter = self.getter;
1392        
1393        WritableOptionalKeyPath {
1394            getter: move |result: &mut Result<Root, E>| {
1395                result.as_mut().ok().and_then(|root| getter(root))
1396            },
1397            _phantom: PhantomData,
1398        }
1399    }
1400    
1401    // Overload: Adapt root type to Box<Root> when Value is Sized (not a container)
1402    pub fn for_box_root(self) -> WritableOptionalKeyPath<Box<Root>, Value, impl for<'r> Fn(&'r mut Box<Root>) -> Option<&'r mut Value> + 'static>
1403    where
1404        Value: Sized,
1405        F: 'static,
1406        Root: 'static,
1407        Value: 'static,
1408    {
1409        let getter = self.getter;
1410        
1411        WritableOptionalKeyPath {
1412            getter: move |boxed: &mut Box<Root>| {
1413                getter(boxed.as_mut())
1414            },
1415            _phantom: PhantomData,
1416        }
1417    }
1418    
1419    // Overload: Adapt root type to Arc<Root> when Value is Sized (not a container)
1420    pub fn for_arc_root(self) -> WritableOptionalKeyPath<Arc<Root>, Value, impl for<'r> Fn(&'r mut Arc<Root>) -> Option<&'r mut Value> + 'static>
1421    where
1422        Value: Sized,
1423        F: 'static,
1424        Root: 'static,
1425        Value: 'static,
1426    {
1427        let getter = self.getter;
1428        
1429        WritableOptionalKeyPath {
1430            getter: move |arc: &mut Arc<Root>| {
1431                // Arc doesn't support mutable access without interior mutability
1432                // This will always return None, but we provide it for API consistency
1433                None
1434            },
1435            _phantom: PhantomData,
1436        }
1437    }
1438    
1439    // Overload: Adapt root type to Rc<Root> when Value is Sized (not a container)
1440    pub fn for_rc_root(self) -> WritableOptionalKeyPath<Rc<Root>, Value, impl for<'r> Fn(&'r mut Rc<Root>) -> Option<&'r mut Value> + 'static>
1441    where
1442        Value: Sized,
1443        F: 'static,
1444        Root: 'static,
1445        Value: 'static,
1446    {
1447        let getter = self.getter;
1448        
1449        WritableOptionalKeyPath {
1450            getter: move |rc: &mut Rc<Root>| {
1451                // Rc doesn't support mutable access without interior mutability
1452                // This will always return None, but we provide it for API consistency
1453                None
1454            },
1455            _phantom: PhantomData,
1456        }
1457    }
1458}
1459
1460// Static factory methods for WritableOptionalKeyPath
1461impl WritableOptionalKeyPath<(), (), fn(&mut ()) -> Option<&mut ()>> {
1462    // Static method for Option<T> -> Option<&mut T>
1463    // Note: This is a factory method. Use instance method `for_option()` to adapt existing keypaths.
1464    pub fn for_option_static<T>() -> WritableOptionalKeyPath<Option<T>, T, impl for<'r> Fn(&'r mut Option<T>) -> Option<&'r mut T>> {
1465        WritableOptionalKeyPath::new(|opt: &mut Option<T>| opt.as_mut())
1466    }
1467}
1468
1469// Enum-specific keypaths
1470/// EnumKeyPath - A keypath for enum variants that supports both extraction and embedding
1471/// Uses generic type parameters instead of dynamic dispatch for zero-cost abstraction
1472/// 
1473/// This struct serves dual purpose:
1474/// 1. As a concrete keypath instance: `EnumKeyPath<Enum, Variant, ExtractFn, EmbedFn>`
1475/// 2. As a namespace for static factory methods: `EnumKeyPath::readable_enum(...)`
1476pub struct EnumKeyPath<Enum = (), Variant = (), ExtractFn = fn(&()) -> Option<&()>, EmbedFn = fn(()) -> ()> 
1477where
1478    ExtractFn: for<'r> Fn(&'r Enum) -> Option<&'r Variant> + 'static,
1479    EmbedFn: Fn(Variant) -> Enum + 'static,
1480{
1481    extractor: OptionalKeyPath<Enum, Variant, ExtractFn>,
1482    embedder: EmbedFn,
1483}
1484
1485impl<Enum, Variant, ExtractFn, EmbedFn> EnumKeyPath<Enum, Variant, ExtractFn, EmbedFn>
1486where
1487    ExtractFn: for<'r> Fn(&'r Enum) -> Option<&'r Variant> + 'static,
1488    EmbedFn: Fn(Variant) -> Enum + 'static,
1489{
1490    /// Create a new EnumKeyPath with extractor and embedder functions
1491    pub fn new(
1492        extractor: ExtractFn,
1493        embedder: EmbedFn,
1494    ) -> Self {
1495        Self {
1496            extractor: OptionalKeyPath::new(extractor),
1497            embedder,
1498        }
1499    }
1500    
1501    /// Extract the value from an enum variant
1502    pub fn get<'r>(&self, enum_value: &'r Enum) -> Option<&'r Variant> {
1503        self.extractor.get(enum_value)
1504    }
1505    
1506    /// Embed a value into the enum variant
1507    pub fn embed(&self, value: Variant) -> Enum {
1508        (self.embedder)(value)
1509    }
1510    
1511    /// Get the underlying OptionalKeyPath for composition
1512    pub fn as_optional(&self) -> &OptionalKeyPath<Enum, Variant, ExtractFn> {
1513        &self.extractor
1514    }
1515    
1516    /// Convert to OptionalKeyPath (loses embedding capability but gains composition)
1517    pub fn to_optional(self) -> OptionalKeyPath<Enum, Variant, ExtractFn> {
1518        self.extractor
1519    }
1520}
1521
1522// Static factory methods for EnumKeyPath
1523impl EnumKeyPath {
1524    /// Create a readable enum keypath with both extraction and embedding
1525    /// Returns an EnumKeyPath that supports both get() and embed() operations
1526    pub fn readable_enum<Enum, Variant, ExtractFn, EmbedFn>(
1527        embedder: EmbedFn,
1528        extractor: ExtractFn,
1529    ) -> EnumKeyPath<Enum, Variant, ExtractFn, EmbedFn>
1530    where
1531        ExtractFn: for<'r> Fn(&'r Enum) -> Option<&'r Variant> + 'static,
1532        EmbedFn: Fn(Variant) -> Enum + 'static,
1533    {
1534        EnumKeyPath::new(extractor, embedder)
1535    }
1536    
1537    /// Extract from a specific enum variant
1538    pub fn for_variant<Enum, Variant, ExtractFn>(
1539        extractor: ExtractFn
1540    ) -> OptionalKeyPath<Enum, Variant, impl for<'r> Fn(&'r Enum) -> Option<&'r Variant>>
1541    where
1542        ExtractFn: Fn(&Enum) -> Option<&Variant>,
1543    {
1544        OptionalKeyPath::new(extractor)
1545    }
1546    
1547    /// Match against multiple variants (returns a tagged union)
1548    pub fn for_match<Enum, Output, MatchFn>(
1549        matcher: MatchFn
1550    ) -> KeyPath<Enum, Output, impl for<'r> Fn(&'r Enum) -> &'r Output>
1551    where
1552        MatchFn: Fn(&Enum) -> &Output,
1553    {
1554        KeyPath::new(matcher)
1555    }
1556    
1557    /// Extract from Result<T, E> - Ok variant
1558    pub fn for_ok<T, E>() -> OptionalKeyPath<Result<T, E>, T, impl for<'r> Fn(&'r Result<T, E>) -> Option<&'r T>> {
1559        OptionalKeyPath::new(|result: &Result<T, E>| result.as_ref().ok())
1560    }
1561    
1562    /// Extract from Result<T, E> - Err variant
1563    pub fn for_err<T, E>() -> OptionalKeyPath<Result<T, E>, E, impl for<'r> Fn(&'r Result<T, E>) -> Option<&'r E>> {
1564        OptionalKeyPath::new(|result: &Result<T, E>| result.as_ref().err())
1565    }
1566    
1567    /// Extract from Option<T> - Some variant
1568    pub fn for_some<T>() -> OptionalKeyPath<Option<T>, T, impl for<'r> Fn(&'r Option<T>) -> Option<&'r T>> {
1569        OptionalKeyPath::new(|opt: &Option<T>| opt.as_ref())
1570    }
1571    
1572    /// Extract from Option<T> - Some variant (alias for for_some for consistency)
1573    pub fn for_option<T>() -> OptionalKeyPath<Option<T>, T, impl for<'r> Fn(&'r Option<T>) -> Option<&'r T>> {
1574        OptionalKeyPath::new(|opt: &Option<T>| opt.as_ref())
1575    }
1576    
1577    /// Unwrap Box<T> -> T
1578    pub fn for_box<T>() -> KeyPath<Box<T>, T, impl for<'r> Fn(&'r Box<T>) -> &'r T> {
1579        KeyPath::new(|b: &Box<T>| b.as_ref())
1580    }
1581    
1582    /// Unwrap Arc<T> -> T
1583    pub fn for_arc<T>() -> KeyPath<Arc<T>, T, impl for<'r> Fn(&'r Arc<T>) -> &'r T> {
1584        KeyPath::new(|arc: &Arc<T>| arc.as_ref())
1585    }
1586    
1587    /// Unwrap Rc<T> -> T
1588    pub fn for_rc<T>() -> KeyPath<std::rc::Rc<T>, T, impl for<'r> Fn(&'r std::rc::Rc<T>) -> &'r T> {
1589        KeyPath::new(|rc: &std::rc::Rc<T>| rc.as_ref())
1590    }
1591
1592    /// Unwrap Box<T> -> T (mutable)
1593    pub fn for_box_mut<T>() -> WritableKeyPath<Box<T>, T, impl for<'r> Fn(&'r mut Box<T>) -> &'r mut T> {
1594        WritableKeyPath::new(|b: &mut Box<T>| b.as_mut())
1595    }
1596
1597    // Note: Arc<T> and Rc<T> don't support direct mutable access without interior mutability
1598    // (e.g., Arc<Mutex<T>> or Rc<RefCell<T>>). These methods are not provided as they
1599    // would require unsafe code or interior mutability patterns.
1600}
1601
1602// Helper to create enum variant keypaths with type inference
1603pub fn variant_of<Enum, Variant, F>(extractor: F) -> OptionalKeyPath<Enum, Variant, F>
1604where
1605    F: for<'r> Fn(&'r Enum) -> Option<&'r Variant>,
1606{
1607    OptionalKeyPath::new(extractor)
1608}
1609
1610// ========== PARTIAL KEYPATHS (Hide Value Type) ==========
1611
1612/// PartialKeyPath - Hides the Value type but keeps Root visible
1613/// Useful for storing keypaths in collections without knowing the exact Value type
1614/// 
1615/// # Why PhantomData<Root>?
1616/// 
1617/// `PhantomData<Root>` is needed because:
1618/// 1. The `Root` type parameter is not actually stored in the struct (only used in the closure)
1619/// 2. Rust needs to know the generic type parameter for:
1620///    - Type checking at compile time
1621///    - Ensuring correct usage (e.g., `PartialKeyPath<User>` can only be used with `&User`)
1622///    - Preventing mixing different Root types
1623/// 3. Without `PhantomData`, Rust would complain that `Root` is unused
1624/// 4. `PhantomData` is zero-sized - it adds no runtime overhead
1625#[derive(Clone)]
1626pub struct PartialKeyPath<Root> {
1627    getter: Rc<dyn for<'r> Fn(&'r Root) -> &'r dyn Any>,
1628    value_type_id: TypeId,
1629    _phantom: PhantomData<Root>,
1630}
1631
1632impl<Root> PartialKeyPath<Root> {
1633    pub fn new<Value>(keypath: KeyPath<Root, Value, impl for<'r> Fn(&'r Root) -> &'r Value + 'static>) -> Self
1634    where
1635        Value: Any + 'static,
1636        Root: 'static,
1637    {
1638        let value_type_id = TypeId::of::<Value>();
1639        let getter = Rc::new(keypath.getter);
1640        
1641        Self {
1642            getter: Rc::new(move |root: &Root| {
1643                let value: &Value = getter(root);
1644                value as &dyn Any
1645            }),
1646            value_type_id,
1647            _phantom: PhantomData,
1648        }
1649    }
1650    
1651    /// Create a PartialKeyPath from a concrete KeyPath
1652    /// Alias for `new()` for consistency with `from()` pattern
1653    pub fn from<Value>(keypath: KeyPath<Root, Value, impl for<'r> Fn(&'r Root) -> &'r Value + 'static>) -> Self
1654    where
1655        Value: Any + 'static,
1656        Root: 'static,
1657    {
1658        Self::new(keypath)
1659    }
1660    
1661    pub fn get<'r>(&self, root: &'r Root) -> &'r dyn Any {
1662        (self.getter)(root)
1663    }
1664    
1665    /// Get the TypeId of the Value type
1666    pub fn value_type_id(&self) -> TypeId {
1667        self.value_type_id
1668    }
1669    
1670    /// Try to downcast the result to a specific type
1671    pub fn get_as<'a, Value: Any>(&self, root: &'a Root) -> Option<&'a Value> {
1672        if self.value_type_id == TypeId::of::<Value>() {
1673            self.get(root).downcast_ref::<Value>()
1674        } else {
1675            None
1676        }
1677    }
1678    
1679    /// Get a human-readable name for the value type
1680    /// Returns a string representation of the TypeId
1681    pub fn kind_name(&self) -> String {
1682        format!("{:?}", self.value_type_id)
1683    }
1684}
1685
1686/// PartialOptionalKeyPath - Hides the Value type but keeps Root visible
1687/// Useful for storing optional keypaths in collections without knowing the exact Value type
1688/// 
1689/// # Why PhantomData<Root>?
1690/// 
1691/// See `PartialKeyPath` documentation for explanation of why `PhantomData` is needed.
1692#[derive(Clone)]
1693pub struct PartialOptionalKeyPath<Root> {
1694    getter: Rc<dyn for<'r> Fn(&'r Root) -> Option<&'r dyn Any>>,
1695    value_type_id: TypeId,
1696    _phantom: PhantomData<Root>,
1697}
1698
1699impl<Root> PartialOptionalKeyPath<Root> {
1700    pub fn new<Value>(keypath: OptionalKeyPath<Root, Value, impl for<'r> Fn(&'r Root) -> Option<&'r Value> + 'static>) -> Self
1701    where
1702        Value: Any + 'static,
1703        Root: 'static,
1704    {
1705        let value_type_id = TypeId::of::<Value>();
1706        let getter = Rc::new(keypath.getter);
1707        
1708        Self {
1709            getter: Rc::new(move |root: &Root| {
1710                getter(root).map(|value: &Value| value as &dyn Any)
1711            }),
1712            value_type_id,
1713            _phantom: PhantomData,
1714        }
1715    }
1716    
1717    pub fn get<'r>(&self, root: &'r Root) -> Option<&'r dyn Any> {
1718        (self.getter)(root)
1719    }
1720    
1721    /// Get the TypeId of the Value type
1722    pub fn value_type_id(&self) -> TypeId {
1723        self.value_type_id
1724    }
1725    
1726    /// Try to downcast the result to a specific type
1727    pub fn get_as<'a, Value: Any>(&self, root: &'a Root) -> Option<Option<&'a Value>> {
1728        if self.value_type_id == TypeId::of::<Value>() {
1729            self.get(root).map(|any| any.downcast_ref::<Value>())
1730        } else {
1731            None
1732        }
1733    }
1734    
1735    /// Chain with another PartialOptionalKeyPath
1736    /// Note: This requires the Value type of the first keypath to match the Root type of the second
1737    /// For type-erased chaining, consider using AnyKeyPath instead
1738    pub fn then<MidValue>(
1739        self,
1740        next: PartialOptionalKeyPath<MidValue>,
1741    ) -> PartialOptionalKeyPath<Root>
1742    where
1743        MidValue: Any + 'static,
1744        Root: 'static,
1745    {
1746        let first = self.getter;
1747        let second = next.getter;
1748        let value_type_id = next.value_type_id;
1749        
1750        PartialOptionalKeyPath {
1751            getter: Rc::new(move |root: &Root| {
1752                first(root).and_then(|any| {
1753                    if let Some(mid_value) = any.downcast_ref::<MidValue>() {
1754                        second(mid_value)
1755                    } else {
1756                        None
1757                    }
1758                })
1759            }),
1760            value_type_id,
1761            _phantom: PhantomData,
1762        }
1763    }
1764}
1765
1766/// PartialWritableKeyPath - Hides the Value type but keeps Root visible (writable)
1767/// 
1768/// # Why PhantomData<Root>?
1769/// 
1770/// See `PartialKeyPath` documentation for explanation of why `PhantomData` is needed.
1771#[derive(Clone)]
1772pub struct PartialWritableKeyPath<Root> {
1773    getter: Rc<dyn for<'r> Fn(&'r mut Root) -> &'r mut dyn Any>,
1774    value_type_id: TypeId,
1775    _phantom: PhantomData<Root>,
1776}
1777
1778impl<Root> PartialWritableKeyPath<Root> {
1779    pub fn new<Value>(keypath: WritableKeyPath<Root, Value, impl for<'r> Fn(&'r mut Root) -> &'r mut Value + 'static>) -> Self
1780    where
1781        Value: Any + 'static,
1782        Root: 'static,
1783    {
1784        let value_type_id = TypeId::of::<Value>();
1785        let getter = Rc::new(keypath.getter);
1786        
1787        Self {
1788            getter: Rc::new(move |root: &mut Root| {
1789                let value: &mut Value = getter(root);
1790                value as &mut dyn Any
1791            }),
1792            value_type_id,
1793            _phantom: PhantomData,
1794        }
1795    }
1796    
1797    /// Create a PartialWritableKeyPath from a concrete WritableKeyPath
1798    /// Alias for `new()` for consistency with `from()` pattern
1799    pub fn from<Value>(keypath: WritableKeyPath<Root, Value, impl for<'r> Fn(&'r mut Root) -> &'r mut Value + 'static>) -> Self
1800    where
1801        Value: Any + 'static,
1802        Root: 'static,
1803    {
1804        Self::new(keypath)
1805    }
1806    
1807    pub fn get_mut<'r>(&self, root: &'r mut Root) -> &'r mut dyn Any {
1808        (self.getter)(root)
1809    }
1810    
1811    /// Get the TypeId of the Value type
1812    pub fn value_type_id(&self) -> TypeId {
1813        self.value_type_id
1814    }
1815    
1816    /// Try to downcast the result to a specific type
1817    pub fn get_mut_as<'a, Value: Any>(&self, root: &'a mut Root) -> Option<&'a mut Value> {
1818        if self.value_type_id == TypeId::of::<Value>() {
1819            self.get_mut(root).downcast_mut::<Value>()
1820        } else {
1821            None
1822        }
1823    }
1824}
1825
1826/// PartialWritableOptionalKeyPath - Hides the Value type but keeps Root visible (writable optional)
1827/// 
1828/// # Why PhantomData<Root>?
1829/// 
1830/// See `PartialKeyPath` documentation for explanation of why `PhantomData` is needed.
1831#[derive(Clone)]
1832pub struct PartialWritableOptionalKeyPath<Root> {
1833    getter: Rc<dyn for<'r> Fn(&'r mut Root) -> Option<&'r mut dyn Any>>,
1834    value_type_id: TypeId,
1835    _phantom: PhantomData<Root>,
1836}
1837
1838impl<Root> PartialWritableOptionalKeyPath<Root> {
1839    pub fn new<Value>(keypath: WritableOptionalKeyPath<Root, Value, impl for<'r> Fn(&'r mut Root) -> Option<&'r mut Value> + 'static>) -> Self
1840    where
1841        Value: Any + 'static,
1842        Root: 'static,
1843    {
1844        let value_type_id = TypeId::of::<Value>();
1845        let getter = Rc::new(keypath.getter);
1846        
1847        Self {
1848            getter: Rc::new(move |root: &mut Root| {
1849                getter(root).map(|value: &mut Value| value as &mut dyn Any)
1850            }),
1851            value_type_id,
1852            _phantom: PhantomData,
1853        }
1854    }
1855    
1856    pub fn get_mut<'r>(&self, root: &'r mut Root) -> Option<&'r mut dyn Any> {
1857        (self.getter)(root)
1858    }
1859    
1860    /// Get the TypeId of the Value type
1861    pub fn value_type_id(&self) -> TypeId {
1862        self.value_type_id
1863    }
1864    
1865    /// Try to downcast the result to a specific type
1866    pub fn get_mut_as<'a, Value: Any>(&self, root: &'a mut Root) -> Option<Option<&'a mut Value>> {
1867        if self.value_type_id == TypeId::of::<Value>() {
1868            self.get_mut(root).map(|any| any.downcast_mut::<Value>())
1869        } else {
1870            None
1871        }
1872    }
1873}
1874
1875// ========== ANY KEYPATHS (Hide Both Root and Value Types) ==========
1876
1877/// AnyKeyPath - Hides both Root and Value types
1878/// Equivalent to Swift's AnyKeyPath
1879/// Useful for storing keypaths in collections without knowing either type
1880/// 
1881/// # Why No PhantomData?
1882/// 
1883/// Unlike `PartialKeyPath`, `AnyKeyPath` doesn't need `PhantomData` because:
1884/// - Both `Root` and `Value` types are completely erased
1885/// - We store `TypeId` instead for runtime type checking
1886/// - The type information is encoded in the closure's behavior, not the struct
1887/// - There's no generic type parameter to track at compile time
1888#[derive(Clone)]
1889pub struct AnyKeyPath {
1890    getter: Rc<dyn for<'r> Fn(&'r dyn Any) -> Option<&'r dyn Any>>,
1891    root_type_id: TypeId,
1892    value_type_id: TypeId,
1893}
1894
1895impl AnyKeyPath {
1896    pub fn new<Root, Value>(keypath: OptionalKeyPath<Root, Value, impl for<'r> Fn(&'r Root) -> Option<&'r Value> + 'static>) -> Self
1897    where
1898        Root: Any + 'static,
1899        Value: Any + 'static,
1900    {
1901        let root_type_id = TypeId::of::<Root>();
1902        let value_type_id = TypeId::of::<Value>();
1903        let getter = keypath.getter;
1904        
1905        Self {
1906            getter: Rc::new(move |any: &dyn Any| {
1907                if let Some(root) = any.downcast_ref::<Root>() {
1908                    getter(root).map(|value: &Value| value as &dyn Any)
1909                } else {
1910                    None
1911                }
1912            }),
1913            root_type_id,
1914            value_type_id,
1915        }
1916    }
1917    
1918    /// Create an AnyKeyPath from a concrete OptionalKeyPath
1919    /// Alias for `new()` for consistency with `from()` pattern
1920    pub fn from<Root, Value>(keypath: OptionalKeyPath<Root, Value, impl for<'r> Fn(&'r Root) -> Option<&'r Value> + 'static>) -> Self
1921    where
1922        Root: Any + 'static,
1923        Value: Any + 'static,
1924    {
1925        Self::new(keypath)
1926    }
1927    
1928    pub fn get<'r>(&self, root: &'r dyn Any) -> Option<&'r dyn Any> {
1929        (self.getter)(root)
1930    }
1931    
1932    /// Get the TypeId of the Root type
1933    pub fn root_type_id(&self) -> TypeId {
1934        self.root_type_id
1935    }
1936    
1937    /// Get the TypeId of the Value type
1938    pub fn value_type_id(&self) -> TypeId {
1939        self.value_type_id
1940    }
1941    
1942    /// Try to get the value with type checking
1943    pub fn get_as<'a, Root: Any, Value: Any>(&self, root: &'a Root) -> Option<Option<&'a Value>> {
1944        if self.root_type_id == TypeId::of::<Root>() && self.value_type_id == TypeId::of::<Value>() {
1945            self.get(root as &dyn Any).map(|any| any.downcast_ref::<Value>())
1946        } else {
1947            None
1948        }
1949    }
1950    
1951    /// Get a human-readable name for the value type
1952    /// Returns a string representation of the TypeId
1953    pub fn kind_name(&self) -> String {
1954        format!("{:?}", self.value_type_id)
1955    }
1956}
1957
1958/// AnyWritableKeyPath - Hides both Root and Value types (writable)
1959#[derive(Clone)]
1960pub struct AnyWritableKeyPath {
1961    getter: Rc<dyn for<'r> Fn(&'r mut dyn Any) -> Option<&'r mut dyn Any>>,
1962    root_type_id: TypeId,
1963    value_type_id: TypeId,
1964}
1965
1966/// FailableCombinedKeyPath - A keypath that supports readable, writable, and owned access patterns
1967/// 
1968/// This keypath type combines the functionality of OptionalKeyPath, WritableOptionalKeyPath,
1969/// and adds owned access. It's useful when you need all three access patterns for the same field.
1970#[derive(Clone)]
1971pub struct FailableCombinedKeyPath<Root, Value, ReadFn, WriteFn, OwnedFn>
1972where
1973    ReadFn: for<'r> Fn(&'r Root) -> Option<&'r Value> + 'static,
1974    WriteFn: for<'r> Fn(&'r mut Root) -> Option<&'r mut Value> + 'static,
1975    OwnedFn: Fn(Root) -> Option<Value> + 'static,
1976{
1977    readable: ReadFn,
1978    writable: WriteFn,
1979    owned: OwnedFn,
1980    _phantom: PhantomData<(Root, Value)>,
1981}
1982
1983impl<Root, Value, ReadFn, WriteFn, OwnedFn> FailableCombinedKeyPath<Root, Value, ReadFn, WriteFn, OwnedFn>
1984where
1985    ReadFn: for<'r> Fn(&'r Root) -> Option<&'r Value> + 'static,
1986    WriteFn: for<'r> Fn(&'r mut Root) -> Option<&'r mut Value> + 'static,
1987    OwnedFn: Fn(Root) -> Option<Value> + 'static,
1988{
1989    /// Create a new FailableCombinedKeyPath with all three access patterns
1990    pub fn new(readable: ReadFn, writable: WriteFn, owned: OwnedFn) -> Self {
1991        Self {
1992            readable,
1993            writable,
1994            owned,
1995            _phantom: PhantomData,
1996        }
1997    }
1998    
1999    /// Get an immutable reference to the value (readable access)
2000    pub fn get<'r>(&self, root: &'r Root) -> Option<&'r Value> {
2001        (self.readable)(root)
2002    }
2003    
2004    /// Get a mutable reference to the value (writable access)
2005    pub fn get_mut<'r>(&self, root: &'r mut Root) -> Option<&'r mut Value> {
2006        (self.writable)(root)
2007    }
2008    
2009    /// Get an owned value (owned access) - consumes the root
2010    pub fn get_failable_owned(&self, root: Root) -> Option<Value> {
2011        (self.owned)(root)
2012    }
2013    
2014    /// Convert to OptionalKeyPath (loses writable and owned capabilities)
2015    pub fn to_optional(self) -> OptionalKeyPath<Root, Value, ReadFn> {
2016        OptionalKeyPath::new(self.readable)
2017    }
2018    
2019    /// Convert to WritableOptionalKeyPath (loses owned capability)
2020    pub fn to_writable_optional(self) -> WritableOptionalKeyPath<Root, Value, WriteFn> {
2021        WritableOptionalKeyPath::new(self.writable)
2022    }
2023    
2024    /// Compose this keypath with another FailableCombinedKeyPath
2025    /// Returns a new FailableCombinedKeyPath that chains both keypaths
2026    pub fn then<SubValue, SubReadFn, SubWriteFn, SubOwnedFn>(
2027        self,
2028        next: FailableCombinedKeyPath<Value, SubValue, SubReadFn, SubWriteFn, SubOwnedFn>,
2029    ) -> 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>
2030    where
2031        SubReadFn: for<'r> Fn(&'r Value) -> Option<&'r SubValue> + 'static,
2032        SubWriteFn: for<'r> Fn(&'r mut Value) -> Option<&'r mut SubValue> + 'static,
2033        SubOwnedFn: Fn(Value) -> Option<SubValue> + 'static,
2034        ReadFn: 'static,
2035        WriteFn: 'static,
2036        OwnedFn: 'static,
2037        Value: 'static,
2038        Root: 'static,
2039        SubValue: 'static,
2040    {
2041        let first_read = self.readable;
2042        let first_write = self.writable;
2043        let first_owned = self.owned;
2044        let second_read = next.readable;
2045        let second_write = next.writable;
2046        let second_owned = next.owned;
2047        
2048        FailableCombinedKeyPath::new(
2049            move |root: &Root| {
2050                first_read(root).and_then(|value| second_read(value))
2051            },
2052            move |root: &mut Root| {
2053                first_write(root).and_then(|value| second_write(value))
2054            },
2055            move |root: Root| {
2056                first_owned(root).and_then(|value| second_owned(value))
2057            },
2058        )
2059    }
2060    
2061    /// Compose with OptionalKeyPath (readable only)
2062    /// Returns a FailableCombinedKeyPath that uses the readable from OptionalKeyPath
2063    /// and creates dummy writable/owned closures that return None
2064    pub fn then_optional<SubValue, SubReadFn>(
2065        self,
2066        next: OptionalKeyPath<Value, SubValue, SubReadFn>,
2067    ) -> 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>
2068    where
2069        SubReadFn: for<'r> Fn(&'r Value) -> Option<&'r SubValue> + 'static,
2070        ReadFn: 'static,
2071        WriteFn: 'static,
2072        OwnedFn: 'static,
2073        Value: 'static,
2074        Root: 'static,
2075        SubValue: 'static,
2076    {
2077        let first_read = self.readable;
2078        let first_write = self.writable;
2079        let first_owned = self.owned;
2080        let second_read = next.getter;
2081        
2082        FailableCombinedKeyPath::new(
2083            move |root: &Root| {
2084                first_read(root).and_then(|value| second_read(value))
2085            },
2086            move |_root: &mut Root| {
2087                None // Writable not supported when composing with OptionalKeyPath
2088            },
2089            move |root: Root| {
2090                first_owned(root).and_then(|value| {
2091                    // Try to get owned value, but OptionalKeyPath doesn't support owned
2092                    None
2093                })
2094            },
2095        )
2096    }
2097}
2098
2099// Factory function for FailableCombinedKeyPath
2100impl FailableCombinedKeyPath<(), (), fn(&()) -> Option<&()>, fn(&mut ()) -> Option<&mut ()>, fn(()) -> Option<()>> {
2101    /// Create a FailableCombinedKeyPath with all three access patterns
2102    pub fn failable_combined<Root, Value, ReadFn, WriteFn, OwnedFn>(
2103        readable: ReadFn,
2104        writable: WriteFn,
2105        owned: OwnedFn,
2106    ) -> FailableCombinedKeyPath<Root, Value, ReadFn, WriteFn, OwnedFn>
2107    where
2108        ReadFn: for<'r> Fn(&'r Root) -> Option<&'r Value> + 'static,
2109        WriteFn: for<'r> Fn(&'r mut Root) -> Option<&'r mut Value> + 'static,
2110        OwnedFn: Fn(Root) -> Option<Value> + 'static,
2111    {
2112        FailableCombinedKeyPath::new(readable, writable, owned)
2113    }
2114}
2115
2116impl AnyWritableKeyPath {
2117    pub fn new<Root, Value>(keypath: WritableOptionalKeyPath<Root, Value, impl for<'r> Fn(&'r mut Root) -> Option<&'r mut Value> + 'static>) -> Self
2118    where
2119        Root: Any + 'static,
2120        Value: Any + 'static,
2121    {
2122        let root_type_id = TypeId::of::<Root>();
2123        let value_type_id = TypeId::of::<Value>();
2124        let getter = keypath.getter;
2125        
2126        Self {
2127            getter: Rc::new(move |any: &mut dyn Any| {
2128                if let Some(root) = any.downcast_mut::<Root>() {
2129                    getter(root).map(|value: &mut Value| value as &mut dyn Any)
2130                } else {
2131                    None
2132                }
2133            }),
2134            root_type_id,
2135            value_type_id,
2136        }
2137    }
2138    
2139    pub fn get_mut<'r>(&self, root: &'r mut dyn Any) -> Option<&'r mut dyn Any> {
2140        (self.getter)(root)
2141    }
2142    
2143    /// Get the TypeId of the Root type
2144    pub fn root_type_id(&self) -> TypeId {
2145        self.root_type_id
2146    }
2147    
2148    /// Get the TypeId of the Value type
2149    pub fn value_type_id(&self) -> TypeId {
2150        self.value_type_id
2151    }
2152    
2153    /// Try to get the value with type checking
2154    pub fn get_mut_as<'a, Root: Any, Value: Any>(&self, root: &'a mut Root) -> Option<Option<&'a mut Value>> {
2155        if self.root_type_id == TypeId::of::<Root>() && self.value_type_id == TypeId::of::<Value>() {
2156            self.get_mut(root as &mut dyn Any).map(|any| any.downcast_mut::<Value>())
2157        } else {
2158            None
2159        }
2160    }
2161}
2162
2163// Conversion methods from concrete keypaths to partial/any keypaths
2164impl<Root, Value, F> KeyPath<Root, Value, F>
2165where
2166    F: for<'r> Fn(&'r Root) -> &'r Value + 'static,
2167    Root: 'static,
2168    Value: Any + 'static,
2169{
2170    /// Convert to PartialKeyPath (hides Value type)
2171    pub fn to_partial(self) -> PartialKeyPath<Root> {
2172        PartialKeyPath::new(self)
2173    }
2174    
2175    /// Alias for `to_partial()` - converts to PartialKeyPath
2176    pub fn to(self) -> PartialKeyPath<Root> {
2177        self.to_partial()
2178    }
2179}
2180
2181impl<Root, Value, F> OptionalKeyPath<Root, Value, F>
2182where
2183    F: for<'r> Fn(&'r Root) -> Option<&'r Value> + 'static,
2184    Root: Any + 'static,
2185    Value: Any + 'static,
2186{
2187    /// Convert to PartialOptionalKeyPath (hides Value type)
2188    pub fn to_partial(self) -> PartialOptionalKeyPath<Root> {
2189        PartialOptionalKeyPath::new(self)
2190    }
2191    
2192    /// Convert to AnyKeyPath (hides both Root and Value types)
2193    pub fn to_any(self) -> AnyKeyPath {
2194        AnyKeyPath::new(self)
2195    }
2196    
2197    /// Convert to PartialOptionalKeyPath (alias for `to_partial()`)
2198    pub fn to(self) -> PartialOptionalKeyPath<Root> {
2199        self.to_partial()
2200    }
2201}
2202
2203impl<Root, Value, F> WritableKeyPath<Root, Value, F>
2204where
2205    F: for<'r> Fn(&'r mut Root) -> &'r mut Value + 'static,
2206    Root: 'static,
2207    Value: Any + 'static,
2208{
2209    /// Convert to PartialWritableKeyPath (hides Value type)
2210    pub fn to_partial(self) -> PartialWritableKeyPath<Root> {
2211        PartialWritableKeyPath::new(self)
2212    }
2213    
2214    /// Alias for `to_partial()` - converts to PartialWritableKeyPath
2215    pub fn to(self) -> PartialWritableKeyPath<Root> {
2216        self.to_partial()
2217    }
2218}
2219
2220impl<Root, Value, F> WritableOptionalKeyPath<Root, Value, F>
2221where
2222    F: for<'r> Fn(&'r mut Root) -> Option<&'r mut Value> + 'static,
2223    Root: Any + 'static,
2224    Value: Any + 'static,
2225{
2226    /// Convert to PartialWritableOptionalKeyPath (hides Value type)
2227    pub fn to_partial(self) -> PartialWritableOptionalKeyPath<Root> {
2228        PartialWritableOptionalKeyPath::new(self)
2229    }
2230    
2231    /// Convert to AnyWritableKeyPath (hides both Root and Value types)
2232    pub fn to_any(self) -> AnyWritableKeyPath {
2233        AnyWritableKeyPath::new(self)
2234    }
2235    
2236    /// Convert to PartialWritableOptionalKeyPath (alias for `to_partial()`)
2237    pub fn to(self) -> PartialWritableOptionalKeyPath<Root> {
2238        self.to_partial()
2239    }
2240}
2241
2242#[cfg(test)]
2243mod tests {
2244    use super::*;
2245    use std::sync::atomic::{AtomicUsize, Ordering};
2246    use std::rc::Rc;
2247
2248    // Global counter to track memory allocations/deallocations
2249    static ALLOC_COUNT: AtomicUsize = AtomicUsize::new(0);
2250    static DEALLOC_COUNT: AtomicUsize = AtomicUsize::new(0);
2251
2252    // Type that panics on clone to detect unwanted cloning
2253    #[derive(Debug)]
2254    struct NoCloneType {
2255        id: usize,
2256        data: String,
2257    }
2258
2259    impl NoCloneType {
2260        fn new(data: String) -> Self {
2261            ALLOC_COUNT.fetch_add(1, Ordering::SeqCst);
2262            Self {
2263                id: ALLOC_COUNT.load(Ordering::SeqCst),
2264                data,
2265            }
2266        }
2267    }
2268
2269    impl Clone for NoCloneType {
2270        fn clone(&self) -> Self {
2271            eprintln!("[DEBUG] NoCloneType should not be cloned! ID: {}", self.id);
2272            unreachable!("NoCloneType should not be cloned! ID: {}", self.id);
2273        }
2274    }
2275
2276    impl Drop for NoCloneType {
2277        fn drop(&mut self) {
2278            DEALLOC_COUNT.fetch_add(1, Ordering::SeqCst);
2279        }
2280    }
2281
2282    // Helper functions for testing memory management
2283    fn reset_memory_counters() {
2284        ALLOC_COUNT.store(0, Ordering::SeqCst);
2285        DEALLOC_COUNT.store(0, Ordering::SeqCst);
2286    }
2287
2288    fn get_alloc_count() -> usize {
2289        ALLOC_COUNT.load(Ordering::SeqCst)
2290    }
2291
2292    fn get_dealloc_count() -> usize {
2293        DEALLOC_COUNT.load(Ordering::SeqCst)
2294    }
2295
2296// Usage example
2297#[derive(Debug)]
2298struct User {
2299    name: String,
2300    metadata: Option<Box<UserMetadata>>,
2301    friends: Vec<Arc<User>>,
2302}
2303
2304#[derive(Debug)]
2305struct UserMetadata {
2306    created_at: String,
2307}
2308
2309fn some_fn() {
2310        let akash = User {
2311        name: "Alice".to_string(),
2312        metadata: Some(Box::new(UserMetadata {
2313            created_at: "2024-01-01".to_string(),
2314        })),
2315        friends: vec![
2316            Arc::new(User {
2317                name: "Bob".to_string(),
2318                metadata: None,
2319                friends: vec![],
2320            }),
2321        ],
2322    };
2323    
2324    // Create keypaths
2325    let name_kp = KeyPath::new(|u: &User| &u.name);
2326    let metadata_kp = OptionalKeyPath::new(|u: &User| u.metadata.as_ref());
2327    let friends_kp = KeyPath::new(|u: &User| &u.friends);
2328    
2329    // Use them
2330        println!("Name: {}", name_kp.get(&akash));
2331    
2332        if let Some(metadata) = metadata_kp.get(&akash) {
2333        println!("Has metadata: {:?}", metadata);
2334    }
2335    
2336    // Access first friend's name
2337        if let Some(first_friend) = akash.friends.get(0) {
2338        println!("First friend: {}", name_kp.get(first_friend));
2339    }
2340    
2341        // Access metadata through Box using for_box()
2342    let created_at_kp = KeyPath::new(|m: &UserMetadata| &m.created_at);
2343    
2344        if let Some(metadata) = akash.metadata.as_ref() {
2345            // Use for_box() to unwrap Box<UserMetadata> to &UserMetadata
2346            let boxed_metadata: &Box<UserMetadata> = metadata;
2347            let unwrapped = boxed_metadata.as_ref();
2348            println!("Created at: {:?}", created_at_kp.get(unwrapped));
2349        }
2350    }
2351
2352    #[test]
2353    fn test_name() {
2354        some_fn();
2355    }
2356    
2357    #[test]
2358    fn test_no_cloning_on_keypath_operations() {
2359        reset_memory_counters();
2360        
2361        // Create a value that panics on clone
2362        let value = NoCloneType::new("test".to_string());
2363        let boxed = Box::new(value);
2364        
2365        // Create keypath - should not clone
2366        let kp = KeyPath::new(|b: &Box<NoCloneType>| b.as_ref());
2367        
2368        // Access value - should not clone
2369        let _ref = kp.get(&boxed);
2370        
2371        // Clone the keypath itself (this is allowed)
2372        let _kp_clone = kp.clone();
2373        
2374        // Access again - should not clone the value
2375        let _ref2 = _kp_clone.get(&boxed);
2376        
2377        // Verify no panics occurred (if we got here, no cloning happened)
2378        assert_eq!(get_alloc_count(), 1);
2379    }
2380    
2381    #[test]
2382    fn test_no_cloning_on_optional_keypath_operations() {
2383        reset_memory_counters();
2384        
2385        let value = NoCloneType::new("test".to_string());
2386        let opt = Some(Box::new(value));
2387        
2388        // Create optional keypath
2389        let okp = OptionalKeyPath::new(|o: &Option<Box<NoCloneType>>| o.as_ref());
2390        
2391        // Access - should not clone
2392        let _ref = okp.get(&opt);
2393        
2394        // Clone keypath (allowed)
2395        let _okp_clone = okp.clone();
2396        
2397        // Chain operations - should not clone values
2398        let chained = okp.then(OptionalKeyPath::new(|b: &Box<NoCloneType>| Some(b.as_ref())));
2399        let _ref2 = chained.get(&opt);
2400        
2401        assert_eq!(get_alloc_count(), 1);
2402    }
2403    
2404    #[test]
2405    fn test_memory_release() {
2406        reset_memory_counters();
2407        
2408        {
2409            let value = NoCloneType::new("test".to_string());
2410            let boxed = Box::new(value);
2411            let kp = KeyPath::new(|b: &Box<NoCloneType>| b.as_ref());
2412            
2413            // Use the keypath
2414            let _ref = kp.get(&boxed);
2415            
2416            // boxed goes out of scope here
2417        }
2418        
2419        // After drop, memory should be released
2420        // Note: This is a best-effort check since drop timing can vary
2421        assert_eq!(get_alloc_count(), 1);
2422        // Deallocation happens when the value is dropped
2423        // We can't reliably test exact timing, but we verify the counter exists
2424    }
2425    
2426    #[test]
2427    fn test_keypath_clone_does_not_clone_underlying_data() {
2428        reset_memory_counters();
2429        
2430        let value = NoCloneType::new("data".to_string());
2431        let rc_value = Rc::new(value);
2432        
2433        // Create keypath
2434        let kp = KeyPath::new(|r: &Rc<NoCloneType>| r.as_ref());
2435        
2436        // Clone keypath multiple times
2437        let kp1 = kp.clone();
2438        let kp2 = kp.clone();
2439        let kp3 = kp1.clone();
2440        
2441        // All should work without cloning the underlying data
2442        let _ref1 = kp.get(&rc_value);
2443        let _ref2 = kp1.get(&rc_value);
2444        let _ref3 = kp2.get(&rc_value);
2445        let _ref4 = kp3.get(&rc_value);
2446        
2447        // Only one allocation should have happened
2448        assert_eq!(get_alloc_count(), 1);
2449    }
2450    
2451    #[test]
2452    fn test_optional_keypath_chaining_no_clone() {
2453        reset_memory_counters();
2454        
2455        let value = NoCloneType::new("value1".to_string());
2456        
2457        struct Container {
2458            inner: Option<Box<NoCloneType>>,
2459        }
2460        
2461        let container = Container {
2462            inner: Some(Box::new(value)),
2463        };
2464        
2465        // Create chained keypath
2466        let kp1 = OptionalKeyPath::new(|c: &Container| c.inner.as_ref());
2467        let kp2 = OptionalKeyPath::new(|b: &Box<NoCloneType>| Some(b.as_ref()));
2468        
2469        // Chain them - should not clone
2470        let chained = kp1.then(kp2);
2471        
2472        // Use chained keypath
2473        let _result = chained.get(&container);
2474        
2475        // Should only have one allocation
2476        assert_eq!(get_alloc_count(), 1);
2477    }
2478    
2479    #[test]
2480    fn test_for_box_no_clone() {
2481        reset_memory_counters();
2482        
2483        let value = NoCloneType::new("test".to_string());
2484        let boxed = Box::new(value);
2485        let opt_boxed = Some(boxed);
2486        
2487        // Create keypath with for_box
2488        let kp = OptionalKeyPath::new(|o: &Option<Box<NoCloneType>>| o.as_ref());
2489        let unwrapped = kp.for_box();
2490        
2491        // Access - should not clone
2492        let _ref = unwrapped.get(&opt_boxed);
2493        
2494        assert_eq!(get_alloc_count(), 1);
2495    }
2496    
2497    // ========== MACRO USAGE EXAMPLES ==========
2498    
2499    #[derive(Debug, PartialEq)]
2500    struct TestUser {
2501        name: String,
2502        age: u32,
2503        metadata: Option<String>,
2504        address: Option<TestAddress>,
2505    }
2506    
2507    #[derive(Debug, PartialEq)]
2508    struct TestAddress {
2509        street: String,
2510        city: String,
2511        country: Option<TestCountry>,
2512    }
2513    
2514    #[derive(Debug, PartialEq)]
2515    struct TestCountry {
2516        name: String,
2517    }
2518    
2519    #[test]
2520    fn test_keypath_macro() {
2521        let user = TestUser {
2522            name: "Alice".to_string(),
2523            age: 30,
2524            metadata: None,
2525            address: None,
2526        };
2527        
2528        // Simple field access using closure
2529        let name_kp = keypath!(|u: &TestUser| &u.name);
2530        assert_eq!(name_kp.get(&user), "Alice");
2531        
2532        // Nested field access
2533        let user_with_address = TestUser {
2534            name: "Bob".to_string(),
2535            age: 25,
2536            metadata: None,
2537            address: Some(TestAddress {
2538                street: "123 Main St".to_string(),
2539                city: "New York".to_string(),
2540                country: None,
2541            }),
2542        };
2543        
2544        let street_kp = keypath!(|u: &TestUser| &u.address.as_ref().unwrap().street);
2545        assert_eq!(street_kp.get(&user_with_address), "123 Main St");
2546        
2547        // Deeper nesting
2548        let user_with_country = TestUser {
2549            name: "Charlie".to_string(),
2550            age: 35,
2551            metadata: None,
2552            address: Some(TestAddress {
2553                street: "456 Oak Ave".to_string(),
2554                city: "London".to_string(),
2555                country: Some(TestCountry {
2556                    name: "UK".to_string(),
2557                }),
2558            }),
2559        };
2560        
2561        let country_name_kp = keypath!(|u: &TestUser| &u.address.as_ref().unwrap().country.as_ref().unwrap().name);
2562        assert_eq!(country_name_kp.get(&user_with_country), "UK");
2563        
2564        // Fallback: using closure
2565        let age_kp = keypath!(|u: &TestUser| &u.age);
2566        assert_eq!(age_kp.get(&user), &30);
2567    }
2568    
2569    #[test]
2570    fn test_opt_keypath_macro() {
2571        let user = TestUser {
2572            name: "Alice".to_string(),
2573            age: 30,
2574            metadata: Some("admin".to_string()),
2575            address: None,
2576        };
2577        
2578        // Simple Option field access using closure
2579        let metadata_kp = opt_keypath!(|u: &TestUser| u.metadata.as_ref());
2580        assert_eq!(metadata_kp.get(&user), Some(&"admin".to_string()));
2581        
2582        // None case
2583        let user_no_metadata = TestUser {
2584            name: "Bob".to_string(),
2585            age: 25,
2586            metadata: None,
2587            address: None,
2588        };
2589        assert_eq!(metadata_kp.get(&user_no_metadata), None);
2590        
2591        // Nested Option access
2592        let user_with_address = TestUser {
2593            name: "Charlie".to_string(),
2594            age: 35,
2595            metadata: None,
2596            address: Some(TestAddress {
2597                street: "789 Pine Rd".to_string(),
2598                city: "Paris".to_string(),
2599                country: None,
2600            }),
2601        };
2602        
2603        let street_kp = opt_keypath!(|u: &TestUser| u.address.as_ref().map(|a| &a.street));
2604        assert_eq!(street_kp.get(&user_with_address), Some(&"789 Pine Rd".to_string()));
2605        
2606        // Deeper nesting through Options
2607        let user_with_country = TestUser {
2608            name: "David".to_string(),
2609            age: 40,
2610            metadata: None,
2611            address: Some(TestAddress {
2612                street: "321 Elm St".to_string(),
2613                city: "Tokyo".to_string(),
2614                country: Some(TestCountry {
2615                    name: "Japan".to_string(),
2616                }),
2617            }),
2618        };
2619        
2620        let country_name_kp = opt_keypath!(|u: &TestUser| u.address.as_ref().and_then(|a| a.country.as_ref().map(|c| &c.name)));
2621        assert_eq!(country_name_kp.get(&user_with_country), Some(&"Japan".to_string()));
2622        
2623        // Fallback: using closure
2624        let metadata_kp2 = opt_keypath!(|u: &TestUser| u.metadata.as_ref());
2625        assert_eq!(metadata_kp2.get(&user), Some(&"admin".to_string()));
2626    }
2627    
2628    #[test]
2629    fn test_writable_keypath_macro() {
2630        let mut user = TestUser {
2631            name: "Alice".to_string(),
2632            age: 30,
2633            metadata: None,
2634            address: None,
2635        };
2636        
2637        // Simple field mutation using closure
2638        let name_kp = writable_keypath!(|u: &mut TestUser| &mut u.name);
2639        *name_kp.get_mut(&mut user) = "Bob".to_string();
2640        assert_eq!(user.name, "Bob");
2641        
2642        // Nested field mutation
2643        let mut user_with_address = TestUser {
2644            name: "Charlie".to_string(),
2645            age: 25,
2646            metadata: None,
2647            address: Some(TestAddress {
2648                street: "123 Main St".to_string(),
2649                city: "New York".to_string(),
2650                country: None,
2651            }),
2652        };
2653        
2654        let street_kp = writable_keypath!(|u: &mut TestUser| &mut u.address.as_mut().unwrap().street);
2655        *street_kp.get_mut(&mut user_with_address) = "456 Oak Ave".to_string();
2656        assert_eq!(user_with_address.address.as_ref().unwrap().street, "456 Oak Ave");
2657        
2658        // Deeper nesting
2659        let mut user_with_country = TestUser {
2660            name: "David".to_string(),
2661            age: 35,
2662            metadata: None,
2663            address: Some(TestAddress {
2664                street: "789 Pine Rd".to_string(),
2665                city: "London".to_string(),
2666                country: Some(TestCountry {
2667                    name: "UK".to_string(),
2668                }),
2669            }),
2670        };
2671        
2672        let country_name_kp = writable_keypath!(|u: &mut TestUser| &mut u.address.as_mut().unwrap().country.as_mut().unwrap().name);
2673        *country_name_kp.get_mut(&mut user_with_country) = "United Kingdom".to_string();
2674        assert_eq!(user_with_country.address.as_ref().unwrap().country.as_ref().unwrap().name, "United Kingdom");
2675        
2676        // Fallback: using closure
2677        let age_kp = writable_keypath!(|u: &mut TestUser| &mut u.age);
2678        *age_kp.get_mut(&mut user) = 31;
2679        assert_eq!(user.age, 31);
2680    }
2681    
2682    #[test]
2683    fn test_writable_opt_keypath_macro() {
2684        let mut user = TestUser {
2685            name: "Alice".to_string(),
2686            age: 30,
2687            metadata: Some("user".to_string()),
2688            address: None,
2689        };
2690        
2691        // Simple Option field mutation using closure
2692        let metadata_kp = writable_opt_keypath!(|u: &mut TestUser| u.metadata.as_mut());
2693        if let Some(metadata) = metadata_kp.get_mut(&mut user) {
2694            *metadata = "admin".to_string();
2695        }
2696        assert_eq!(user.metadata, Some("admin".to_string()));
2697        
2698        // None case - should return None
2699        let mut user_no_metadata = TestUser {
2700            name: "Bob".to_string(),
2701            age: 25,
2702            metadata: None,
2703            address: None,
2704        };
2705        assert_eq!(metadata_kp.get_mut(&mut user_no_metadata), None);
2706        
2707        // Nested Option access
2708        let mut user_with_address = TestUser {
2709            name: "Charlie".to_string(),
2710            age: 35,
2711            metadata: None,
2712            address: Some(TestAddress {
2713                street: "123 Main St".to_string(),
2714                city: "New York".to_string(),
2715                country: None,
2716            }),
2717        };
2718        
2719        let street_kp = writable_opt_keypath!(|u: &mut TestUser| u.address.as_mut().map(|a| &mut a.street));
2720        if let Some(street) = street_kp.get_mut(&mut user_with_address) {
2721            *street = "456 Oak Ave".to_string();
2722        }
2723        assert_eq!(user_with_address.address.as_ref().unwrap().street, "456 Oak Ave");
2724        
2725        // Deeper nesting through Options
2726        let mut user_with_country = TestUser {
2727            name: "David".to_string(),
2728            age: 40,
2729            metadata: None,
2730            address: Some(TestAddress {
2731                street: "789 Pine Rd".to_string(),
2732                city: "Tokyo".to_string(),
2733                country: Some(TestCountry {
2734                    name: "Japan".to_string(),
2735                }),
2736            }),
2737        };
2738        
2739        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)));
2740        if let Some(country_name) = country_name_kp.get_mut(&mut user_with_country) {
2741            *country_name = "Nippon".to_string();
2742        }
2743        assert_eq!(user_with_country.address.as_ref().unwrap().country.as_ref().unwrap().name, "Nippon");
2744        
2745        // Fallback: using closure
2746        let metadata_kp2 = writable_opt_keypath!(|u: &mut TestUser| u.metadata.as_mut());
2747        if let Some(metadata) = metadata_kp2.get_mut(&mut user) {
2748            *metadata = "super_admin".to_string();
2749        }
2750        assert_eq!(user.metadata, Some("super_admin".to_string()));
2751    }
2752}
2753
2754// ========== WithContainer Trait ==========
2755
2756/// Trait for no-clone callback-based access to container types
2757/// Provides methods to execute closures with references to values inside containers
2758/// without requiring cloning of the values
2759pub trait WithContainer<Root, Value> {
2760    /// Execute a closure with a reference to the value inside an Arc
2761    fn with_arc<F, R>(&self, arc: &Arc<Root>, f: F) -> R
2762    where
2763        F: FnOnce(&Value) -> R;
2764
2765    /// Execute a closure with a reference to the value inside a Box
2766    fn with_box<F, R>(&self, boxed: &Box<Root>, f: F) -> R
2767    where
2768        F: FnOnce(&Value) -> R;
2769
2770    /// Execute a closure with a mutable reference to the value inside a Box
2771    fn with_box_mut<F, R>(&self, boxed: &mut Box<Root>, f: F) -> R
2772    where
2773        F: FnOnce(&mut Value) -> R;
2774
2775    /// Execute a closure with a reference to the value inside an Rc
2776    fn with_rc<F, R>(&self, rc: &Rc<Root>, f: F) -> R
2777    where
2778        F: FnOnce(&Value) -> R;
2779
2780    /// Execute a closure with a reference to the value inside a Result
2781    fn with_result<F, R, E>(&self, result: &Result<Root, E>, f: F) -> Option<R>
2782    where
2783        F: FnOnce(&Value) -> R;
2784
2785    /// Execute a closure with a mutable reference to the value inside a Result
2786    fn with_result_mut<F, R, E>(&self, result: &mut Result<Root, E>, f: F) -> Option<R>
2787    where
2788        F: FnOnce(&mut Value) -> R;
2789
2790    /// Execute a closure with a reference to the value inside an Option
2791    fn with_option<F, R>(&self, option: &Option<Root>, f: F) -> Option<R>
2792    where
2793        F: FnOnce(&Value) -> R;
2794
2795    /// Execute a closure with a mutable reference to the value inside an Option
2796    fn with_option_mut<F, R>(&self, option: &mut Option<Root>, f: F) -> Option<R>
2797    where
2798        F: FnOnce(&mut Value) -> R;
2799
2800    /// Execute a closure with a reference to the value inside a RefCell
2801    fn with_refcell<F, R>(&self, refcell: &RefCell<Root>, f: F) -> Option<R>
2802    where
2803        F: FnOnce(&Value) -> R;
2804
2805    /// Execute a closure with a mutable reference to the value inside a RefCell
2806    fn with_refcell_mut<F, R>(&self, refcell: &RefCell<Root>, f: F) -> Option<R>
2807    where
2808        F: FnOnce(&mut Value) -> R;
2809
2810    #[cfg(feature = "tagged")]
2811    /// Execute a closure with a reference to the value inside a Tagged
2812    fn with_tagged<F, R, Tag>(&self, tagged: &Tagged<Root, Tag>, f: F) -> R
2813    where
2814        Tagged<Root, Tag>: std::ops::Deref<Target = Root>,
2815        F: FnOnce(&Value) -> R;
2816
2817    /// Execute a closure with a reference to the value inside a Mutex
2818    fn with_mutex<F, R>(&self, mutex: &Mutex<Root>, f: F) -> Option<R>
2819    where
2820        F: FnOnce(&Value) -> R;
2821
2822    /// Execute a closure with a mutable reference to the value inside a Mutex
2823    fn with_mutex_mut<F, R>(&self, mutex: &mut Mutex<Root>, f: F) -> Option<R>
2824    where
2825        F: FnOnce(&mut Value) -> R;
2826
2827    /// Execute a closure with a reference to the value inside an RwLock
2828    fn with_rwlock<F, R>(&self, rwlock: &RwLock<Root>, f: F) -> Option<R>
2829    where
2830        F: FnOnce(&Value) -> R;
2831
2832    /// Execute a closure with a mutable reference to the value inside an RwLock
2833    fn with_rwlock_mut<F, R>(&self, rwlock: &mut RwLock<Root>, f: F) -> Option<R>
2834    where
2835        F: FnOnce(&mut Value) -> R;
2836
2837    /// Execute a closure with a reference to the value inside an Arc<RwLock<Root>>
2838    fn with_arc_rwlock<F, R>(&self, arc_rwlock: &Arc<RwLock<Root>>, f: F) -> Option<R>
2839    where
2840        F: FnOnce(&Value) -> R;
2841
2842    /// Execute a closure with a mutable reference to the value inside an Arc<RwLock<Root>>
2843    fn with_arc_rwlock_mut<F, R>(&self, arc_rwlock: &Arc<RwLock<Root>>, f: F) -> Option<R>
2844    where
2845        F: FnOnce(&mut Value) -> R;
2846}
2847
2848// Implement WithContainer for KeyPath
2849impl<Root, Value, F> WithContainer<Root, Value> for KeyPath<Root, Value, F>
2850where
2851    F: for<'r> Fn(&'r Root) -> &'r Value + Clone,
2852{
2853    fn with_arc<Callback, R>(&self, arc: &Arc<Root>, f: Callback) -> R
2854    where
2855        Callback: FnOnce(&Value) -> R,
2856    {
2857        self.with_arc(arc, f)
2858    }
2859
2860    fn with_box<Callback, R>(&self, boxed: &Box<Root>, f: Callback) -> R
2861    where
2862        Callback: FnOnce(&Value) -> R,
2863    {
2864        self.with_box(boxed, f)
2865    }
2866
2867    fn with_box_mut<Callback, R>(&self, _boxed: &mut Box<Root>, _f: Callback) -> R
2868    where
2869        Callback: FnOnce(&mut Value) -> R,
2870    {
2871        eprintln!("[DEBUG] KeyPath does not support mutable access - use WritableKeyPath instead");
2872        unreachable!("KeyPath does not support mutable access - use WritableKeyPath instead")
2873    }
2874
2875    fn with_rc<Callback, R>(&self, rc: &Rc<Root>, f: Callback) -> R
2876    where
2877        Callback: FnOnce(&Value) -> R,
2878    {
2879        self.with_rc(rc, f)
2880    }
2881
2882    fn with_result<Callback, R, E>(&self, result: &Result<Root, E>, f: Callback) -> Option<R>
2883    where
2884        Callback: FnOnce(&Value) -> R,
2885    {
2886        self.with_result(result, f)
2887    }
2888
2889    fn with_result_mut<Callback, R, E>(&self, _result: &mut Result<Root, E>, _f: Callback) -> Option<R>
2890    where
2891        Callback: FnOnce(&mut Value) -> R,
2892    {
2893        None
2894    }
2895
2896    fn with_option<Callback, R>(&self, option: &Option<Root>, f: Callback) -> Option<R>
2897    where
2898        Callback: FnOnce(&Value) -> R,
2899    {
2900        self.with_option(option, f)
2901    }
2902
2903    fn with_option_mut<Callback, R>(&self, _option: &mut Option<Root>, _f: Callback) -> Option<R>
2904    where
2905        Callback: FnOnce(&mut Value) -> R,
2906    {
2907        None
2908    }
2909
2910    fn with_refcell<Callback, R>(&self, refcell: &RefCell<Root>, f: Callback) -> Option<R>
2911    where
2912        Callback: FnOnce(&Value) -> R,
2913    {
2914        self.with_refcell(refcell, f)
2915    }
2916
2917    fn with_refcell_mut<Callback, R>(&self, _refcell: &RefCell<Root>, _f: Callback) -> Option<R>
2918    where
2919        Callback: FnOnce(&mut Value) -> R,
2920    {
2921        None
2922    }
2923
2924    #[cfg(feature = "tagged")]
2925    fn with_tagged<Tag, Callback, R>(&self, tagged: &Tagged<Root, Tag>, f: Callback) -> R
2926    where
2927        Tagged<Root, Tag>: std::ops::Deref<Target = Root>,
2928        Callback: FnOnce(&Value) -> R,
2929    {
2930        self.with_tagged(tagged, f)
2931    }
2932
2933    fn with_mutex<Callback, R>(&self, mutex: &Mutex<Root>, f: Callback) -> Option<R>
2934    where
2935        Callback: FnOnce(&Value) -> R,
2936    {
2937        self.with_mutex(mutex, f)
2938    }
2939
2940    fn with_mutex_mut<Callback, R>(&self, _mutex: &mut Mutex<Root>, _f: Callback) -> Option<R>
2941    where
2942        Callback: FnOnce(&mut Value) -> R,
2943    {
2944        None
2945    }
2946
2947    fn with_rwlock<Callback, R>(&self, rwlock: &RwLock<Root>, f: Callback) -> Option<R>
2948    where
2949        Callback: FnOnce(&Value) -> R,
2950    {
2951        self.with_rwlock(rwlock, f)
2952    }
2953
2954    fn with_rwlock_mut<Callback, R>(&self, _rwlock: &mut RwLock<Root>, _f: Callback) -> Option<R>
2955    where
2956        Callback: FnOnce(&mut Value) -> R,
2957    {
2958        None
2959    }
2960
2961    fn with_arc_rwlock<Callback, R>(&self, arc_rwlock: &Arc<RwLock<Root>>, f: Callback) -> Option<R>
2962    where
2963        Callback: FnOnce(&Value) -> R,
2964    {
2965        self.with_arc_rwlock(arc_rwlock, f)
2966    }
2967
2968    fn with_arc_rwlock_mut<Callback, R>(&self, _arc_rwlock: &Arc<RwLock<Root>>, _f: Callback) -> Option<R>
2969    where
2970        Callback: FnOnce(&mut Value) -> R,
2971    {
2972        None
2973    }
2974}
2975
2976// Implement WithContainer for OptionalKeyPath - read-only operations only
2977impl<Root, Value, F> WithContainer<Root, Value> for OptionalKeyPath<Root, Value, F>
2978where
2979    F: for<'r> Fn(&'r Root) -> Option<&'r Value> + Clone,
2980{
2981    fn with_arc<Callback, R>(&self, arc: &Arc<Root>, f: Callback) -> R
2982    where
2983        Callback: FnOnce(&Value) -> R,
2984    {
2985        self.with_arc(arc, f)
2986    }
2987
2988    fn with_box<Callback, R>(&self, boxed: &Box<Root>, f: Callback) -> R
2989    where
2990        Callback: FnOnce(&Value) -> R,
2991    {
2992        self.with_box(boxed, f)
2993    }
2994
2995    fn with_box_mut<Callback, R>(&self, _boxed: &mut Box<Root>, _f: Callback) -> R
2996    where
2997        Callback: FnOnce(&mut Value) -> R,
2998    {
2999        eprintln!("[DEBUG] OptionalKeyPath does not support mutable access - use WritableOptionalKeyPath instead");
3000        unreachable!("OptionalKeyPath does not support mutable access - use WritableOptionalKeyPath instead")
3001    }
3002
3003    fn with_rc<Callback, R>(&self, rc: &Rc<Root>, f: Callback) -> R
3004    where
3005        Callback: FnOnce(&Value) -> R,
3006    {
3007        self.with_rc(rc, f)
3008    }
3009
3010    fn with_result<Callback, R, E>(&self, result: &Result<Root, E>, f: Callback) -> Option<R>
3011    where
3012        Callback: FnOnce(&Value) -> R,
3013    {
3014        self.with_result(result, f)
3015    }
3016
3017    fn with_result_mut<Callback, R, E>(&self, _result: &mut Result<Root, E>, _f: Callback) -> Option<R>
3018    where
3019        Callback: FnOnce(&mut Value) -> R,
3020    {
3021        None // OptionalKeyPath doesn't support mutable access
3022    }
3023
3024    fn with_option<Callback, R>(&self, option: &Option<Root>, f: Callback) -> Option<R>
3025    where
3026        Callback: FnOnce(&Value) -> R,
3027    {
3028        self.with_option(option, f)
3029    }
3030
3031    fn with_option_mut<Callback, R>(&self, _option: &mut Option<Root>, _f: Callback) -> Option<R>
3032    where
3033        Callback: FnOnce(&mut Value) -> R,
3034    {
3035        None // OptionalKeyPath doesn't support mutable access
3036    }
3037
3038    fn with_refcell<Callback, R>(&self, refcell: &RefCell<Root>, f: Callback) -> Option<R>
3039    where
3040        Callback: FnOnce(&Value) -> R,
3041    {
3042        self.with_refcell(refcell, f)
3043    }
3044
3045    fn with_refcell_mut<Callback, R>(&self, _refcell: &RefCell<Root>, _f: Callback) -> Option<R>
3046    where
3047        Callback: FnOnce(&mut Value) -> R,
3048    {
3049        None // OptionalKeyPath doesn't support mutable access
3050    }
3051
3052    #[cfg(feature = "tagged")]
3053    fn with_tagged<Tag, Callback, R>(&self, tagged: &Tagged<Root, Tag>, f: Callback) -> R
3054    where
3055        Tagged<Root, Tag>: std::ops::Deref<Target = Root>,
3056        Callback: FnOnce(&Value) -> R,
3057    {
3058        self.with_tagged(tagged, f)
3059    }
3060
3061    fn with_mutex<Callback, R>(&self, mutex: &Mutex<Root>, f: Callback) -> Option<R>
3062    where
3063        Callback: FnOnce(&Value) -> R,
3064    {
3065        self.with_mutex(mutex, f)
3066    }
3067
3068    fn with_mutex_mut<Callback, R>(&self, _mutex: &mut Mutex<Root>, _f: Callback) -> Option<R>
3069    where
3070        Callback: FnOnce(&mut Value) -> R,
3071    {
3072        None // OptionalKeyPath doesn't support mutable access
3073    }
3074
3075    fn with_rwlock<Callback, R>(&self, rwlock: &RwLock<Root>, f: Callback) -> Option<R>
3076    where
3077        Callback: FnOnce(&Value) -> R,
3078    {
3079        self.with_rwlock(rwlock, f)
3080    }
3081
3082    fn with_rwlock_mut<Callback, R>(&self, _rwlock: &mut RwLock<Root>, _f: Callback) -> Option<R>
3083    where
3084        Callback: FnOnce(&mut Value) -> R,
3085    {
3086        None // OptionalKeyPath doesn't support mutable access
3087    }
3088
3089    fn with_arc_rwlock<Callback, R>(&self, arc_rwlock: &Arc<RwLock<Root>>, f: Callback) -> Option<R>
3090    where
3091        Callback: FnOnce(&Value) -> R,
3092    {
3093        self.with_arc_rwlock(arc_rwlock, f)
3094    }
3095
3096    fn with_arc_rwlock_mut<Callback, R>(&self, _arc_rwlock: &Arc<RwLock<Root>>, _f: Callback) -> Option<R>
3097    where
3098        Callback: FnOnce(&mut Value) -> R,
3099    {
3100        None // OptionalKeyPath doesn't support mutable access - use WritableOptionalKeyPath instead
3101    }
3102}
3103
3104// Implement WithContainer for WritableKeyPath - supports all mutable operations
3105impl<Root, Value, F> WithContainer<Root, Value> for WritableKeyPath<Root, Value, F>
3106where
3107    F: for<'r> Fn(&'r mut Root) -> &'r mut Value,
3108{
3109    fn with_arc<Callback, R>(&self, _arc: &Arc<Root>, _f: Callback) -> R
3110    where
3111        Callback: FnOnce(&Value) -> R,
3112    {
3113        // Arc doesn't support mutable access without interior mutability
3114        // This method requires &mut Arc<Root> which we don't have
3115        eprintln!("[DEBUG] WritableKeyPath::with_arc requires &mut Arc<Root> or interior mutability");
3116        unreachable!("WritableKeyPath::with_arc requires &mut Arc<Root> or interior mutability")
3117    }
3118
3119    fn with_box<Callback, R>(&self, boxed: &Box<Root>, f: Callback) -> R
3120    where
3121        Callback: FnOnce(&Value) -> R,
3122    {
3123        // Box doesn't support getting mutable reference from immutable reference
3124        // This is a limitation - we'd need &mut Box<Root> for mutable access
3125        eprintln!("[DEBUG] WritableKeyPath::with_box requires &mut Box<Root> - use with_box_mut instead");
3126        unreachable!("WritableKeyPath::with_box requires &mut Box<Root> - use with_box_mut instead")
3127    }
3128
3129    fn with_box_mut<Callback, R>(&self, boxed: &mut Box<Root>, f: Callback) -> R
3130    where
3131        Callback: FnOnce(&mut Value) -> R,
3132    {
3133        let value = self.get_mut(boxed.as_mut());
3134        f(value)
3135    }
3136
3137    fn with_rc<Callback, R>(&self, _rc: &Rc<Root>, _f: Callback) -> R
3138    where
3139        Callback: FnOnce(&Value) -> R,
3140    {
3141        // Rc doesn't support mutable access without interior mutability
3142        // This method requires &mut Rc<Root> which we don't have
3143        eprintln!("[DEBUG] WritableKeyPath::with_rc requires &mut Rc<Root> or interior mutability");
3144        unreachable!("WritableKeyPath::with_rc requires &mut Rc<Root> or interior mutability")
3145    }
3146
3147    fn with_result<Callback, R, E>(&self, _result: &Result<Root, E>, _f: Callback) -> Option<R>
3148    where
3149        Callback: FnOnce(&Value) -> R,
3150    {
3151        // WritableKeyPath requires &mut Root, but we only have &Result<Root, E>
3152        // This is a limitation - use with_result_mut for mutable access
3153        None
3154    }
3155
3156    fn with_result_mut<Callback, R, E>(&self, result: &mut Result<Root, E>, f: Callback) -> Option<R>
3157    where
3158        Callback: FnOnce(&mut Value) -> R,
3159    {
3160        result.as_mut().ok().map(|root| {
3161            let value = self.get_mut(root);
3162            f(value)
3163        })
3164    }
3165
3166    fn with_option<Callback, R>(&self, _option: &Option<Root>, _f: Callback) -> Option<R>
3167    where
3168        Callback: FnOnce(&Value) -> R,
3169    {
3170        // WritableKeyPath requires &mut Root, but we only have &Option<Root>
3171        // This is a limitation - use with_option_mut for mutable access
3172        None
3173    }
3174
3175    fn with_option_mut<Callback, R>(&self, option: &mut Option<Root>, f: Callback) -> Option<R>
3176    where
3177        Callback: FnOnce(&mut Value) -> R,
3178    {
3179        option.as_mut().map(|root| {
3180            let value = self.get_mut(root);
3181            f(value)
3182        })
3183    }
3184
3185    fn with_refcell<Callback, R>(&self, refcell: &RefCell<Root>, f: Callback) -> Option<R>
3186    where
3187        Callback: FnOnce(&Value) -> R,
3188    {
3189        // RefCell doesn't allow getting mutable reference from immutable borrow
3190        // This is a limitation - we'd need try_borrow_mut for mutable access
3191        None
3192    }
3193
3194    fn with_refcell_mut<Callback, R>(&self, refcell: &RefCell<Root>, f: Callback) -> Option<R>
3195    where
3196        Callback: FnOnce(&mut Value) -> R,
3197    {
3198        refcell.try_borrow_mut().ok().map(|mut borrow| {
3199            let value = self.get_mut(&mut *borrow);
3200            f(value)
3201        })
3202    }
3203
3204    #[cfg(feature = "tagged")]
3205    fn with_tagged<Tag, Callback, R>(&self, _tagged: &Tagged<Root, Tag>, _f: Callback) -> R
3206    where
3207        Tagged<Root, Tag>: std::ops::Deref<Target = Root>,
3208        Callback: FnOnce(&Value) -> R,
3209    {
3210        // WritableKeyPath requires &mut Root, but we only have &Tagged<Root, Tag>
3211        // This is a limitation - Tagged doesn't support mutable access without interior mutability
3212        eprintln!("[DEBUG] WritableKeyPath::with_tagged requires &mut Tagged<Root, Tag> or interior mutability");
3213        unreachable!("WritableKeyPath::with_tagged requires &mut Tagged<Root, Tag> or interior mutability")
3214    }
3215
3216    fn with_mutex<Callback, R>(&self, mutex: &Mutex<Root>, f: Callback) -> Option<R>
3217    where
3218        Callback: FnOnce(&Value) -> R,
3219    {
3220        mutex.lock().ok().map(|mut guard| {
3221            let value = self.get_mut(&mut *guard);
3222            f(value)
3223        })
3224    }
3225
3226    fn with_mutex_mut<Callback, R>(&self, mutex: &mut Mutex<Root>, f: Callback) -> Option<R>
3227    where
3228        Callback: FnOnce(&mut Value) -> R,
3229    {
3230        // Mutex::get_mut returns Result<&mut Root, PoisonError>
3231        mutex.get_mut().ok().map(|root| {
3232            let value = self.get_mut(root);
3233            f(value)
3234        })
3235    }
3236
3237    fn with_rwlock<Callback, R>(&self, rwlock: &RwLock<Root>, f: Callback) -> Option<R>
3238    where
3239        Callback: FnOnce(&Value) -> R,
3240    {
3241        // RwLock read guard doesn't allow mutable access
3242        // This is a limitation - we'd need write() for mutable access
3243        None
3244    }
3245
3246    fn with_rwlock_mut<Callback, R>(&self, rwlock: &mut RwLock<Root>, f: Callback) -> Option<R>
3247    where
3248        Callback: FnOnce(&mut Value) -> R,
3249    {
3250        // RwLock::get_mut returns Result<&mut Root, PoisonError>
3251        rwlock.get_mut().ok().map(|root| {
3252            let value = self.get_mut(root);
3253            f(value)
3254        })
3255    }
3256
3257    fn with_arc_rwlock<Callback, R>(&self, arc_rwlock: &Arc<RwLock<Root>>, f: Callback) -> Option<R>
3258    where
3259        Callback: FnOnce(&Value) -> R,
3260    {
3261        // Arc<RwLock> read guard doesn't allow mutable access
3262        // This is a limitation - we'd need write() for mutable access
3263        None
3264    }
3265
3266    fn with_arc_rwlock_mut<Callback, R>(&self, arc_rwlock: &Arc<RwLock<Root>>, f: Callback) -> Option<R>
3267    where
3268        Callback: FnOnce(&mut Value) -> R,
3269    {
3270        arc_rwlock.write().ok().map(|mut guard| {
3271            let value = self.get_mut(&mut *guard);
3272            f(value)
3273        })
3274    }
3275}
3276
3277// Implement WithContainer for WritableOptionalKeyPath - supports all mutable operations
3278impl<Root, Value, F> WithContainer<Root, Value> for WritableOptionalKeyPath<Root, Value, F>
3279where
3280    F: for<'r> Fn(&'r mut Root) -> Option<&'r mut Value>,
3281{
3282    fn with_arc<Callback, R>(&self, _arc: &Arc<Root>, _f: Callback) -> R
3283    where
3284        Callback: FnOnce(&Value) -> R,
3285    {
3286        // Arc doesn't support mutable access without interior mutability
3287        // This method requires &mut Arc<Root> which we don't have
3288        eprintln!("[DEBUG] WritableOptionalKeyPath::with_arc requires &mut Arc<Root> or interior mutability");
3289        unreachable!("WritableOptionalKeyPath::with_arc requires &mut Arc<Root> or interior mutability")
3290    }
3291
3292    fn with_box<Callback, R>(&self, _boxed: &Box<Root>, _f: Callback) -> R
3293    where
3294        Callback: FnOnce(&Value) -> R,
3295    {
3296        // WritableOptionalKeyPath requires &mut Root, but we only have &Box<Root>
3297        // This is a limitation - use with_box_mut for mutable access
3298        eprintln!("[DEBUG] WritableOptionalKeyPath::with_box requires &mut Box<Root> - use with_box_mut instead");
3299        unreachable!("WritableOptionalKeyPath::with_box requires &mut Box<Root> - use with_box_mut instead")
3300    }
3301
3302    fn with_box_mut<Callback, R>(&self, boxed: &mut Box<Root>, f: Callback) -> R
3303    where
3304        Callback: FnOnce(&mut Value) -> R,
3305    {
3306        if let Some(value) = self.get_mut(boxed.as_mut()) {
3307            f(value)
3308        } else {
3309            eprintln!("[DEBUG] WritableOptionalKeyPath failed to get value from Box");
3310            unreachable!("WritableOptionalKeyPath failed to get value from Box")
3311        }
3312    }
3313
3314    fn with_rc<Callback, R>(&self, _rc: &Rc<Root>, _f: Callback) -> R
3315    where
3316        Callback: FnOnce(&Value) -> R,
3317    {
3318        // Rc doesn't support mutable access without interior mutability
3319        // This method requires &mut Rc<Root> which we don't have
3320        eprintln!("[DEBUG] WritableOptionalKeyPath::with_rc requires &mut Rc<Root> or interior mutability");
3321        unreachable!("WritableOptionalKeyPath::with_rc requires &mut Rc<Root> or interior mutability")
3322    }
3323
3324    fn with_result<Callback, R, E>(&self, _result: &Result<Root, E>, _f: Callback) -> Option<R>
3325    where
3326        Callback: FnOnce(&Value) -> R,
3327    {
3328        // WritableOptionalKeyPath requires &mut Root, but we only have &Result<Root, E>
3329        // This is a limitation - use with_result_mut for mutable access
3330        None
3331    }
3332
3333    fn with_result_mut<Callback, R, E>(&self, result: &mut Result<Root, E>, f: Callback) -> Option<R>
3334    where
3335        Callback: FnOnce(&mut Value) -> R,
3336    {
3337        result.as_mut().ok().and_then(|root| {
3338            self.get_mut(root).map(|value| f(value))
3339        })
3340    }
3341
3342    fn with_option<Callback, R>(&self, _option: &Option<Root>, _f: Callback) -> Option<R>
3343    where
3344        Callback: FnOnce(&Value) -> R,
3345    {
3346        // WritableOptionalKeyPath requires &mut Root, but we only have &Option<Root>
3347        // This is a limitation - use with_option_mut for mutable access
3348        None
3349    }
3350
3351    fn with_option_mut<Callback, R>(&self, option: &mut Option<Root>, f: Callback) -> Option<R>
3352    where
3353        Callback: FnOnce(&mut Value) -> R,
3354    {
3355        option.as_mut().and_then(|root| {
3356            self.get_mut(root).map(|value| f(value))
3357        })
3358    }
3359
3360    fn with_refcell<Callback, R>(&self, _refcell: &RefCell<Root>, _f: Callback) -> Option<R>
3361    where
3362        Callback: FnOnce(&Value) -> R,
3363    {
3364        // RefCell doesn't allow getting mutable reference from immutable borrow
3365        // This is a limitation - we'd need try_borrow_mut for mutable access
3366        None
3367    }
3368
3369    fn with_refcell_mut<Callback, R>(&self, refcell: &RefCell<Root>, f: Callback) -> Option<R>
3370    where
3371        Callback: FnOnce(&mut Value) -> R,
3372    {
3373        refcell.try_borrow_mut().ok().and_then(|mut borrow| {
3374            self.get_mut(&mut *borrow).map(|value| f(value))
3375        })
3376    }
3377
3378    #[cfg(feature = "tagged")]
3379    fn with_tagged<Tag, Callback, R>(&self, _tagged: &Tagged<Root, Tag>, _f: Callback) -> R
3380    where
3381        Tagged<Root, Tag>: std::ops::Deref<Target = Root>,
3382        Callback: FnOnce(&Value) -> R,
3383    {
3384        // WritableOptionalKeyPath requires &mut Root, but we only have &Tagged<Root, Tag>
3385        // This is a limitation - Tagged doesn't support mutable access without interior mutability
3386        eprintln!("[DEBUG] WritableOptionalKeyPath::with_tagged requires &mut Tagged<Root, Tag> or interior mutability");
3387        unreachable!("WritableOptionalKeyPath::with_tagged requires &mut Tagged<Root, Tag> or interior mutability")
3388    }
3389
3390    fn with_mutex<Callback, R>(&self, mutex: &Mutex<Root>, f: Callback) -> Option<R>
3391    where
3392        Callback: FnOnce(&Value) -> R,
3393    {
3394        mutex.lock().ok().and_then(|mut guard| {
3395            self.get_mut(&mut *guard).map(|value| f(value))
3396        })
3397    }
3398
3399    fn with_mutex_mut<Callback, R>(&self, mutex: &mut Mutex<Root>, f: Callback) -> Option<R>
3400    where
3401        Callback: FnOnce(&mut Value) -> R,
3402    {
3403        // Mutex::get_mut returns Result<&mut Root, PoisonError>
3404        mutex.get_mut().ok().and_then(|root| {
3405            self.get_mut(root).map(|value| f(value))
3406        })
3407    }
3408
3409    fn with_rwlock<Callback, R>(&self, _rwlock: &RwLock<Root>, _f: Callback) -> Option<R>
3410    where
3411        Callback: FnOnce(&Value) -> R,
3412    {
3413        // RwLock read guard doesn't allow mutable access
3414        // This is a limitation - we'd need write() for mutable access
3415        None
3416    }
3417
3418    fn with_rwlock_mut<Callback, R>(&self, rwlock: &mut RwLock<Root>, f: Callback) -> Option<R>
3419    where
3420        Callback: FnOnce(&mut Value) -> R,
3421    {
3422        // RwLock::get_mut returns Result<&mut Root, PoisonError>
3423        rwlock.get_mut().ok().and_then(|root| {
3424            self.get_mut(root).map(|value| f(value))
3425        })
3426    }
3427
3428    fn with_arc_rwlock<Callback, R>(&self, _arc_rwlock: &Arc<RwLock<Root>>, _f: Callback) -> Option<R>
3429    where
3430        Callback: FnOnce(&Value) -> R,
3431    {
3432        // Arc<RwLock> read guard doesn't allow mutable access
3433        // This is a limitation - we'd need write() for mutable access
3434        None
3435    }
3436
3437    fn with_arc_rwlock_mut<Callback, R>(&self, arc_rwlock: &Arc<RwLock<Root>>, f: Callback) -> Option<R>
3438    where
3439        Callback: FnOnce(&mut Value) -> R,
3440    {
3441        arc_rwlock.write().ok().and_then(|mut guard| {
3442            self.get_mut(&mut *guard).map(|value| f(value))
3443        })
3444    }
3445}