rust_keypaths/
lib.rs

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