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;
10// use std::ops::Shr;
11use std::fmt;
12
13// ========== FUNCTIONAL KEYPATH CHAIN (Compose first, apply container at get) ==========
14
15/// A composed keypath chain through Arc<Mutex<T>> - functional style
16/// Build the chain first, then apply container at get() time
17/// 
18/// # Example
19/// ```rust
20/// // Functional style: compose first, then apply container at get()
21/// ContainerTest::mutex_data_r()
22///     .chain_arc_mutex_at_kp(SomeStruct::data_r())
23///     .get(&container, |value| println!("Value: {}", value));
24/// ```
25pub struct ArcMutexKeyPathChain<Root, MutexValue, InnerValue, SubValue, F, G>
26where
27    F: for<'r> Fn(&'r Root) -> &'r MutexValue,
28    G: for<'r> Fn(&'r InnerValue) -> &'r SubValue,
29{
30    outer_keypath: KeyPath<Root, MutexValue, F>,
31    inner_keypath: KeyPath<InnerValue, SubValue, G>,
32}
33
34impl<Root, MutexValue, InnerValue, SubValue, F, G> ArcMutexKeyPathChain<Root, MutexValue, InnerValue, SubValue, F, G>
35where
36    F: for<'r> Fn(&'r Root) -> &'r MutexValue,
37    G: for<'r> Fn(&'r InnerValue) -> &'r SubValue,
38    MutexValue: std::borrow::Borrow<Arc<Mutex<InnerValue>>>,
39{
40    /// Apply the composed keypath chain to a container, executing callback with the value (read)
41    /// Consumes self - functional style (compose once, apply once)
42    pub fn get<Callback>(self, container: &Root, callback: Callback) -> Option<()>
43    where
44        Callback: FnOnce(&SubValue) -> (),
45    {
46        let arc_mutex_ref = self.outer_keypath.get(container);
47        arc_mutex_ref.borrow().lock().ok().map(|guard| {
48            let value = self.inner_keypath.get(&*guard);
49            callback(value)
50        })
51    }
52
53    /// Chain with another readable keypath through another level
54    pub fn then<NextValue, H>(
55        self,
56        next: KeyPath<SubValue, NextValue, H>,
57    ) -> ArcMutexKeyPathChain<Root, MutexValue, InnerValue, NextValue, F, impl for<'r> Fn(&'r InnerValue) -> &'r NextValue + 'static>
58    where
59        H: for<'r> Fn(&'r SubValue) -> &'r NextValue,
60        G: 'static,
61        H: 'static,
62        InnerValue: 'static,
63        SubValue: 'static,
64        NextValue: 'static,
65    {
66        let first = self.inner_keypath;
67        let second = next;
68        
69        let composed = KeyPath::new(move |inner: &InnerValue| {
70            let sub = first.get(inner);
71            second.get(sub)
72        });
73        
74        ArcMutexKeyPathChain {
75            outer_keypath: self.outer_keypath,
76            inner_keypath: composed,
77        }
78    }
79
80    /// Chain with an optional readable keypath through another level
81    pub fn chain_optional<NextValue, H>(
82        self,
83        next: OptionalKeyPath<SubValue, NextValue, H>,
84    ) -> ArcMutexOptionalKeyPathChain<Root, MutexValue, InnerValue, NextValue, F, impl for<'r> Fn(&'r InnerValue) -> Option<&'r NextValue> + 'static>
85    where
86        H: for<'r> Fn(&'r SubValue) -> Option<&'r NextValue>,
87        G: 'static,
88        H: 'static,
89        InnerValue: 'static,
90        SubValue: 'static,
91        NextValue: 'static,
92    {
93        let first = self.inner_keypath;
94        let second = next;
95        
96        let composed = OptionalKeyPath::new(move |inner: &InnerValue| {
97            let sub = first.get(inner);
98            second.get(sub)
99        });
100        
101        ArcMutexOptionalKeyPathChain {
102            outer_keypath: self.outer_keypath,
103            inner_keypath: composed,
104        }
105    }
106}
107
108// ========== WRITABLE MUTEX KEYPATH CHAINS ==========
109
110/// A composed writable keypath chain through Arc<Mutex<T>> - functional style
111/// Build the chain first, then apply container at get_mut() time
112pub struct ArcMutexWritableKeyPathChain<Root, MutexValue, InnerValue, SubValue, F, G>
113where
114    F: for<'r> Fn(&'r Root) -> &'r MutexValue,
115    G: for<'r> Fn(&'r mut InnerValue) -> &'r mut SubValue,
116{
117    outer_keypath: KeyPath<Root, MutexValue, F>,
118    inner_keypath: WritableKeyPath<InnerValue, SubValue, G>,
119}
120
121impl<Root, MutexValue, InnerValue, SubValue, F, G> ArcMutexWritableKeyPathChain<Root, MutexValue, InnerValue, SubValue, F, G>
122where
123    F: for<'r> Fn(&'r Root) -> &'r MutexValue,
124    G: for<'r> Fn(&'r mut InnerValue) -> &'r mut SubValue,
125    MutexValue: std::borrow::Borrow<Arc<Mutex<InnerValue>>>,
126{
127    /// Apply the composed keypath chain to a container with mutable access
128    /// Consumes self - functional style (compose once, apply once)
129    pub fn get_mut<Callback, R>(self, container: &Root, callback: Callback) -> Option<R>
130    where
131        Callback: FnOnce(&mut SubValue) -> R,
132    {
133        let arc_mutex_ref = self.outer_keypath.get(container);
134        arc_mutex_ref.borrow().lock().ok().map(|mut guard| {
135            let value_ref = self.inner_keypath.get_mut(&mut *guard);
136            callback(value_ref)
137        })
138    }
139
140    /// Chain with another writable keypath through another level
141    pub fn then<NextValue, H>(
142        self,
143        next: WritableKeyPath<SubValue, NextValue, H>,
144    ) -> ArcMutexWritableKeyPathChain<Root, MutexValue, InnerValue, NextValue, F, impl for<'r> Fn(&'r mut InnerValue) -> &'r mut NextValue + 'static>
145    where
146        H: for<'r> Fn(&'r mut SubValue) -> &'r mut NextValue,
147        G: 'static,
148        H: 'static,
149        InnerValue: 'static,
150        SubValue: 'static,
151        NextValue: 'static,
152    {
153        let first = self.inner_keypath;
154        let second = next;
155        
156        let composed = WritableKeyPath::new(move |inner: &mut InnerValue| {
157            let sub = first.get_mut(inner);
158            second.get_mut(sub)
159        });
160        
161        ArcMutexWritableKeyPathChain {
162            outer_keypath: self.outer_keypath,
163            inner_keypath: composed,
164        }
165    }
166
167    /// Chain with an optional writable keypath through another level
168    pub fn chain_optional<NextValue, H>(
169        self,
170        next: WritableOptionalKeyPath<SubValue, NextValue, H>,
171    ) -> ArcMutexWritableOptionalKeyPathChain<Root, MutexValue, InnerValue, NextValue, F, impl for<'r> Fn(&'r mut InnerValue) -> Option<&'r mut NextValue> + 'static>
172    where
173        H: for<'r> Fn(&'r mut SubValue) -> Option<&'r mut NextValue>,
174        G: 'static,
175        H: 'static,
176        InnerValue: 'static,
177        SubValue: 'static,
178        NextValue: 'static,
179    {
180        let first = self.inner_keypath;
181        let second = next;
182        
183        let composed = WritableOptionalKeyPath::new(move |inner: &mut InnerValue| {
184            let sub = first.get_mut(inner);
185            second.get_mut(sub)
186        });
187        
188        ArcMutexWritableOptionalKeyPathChain {
189            outer_keypath: self.outer_keypath,
190            inner_keypath: composed,
191        }
192    }
193}
194
195/// A composed writable optional keypath chain through Arc<Mutex<T>> - functional style
196pub struct ArcMutexWritableOptionalKeyPathChain<Root, MutexValue, InnerValue, SubValue, F, G>
197where
198    F: for<'r> Fn(&'r Root) -> &'r MutexValue,
199    G: for<'r> Fn(&'r mut InnerValue) -> Option<&'r mut SubValue>,
200{
201    outer_keypath: KeyPath<Root, MutexValue, F>,
202    inner_keypath: WritableOptionalKeyPath<InnerValue, SubValue, G>,
203}
204
205impl<Root, MutexValue, InnerValue, SubValue, F, G> ArcMutexWritableOptionalKeyPathChain<Root, MutexValue, InnerValue, SubValue, F, G>
206where
207    F: for<'r> Fn(&'r Root) -> &'r MutexValue,
208    G: for<'r> Fn(&'r mut InnerValue) -> Option<&'r mut SubValue>,
209    MutexValue: std::borrow::Borrow<Arc<Mutex<InnerValue>>>,
210{
211    /// Apply the composed keypath chain to a container with mutable access (if value exists)
212    /// Consumes self - functional style (compose once, apply once)
213    pub fn get_mut<Callback, R>(self, container: &Root, callback: Callback) -> Option<R>
214    where
215        Callback: FnOnce(&mut SubValue) -> R,
216    {
217        let arc_mutex_ref = self.outer_keypath.get(container);
218        arc_mutex_ref.borrow().lock().ok().and_then(|mut guard| {
219            self.inner_keypath.get_mut(&mut *guard).map(|value_ref| callback(value_ref))
220        })
221    }
222
223    /// Chain with another writable keypath through another level
224    pub fn then<NextValue, H>(
225        self,
226        next: WritableKeyPath<SubValue, NextValue, H>,
227    ) -> ArcMutexWritableOptionalKeyPathChain<Root, MutexValue, InnerValue, NextValue, F, impl for<'r> Fn(&'r mut InnerValue) -> Option<&'r mut NextValue> + 'static>
228    where
229        H: for<'r> Fn(&'r mut SubValue) -> &'r mut NextValue,
230        G: 'static,
231        H: 'static,
232        InnerValue: 'static,
233        SubValue: 'static,
234        NextValue: 'static,
235    {
236        let first = self.inner_keypath;
237        let second = next;
238        
239        let composed = WritableOptionalKeyPath::new(move |inner: &mut InnerValue| {
240            first.get_mut(inner).map(|sub| second.get_mut(sub))
241        });
242        
243        ArcMutexWritableOptionalKeyPathChain {
244            outer_keypath: self.outer_keypath,
245            inner_keypath: composed,
246        }
247    }
248
249    /// Chain with an optional writable keypath through another level
250    pub fn chain_optional<NextValue, H>(
251        self,
252        next: WritableOptionalKeyPath<SubValue, NextValue, H>,
253    ) -> ArcMutexWritableOptionalKeyPathChain<Root, MutexValue, InnerValue, NextValue, F, impl for<'r> Fn(&'r mut InnerValue) -> Option<&'r mut NextValue> + 'static>
254    where
255        H: for<'r> Fn(&'r mut SubValue) -> Option<&'r mut NextValue>,
256        G: 'static,
257        H: 'static,
258        InnerValue: 'static,
259        SubValue: 'static,
260        NextValue: 'static,
261    {
262        let first = self.inner_keypath;
263        let second = next;
264        
265        let composed = WritableOptionalKeyPath::new(move |inner: &mut InnerValue| {
266            first.get_mut(inner).and_then(|sub| second.get_mut(sub))
267        });
268        
269        ArcMutexWritableOptionalKeyPathChain {
270            outer_keypath: self.outer_keypath,
271            inner_keypath: composed,
272        }
273    }
274}
275
276/// A composed optional keypath chain through Arc<Mutex<T>> - functional style
277pub struct ArcMutexOptionalKeyPathChain<Root, MutexValue, InnerValue, SubValue, F, G>
278where
279    F: for<'r> Fn(&'r Root) -> &'r MutexValue,
280    G: for<'r> Fn(&'r InnerValue) -> Option<&'r SubValue>,
281{
282    outer_keypath: KeyPath<Root, MutexValue, F>,
283    inner_keypath: OptionalKeyPath<InnerValue, SubValue, G>,
284}
285
286impl<Root, MutexValue, InnerValue, SubValue, F, G> ArcMutexOptionalKeyPathChain<Root, MutexValue, InnerValue, SubValue, F, G>
287where
288    F: for<'r> Fn(&'r Root) -> &'r MutexValue,
289    G: for<'r> Fn(&'r InnerValue) -> Option<&'r SubValue>,
290    MutexValue: std::borrow::Borrow<Arc<Mutex<InnerValue>>>,
291{
292    /// Apply the composed keypath chain to a container, executing callback with the value
293    /// Consumes self - functional style (compose once, apply once)
294    pub fn get<Callback>(self, container: &Root, callback: Callback) -> Option<()>
295    where
296        Callback: FnOnce(&SubValue) -> (),
297    {
298        let arc_mutex_ref = self.outer_keypath.get(container);
299        arc_mutex_ref.borrow().lock().ok().and_then(|guard| {
300            self.inner_keypath.get(&*guard).map(|value| callback(value))
301        })
302    }
303
304    /// Chain with another readable keypath through another level
305    pub fn then<NextValue, H>(
306        self,
307        next: KeyPath<SubValue, NextValue, H>,
308    ) -> ArcMutexOptionalKeyPathChain<Root, MutexValue, InnerValue, NextValue, F, impl for<'r> Fn(&'r InnerValue) -> Option<&'r NextValue> + 'static>
309    where
310        H: for<'r> Fn(&'r SubValue) -> &'r NextValue,
311        G: 'static,
312        H: 'static,
313        InnerValue: 'static,
314        SubValue: 'static,
315        NextValue: 'static,
316    {
317        let first = self.inner_keypath;
318        let second = next;
319        
320        let composed = OptionalKeyPath::new(move |inner: &InnerValue| {
321            first.get(inner).map(|sub| second.get(sub))
322        });
323        
324        ArcMutexOptionalKeyPathChain {
325            outer_keypath: self.outer_keypath,
326            inner_keypath: composed,
327        }
328    }
329
330    /// Chain with an optional readable keypath through another level
331    pub fn chain_optional<NextValue, H>(
332        self,
333        next: OptionalKeyPath<SubValue, NextValue, H>,
334    ) -> ArcMutexOptionalKeyPathChain<Root, MutexValue, InnerValue, NextValue, F, impl for<'r> Fn(&'r InnerValue) -> Option<&'r NextValue> + 'static>
335    where
336        H: for<'r> Fn(&'r SubValue) -> Option<&'r NextValue>,
337        G: 'static,
338        H: 'static,
339        InnerValue: 'static,
340        SubValue: 'static,
341        NextValue: 'static,
342    {
343        let first = self.inner_keypath;
344        let second = next;
345        
346        let composed = OptionalKeyPath::new(move |inner: &InnerValue| {
347            first.get(inner).and_then(|sub| second.get(sub))
348        });
349        
350        ArcMutexOptionalKeyPathChain {
351            outer_keypath: self.outer_keypath,
352            inner_keypath: composed,
353        }
354    }
355}
356
357/// A composed keypath chain from OptionalKeyPath through Arc<Mutex<T>> - functional style
358pub struct OptionalArcMutexKeyPathChain<Root, MutexValue, InnerValue, SubValue, F, G>
359where
360    F: for<'r> Fn(&'r Root) -> Option<&'r MutexValue>,
361    G: for<'r> Fn(&'r InnerValue) -> &'r SubValue,
362{
363    outer_keypath: OptionalKeyPath<Root, MutexValue, F>,
364    inner_keypath: KeyPath<InnerValue, SubValue, G>,
365}
366
367impl<Root, MutexValue, InnerValue, SubValue, F, G> OptionalArcMutexKeyPathChain<Root, MutexValue, InnerValue, SubValue, F, G>
368where
369    F: for<'r> Fn(&'r Root) -> Option<&'r MutexValue>,
370    G: for<'r> Fn(&'r InnerValue) -> &'r SubValue,
371    MutexValue: std::borrow::Borrow<Arc<Mutex<InnerValue>>>,
372{
373    /// Apply the composed keypath chain to a container, executing callback with the value
374    /// Consumes self - functional style (compose once, apply once)
375    pub fn get<Callback>(self, container: &Root, callback: Callback) -> Option<()>
376    where
377        Callback: FnOnce(&SubValue) -> (),
378    {
379        self.outer_keypath.get(container).and_then(|arc_mutex_ref| {
380            arc_mutex_ref.borrow().lock().ok().map(|guard| {
381                let value = self.inner_keypath.get(&*guard);
382                callback(value)
383            })
384        })
385    }
386
387    /// Chain with another readable keypath through another level
388    pub fn then<NextValue, H>(
389        self,
390        next: KeyPath<SubValue, NextValue, H>,
391    ) -> OptionalArcMutexKeyPathChain<Root, MutexValue, InnerValue, NextValue, F, impl for<'r> Fn(&'r InnerValue) -> &'r NextValue + 'static>
392    where
393        H: for<'r> Fn(&'r SubValue) -> &'r NextValue,
394        G: 'static,
395        H: 'static,
396        InnerValue: 'static,
397        SubValue: 'static,
398        NextValue: 'static,
399    {
400        let first = self.inner_keypath;
401        let second = next;
402        
403        let composed = KeyPath::new(move |inner: &InnerValue| {
404            let sub = first.get(inner);
405            second.get(sub)
406        });
407        
408        OptionalArcMutexKeyPathChain {
409            outer_keypath: self.outer_keypath,
410            inner_keypath: composed,
411        }
412    }
413
414    /// Chain with an optional readable keypath through another level
415    pub fn chain_optional<NextValue, H>(
416        self,
417        next: OptionalKeyPath<SubValue, NextValue, H>,
418    ) -> OptionalArcMutexOptionalKeyPathChain<Root, MutexValue, InnerValue, NextValue, F, impl for<'r> Fn(&'r InnerValue) -> Option<&'r NextValue> + 'static>
419    where
420        H: for<'r> Fn(&'r SubValue) -> Option<&'r NextValue>,
421        G: 'static,
422        H: 'static,
423        InnerValue: 'static,
424        SubValue: 'static,
425        NextValue: 'static,
426    {
427        let first = self.inner_keypath;
428        let second = next;
429        
430        let composed = OptionalKeyPath::new(move |inner: &InnerValue| {
431            let sub = first.get(inner);
432            second.get(sub)
433        });
434        
435        OptionalArcMutexOptionalKeyPathChain {
436            outer_keypath: self.outer_keypath,
437            inner_keypath: composed,
438        }
439    }
440}
441
442/// A composed optional keypath chain from OptionalKeyPath through Arc<Mutex<T>> - functional style
443pub struct OptionalArcMutexOptionalKeyPathChain<Root, MutexValue, InnerValue, SubValue, F, G>
444where
445    F: for<'r> Fn(&'r Root) -> Option<&'r MutexValue>,
446    G: for<'r> Fn(&'r InnerValue) -> Option<&'r SubValue>,
447{
448    outer_keypath: OptionalKeyPath<Root, MutexValue, F>,
449    inner_keypath: OptionalKeyPath<InnerValue, SubValue, G>,
450}
451
452impl<Root, MutexValue, InnerValue, SubValue, F, G> OptionalArcMutexOptionalKeyPathChain<Root, MutexValue, InnerValue, SubValue, F, G>
453where
454    F: for<'r> Fn(&'r Root) -> Option<&'r MutexValue>,
455    G: for<'r> Fn(&'r InnerValue) -> Option<&'r SubValue>,
456    MutexValue: std::borrow::Borrow<Arc<Mutex<InnerValue>>>,
457{
458    /// Apply the composed keypath chain to a container, executing callback with the value
459    /// Consumes self - functional style (compose once, apply once)
460    pub fn get<Callback>(self, container: &Root, callback: Callback) -> Option<()>
461    where
462        Callback: FnOnce(&SubValue) -> (),
463    {
464        self.outer_keypath.get(container).and_then(|arc_mutex_ref| {
465            arc_mutex_ref.borrow().lock().ok().and_then(|guard| {
466                self.inner_keypath.get(&*guard).map(|value| callback(value))
467            })
468        })
469    }
470
471    /// Chain with another readable keypath through another level
472    pub fn then<NextValue, H>(
473        self,
474        next: KeyPath<SubValue, NextValue, H>,
475    ) -> OptionalArcMutexOptionalKeyPathChain<Root, MutexValue, InnerValue, NextValue, F, impl for<'r> Fn(&'r InnerValue) -> Option<&'r NextValue> + 'static>
476    where
477        H: for<'r> Fn(&'r SubValue) -> &'r NextValue,
478        G: 'static,
479        H: 'static,
480        InnerValue: 'static,
481        SubValue: 'static,
482        NextValue: 'static,
483    {
484        let first = self.inner_keypath;
485        let second = next;
486        
487        let composed = OptionalKeyPath::new(move |inner: &InnerValue| {
488            first.get(inner).map(|sub| second.get(sub))
489        });
490        
491        OptionalArcMutexOptionalKeyPathChain {
492            outer_keypath: self.outer_keypath,
493            inner_keypath: composed,
494        }
495    }
496
497    /// Chain with an optional readable keypath through another level
498    pub fn chain_optional<NextValue, H>(
499        self,
500        next: OptionalKeyPath<SubValue, NextValue, H>,
501    ) -> OptionalArcMutexOptionalKeyPathChain<Root, MutexValue, InnerValue, NextValue, F, impl for<'r> Fn(&'r InnerValue) -> Option<&'r NextValue> + 'static>
502    where
503        H: for<'r> Fn(&'r SubValue) -> Option<&'r NextValue>,
504        G: 'static,
505        H: 'static,
506        InnerValue: 'static,
507        SubValue: 'static,
508        NextValue: 'static,
509    {
510        let first = self.inner_keypath;
511        let second = next;
512        
513        let composed = OptionalKeyPath::new(move |inner: &InnerValue| {
514            first.get(inner).and_then(|sub| second.get(sub))
515        });
516        
517        OptionalArcMutexOptionalKeyPathChain {
518            outer_keypath: self.outer_keypath,
519            inner_keypath: composed,
520        }
521    }
522}
523
524// ========== FUNCTIONAL RWLOCK KEYPATH CHAINS ==========
525
526/// A composed keypath chain through Arc<RwLock<T>> - functional style
527/// Build the chain first, then apply container at get() time
528/// 
529/// # Example
530/// ```rust
531/// // Functional style: compose first, then apply container at get()
532/// ContainerTest::rwlock_data_r()
533///     .chain_arc_rwlock_at_kp(SomeStruct::data_r())
534///     .get(&container, |value| println!("Value: {}", value));
535/// ```
536pub struct ArcRwLockKeyPathChain<Root, RwLockValue, InnerValue, SubValue, F, G>
537where
538    F: for<'r> Fn(&'r Root) -> &'r RwLockValue,
539    G: for<'r> Fn(&'r InnerValue) -> &'r SubValue,
540{
541    outer_keypath: KeyPath<Root, RwLockValue, F>,
542    inner_keypath: KeyPath<InnerValue, SubValue, G>,
543}
544
545impl<Root, RwLockValue, InnerValue, SubValue, F, G> ArcRwLockKeyPathChain<Root, RwLockValue, InnerValue, SubValue, F, G>
546where
547    F: for<'r> Fn(&'r Root) -> &'r RwLockValue,
548    G: for<'r> Fn(&'r InnerValue) -> &'r SubValue,
549    RwLockValue: std::borrow::Borrow<Arc<RwLock<InnerValue>>>,
550{
551    /// Apply the composed keypath chain to a container, executing callback with the value (read lock)
552    /// Consumes self - functional style (compose once, apply once)
553    pub fn get<Callback>(self, container: &Root, callback: Callback) -> Option<()>
554    where
555        Callback: FnOnce(&SubValue) -> (),
556    {
557        let arc_rwlock_ref = self.outer_keypath.get(container);
558        arc_rwlock_ref.borrow().read().ok().map(|guard| {
559            let value = self.inner_keypath.get(&*guard);
560            callback(value)
561        })
562    }
563
564    /// Chain with another readable keypath through another level
565    /// This allows composing deeper keypaths through the same Arc<RwLock<T>> structure
566    pub fn then<NextValue, H>(
567        self,
568        next: KeyPath<SubValue, NextValue, H>,
569    ) -> ArcRwLockKeyPathChain<Root, RwLockValue, InnerValue, NextValue, F, impl for<'r> Fn(&'r InnerValue) -> &'r NextValue + 'static>
570    where
571        H: for<'r> Fn(&'r SubValue) -> &'r NextValue,
572        G: 'static,
573        H: 'static,
574        InnerValue: 'static,
575        SubValue: 'static,
576        NextValue: 'static,
577    {
578        let first = self.inner_keypath;
579        let second = next;
580        
581        let composed = KeyPath::new(move |inner: &InnerValue| {
582            let sub = first.get(inner);
583            second.get(sub)
584        });
585        
586        ArcRwLockKeyPathChain {
587            outer_keypath: self.outer_keypath,
588            inner_keypath: composed,
589        }
590    }
591
592    /// Chain with an optional readable keypath through another level
593    pub fn chain_optional<NextValue, H>(
594        self,
595        next: OptionalKeyPath<SubValue, NextValue, H>,
596    ) -> ArcRwLockOptionalKeyPathChain<Root, RwLockValue, InnerValue, NextValue, F, impl for<'r> Fn(&'r InnerValue) -> Option<&'r NextValue> + 'static>
597    where
598        H: for<'r> Fn(&'r SubValue) -> Option<&'r NextValue>,
599        G: 'static,
600        H: 'static,
601        InnerValue: 'static,
602        SubValue: 'static,
603        NextValue: 'static,
604    {
605        let first = self.inner_keypath;
606        let second = next;
607        
608        let composed = OptionalKeyPath::new(move |inner: &InnerValue| {
609            let sub = first.get(inner);
610            second.get(sub)
611        });
612        
613        ArcRwLockOptionalKeyPathChain {
614            outer_keypath: self.outer_keypath,
615            inner_keypath: composed,
616        }
617    }
618}
619
620/// A composed optional keypath chain through Arc<RwLock<T>> - functional style
621pub struct ArcRwLockOptionalKeyPathChain<Root, RwLockValue, InnerValue, SubValue, F, G>
622where
623    F: for<'r> Fn(&'r Root) -> &'r RwLockValue,
624    G: for<'r> Fn(&'r InnerValue) -> Option<&'r SubValue>,
625{
626    outer_keypath: KeyPath<Root, RwLockValue, F>,
627    inner_keypath: OptionalKeyPath<InnerValue, SubValue, G>,
628}
629
630impl<Root, RwLockValue, InnerValue, SubValue, F, G> ArcRwLockOptionalKeyPathChain<Root, RwLockValue, InnerValue, SubValue, F, G>
631where
632    F: for<'r> Fn(&'r Root) -> &'r RwLockValue,
633    G: for<'r> Fn(&'r InnerValue) -> Option<&'r SubValue>,
634    RwLockValue: std::borrow::Borrow<Arc<RwLock<InnerValue>>>,
635{
636    /// Apply the composed keypath chain to a container, executing callback with the value (read lock)
637    /// Consumes self - functional style (compose once, apply once)
638    pub fn get<Callback>(self, container: &Root, callback: Callback) -> Option<()>
639    where
640        Callback: FnOnce(&SubValue) -> (),
641    {
642        let arc_rwlock_ref = self.outer_keypath.get(container);
643        arc_rwlock_ref.borrow().read().ok().and_then(|guard| {
644            self.inner_keypath.get(&*guard).map(|value| callback(value))
645        })
646    }
647}
648
649/// A composed keypath chain from OptionalKeyPath through Arc<RwLock<T>> - functional style
650pub struct OptionalArcRwLockKeyPathChain<Root, RwLockValue, InnerValue, SubValue, F, G>
651where
652    F: for<'r> Fn(&'r Root) -> Option<&'r RwLockValue>,
653    G: for<'r> Fn(&'r InnerValue) -> &'r SubValue,
654{
655    outer_keypath: OptionalKeyPath<Root, RwLockValue, F>,
656    inner_keypath: KeyPath<InnerValue, SubValue, G>,
657}
658
659impl<Root, RwLockValue, InnerValue, SubValue, F, G> OptionalArcRwLockKeyPathChain<Root, RwLockValue, InnerValue, SubValue, F, G>
660where
661    F: for<'r> Fn(&'r Root) -> Option<&'r RwLockValue>,
662    G: for<'r> Fn(&'r InnerValue) -> &'r SubValue,
663    RwLockValue: std::borrow::Borrow<Arc<RwLock<InnerValue>>>,
664{
665    /// Apply the composed keypath chain to a container, executing callback with the value (read lock)
666    /// Consumes self - functional style (compose once, apply once)
667    pub fn get<Callback>(self, container: &Root, callback: Callback) -> Option<()>
668    where
669        Callback: FnOnce(&SubValue) -> (),
670    {
671        self.outer_keypath.get(container).and_then(|arc_rwlock_ref| {
672            arc_rwlock_ref.borrow().read().ok().map(|guard| {
673                let value = self.inner_keypath.get(&*guard);
674                callback(value)
675            })
676        })
677    }
678
679    /// Chain with another readable keypath through another level
680    pub fn then<NextValue, H>(
681        self,
682        next: KeyPath<SubValue, NextValue, H>,
683    ) -> OptionalArcRwLockKeyPathChain<Root, RwLockValue, InnerValue, NextValue, F, impl for<'r> Fn(&'r InnerValue) -> &'r NextValue + 'static>
684    where
685        H: for<'r> Fn(&'r SubValue) -> &'r NextValue,
686        G: 'static,
687        H: 'static,
688        InnerValue: 'static,
689        SubValue: 'static,
690        NextValue: 'static,
691    {
692        let first = self.inner_keypath;
693        let second = next;
694        
695        let composed = KeyPath::new(move |inner: &InnerValue| {
696            let sub = first.get(inner);
697            second.get(sub)
698        });
699        
700        OptionalArcRwLockKeyPathChain {
701            outer_keypath: self.outer_keypath,
702            inner_keypath: composed,
703        }
704    }
705
706    /// Chain with an optional readable keypath through another level
707    pub fn chain_optional<NextValue, H>(
708        self,
709        next: OptionalKeyPath<SubValue, NextValue, H>,
710    ) -> OptionalArcRwLockOptionalKeyPathChain<Root, RwLockValue, InnerValue, NextValue, F, impl for<'r> Fn(&'r InnerValue) -> Option<&'r NextValue> + 'static>
711    where
712        H: for<'r> Fn(&'r SubValue) -> Option<&'r NextValue>,
713        G: 'static,
714        H: 'static,
715        InnerValue: 'static,
716        SubValue: 'static,
717        NextValue: 'static,
718    {
719        let first = self.inner_keypath;
720        let second = next;
721        
722        let composed = OptionalKeyPath::new(move |inner: &InnerValue| {
723            let sub = first.get(inner);
724            second.get(sub)
725        });
726        
727        OptionalArcRwLockOptionalKeyPathChain {
728            outer_keypath: self.outer_keypath,
729            inner_keypath: composed,
730        }
731    }
732}
733
734/// A composed optional keypath chain from OptionalKeyPath through Arc<RwLock<T>> - functional style
735pub struct OptionalArcRwLockOptionalKeyPathChain<Root, RwLockValue, InnerValue, SubValue, F, G>
736where
737    F: for<'r> Fn(&'r Root) -> Option<&'r RwLockValue>,
738    G: for<'r> Fn(&'r InnerValue) -> Option<&'r SubValue>,
739{
740    outer_keypath: OptionalKeyPath<Root, RwLockValue, F>,
741    inner_keypath: OptionalKeyPath<InnerValue, SubValue, G>,
742}
743
744impl<Root, RwLockValue, InnerValue, SubValue, F, G> OptionalArcRwLockOptionalKeyPathChain<Root, RwLockValue, InnerValue, SubValue, F, G>
745where
746    F: for<'r> Fn(&'r Root) -> Option<&'r RwLockValue>,
747    G: for<'r> Fn(&'r InnerValue) -> Option<&'r SubValue>,
748    RwLockValue: std::borrow::Borrow<Arc<RwLock<InnerValue>>>,
749{
750    /// Apply the composed keypath chain to a container, executing callback with the value (read lock)
751    /// Consumes self - functional style (compose once, apply once)
752    pub fn get<Callback>(self, container: &Root, callback: Callback) -> Option<()>
753    where
754        Callback: FnOnce(&SubValue) -> (),
755    {
756        self.outer_keypath.get(container).and_then(|arc_rwlock_ref| {
757            arc_rwlock_ref.borrow().read().ok().and_then(|guard| {
758                self.inner_keypath.get(&*guard).map(|value| callback(value))
759            })
760        })
761    }
762
763    /// Chain with another readable keypath through another level
764    pub fn then<NextValue, H>(
765        self,
766        next: KeyPath<SubValue, NextValue, H>,
767    ) -> OptionalArcRwLockOptionalKeyPathChain<Root, RwLockValue, InnerValue, NextValue, F, impl for<'r> Fn(&'r InnerValue) -> Option<&'r NextValue> + 'static>
768    where
769        H: for<'r> Fn(&'r SubValue) -> &'r NextValue,
770        G: 'static,
771        H: 'static,
772        InnerValue: 'static,
773        SubValue: 'static,
774        NextValue: 'static,
775    {
776        let first = self.inner_keypath;
777        let second = next;
778        
779        let composed = OptionalKeyPath::new(move |inner: &InnerValue| {
780            first.get(inner).map(|sub| second.get(sub))
781        });
782        
783        OptionalArcRwLockOptionalKeyPathChain {
784            outer_keypath: self.outer_keypath,
785            inner_keypath: composed,
786        }
787    }
788
789    /// Chain with an optional readable keypath through another level
790    pub fn chain_optional<NextValue, H>(
791        self,
792        next: OptionalKeyPath<SubValue, NextValue, H>,
793    ) -> OptionalArcRwLockOptionalKeyPathChain<Root, RwLockValue, InnerValue, NextValue, F, impl for<'r> Fn(&'r InnerValue) -> Option<&'r NextValue> + 'static>
794    where
795        H: for<'r> Fn(&'r SubValue) -> Option<&'r NextValue>,
796        G: 'static,
797        H: 'static,
798        InnerValue: 'static,
799        SubValue: 'static,
800        NextValue: 'static,
801    {
802        let first = self.inner_keypath;
803        let second = next;
804        
805        let composed = OptionalKeyPath::new(move |inner: &InnerValue| {
806            first.get(inner).and_then(|sub| second.get(sub))
807        });
808        
809        OptionalArcRwLockOptionalKeyPathChain {
810            outer_keypath: self.outer_keypath,
811            inner_keypath: composed,
812        }
813    }
814}
815
816// ========== WRITABLE MUTEX KEYPATH CHAINS FROM OPTIONAL KEYPATHS ==========
817
818/// A composed writable keypath chain from optional keypath through Arc<Mutex<T>> - functional style
819/// Build the chain first, then apply container at get_mut() time
820pub struct OptionalArcMutexWritableKeyPathChain<Root, MutexValue, InnerValue, SubValue, F, G>
821where
822    F: for<'r> Fn(&'r Root) -> Option<&'r MutexValue>,
823    G: for<'r> Fn(&'r mut InnerValue) -> &'r mut SubValue,
824{
825    outer_keypath: OptionalKeyPath<Root, MutexValue, F>,
826    inner_keypath: WritableKeyPath<InnerValue, SubValue, G>,
827}
828
829impl<Root, MutexValue, InnerValue, SubValue, F, G> OptionalArcMutexWritableKeyPathChain<Root, MutexValue, InnerValue, SubValue, F, G>
830where
831    F: for<'r> Fn(&'r Root) -> Option<&'r MutexValue>,
832    G: for<'r> Fn(&'r mut InnerValue) -> &'r mut SubValue,
833    MutexValue: std::borrow::Borrow<Arc<Mutex<InnerValue>>>,
834{
835    /// Apply the composed keypath chain to a container with mutable access
836    /// Consumes self - functional style (compose once, apply once)
837    pub fn get_mut<Callback, R>(self, container: &Root, callback: Callback) -> Option<R>
838    where
839        Callback: FnOnce(&mut SubValue) -> R,
840    {
841        self.outer_keypath.get(container).and_then(|arc_mutex_ref| {
842            arc_mutex_ref.borrow().lock().ok().map(|mut guard| {
843                let value_ref = self.inner_keypath.get_mut(&mut *guard);
844                callback(value_ref)
845            })
846        })
847    }
848
849    /// Chain with another writable keypath through another level
850    pub fn then<NextValue, H>(
851        self,
852        next: WritableKeyPath<SubValue, NextValue, H>,
853    ) -> OptionalArcMutexWritableKeyPathChain<Root, MutexValue, InnerValue, NextValue, F, impl for<'r> Fn(&'r mut InnerValue) -> &'r mut NextValue + 'static>
854    where
855        H: for<'r> Fn(&'r mut SubValue) -> &'r mut NextValue,
856        G: 'static,
857        H: 'static,
858        InnerValue: 'static,
859        SubValue: 'static,
860        NextValue: 'static,
861    {
862        let first = self.inner_keypath;
863        let second = next;
864        
865        let composed = WritableKeyPath::new(move |inner: &mut InnerValue| {
866            let sub = first.get_mut(inner);
867            second.get_mut(sub)
868        });
869        
870        OptionalArcMutexWritableKeyPathChain {
871            outer_keypath: self.outer_keypath,
872            inner_keypath: composed,
873        }
874    }
875
876    /// Chain with an optional writable keypath through another level
877    pub fn chain_optional<NextValue, H>(
878        self,
879        next: WritableOptionalKeyPath<SubValue, NextValue, H>,
880    ) -> OptionalArcMutexWritableOptionalKeyPathChain<Root, MutexValue, InnerValue, NextValue, F, impl for<'r> Fn(&'r mut InnerValue) -> Option<&'r mut NextValue> + 'static>
881    where
882        H: for<'r> Fn(&'r mut SubValue) -> Option<&'r mut NextValue>,
883        G: 'static,
884        H: 'static,
885        InnerValue: 'static,
886        SubValue: 'static,
887        NextValue: 'static,
888    {
889        let first = self.inner_keypath;
890        let second = next;
891        
892        let composed = WritableOptionalKeyPath::new(move |inner: &mut InnerValue| {
893            let sub = first.get_mut(inner);
894            second.get_mut(sub)
895        });
896        
897        OptionalArcMutexWritableOptionalKeyPathChain {
898            outer_keypath: self.outer_keypath,
899            inner_keypath: composed,
900        }
901    }
902}
903
904/// A composed writable optional keypath chain from optional keypath through Arc<Mutex<T>> - functional style
905/// Build the chain first, then apply container at get_mut() time
906pub struct OptionalArcMutexWritableOptionalKeyPathChain<Root, MutexValue, InnerValue, SubValue, F, G>
907where
908    F: for<'r> Fn(&'r Root) -> Option<&'r MutexValue>,
909    G: for<'r> Fn(&'r mut InnerValue) -> Option<&'r mut SubValue>,
910{
911    outer_keypath: OptionalKeyPath<Root, MutexValue, F>,
912    inner_keypath: WritableOptionalKeyPath<InnerValue, SubValue, G>,
913}
914
915impl<Root, MutexValue, InnerValue, SubValue, F, G> OptionalArcMutexWritableOptionalKeyPathChain<Root, MutexValue, InnerValue, SubValue, F, G>
916where
917    F: for<'r> Fn(&'r Root) -> Option<&'r MutexValue>,
918    G: for<'r> Fn(&'r mut InnerValue) -> Option<&'r mut SubValue>,
919    MutexValue: std::borrow::Borrow<Arc<Mutex<InnerValue>>>,
920{
921    /// Apply the composed keypath chain to a container with mutable access (if value exists)
922    /// Consumes self - functional style (compose once, apply once)
923    pub fn get_mut<Callback, R>(self, container: &Root, callback: Callback) -> Option<R>
924    where
925        Callback: FnOnce(&mut SubValue) -> R,
926    {
927        self.outer_keypath.get(container).and_then(|arc_mutex_ref| {
928            arc_mutex_ref.borrow().lock().ok().and_then(|mut guard| {
929                self.inner_keypath.get_mut(&mut *guard).map(|value_ref| callback(value_ref))
930            })
931        })
932    }
933
934    /// Chain with another writable keypath through another level
935    pub fn then<NextValue, H>(
936        self,
937        next: WritableKeyPath<SubValue, NextValue, H>,
938    ) -> OptionalArcMutexWritableOptionalKeyPathChain<Root, MutexValue, InnerValue, NextValue, F, impl for<'r> Fn(&'r mut InnerValue) -> Option<&'r mut NextValue> + 'static>
939    where
940        H: for<'r> Fn(&'r mut SubValue) -> &'r mut NextValue,
941        G: 'static,
942        H: 'static,
943        InnerValue: 'static,
944        SubValue: 'static,
945        NextValue: 'static,
946    {
947        let first = self.inner_keypath;
948        let second = next;
949        
950        let composed = WritableOptionalKeyPath::new(move |inner: &mut InnerValue| {
951            first.get_mut(inner).map(|sub| second.get_mut(sub))
952        });
953        
954        OptionalArcMutexWritableOptionalKeyPathChain {
955            outer_keypath: self.outer_keypath,
956            inner_keypath: composed,
957        }
958    }
959
960    /// Chain with an optional writable keypath through another level
961    pub fn chain_optional<NextValue, H>(
962        self,
963        next: WritableOptionalKeyPath<SubValue, NextValue, H>,
964    ) -> OptionalArcMutexWritableOptionalKeyPathChain<Root, MutexValue, InnerValue, NextValue, F, impl for<'r> Fn(&'r mut InnerValue) -> Option<&'r mut NextValue> + 'static>
965    where
966        H: for<'r> Fn(&'r mut SubValue) -> Option<&'r mut NextValue>,
967        G: 'static,
968        H: 'static,
969        InnerValue: 'static,
970        SubValue: 'static,
971        NextValue: 'static,
972    {
973        let first = self.inner_keypath;
974        let second = next;
975        
976        let composed = WritableOptionalKeyPath::new(move |inner: &mut InnerValue| {
977            first.get_mut(inner).and_then(|sub| second.get_mut(sub))
978        });
979        
980        OptionalArcMutexWritableOptionalKeyPathChain {
981            outer_keypath: self.outer_keypath,
982            inner_keypath: composed,
983        }
984    }
985}
986
987// ========== WRITABLE RWLOCK KEYPATH CHAINS FROM OPTIONAL KEYPATHS ==========
988
989/// A composed writable keypath chain from optional keypath through Arc<RwLock<T>> - functional style
990/// Build the chain first, then apply container at get_mut() time (uses write lock)
991pub struct OptionalArcRwLockWritableKeyPathChain<Root, RwLockValue, InnerValue, SubValue, F, G>
992where
993    F: for<'r> Fn(&'r Root) -> Option<&'r RwLockValue>,
994    G: for<'r> Fn(&'r mut InnerValue) -> &'r mut SubValue,
995{
996    outer_keypath: OptionalKeyPath<Root, RwLockValue, F>,
997    inner_keypath: WritableKeyPath<InnerValue, SubValue, G>,
998}
999
1000impl<Root, RwLockValue, InnerValue, SubValue, F, G> OptionalArcRwLockWritableKeyPathChain<Root, RwLockValue, InnerValue, SubValue, F, G>
1001where
1002    F: for<'r> Fn(&'r Root) -> Option<&'r RwLockValue>,
1003    G: for<'r> Fn(&'r mut InnerValue) -> &'r mut SubValue,
1004    RwLockValue: std::borrow::Borrow<Arc<RwLock<InnerValue>>>,
1005{
1006    /// Apply the composed keypath chain to a container with mutable access (write lock)
1007    /// Consumes self - functional style (compose once, apply once)
1008    pub fn get_mut<Callback, R>(self, container: &Root, callback: Callback) -> Option<R>
1009    where
1010        Callback: FnOnce(&mut SubValue) -> R,
1011    {
1012        self.outer_keypath.get(container).and_then(|arc_rwlock_ref| {
1013            arc_rwlock_ref.borrow().write().ok().map(|mut guard| {
1014                let value_ref = self.inner_keypath.get_mut(&mut *guard);
1015                callback(value_ref)
1016            })
1017        })
1018    }
1019
1020    /// Chain with another writable keypath through another level
1021    pub fn then<NextValue, H>(
1022        self,
1023        next: WritableKeyPath<SubValue, NextValue, H>,
1024    ) -> OptionalArcRwLockWritableKeyPathChain<Root, RwLockValue, InnerValue, NextValue, F, impl for<'r> Fn(&'r mut InnerValue) -> &'r mut NextValue + 'static>
1025    where
1026        H: for<'r> Fn(&'r mut SubValue) -> &'r mut NextValue,
1027        G: 'static,
1028        H: 'static,
1029        InnerValue: 'static,
1030        SubValue: 'static,
1031        NextValue: 'static,
1032    {
1033        let first = self.inner_keypath;
1034        let second = next;
1035        
1036        let composed = WritableKeyPath::new(move |inner: &mut InnerValue| {
1037            let sub = first.get_mut(inner);
1038            second.get_mut(sub)
1039        });
1040        
1041        OptionalArcRwLockWritableKeyPathChain {
1042            outer_keypath: self.outer_keypath,
1043            inner_keypath: composed,
1044        }
1045    }
1046
1047    /// Chain with an optional writable keypath through another level
1048    pub fn chain_optional<NextValue, H>(
1049        self,
1050        next: WritableOptionalKeyPath<SubValue, NextValue, H>,
1051    ) -> OptionalArcRwLockWritableOptionalKeyPathChain<Root, RwLockValue, InnerValue, NextValue, F, impl for<'r> Fn(&'r mut InnerValue) -> Option<&'r mut NextValue> + 'static>
1052    where
1053        H: for<'r> Fn(&'r mut SubValue) -> Option<&'r mut NextValue>,
1054        G: 'static,
1055        H: 'static,
1056        InnerValue: 'static,
1057        SubValue: 'static,
1058        NextValue: 'static,
1059    {
1060        let first = self.inner_keypath;
1061        let second = next;
1062        
1063        let composed = WritableOptionalKeyPath::new(move |inner: &mut InnerValue| {
1064            let sub = first.get_mut(inner);
1065            second.get_mut(sub)
1066        });
1067        
1068        OptionalArcRwLockWritableOptionalKeyPathChain {
1069            outer_keypath: self.outer_keypath,
1070            inner_keypath: composed,
1071        }
1072    }
1073}
1074
1075/// A composed writable optional keypath chain from optional keypath through Arc<RwLock<T>> - functional style
1076/// Build the chain first, then apply container at get_mut() time (uses write lock)
1077pub struct OptionalArcRwLockWritableOptionalKeyPathChain<Root, RwLockValue, InnerValue, SubValue, F, G>
1078where
1079    F: for<'r> Fn(&'r Root) -> Option<&'r RwLockValue>,
1080    G: for<'r> Fn(&'r mut InnerValue) -> Option<&'r mut SubValue>,
1081{
1082    outer_keypath: OptionalKeyPath<Root, RwLockValue, F>,
1083    inner_keypath: WritableOptionalKeyPath<InnerValue, SubValue, G>,
1084}
1085
1086impl<Root, RwLockValue, InnerValue, SubValue, F, G> OptionalArcRwLockWritableOptionalKeyPathChain<Root, RwLockValue, InnerValue, SubValue, F, G>
1087where
1088    F: for<'r> Fn(&'r Root) -> Option<&'r RwLockValue>,
1089    G: for<'r> Fn(&'r mut InnerValue) -> Option<&'r mut SubValue>,
1090    RwLockValue: std::borrow::Borrow<Arc<RwLock<InnerValue>>>,
1091{
1092    /// Apply the composed keypath chain to a container with mutable access (write lock, if value exists)
1093    /// Consumes self - functional style (compose once, apply once)
1094    pub fn get_mut<Callback, R>(self, container: &Root, callback: Callback) -> Option<R>
1095    where
1096        Callback: FnOnce(&mut SubValue) -> R,
1097    {
1098        self.outer_keypath.get(container).and_then(|arc_rwlock_ref| {
1099            arc_rwlock_ref.borrow().write().ok().and_then(|mut guard| {
1100                self.inner_keypath.get_mut(&mut *guard).map(|value_ref| callback(value_ref))
1101            })
1102        })
1103    }
1104
1105    /// Chain with another writable keypath through another level
1106    pub fn then<NextValue, H>(
1107        self,
1108        next: WritableKeyPath<SubValue, NextValue, H>,
1109    ) -> OptionalArcRwLockWritableOptionalKeyPathChain<Root, RwLockValue, InnerValue, NextValue, F, impl for<'r> Fn(&'r mut InnerValue) -> Option<&'r mut NextValue> + 'static>
1110    where
1111        H: for<'r> Fn(&'r mut SubValue) -> &'r mut NextValue,
1112        G: 'static,
1113        H: 'static,
1114        InnerValue: 'static,
1115        SubValue: 'static,
1116        NextValue: 'static,
1117    {
1118        let first = self.inner_keypath;
1119        let second = next;
1120        
1121        let composed = WritableOptionalKeyPath::new(move |inner: &mut InnerValue| {
1122            first.get_mut(inner).map(|sub| second.get_mut(sub))
1123        });
1124        
1125        OptionalArcRwLockWritableOptionalKeyPathChain {
1126            outer_keypath: self.outer_keypath,
1127            inner_keypath: composed,
1128        }
1129    }
1130
1131    /// Chain with an optional writable keypath through another level
1132    pub fn chain_optional<NextValue, H>(
1133        self,
1134        next: WritableOptionalKeyPath<SubValue, NextValue, H>,
1135    ) -> OptionalArcRwLockWritableOptionalKeyPathChain<Root, RwLockValue, InnerValue, NextValue, F, impl for<'r> Fn(&'r mut InnerValue) -> Option<&'r mut NextValue> + 'static>
1136    where
1137        H: for<'r> Fn(&'r mut SubValue) -> Option<&'r mut NextValue>,
1138        G: 'static,
1139        H: 'static,
1140        InnerValue: 'static,
1141        SubValue: 'static,
1142        NextValue: 'static,
1143    {
1144        let first = self.inner_keypath;
1145        let second = next;
1146        
1147        let composed = WritableOptionalKeyPath::new(move |inner: &mut InnerValue| {
1148            first.get_mut(inner).and_then(|sub| second.get_mut(sub))
1149        });
1150        
1151        OptionalArcRwLockWritableOptionalKeyPathChain {
1152            outer_keypath: self.outer_keypath,
1153            inner_keypath: composed,
1154        }
1155    }
1156}
1157
1158// ========== WRITABLE RWLOCK KEYPATH CHAINS ==========
1159
1160/// A composed writable keypath chain through Arc<RwLock<T>> - functional style
1161/// Build the chain first, then apply container at get_mut() time (uses write lock)
1162pub struct ArcRwLockWritableKeyPathChain<Root, RwLockValue, InnerValue, SubValue, F, G>
1163where
1164    F: for<'r> Fn(&'r Root) -> &'r RwLockValue,
1165    G: for<'r> Fn(&'r mut InnerValue) -> &'r mut SubValue,
1166{
1167    outer_keypath: KeyPath<Root, RwLockValue, F>,
1168    inner_keypath: WritableKeyPath<InnerValue, SubValue, G>,
1169}
1170
1171impl<Root, RwLockValue, InnerValue, SubValue, F, G> ArcRwLockWritableKeyPathChain<Root, RwLockValue, InnerValue, SubValue, F, G>
1172where
1173    F: for<'r> Fn(&'r Root) -> &'r RwLockValue,
1174    G: for<'r> Fn(&'r mut InnerValue) -> &'r mut SubValue,
1175    RwLockValue: std::borrow::Borrow<Arc<RwLock<InnerValue>>>,
1176{
1177    /// Apply the composed keypath chain to a container with mutable access (write lock)
1178    /// Consumes self - functional style (compose once, apply once)
1179    pub fn get_mut<Callback, R>(self, container: &Root, callback: Callback) -> Option<R>
1180    where
1181        Callback: FnOnce(&mut SubValue) -> R,
1182    {
1183        let arc_rwlock_ref = self.outer_keypath.get(container);
1184        arc_rwlock_ref.borrow().write().ok().map(|mut guard| {
1185            let value_ref = self.inner_keypath.get_mut(&mut *guard);
1186            callback(value_ref)
1187        })
1188    }
1189
1190    /// Monadic composition: chain with another writable keypath
1191    /// This allows composing deeper keypaths through the same Arc<RwLock<T>> structure
1192    /// 
1193    /// # Example
1194    /// ```rust,ignore
1195    /// // Compose: Root -> Arc<RwLock<InnerValue>> -> InnerValue -> SubValue -> NextValue
1196    /// let chain = root_keypath
1197    ///     .chain_arc_rwlock_writable_at_kp(inner_keypath)
1198    ///     .then(next_keypath);
1199    /// ```
1200    pub fn then<NextValue, H>(
1201        self,
1202        next: WritableKeyPath<SubValue, NextValue, H>,
1203    ) -> ArcRwLockWritableKeyPathChain<Root, RwLockValue, InnerValue, NextValue, F, impl for<'r> Fn(&'r mut InnerValue) -> &'r mut NextValue + 'static>
1204    where
1205        H: for<'r> Fn(&'r mut SubValue) -> &'r mut NextValue,
1206        G: 'static,
1207        H: 'static,
1208        InnerValue: 'static,
1209        SubValue: 'static,
1210        NextValue: 'static,
1211    {
1212        let first = self.inner_keypath;
1213        let second = next;
1214        
1215        // Create a new composed writable keypath
1216        let composed = WritableKeyPath::new(move |inner: &mut InnerValue| {
1217            let sub = first.get_mut(inner);
1218            second.get_mut(sub)
1219        });
1220        
1221        ArcRwLockWritableKeyPathChain {
1222            outer_keypath: self.outer_keypath,
1223            inner_keypath: composed,
1224        }
1225    }
1226
1227    /// Monadic composition: chain with a writable optional keypath (for Option fields)
1228    /// This allows composing through Option types within the same Arc<RwLock<T>> structure
1229    /// 
1230    /// # Example
1231    /// ```rust,ignore
1232    /// // Compose: Root -> Arc<RwLock<InnerValue>> -> InnerValue -> Option<SubValue> -> NextValue
1233    /// let chain = root_keypath
1234    ///     .chain_arc_rwlock_writable_at_kp(inner_keypath)
1235    ///     .chain_optional(optional_keypath);
1236    /// ```
1237    pub fn chain_optional<NextValue, H>(
1238        self,
1239        next: WritableOptionalKeyPath<SubValue, NextValue, H>,
1240    ) -> ArcRwLockWritableOptionalKeyPathChain<Root, RwLockValue, InnerValue, NextValue, F, impl for<'r> Fn(&'r mut InnerValue) -> Option<&'r mut NextValue> + 'static>
1241    where
1242        H: for<'r> Fn(&'r mut SubValue) -> Option<&'r mut NextValue>,
1243        G: 'static,
1244        H: 'static,
1245        InnerValue: 'static,
1246        SubValue: 'static,
1247        NextValue: 'static,
1248    {
1249        let first = self.inner_keypath;
1250        let second = next;
1251        
1252        // Create a new composed writable optional keypath
1253        let composed = WritableOptionalKeyPath::new(move |inner: &mut InnerValue| {
1254            let sub = first.get_mut(inner);
1255            second.get_mut(sub)
1256        });
1257        
1258        ArcRwLockWritableOptionalKeyPathChain {
1259            outer_keypath: self.outer_keypath,
1260            inner_keypath: composed,
1261        }
1262    }
1263}
1264
1265/// A composed writable optional keypath chain through Arc<RwLock<T>> - functional style
1266/// Build the chain first, then apply container at get_mut() time (uses write lock)
1267pub struct ArcRwLockWritableOptionalKeyPathChain<Root, RwLockValue, InnerValue, SubValue, F, G>
1268where
1269    F: for<'r> Fn(&'r Root) -> &'r RwLockValue,
1270    G: for<'r> Fn(&'r mut InnerValue) -> Option<&'r mut SubValue>,
1271{
1272    outer_keypath: KeyPath<Root, RwLockValue, F>,
1273    inner_keypath: WritableOptionalKeyPath<InnerValue, SubValue, G>,
1274}
1275
1276impl<Root, RwLockValue, InnerValue, SubValue, F, G> ArcRwLockWritableOptionalKeyPathChain<Root, RwLockValue, InnerValue, SubValue, F, G>
1277where
1278    F: for<'r> Fn(&'r Root) -> &'r RwLockValue,
1279    G: for<'r> Fn(&'r mut InnerValue) -> Option<&'r mut SubValue>,
1280    RwLockValue: std::borrow::Borrow<Arc<RwLock<InnerValue>>>,
1281{
1282    /// Apply the composed keypath chain to a container with mutable access (write lock, if value exists)
1283    /// Consumes self - functional style (compose once, apply once)
1284    pub fn get_mut<Callback, R>(self, container: &Root, callback: Callback) -> Option<R>
1285    where
1286        Callback: FnOnce(&mut SubValue) -> R,
1287    {
1288        let arc_rwlock_ref = self.outer_keypath.get(container);
1289        arc_rwlock_ref.borrow().write().ok().and_then(|mut guard| {
1290            self.inner_keypath.get_mut(&mut *guard).map(|value_ref| callback(value_ref))
1291        })
1292    }
1293
1294    /// Monadic composition: chain with another writable keypath
1295    /// This allows composing deeper keypaths through the same Arc<RwLock<T>> structure
1296    pub fn then<NextValue, H>(
1297        self,
1298        next: WritableKeyPath<SubValue, NextValue, H>,
1299    ) -> ArcRwLockWritableOptionalKeyPathChain<Root, RwLockValue, InnerValue, NextValue, F, impl for<'r> Fn(&'r mut InnerValue) -> Option<&'r mut NextValue> + 'static>
1300    where
1301        H: for<'r> Fn(&'r mut SubValue) -> &'r mut NextValue,
1302        G: 'static,
1303        H: 'static,
1304        InnerValue: 'static,
1305        SubValue: 'static,
1306        NextValue: 'static,
1307    {
1308        let first = self.inner_keypath;
1309        let second = next;
1310        
1311        // Create a new composed writable optional keypath
1312        let composed = WritableOptionalKeyPath::new(move |inner: &mut InnerValue| {
1313            if let Some(sub) = first.get_mut(inner) {
1314                Some(second.get_mut(sub))
1315            } else {
1316                None
1317            }
1318        });
1319        
1320        ArcRwLockWritableOptionalKeyPathChain {
1321            outer_keypath: self.outer_keypath,
1322            inner_keypath: composed,
1323        }
1324    }
1325
1326    /// Monadic composition: chain with another writable optional keypath (for Option fields)
1327    /// This allows composing through Option types within the same Arc<RwLock<T>> structure
1328    pub fn chain_optional<NextValue, H>(
1329        self,
1330        next: WritableOptionalKeyPath<SubValue, NextValue, H>,
1331    ) -> ArcRwLockWritableOptionalKeyPathChain<Root, RwLockValue, InnerValue, NextValue, F, impl for<'r> Fn(&'r mut InnerValue) -> Option<&'r mut NextValue> + 'static>
1332    where
1333        H: for<'r> Fn(&'r mut SubValue) -> Option<&'r mut NextValue>,
1334        G: 'static,
1335        H: 'static,
1336        InnerValue: 'static,
1337        SubValue: 'static,
1338        NextValue: 'static,
1339    {
1340        let first = self.inner_keypath;
1341        let second = next;
1342        
1343        // Create a new composed writable optional keypath
1344        let composed = WritableOptionalKeyPath::new(move |inner: &mut InnerValue| {
1345            first.get_mut(inner).and_then(|sub| second.get_mut(sub))
1346        });
1347        
1348        ArcRwLockWritableOptionalKeyPathChain {
1349            outer_keypath: self.outer_keypath,
1350            inner_keypath: composed,
1351        }
1352    }
1353}
1354
1355// ========== PARKING_LOT MUTEX/RWLOCK CHAIN TYPES ==========
1356
1357#[cfg(feature = "parking_lot")]
1358use parking_lot::{Mutex as ParkingMutex, RwLock as ParkingRwLock};
1359
1360/// A composed keypath chain through Arc<parking_lot::Mutex<T>> - functional style
1361#[cfg(feature = "parking_lot")]
1362pub struct ArcParkingMutexKeyPathChain<Root, InnerValue, SubValue, F, G>
1363where
1364    F: for<'r> Fn(&'r Root) -> &'r Arc<parking_lot::Mutex<InnerValue>>,
1365    G: for<'r> Fn(&'r InnerValue) -> &'r SubValue,
1366{
1367    outer_keypath: KeyPath<Root, Arc<parking_lot::Mutex<InnerValue>>, F>,
1368    inner_keypath: KeyPath<InnerValue, SubValue, G>,
1369}
1370
1371#[cfg(feature = "parking_lot")]
1372impl<Root, InnerValue, SubValue, F, G> ArcParkingMutexKeyPathChain<Root, InnerValue, SubValue, F, G>
1373where
1374    F: for<'r> Fn(&'r Root) -> &'r Arc<parking_lot::Mutex<InnerValue>>,
1375    G: for<'r> Fn(&'r InnerValue) -> &'r SubValue,
1376{
1377    /// Apply the composed keypath chain to a container (read)
1378    pub fn get<Callback>(self, container: &Root, callback: Callback)
1379    where
1380        Callback: FnOnce(&SubValue) -> (),
1381    {
1382        let arc_mutex_ref = self.outer_keypath.get(container);
1383        let guard = arc_mutex_ref.lock();
1384        let value = self.inner_keypath.get(&*guard);
1385        callback(value);
1386    }
1387
1388    /// Chain with another readable keypath through another level
1389    pub fn then<NextValue, H>(
1390        self,
1391        next: KeyPath<SubValue, NextValue, H>,
1392    ) -> ArcParkingMutexKeyPathChain<Root, InnerValue, NextValue, F, impl for<'r> Fn(&'r InnerValue) -> &'r NextValue + 'static>
1393    where
1394        H: for<'r> Fn(&'r SubValue) -> &'r NextValue,
1395        G: 'static,
1396        H: 'static,
1397        InnerValue: 'static,
1398        SubValue: 'static,
1399        NextValue: 'static,
1400    {
1401        let first = self.inner_keypath;
1402        let second = next;
1403        
1404        let composed = KeyPath::new(move |inner: &InnerValue| {
1405            let sub = first.get(inner);
1406            second.get(sub)
1407        });
1408        
1409        ArcParkingMutexKeyPathChain {
1410            outer_keypath: self.outer_keypath,
1411            inner_keypath: composed,
1412        }
1413    }
1414
1415    /// Chain with an optional readable keypath through another level
1416    pub fn chain_optional<NextValue, H>(
1417        self,
1418        next: OptionalKeyPath<SubValue, NextValue, H>,
1419    ) -> ArcParkingMutexOptionalKeyPathChain<Root, InnerValue, NextValue, F, impl for<'r> Fn(&'r InnerValue) -> Option<&'r NextValue> + 'static>
1420    where
1421        H: for<'r> Fn(&'r SubValue) -> Option<&'r NextValue>,
1422        G: 'static,
1423        H: 'static,
1424        InnerValue: 'static,
1425        SubValue: 'static,
1426        NextValue: 'static,
1427    {
1428        let first = self.inner_keypath;
1429        let second = next;
1430        
1431        let composed = OptionalKeyPath::new(move |inner: &InnerValue| {
1432            let sub = first.get(inner);
1433            second.get(sub)
1434        });
1435        
1436        ArcParkingMutexOptionalKeyPathChain {
1437            outer_keypath: self.outer_keypath,
1438            inner_keypath: composed,
1439        }
1440    }
1441}
1442
1443/// A composed optional keypath chain through Arc<parking_lot::Mutex<T>> - functional style
1444#[cfg(feature = "parking_lot")]
1445pub struct ArcParkingMutexOptionalKeyPathChain<Root, InnerValue, SubValue, F, G>
1446where
1447    F: for<'r> Fn(&'r Root) -> &'r Arc<parking_lot::Mutex<InnerValue>>,
1448    G: for<'r> Fn(&'r InnerValue) -> Option<&'r SubValue>,
1449{
1450    outer_keypath: KeyPath<Root, Arc<parking_lot::Mutex<InnerValue>>, F>,
1451    inner_keypath: OptionalKeyPath<InnerValue, SubValue, G>,
1452}
1453
1454#[cfg(feature = "parking_lot")]
1455impl<Root, InnerValue, SubValue, F, G> ArcParkingMutexOptionalKeyPathChain<Root, InnerValue, SubValue, F, G>
1456where
1457    F: for<'r> Fn(&'r Root) -> &'r Arc<parking_lot::Mutex<InnerValue>>,
1458    G: for<'r> Fn(&'r InnerValue) -> Option<&'r SubValue>,
1459{
1460    /// Apply the composed keypath chain to a container (read, if value exists)
1461    pub fn get<Callback>(self, container: &Root, callback: Callback) -> Option<()>
1462    where
1463        Callback: FnOnce(&SubValue) -> (),
1464    {
1465        let arc_mutex_ref = self.outer_keypath.get(container);
1466        let guard = arc_mutex_ref.lock();
1467        self.inner_keypath.get(&*guard).map(|value| callback(value))
1468    }
1469
1470    /// Chain with another readable keypath through another level
1471    pub fn then<NextValue, H>(
1472        self,
1473        next: KeyPath<SubValue, NextValue, H>,
1474    ) -> ArcParkingMutexOptionalKeyPathChain<Root, InnerValue, NextValue, F, impl for<'r> Fn(&'r InnerValue) -> Option<&'r NextValue> + 'static>
1475    where
1476        H: for<'r> Fn(&'r SubValue) -> &'r NextValue,
1477        G: 'static,
1478        H: 'static,
1479        InnerValue: 'static,
1480        SubValue: 'static,
1481        NextValue: 'static,
1482    {
1483        let first = self.inner_keypath;
1484        let second = next;
1485        
1486        let composed = OptionalKeyPath::new(move |inner: &InnerValue| {
1487            first.get(inner).map(|sub| second.get(sub))
1488        });
1489        
1490        ArcParkingMutexOptionalKeyPathChain {
1491            outer_keypath: self.outer_keypath,
1492            inner_keypath: composed,
1493        }
1494    }
1495
1496    /// Chain with an optional readable keypath through another level
1497    pub fn chain_optional<NextValue, H>(
1498        self,
1499        next: OptionalKeyPath<SubValue, NextValue, H>,
1500    ) -> ArcParkingMutexOptionalKeyPathChain<Root, InnerValue, NextValue, F, impl for<'r> Fn(&'r InnerValue) -> Option<&'r NextValue> + 'static>
1501    where
1502        H: for<'r> Fn(&'r SubValue) -> Option<&'r NextValue>,
1503        G: 'static,
1504        H: 'static,
1505        InnerValue: 'static,
1506        SubValue: 'static,
1507        NextValue: 'static,
1508    {
1509        let first = self.inner_keypath;
1510        let second = next;
1511        
1512        let composed = OptionalKeyPath::new(move |inner: &InnerValue| {
1513            first.get(inner).and_then(|sub| second.get(sub))
1514        });
1515        
1516        ArcParkingMutexOptionalKeyPathChain {
1517            outer_keypath: self.outer_keypath,
1518            inner_keypath: composed,
1519        }
1520    }
1521}
1522
1523/// A composed writable keypath chain through Arc<parking_lot::Mutex<T>> - functional style
1524#[cfg(feature = "parking_lot")]
1525pub struct ArcParkingMutexWritableKeyPathChain<Root, InnerValue, SubValue, F, G>
1526where
1527    F: for<'r> Fn(&'r Root) -> &'r Arc<parking_lot::Mutex<InnerValue>>,
1528    G: for<'r> Fn(&'r mut InnerValue) -> &'r mut SubValue,
1529{
1530    outer_keypath: KeyPath<Root, Arc<parking_lot::Mutex<InnerValue>>, F>,
1531    inner_keypath: WritableKeyPath<InnerValue, SubValue, G>,
1532}
1533
1534#[cfg(feature = "parking_lot")]
1535impl<Root, InnerValue, SubValue, F, G> ArcParkingMutexWritableKeyPathChain<Root, InnerValue, SubValue, F, G>
1536where
1537    F: for<'r> Fn(&'r Root) -> &'r Arc<parking_lot::Mutex<InnerValue>>,
1538    G: for<'r> Fn(&'r mut InnerValue) -> &'r mut SubValue,
1539{
1540    /// Apply the composed keypath chain to a container with mutable access
1541    pub fn get_mut<Callback, R>(self, container: &Root, callback: Callback) -> R
1542    where
1543        Callback: FnOnce(&mut SubValue) -> R,
1544    {
1545        let arc_mutex_ref = self.outer_keypath.get(container);
1546        let mut guard = arc_mutex_ref.lock();
1547        let value_ref = self.inner_keypath.get_mut(&mut *guard);
1548        callback(value_ref)
1549    }
1550
1551    /// Chain with another writable keypath through another level
1552    pub fn then<NextValue, H>(
1553        self,
1554        next: WritableKeyPath<SubValue, NextValue, H>,
1555    ) -> ArcParkingMutexWritableKeyPathChain<Root, InnerValue, NextValue, F, impl for<'r> Fn(&'r mut InnerValue) -> &'r mut NextValue + 'static>
1556    where
1557        H: for<'r> Fn(&'r mut SubValue) -> &'r mut NextValue,
1558        G: 'static,
1559        H: 'static,
1560        InnerValue: 'static,
1561        SubValue: 'static,
1562        NextValue: 'static,
1563    {
1564        let first = self.inner_keypath;
1565        let second = next;
1566        
1567        let composed = WritableKeyPath::new(move |inner: &mut InnerValue| {
1568            let sub = first.get_mut(inner);
1569            second.get_mut(sub)
1570        });
1571        
1572        ArcParkingMutexWritableKeyPathChain {
1573            outer_keypath: self.outer_keypath,
1574            inner_keypath: composed,
1575        }
1576    }
1577
1578    /// Chain with an optional writable keypath through another level
1579    pub fn chain_optional<NextValue, H>(
1580        self,
1581        next: WritableOptionalKeyPath<SubValue, NextValue, H>,
1582    ) -> ArcParkingMutexWritableOptionalKeyPathChain<Root, InnerValue, NextValue, F, impl for<'r> Fn(&'r mut InnerValue) -> Option<&'r mut NextValue> + 'static>
1583    where
1584        H: for<'r> Fn(&'r mut SubValue) -> Option<&'r mut NextValue>,
1585        G: 'static,
1586        H: 'static,
1587        InnerValue: 'static,
1588        SubValue: 'static,
1589        NextValue: 'static,
1590    {
1591        let first = self.inner_keypath;
1592        let second = next;
1593        
1594        let composed = WritableOptionalKeyPath::new(move |inner: &mut InnerValue| {
1595            let sub = first.get_mut(inner);
1596            second.get_mut(sub)
1597        });
1598        
1599        ArcParkingMutexWritableOptionalKeyPathChain {
1600            outer_keypath: self.outer_keypath,
1601            inner_keypath: composed,
1602        }
1603    }
1604}
1605
1606/// A composed writable optional keypath chain through Arc<parking_lot::Mutex<T>> - functional style
1607#[cfg(feature = "parking_lot")]
1608pub struct ArcParkingMutexWritableOptionalKeyPathChain<Root, InnerValue, SubValue, F, G>
1609where
1610    F: for<'r> Fn(&'r Root) -> &'r Arc<parking_lot::Mutex<InnerValue>>,
1611    G: for<'r> Fn(&'r mut InnerValue) -> Option<&'r mut SubValue>,
1612{
1613    outer_keypath: KeyPath<Root, Arc<parking_lot::Mutex<InnerValue>>, F>,
1614    inner_keypath: WritableOptionalKeyPath<InnerValue, SubValue, G>,
1615}
1616
1617#[cfg(feature = "parking_lot")]
1618impl<Root, InnerValue, SubValue, F, G> ArcParkingMutexWritableOptionalKeyPathChain<Root, InnerValue, SubValue, F, G>
1619where
1620    F: for<'r> Fn(&'r Root) -> &'r Arc<parking_lot::Mutex<InnerValue>>,
1621    G: for<'r> Fn(&'r mut InnerValue) -> Option<&'r mut SubValue>,
1622{
1623    /// Apply the composed keypath chain to a container with mutable access (if value exists)
1624    pub fn get_mut<Callback, R>(self, container: &Root, callback: Callback) -> Option<R>
1625    where
1626        Callback: FnOnce(&mut SubValue) -> R,
1627    {
1628        let arc_mutex_ref = self.outer_keypath.get(container);
1629        let mut guard = arc_mutex_ref.lock();
1630        self.inner_keypath.get_mut(&mut *guard).map(|value_ref| callback(value_ref))
1631    }
1632
1633    /// Chain with another writable keypath through another level
1634    pub fn then<NextValue, H>(
1635        self,
1636        next: WritableKeyPath<SubValue, NextValue, H>,
1637    ) -> ArcParkingMutexWritableOptionalKeyPathChain<Root, InnerValue, NextValue, F, impl for<'r> Fn(&'r mut InnerValue) -> Option<&'r mut NextValue> + 'static>
1638    where
1639        H: for<'r> Fn(&'r mut SubValue) -> &'r mut NextValue,
1640        G: 'static,
1641        H: 'static,
1642        InnerValue: 'static,
1643        SubValue: 'static,
1644        NextValue: 'static,
1645    {
1646        let first = self.inner_keypath;
1647        let second = next;
1648        
1649        let composed = WritableOptionalKeyPath::new(move |inner: &mut InnerValue| {
1650            first.get_mut(inner).map(|sub| second.get_mut(sub))
1651        });
1652        
1653        ArcParkingMutexWritableOptionalKeyPathChain {
1654            outer_keypath: self.outer_keypath,
1655            inner_keypath: composed,
1656        }
1657    }
1658
1659    /// Chain with an optional writable keypath through another level
1660    pub fn chain_optional<NextValue, H>(
1661        self,
1662        next: WritableOptionalKeyPath<SubValue, NextValue, H>,
1663    ) -> ArcParkingMutexWritableOptionalKeyPathChain<Root, InnerValue, NextValue, F, impl for<'r> Fn(&'r mut InnerValue) -> Option<&'r mut NextValue> + 'static>
1664    where
1665        H: for<'r> Fn(&'r mut SubValue) -> Option<&'r mut NextValue>,
1666        G: 'static,
1667        H: 'static,
1668        InnerValue: 'static,
1669        SubValue: 'static,
1670        NextValue: 'static,
1671    {
1672        let first = self.inner_keypath;
1673        let second = next;
1674        
1675        let composed = WritableOptionalKeyPath::new(move |inner: &mut InnerValue| {
1676            first.get_mut(inner).and_then(|sub| second.get_mut(sub))
1677        });
1678        
1679        ArcParkingMutexWritableOptionalKeyPathChain {
1680            outer_keypath: self.outer_keypath,
1681            inner_keypath: composed,
1682        }
1683    }
1684}
1685
1686/// A composed keypath chain through Arc<parking_lot::RwLock<T>> - functional style
1687#[cfg(feature = "parking_lot")]
1688pub struct ArcParkingRwLockKeyPathChain<Root, InnerValue, SubValue, F, G>
1689where
1690    F: for<'r> Fn(&'r Root) -> &'r Arc<parking_lot::RwLock<InnerValue>>,
1691    G: for<'r> Fn(&'r InnerValue) -> &'r SubValue,
1692{
1693    outer_keypath: KeyPath<Root, Arc<parking_lot::RwLock<InnerValue>>, F>,
1694    inner_keypath: KeyPath<InnerValue, SubValue, G>,
1695}
1696
1697#[cfg(feature = "parking_lot")]
1698impl<Root, InnerValue, SubValue, F, G> ArcParkingRwLockKeyPathChain<Root, InnerValue, SubValue, F, G>
1699where
1700    F: for<'r> Fn(&'r Root) -> &'r Arc<parking_lot::RwLock<InnerValue>>,
1701    G: for<'r> Fn(&'r InnerValue) -> &'r SubValue,
1702{
1703    /// Apply the composed keypath chain to a container (read lock)
1704    pub fn get<Callback>(self, container: &Root, callback: Callback)
1705    where
1706        Callback: FnOnce(&SubValue) -> (),
1707    {
1708        let arc_rwlock_ref = self.outer_keypath.get(container);
1709        let guard = arc_rwlock_ref.read();
1710        let value = self.inner_keypath.get(&*guard);
1711        callback(value);
1712    }
1713
1714    /// Chain with another readable keypath through another level
1715    pub fn then<NextValue, H>(
1716        self,
1717        next: KeyPath<SubValue, NextValue, H>,
1718    ) -> ArcParkingRwLockKeyPathChain<Root, InnerValue, NextValue, F, impl for<'r> Fn(&'r InnerValue) -> &'r NextValue + 'static>
1719    where
1720        H: for<'r> Fn(&'r SubValue) -> &'r NextValue,
1721        G: 'static,
1722        H: 'static,
1723        InnerValue: 'static,
1724        SubValue: 'static,
1725        NextValue: 'static,
1726    {
1727        let first = self.inner_keypath;
1728        let second = next;
1729        
1730        let composed = KeyPath::new(move |inner: &InnerValue| {
1731            let sub = first.get(inner);
1732            second.get(sub)
1733        });
1734        
1735        ArcParkingRwLockKeyPathChain {
1736            outer_keypath: self.outer_keypath,
1737            inner_keypath: composed,
1738        }
1739    }
1740
1741    /// Chain with an optional readable keypath through another level
1742    pub fn chain_optional<NextValue, H>(
1743        self,
1744        next: OptionalKeyPath<SubValue, NextValue, H>,
1745    ) -> ArcParkingRwLockOptionalKeyPathChain<Root, InnerValue, NextValue, F, impl for<'r> Fn(&'r InnerValue) -> Option<&'r NextValue> + 'static>
1746    where
1747        H: for<'r> Fn(&'r SubValue) -> Option<&'r NextValue>,
1748        G: 'static,
1749        H: 'static,
1750        InnerValue: 'static,
1751        SubValue: 'static,
1752        NextValue: 'static,
1753    {
1754        let first = self.inner_keypath;
1755        let second = next;
1756        
1757        let composed = OptionalKeyPath::new(move |inner: &InnerValue| {
1758            let sub = first.get(inner);
1759            second.get(sub)
1760        });
1761        
1762        ArcParkingRwLockOptionalKeyPathChain {
1763            outer_keypath: self.outer_keypath,
1764            inner_keypath: composed,
1765        }
1766    }
1767}
1768
1769/// A composed optional keypath chain through Arc<parking_lot::RwLock<T>> - functional style
1770#[cfg(feature = "parking_lot")]
1771pub struct ArcParkingRwLockOptionalKeyPathChain<Root, InnerValue, SubValue, F, G>
1772where
1773    F: for<'r> Fn(&'r Root) -> &'r Arc<parking_lot::RwLock<InnerValue>>,
1774    G: for<'r> Fn(&'r InnerValue) -> Option<&'r SubValue>,
1775{
1776    outer_keypath: KeyPath<Root, Arc<parking_lot::RwLock<InnerValue>>, F>,
1777    inner_keypath: OptionalKeyPath<InnerValue, SubValue, G>,
1778}
1779
1780#[cfg(feature = "parking_lot")]
1781impl<Root, InnerValue, SubValue, F, G> ArcParkingRwLockOptionalKeyPathChain<Root, InnerValue, SubValue, F, G>
1782where
1783    F: for<'r> Fn(&'r Root) -> &'r Arc<parking_lot::RwLock<InnerValue>>,
1784    G: for<'r> Fn(&'r InnerValue) -> Option<&'r SubValue>,
1785{
1786    /// Apply the composed keypath chain to a container (read lock, if value exists)
1787    pub fn get<Callback>(self, container: &Root, callback: Callback) -> Option<()>
1788    where
1789        Callback: FnOnce(&SubValue) -> (),
1790    {
1791        let arc_rwlock_ref = self.outer_keypath.get(container);
1792        let guard = arc_rwlock_ref.read();
1793        self.inner_keypath.get(&*guard).map(|value| callback(value))
1794    }
1795
1796    /// Chain with another readable keypath through another level
1797    pub fn then<NextValue, H>(
1798        self,
1799        next: KeyPath<SubValue, NextValue, H>,
1800    ) -> ArcParkingRwLockOptionalKeyPathChain<Root, InnerValue, NextValue, F, impl for<'r> Fn(&'r InnerValue) -> Option<&'r NextValue> + 'static>
1801    where
1802        H: for<'r> Fn(&'r SubValue) -> &'r NextValue,
1803        G: 'static,
1804        H: 'static,
1805        InnerValue: 'static,
1806        SubValue: 'static,
1807        NextValue: 'static,
1808    {
1809        let first = self.inner_keypath;
1810        let second = next;
1811        
1812        let composed = OptionalKeyPath::new(move |inner: &InnerValue| {
1813            first.get(inner).map(|sub| second.get(sub))
1814        });
1815        
1816        ArcParkingRwLockOptionalKeyPathChain {
1817            outer_keypath: self.outer_keypath,
1818            inner_keypath: composed,
1819        }
1820    }
1821
1822    /// Chain with an optional readable keypath through another level
1823    pub fn chain_optional<NextValue, H>(
1824        self,
1825        next: OptionalKeyPath<SubValue, NextValue, H>,
1826    ) -> ArcParkingRwLockOptionalKeyPathChain<Root, InnerValue, NextValue, F, impl for<'r> Fn(&'r InnerValue) -> Option<&'r NextValue> + 'static>
1827    where
1828        H: for<'r> Fn(&'r SubValue) -> Option<&'r NextValue>,
1829        G: 'static,
1830        H: 'static,
1831        InnerValue: 'static,
1832        SubValue: 'static,
1833        NextValue: 'static,
1834    {
1835        let first = self.inner_keypath;
1836        let second = next;
1837        
1838        let composed = OptionalKeyPath::new(move |inner: &InnerValue| {
1839            first.get(inner).and_then(|sub| second.get(sub))
1840        });
1841        
1842        ArcParkingRwLockOptionalKeyPathChain {
1843            outer_keypath: self.outer_keypath,
1844            inner_keypath: composed,
1845        }
1846    }
1847}
1848
1849/// A composed writable keypath chain through Arc<parking_lot::RwLock<T>> - functional style
1850#[cfg(feature = "parking_lot")]
1851pub struct ArcParkingRwLockWritableKeyPathChain<Root, InnerValue, SubValue, F, G>
1852where
1853    F: for<'r> Fn(&'r Root) -> &'r Arc<parking_lot::RwLock<InnerValue>>,
1854    G: for<'r> Fn(&'r mut InnerValue) -> &'r mut SubValue,
1855{
1856    outer_keypath: KeyPath<Root, Arc<parking_lot::RwLock<InnerValue>>, F>,
1857    inner_keypath: WritableKeyPath<InnerValue, SubValue, G>,
1858}
1859
1860#[cfg(feature = "parking_lot")]
1861impl<Root, InnerValue, SubValue, F, G> ArcParkingRwLockWritableKeyPathChain<Root, InnerValue, SubValue, F, G>
1862where
1863    F: for<'r> Fn(&'r Root) -> &'r Arc<parking_lot::RwLock<InnerValue>>,
1864    G: for<'r> Fn(&'r mut InnerValue) -> &'r mut SubValue,
1865{
1866    /// Apply the composed keypath chain to a container with mutable access (write lock)
1867    pub fn get_mut<Callback, R>(self, container: &Root, callback: Callback) -> R
1868    where
1869        Callback: FnOnce(&mut SubValue) -> R,
1870    {
1871        let arc_rwlock_ref = self.outer_keypath.get(container);
1872        let mut guard = arc_rwlock_ref.write();
1873        let value_ref = self.inner_keypath.get_mut(&mut *guard);
1874        callback(value_ref)
1875    }
1876
1877    /// Monadic composition: chain with another writable keypath
1878    /// This allows composing deeper keypaths through the same Arc<parking_lot::RwLock<T>> structure
1879    pub fn then<NextValue, H>(
1880        self,
1881        next: WritableKeyPath<SubValue, NextValue, H>,
1882    ) -> ArcParkingRwLockWritableKeyPathChain<Root, InnerValue, NextValue, F, impl for<'r> Fn(&'r mut InnerValue) -> &'r mut NextValue + 'static>
1883    where
1884        H: for<'r> Fn(&'r mut SubValue) -> &'r mut NextValue,
1885        G: 'static,
1886        H: 'static,
1887        InnerValue: 'static,
1888        SubValue: 'static,
1889        NextValue: 'static,
1890    {
1891        let first = self.inner_keypath;
1892        let second = next;
1893        
1894        // Create a new composed writable keypath
1895        let composed = WritableKeyPath::new(move |inner: &mut InnerValue| {
1896            let sub = first.get_mut(inner);
1897            second.get_mut(sub)
1898        });
1899        
1900        ArcParkingRwLockWritableKeyPathChain {
1901            outer_keypath: self.outer_keypath,
1902            inner_keypath: composed,
1903        }
1904    }
1905
1906    /// Monadic composition: chain with a writable optional keypath (for Option fields)
1907    /// This allows composing through Option types within the same Arc<parking_lot::RwLock<T>> structure
1908    pub fn chain_optional<NextValue, H>(
1909        self,
1910        next: WritableOptionalKeyPath<SubValue, NextValue, H>,
1911    ) -> ArcParkingRwLockWritableOptionalKeyPathChain<Root, InnerValue, NextValue, F, impl for<'r> Fn(&'r mut InnerValue) -> Option<&'r mut NextValue> + 'static>
1912    where
1913        H: for<'r> Fn(&'r mut SubValue) -> Option<&'r mut NextValue>,
1914        G: 'static,
1915        H: 'static,
1916        InnerValue: 'static,
1917        SubValue: 'static,
1918        NextValue: 'static,
1919    {
1920        let first = self.inner_keypath;
1921        let second = next;
1922        
1923        // Create a new composed writable optional keypath
1924        // first.get_mut returns &mut SubValue (not Option), second.get_mut returns Option<&mut NextValue>
1925        let composed = WritableOptionalKeyPath::new(move |inner: &mut InnerValue| {
1926            let sub = first.get_mut(inner);
1927            second.get_mut(sub)
1928        });
1929        
1930        ArcParkingRwLockWritableOptionalKeyPathChain {
1931            outer_keypath: self.outer_keypath,
1932            inner_keypath: composed,
1933        }
1934    }
1935}
1936
1937/// A composed writable optional keypath chain through Arc<parking_lot::RwLock<T>> - functional style
1938#[cfg(feature = "parking_lot")]
1939pub struct ArcParkingRwLockWritableOptionalKeyPathChain<Root, InnerValue, SubValue, F, G>
1940where
1941    F: for<'r> Fn(&'r Root) -> &'r Arc<parking_lot::RwLock<InnerValue>>,
1942    G: for<'r> Fn(&'r mut InnerValue) -> Option<&'r mut SubValue>,
1943{
1944    outer_keypath: KeyPath<Root, Arc<parking_lot::RwLock<InnerValue>>, F>,
1945    inner_keypath: WritableOptionalKeyPath<InnerValue, SubValue, G>,
1946}
1947
1948#[cfg(feature = "parking_lot")]
1949impl<Root, InnerValue, SubValue, F, G> ArcParkingRwLockWritableOptionalKeyPathChain<Root, InnerValue, SubValue, F, G>
1950where
1951    F: for<'r> Fn(&'r Root) -> &'r Arc<parking_lot::RwLock<InnerValue>>,
1952    G: for<'r> Fn(&'r mut InnerValue) -> Option<&'r mut SubValue>,
1953{
1954    /// Apply the composed keypath chain to a container with mutable access (write lock, if value exists)
1955    pub fn get_mut<Callback, R>(self, container: &Root, callback: Callback) -> Option<R>
1956    where
1957        Callback: FnOnce(&mut SubValue) -> R,
1958    {
1959        let arc_rwlock_ref = self.outer_keypath.get(container);
1960        let mut guard = arc_rwlock_ref.write();
1961        self.inner_keypath.get_mut(&mut *guard).map(|value_ref| callback(value_ref))
1962    }
1963
1964    /// Monadic composition: chain with another writable keypath
1965    /// This allows composing deeper keypaths through the same Arc<parking_lot::RwLock<T>> structure
1966    pub fn then<NextValue, H>(
1967        self,
1968        next: WritableKeyPath<SubValue, NextValue, H>,
1969    ) -> ArcParkingRwLockWritableOptionalKeyPathChain<Root, InnerValue, NextValue, F, impl for<'r> Fn(&'r mut InnerValue) -> Option<&'r mut NextValue> + 'static>
1970    where
1971        H: for<'r> Fn(&'r mut SubValue) -> &'r mut NextValue,
1972        G: 'static,
1973        H: 'static,
1974        InnerValue: 'static,
1975        SubValue: 'static,
1976        NextValue: 'static,
1977    {
1978        let first_keypath = self.inner_keypath;
1979        let second_keypath = next;
1980        
1981        // Create a new composed writable optional keypath
1982        // first_keypath.get_mut returns Option<&mut SubValue>, second_keypath.get_mut returns &mut NextValue
1983        let composed = WritableOptionalKeyPath::new(move |inner: &mut InnerValue| {
1984            first_keypath.get_mut(inner).map(|sub| second_keypath.get_mut(sub))
1985        });
1986        
1987        ArcParkingRwLockWritableOptionalKeyPathChain {
1988            outer_keypath: self.outer_keypath,
1989            inner_keypath: composed,
1990        }
1991    }
1992
1993    /// Monadic composition: chain with another writable optional keypath (for Option fields)
1994    /// This allows composing through Option types within the same Arc<parking_lot::RwLock<T>> structure
1995    pub fn chain_optional<NextValue, H>(
1996        self,
1997        next: WritableOptionalKeyPath<SubValue, NextValue, H>,
1998    ) -> ArcParkingRwLockWritableOptionalKeyPathChain<Root, InnerValue, NextValue, F, impl for<'r> Fn(&'r mut InnerValue) -> Option<&'r mut NextValue> + 'static>
1999    where
2000        H: for<'r> Fn(&'r mut SubValue) -> Option<&'r mut NextValue>,
2001        G: 'static,
2002        H: 'static,
2003        InnerValue: 'static,
2004        SubValue: 'static,
2005        NextValue: 'static,
2006    {
2007        let first = self.inner_keypath;
2008        let second = next;
2009        
2010        // Create a new composed writable optional keypath
2011        let composed = WritableOptionalKeyPath::new(move |inner: &mut InnerValue| {
2012            first.get_mut(inner).and_then(|sub| second.get_mut(sub))
2013        });
2014        
2015        ArcParkingRwLockWritableOptionalKeyPathChain {
2016            outer_keypath: self.outer_keypath,
2017            inner_keypath: composed,
2018        }
2019    }
2020}
2021
2022// ========== OPTIONAL PARKING_LOT MUTEX KEYPATH CHAINS (from OptionalKeyPath) ==========
2023
2024/// A composed keypath chain from optional keypath through Arc<parking_lot::Mutex<T>> - functional style
2025#[cfg(feature = "parking_lot")]
2026pub struct OptionalArcParkingMutexKeyPathChain<Root, InnerValue, SubValue, F, G>
2027where
2028    F: for<'r> Fn(&'r Root) -> Option<&'r Arc<parking_lot::Mutex<InnerValue>>>,
2029    G: for<'r> Fn(&'r InnerValue) -> &'r SubValue,
2030{
2031    outer_keypath: OptionalKeyPath<Root, Arc<parking_lot::Mutex<InnerValue>>, F>,
2032    inner_keypath: KeyPath<InnerValue, SubValue, G>,
2033}
2034
2035#[cfg(feature = "parking_lot")]
2036impl<Root, InnerValue, SubValue, F, G> OptionalArcParkingMutexKeyPathChain<Root, InnerValue, SubValue, F, G>
2037where
2038    F: for<'r> Fn(&'r Root) -> Option<&'r Arc<parking_lot::Mutex<InnerValue>>>,
2039    G: for<'r> Fn(&'r InnerValue) -> &'r SubValue,
2040{
2041    /// Apply the composed keypath chain to a container
2042    pub fn get<Callback>(self, container: &Root, callback: Callback) -> Option<()>
2043    where
2044        Callback: FnOnce(&SubValue) -> (),
2045    {
2046        self.outer_keypath.get(container).map(|arc_mutex_ref| {
2047            let guard = arc_mutex_ref.lock();
2048            let value = self.inner_keypath.get(&*guard);
2049            callback(value)
2050        })
2051    }
2052
2053    /// Chain with another readable keypath through another level
2054    pub fn then<NextValue, H>(
2055        self,
2056        next: KeyPath<SubValue, NextValue, H>,
2057    ) -> OptionalArcParkingMutexKeyPathChain<Root, InnerValue, NextValue, F, impl for<'r> Fn(&'r InnerValue) -> &'r NextValue + 'static>
2058    where
2059        H: for<'r> Fn(&'r SubValue) -> &'r NextValue,
2060        G: 'static,
2061        H: 'static,
2062        InnerValue: 'static,
2063        SubValue: 'static,
2064        NextValue: 'static,
2065    {
2066        let first = self.inner_keypath;
2067        let second = next;
2068        
2069        let composed = KeyPath::new(move |inner: &InnerValue| {
2070            let sub = first.get(inner);
2071            second.get(sub)
2072        });
2073        
2074        OptionalArcParkingMutexKeyPathChain {
2075            outer_keypath: self.outer_keypath,
2076            inner_keypath: composed,
2077        }
2078    }
2079
2080    /// Chain with an optional readable keypath through another level
2081    pub fn chain_optional<NextValue, H>(
2082        self,
2083        next: OptionalKeyPath<SubValue, NextValue, H>,
2084    ) -> OptionalArcParkingMutexOptionalKeyPathChain<Root, InnerValue, NextValue, F, impl for<'r> Fn(&'r InnerValue) -> Option<&'r NextValue> + 'static>
2085    where
2086        H: for<'r> Fn(&'r SubValue) -> Option<&'r NextValue>,
2087        G: 'static,
2088        H: 'static,
2089        InnerValue: 'static,
2090        SubValue: 'static,
2091        NextValue: 'static,
2092    {
2093        let first = self.inner_keypath;
2094        let second = next;
2095        
2096        let composed = OptionalKeyPath::new(move |inner: &InnerValue| {
2097            let sub = first.get(inner);
2098            second.get(sub)
2099        });
2100        
2101        OptionalArcParkingMutexOptionalKeyPathChain {
2102            outer_keypath: self.outer_keypath,
2103            inner_keypath: composed,
2104        }
2105    }
2106}
2107
2108/// A composed optional keypath chain from optional keypath through Arc<parking_lot::Mutex<T>>
2109#[cfg(feature = "parking_lot")]
2110pub struct OptionalArcParkingMutexOptionalKeyPathChain<Root, InnerValue, SubValue, F, G>
2111where
2112    F: for<'r> Fn(&'r Root) -> Option<&'r Arc<parking_lot::Mutex<InnerValue>>>,
2113    G: for<'r> Fn(&'r InnerValue) -> Option<&'r SubValue>,
2114{
2115    outer_keypath: OptionalKeyPath<Root, Arc<parking_lot::Mutex<InnerValue>>, F>,
2116    inner_keypath: OptionalKeyPath<InnerValue, SubValue, G>,
2117}
2118
2119#[cfg(feature = "parking_lot")]
2120impl<Root, InnerValue, SubValue, F, G> OptionalArcParkingMutexOptionalKeyPathChain<Root, InnerValue, SubValue, F, G>
2121where
2122    F: for<'r> Fn(&'r Root) -> Option<&'r Arc<parking_lot::Mutex<InnerValue>>>,
2123    G: for<'r> Fn(&'r InnerValue) -> Option<&'r SubValue>,
2124{
2125    /// Apply the composed keypath chain to a container
2126    pub fn get<Callback>(self, container: &Root, callback: Callback) -> Option<()>
2127    where
2128        Callback: FnOnce(&SubValue) -> (),
2129    {
2130        self.outer_keypath.get(container).and_then(|arc_mutex_ref| {
2131            let guard = arc_mutex_ref.lock();
2132            self.inner_keypath.get(&*guard).map(|value| callback(value))
2133        })
2134    }
2135
2136    /// Chain with another readable keypath through another level
2137    pub fn then<NextValue, H>(
2138        self,
2139        next: KeyPath<SubValue, NextValue, H>,
2140    ) -> OptionalArcParkingMutexOptionalKeyPathChain<Root, InnerValue, NextValue, F, impl for<'r> Fn(&'r InnerValue) -> Option<&'r NextValue> + 'static>
2141    where
2142        H: for<'r> Fn(&'r SubValue) -> &'r NextValue,
2143        G: 'static,
2144        H: 'static,
2145        InnerValue: 'static,
2146        SubValue: 'static,
2147        NextValue: 'static,
2148    {
2149        let first = self.inner_keypath;
2150        let second = next;
2151        
2152        let composed = OptionalKeyPath::new(move |inner: &InnerValue| {
2153            first.get(inner).map(|sub| second.get(sub))
2154        });
2155        
2156        OptionalArcParkingMutexOptionalKeyPathChain {
2157            outer_keypath: self.outer_keypath,
2158            inner_keypath: composed,
2159        }
2160    }
2161
2162    /// Chain with an optional readable keypath through another level
2163    pub fn chain_optional<NextValue, H>(
2164        self,
2165        next: OptionalKeyPath<SubValue, NextValue, H>,
2166    ) -> OptionalArcParkingMutexOptionalKeyPathChain<Root, InnerValue, NextValue, F, impl for<'r> Fn(&'r InnerValue) -> Option<&'r NextValue> + 'static>
2167    where
2168        H: for<'r> Fn(&'r SubValue) -> Option<&'r NextValue>,
2169        G: 'static,
2170        H: 'static,
2171        InnerValue: 'static,
2172        SubValue: 'static,
2173        NextValue: 'static,
2174    {
2175        let first = self.inner_keypath;
2176        let second = next;
2177        
2178        let composed = OptionalKeyPath::new(move |inner: &InnerValue| {
2179            first.get(inner).and_then(|sub| second.get(sub))
2180        });
2181        
2182        OptionalArcParkingMutexOptionalKeyPathChain {
2183            outer_keypath: self.outer_keypath,
2184            inner_keypath: composed,
2185        }
2186    }
2187}
2188
2189/// A composed writable keypath chain from optional keypath through Arc<parking_lot::Mutex<T>>
2190#[cfg(feature = "parking_lot")]
2191pub struct OptionalArcParkingMutexWritableKeyPathChain<Root, InnerValue, SubValue, F, G>
2192where
2193    F: for<'r> Fn(&'r Root) -> Option<&'r Arc<parking_lot::Mutex<InnerValue>>>,
2194    G: for<'r> Fn(&'r mut InnerValue) -> &'r mut SubValue,
2195{
2196    outer_keypath: OptionalKeyPath<Root, Arc<parking_lot::Mutex<InnerValue>>, F>,
2197    inner_keypath: WritableKeyPath<InnerValue, SubValue, G>,
2198}
2199
2200#[cfg(feature = "parking_lot")]
2201impl<Root, InnerValue, SubValue, F, G> OptionalArcParkingMutexWritableKeyPathChain<Root, InnerValue, SubValue, F, G>
2202where
2203    F: for<'r> Fn(&'r Root) -> Option<&'r Arc<parking_lot::Mutex<InnerValue>>>,
2204    G: for<'r> Fn(&'r mut InnerValue) -> &'r mut SubValue,
2205{
2206    /// Apply the composed keypath chain to a container with mutable access
2207    pub fn get_mut<Callback, R>(self, container: &Root, callback: Callback) -> Option<R>
2208    where
2209        Callback: FnOnce(&mut SubValue) -> R,
2210    {
2211        self.outer_keypath.get(container).map(|arc_mutex_ref| {
2212            let mut guard = arc_mutex_ref.lock();
2213            let value_ref = self.inner_keypath.get_mut(&mut *guard);
2214            callback(value_ref)
2215        })
2216    }
2217
2218    /// Chain with another writable keypath through another level
2219    pub fn then<NextValue, H>(
2220        self,
2221        next: WritableKeyPath<SubValue, NextValue, H>,
2222    ) -> OptionalArcParkingMutexWritableKeyPathChain<Root, InnerValue, NextValue, F, impl for<'r> Fn(&'r mut InnerValue) -> &'r mut NextValue + 'static>
2223    where
2224        H: for<'r> Fn(&'r mut SubValue) -> &'r mut NextValue,
2225        G: 'static,
2226        H: 'static,
2227        InnerValue: 'static,
2228        SubValue: 'static,
2229        NextValue: 'static,
2230    {
2231        let first = self.inner_keypath;
2232        let second = next;
2233        
2234        let composed = WritableKeyPath::new(move |inner: &mut InnerValue| {
2235            let sub = first.get_mut(inner);
2236            second.get_mut(sub)
2237        });
2238        
2239        OptionalArcParkingMutexWritableKeyPathChain {
2240            outer_keypath: self.outer_keypath,
2241            inner_keypath: composed,
2242        }
2243    }
2244
2245    /// Chain with an optional writable keypath through another level
2246    pub fn chain_optional<NextValue, H>(
2247        self,
2248        next: WritableOptionalKeyPath<SubValue, NextValue, H>,
2249    ) -> OptionalArcParkingMutexWritableOptionalKeyPathChain<Root, InnerValue, NextValue, F, impl for<'r> Fn(&'r mut InnerValue) -> Option<&'r mut NextValue> + 'static>
2250    where
2251        H: for<'r> Fn(&'r mut SubValue) -> Option<&'r mut NextValue>,
2252        G: 'static,
2253        H: 'static,
2254        InnerValue: 'static,
2255        SubValue: 'static,
2256        NextValue: 'static,
2257    {
2258        let first = self.inner_keypath;
2259        let second = next;
2260        
2261        let composed = WritableOptionalKeyPath::new(move |inner: &mut InnerValue| {
2262            let sub = first.get_mut(inner);
2263            second.get_mut(sub)
2264        });
2265        
2266        OptionalArcParkingMutexWritableOptionalKeyPathChain {
2267            outer_keypath: self.outer_keypath,
2268            inner_keypath: composed,
2269        }
2270    }
2271}
2272
2273/// A composed writable optional keypath chain from optional keypath through Arc<parking_lot::Mutex<T>>
2274#[cfg(feature = "parking_lot")]
2275pub struct OptionalArcParkingMutexWritableOptionalKeyPathChain<Root, InnerValue, SubValue, F, G>
2276where
2277    F: for<'r> Fn(&'r Root) -> Option<&'r Arc<parking_lot::Mutex<InnerValue>>>,
2278    G: for<'r> Fn(&'r mut InnerValue) -> Option<&'r mut SubValue>,
2279{
2280    outer_keypath: OptionalKeyPath<Root, Arc<parking_lot::Mutex<InnerValue>>, F>,
2281    inner_keypath: WritableOptionalKeyPath<InnerValue, SubValue, G>,
2282}
2283
2284#[cfg(feature = "parking_lot")]
2285impl<Root, InnerValue, SubValue, F, G> OptionalArcParkingMutexWritableOptionalKeyPathChain<Root, InnerValue, SubValue, F, G>
2286where
2287    F: for<'r> Fn(&'r Root) -> Option<&'r Arc<parking_lot::Mutex<InnerValue>>>,
2288    G: for<'r> Fn(&'r mut InnerValue) -> Option<&'r mut SubValue>,
2289{
2290    /// Apply the composed keypath chain to a container with mutable access (if value exists)
2291    pub fn get_mut<Callback, R>(self, container: &Root, callback: Callback) -> Option<R>
2292    where
2293        Callback: FnOnce(&mut SubValue) -> R,
2294    {
2295        self.outer_keypath.get(container).and_then(|arc_mutex_ref| {
2296            let mut guard = arc_mutex_ref.lock();
2297            self.inner_keypath.get_mut(&mut *guard).map(|value_ref| callback(value_ref))
2298        })
2299    }
2300
2301    /// Chain with another writable keypath through another level
2302    pub fn then<NextValue, H>(
2303        self,
2304        next: WritableKeyPath<SubValue, NextValue, H>,
2305    ) -> OptionalArcParkingMutexWritableOptionalKeyPathChain<Root, InnerValue, NextValue, F, impl for<'r> Fn(&'r mut InnerValue) -> Option<&'r mut NextValue> + 'static>
2306    where
2307        H: for<'r> Fn(&'r mut SubValue) -> &'r mut NextValue,
2308        G: 'static,
2309        H: 'static,
2310        InnerValue: 'static,
2311        SubValue: 'static,
2312        NextValue: 'static,
2313    {
2314        let first = self.inner_keypath;
2315        let second = next;
2316        
2317        let composed = WritableOptionalKeyPath::new(move |inner: &mut InnerValue| {
2318            first.get_mut(inner).map(|sub| second.get_mut(sub))
2319        });
2320        
2321        OptionalArcParkingMutexWritableOptionalKeyPathChain {
2322            outer_keypath: self.outer_keypath,
2323            inner_keypath: composed,
2324        }
2325    }
2326
2327    /// Chain with an optional writable keypath through another level
2328    pub fn chain_optional<NextValue, H>(
2329        self,
2330        next: WritableOptionalKeyPath<SubValue, NextValue, H>,
2331    ) -> OptionalArcParkingMutexWritableOptionalKeyPathChain<Root, InnerValue, NextValue, F, impl for<'r> Fn(&'r mut InnerValue) -> Option<&'r mut NextValue> + 'static>
2332    where
2333        H: for<'r> Fn(&'r mut SubValue) -> Option<&'r mut NextValue>,
2334        G: 'static,
2335        H: 'static,
2336        InnerValue: 'static,
2337        SubValue: 'static,
2338        NextValue: 'static,
2339    {
2340        let first = self.inner_keypath;
2341        let second = next;
2342        
2343        let composed = WritableOptionalKeyPath::new(move |inner: &mut InnerValue| {
2344            first.get_mut(inner).and_then(|sub| second.get_mut(sub))
2345        });
2346        
2347        OptionalArcParkingMutexWritableOptionalKeyPathChain {
2348            outer_keypath: self.outer_keypath,
2349            inner_keypath: composed,
2350        }
2351    }
2352}
2353
2354// ========== OPTIONAL PARKING_LOT RWLOCK KEYPATH CHAINS (from OptionalKeyPath) ==========
2355
2356/// A composed keypath chain from optional keypath through Arc<parking_lot::RwLock<T>> - functional style
2357#[cfg(feature = "parking_lot")]
2358pub struct OptionalArcParkingRwLockKeyPathChain<Root, InnerValue, SubValue, F, G>
2359where
2360    F: for<'r> Fn(&'r Root) -> Option<&'r Arc<parking_lot::RwLock<InnerValue>>>,
2361    G: for<'r> Fn(&'r InnerValue) -> &'r SubValue,
2362{
2363    outer_keypath: OptionalKeyPath<Root, Arc<parking_lot::RwLock<InnerValue>>, F>,
2364    inner_keypath: KeyPath<InnerValue, SubValue, G>,
2365}
2366
2367#[cfg(feature = "parking_lot")]
2368impl<Root, InnerValue, SubValue, F, G> OptionalArcParkingRwLockKeyPathChain<Root, InnerValue, SubValue, F, G>
2369where
2370    F: for<'r> Fn(&'r Root) -> Option<&'r Arc<parking_lot::RwLock<InnerValue>>>,
2371    G: for<'r> Fn(&'r InnerValue) -> &'r SubValue,
2372{
2373    /// Apply the composed keypath chain to a container (read lock)
2374    pub fn get<Callback>(self, container: &Root, callback: Callback) -> Option<()>
2375    where
2376        Callback: FnOnce(&SubValue) -> (),
2377    {
2378        self.outer_keypath.get(container).map(|arc_rwlock_ref| {
2379            let guard = arc_rwlock_ref.read();
2380            let value = self.inner_keypath.get(&*guard);
2381            callback(value)
2382        })
2383    }
2384
2385    /// Chain with another readable keypath through another level
2386    pub fn then<NextValue, H>(
2387        self,
2388        next: KeyPath<SubValue, NextValue, H>,
2389    ) -> OptionalArcParkingRwLockKeyPathChain<Root, InnerValue, NextValue, F, impl for<'r> Fn(&'r InnerValue) -> &'r NextValue + 'static>
2390    where
2391        H: for<'r> Fn(&'r SubValue) -> &'r NextValue,
2392        G: 'static,
2393        H: 'static,
2394        InnerValue: 'static,
2395        SubValue: 'static,
2396        NextValue: 'static,
2397    {
2398        let first = self.inner_keypath;
2399        let second = next;
2400        
2401        let composed = KeyPath::new(move |inner: &InnerValue| {
2402            let sub = first.get(inner);
2403            second.get(sub)
2404        });
2405        
2406        OptionalArcParkingRwLockKeyPathChain {
2407            outer_keypath: self.outer_keypath,
2408            inner_keypath: composed,
2409        }
2410    }
2411
2412    /// Chain with an optional readable keypath through another level
2413    pub fn chain_optional<NextValue, H>(
2414        self,
2415        next: OptionalKeyPath<SubValue, NextValue, H>,
2416    ) -> OptionalArcParkingRwLockOptionalKeyPathChain<Root, InnerValue, NextValue, F, impl for<'r> Fn(&'r InnerValue) -> Option<&'r NextValue> + 'static>
2417    where
2418        H: for<'r> Fn(&'r SubValue) -> Option<&'r NextValue>,
2419        G: 'static,
2420        H: 'static,
2421        InnerValue: 'static,
2422        SubValue: 'static,
2423        NextValue: 'static,
2424    {
2425        let first = self.inner_keypath;
2426        let second = next;
2427        
2428        let composed = OptionalKeyPath::new(move |inner: &InnerValue| {
2429            let sub = first.get(inner);
2430            second.get(sub)
2431        });
2432        
2433        OptionalArcParkingRwLockOptionalKeyPathChain {
2434            outer_keypath: self.outer_keypath,
2435            inner_keypath: composed,
2436        }
2437    }
2438}
2439
2440/// A composed optional keypath chain from optional keypath through Arc<parking_lot::RwLock<T>>
2441#[cfg(feature = "parking_lot")]
2442pub struct OptionalArcParkingRwLockOptionalKeyPathChain<Root, InnerValue, SubValue, F, G>
2443where
2444    F: for<'r> Fn(&'r Root) -> Option<&'r Arc<parking_lot::RwLock<InnerValue>>>,
2445    G: for<'r> Fn(&'r InnerValue) -> Option<&'r SubValue>,
2446{
2447    outer_keypath: OptionalKeyPath<Root, Arc<parking_lot::RwLock<InnerValue>>, F>,
2448    inner_keypath: OptionalKeyPath<InnerValue, SubValue, G>,
2449}
2450
2451#[cfg(feature = "parking_lot")]
2452impl<Root, InnerValue, SubValue, F, G> OptionalArcParkingRwLockOptionalKeyPathChain<Root, InnerValue, SubValue, F, G>
2453where
2454    F: for<'r> Fn(&'r Root) -> Option<&'r Arc<parking_lot::RwLock<InnerValue>>>,
2455    G: for<'r> Fn(&'r InnerValue) -> Option<&'r SubValue>,
2456{
2457    /// Apply the composed keypath chain to a container (read lock)
2458    pub fn get<Callback>(self, container: &Root, callback: Callback) -> Option<()>
2459    where
2460        Callback: FnOnce(&SubValue) -> (),
2461    {
2462        self.outer_keypath.get(container).and_then(|arc_rwlock_ref| {
2463            let guard = arc_rwlock_ref.read();
2464            self.inner_keypath.get(&*guard).map(|value| callback(value))
2465        })
2466    }
2467
2468    /// Chain with another readable keypath through another level
2469    pub fn then<NextValue, H>(
2470        self,
2471        next: KeyPath<SubValue, NextValue, H>,
2472    ) -> OptionalArcParkingRwLockOptionalKeyPathChain<Root, InnerValue, NextValue, F, impl for<'r> Fn(&'r InnerValue) -> Option<&'r NextValue> + 'static>
2473    where
2474        H: for<'r> Fn(&'r SubValue) -> &'r NextValue,
2475        G: 'static,
2476        H: 'static,
2477        InnerValue: 'static,
2478        SubValue: 'static,
2479        NextValue: 'static,
2480    {
2481        let first = self.inner_keypath;
2482        let second = next;
2483        
2484        let composed = OptionalKeyPath::new(move |inner: &InnerValue| {
2485            first.get(inner).map(|sub| second.get(sub))
2486        });
2487        
2488        OptionalArcParkingRwLockOptionalKeyPathChain {
2489            outer_keypath: self.outer_keypath,
2490            inner_keypath: composed,
2491        }
2492    }
2493
2494    /// Chain with an optional readable keypath through another level
2495    pub fn chain_optional<NextValue, H>(
2496        self,
2497        next: OptionalKeyPath<SubValue, NextValue, H>,
2498    ) -> OptionalArcParkingRwLockOptionalKeyPathChain<Root, InnerValue, NextValue, F, impl for<'r> Fn(&'r InnerValue) -> Option<&'r NextValue> + 'static>
2499    where
2500        H: for<'r> Fn(&'r SubValue) -> Option<&'r NextValue>,
2501        G: 'static,
2502        H: 'static,
2503        InnerValue: 'static,
2504        SubValue: 'static,
2505        NextValue: 'static,
2506    {
2507        let first = self.inner_keypath;
2508        let second = next;
2509        
2510        let composed = OptionalKeyPath::new(move |inner: &InnerValue| {
2511            first.get(inner).and_then(|sub| second.get(sub))
2512        });
2513        
2514        OptionalArcParkingRwLockOptionalKeyPathChain {
2515            outer_keypath: self.outer_keypath,
2516            inner_keypath: composed,
2517        }
2518    }
2519}
2520
2521/// A composed writable keypath chain from optional keypath through Arc<parking_lot::RwLock<T>>
2522#[cfg(feature = "parking_lot")]
2523pub struct OptionalArcParkingRwLockWritableKeyPathChain<Root, InnerValue, SubValue, F, G>
2524where
2525    F: for<'r> Fn(&'r Root) -> Option<&'r Arc<parking_lot::RwLock<InnerValue>>>,
2526    G: for<'r> Fn(&'r mut InnerValue) -> &'r mut SubValue,
2527{
2528    outer_keypath: OptionalKeyPath<Root, Arc<parking_lot::RwLock<InnerValue>>, F>,
2529    inner_keypath: WritableKeyPath<InnerValue, SubValue, G>,
2530}
2531
2532#[cfg(feature = "parking_lot")]
2533impl<Root, InnerValue, SubValue, F, G> OptionalArcParkingRwLockWritableKeyPathChain<Root, InnerValue, SubValue, F, G>
2534where
2535    F: for<'r> Fn(&'r Root) -> Option<&'r Arc<parking_lot::RwLock<InnerValue>>>,
2536    G: for<'r> Fn(&'r mut InnerValue) -> &'r mut SubValue,
2537{
2538    /// Apply the composed keypath chain to a container with mutable access (write lock)
2539    pub fn get_mut<Callback, R>(self, container: &Root, callback: Callback) -> Option<R>
2540    where
2541        Callback: FnOnce(&mut SubValue) -> R,
2542    {
2543        self.outer_keypath.get(container).map(|arc_rwlock_ref| {
2544            let mut guard = arc_rwlock_ref.write();
2545            let value_ref = self.inner_keypath.get_mut(&mut *guard);
2546            callback(value_ref)
2547        })
2548    }
2549
2550    /// Chain with another writable keypath through another level
2551    pub fn then<NextValue, H>(
2552        self,
2553        next: WritableKeyPath<SubValue, NextValue, H>,
2554    ) -> OptionalArcParkingRwLockWritableKeyPathChain<Root, InnerValue, NextValue, F, impl for<'r> Fn(&'r mut InnerValue) -> &'r mut NextValue + 'static>
2555    where
2556        H: for<'r> Fn(&'r mut SubValue) -> &'r mut NextValue,
2557        G: 'static,
2558        H: 'static,
2559        InnerValue: 'static,
2560        SubValue: 'static,
2561        NextValue: 'static,
2562    {
2563        let first = self.inner_keypath;
2564        let second = next;
2565        
2566        let composed = WritableKeyPath::new(move |inner: &mut InnerValue| {
2567            let sub = first.get_mut(inner);
2568            second.get_mut(sub)
2569        });
2570        
2571        OptionalArcParkingRwLockWritableKeyPathChain {
2572            outer_keypath: self.outer_keypath,
2573            inner_keypath: composed,
2574        }
2575    }
2576
2577    /// Chain with an optional writable keypath through another level
2578    pub fn chain_optional<NextValue, H>(
2579        self,
2580        next: WritableOptionalKeyPath<SubValue, NextValue, H>,
2581    ) -> OptionalArcParkingRwLockWritableOptionalKeyPathChain<Root, InnerValue, NextValue, F, impl for<'r> Fn(&'r mut InnerValue) -> Option<&'r mut NextValue> + 'static>
2582    where
2583        H: for<'r> Fn(&'r mut SubValue) -> Option<&'r mut NextValue>,
2584        G: 'static,
2585        H: 'static,
2586        InnerValue: 'static,
2587        SubValue: 'static,
2588        NextValue: 'static,
2589    {
2590        let first = self.inner_keypath;
2591        let second = next;
2592        
2593        let composed = WritableOptionalKeyPath::new(move |inner: &mut InnerValue| {
2594            let sub = first.get_mut(inner);
2595            second.get_mut(sub)
2596        });
2597        
2598        OptionalArcParkingRwLockWritableOptionalKeyPathChain {
2599            outer_keypath: self.outer_keypath,
2600            inner_keypath: composed,
2601        }
2602    }
2603}
2604
2605/// A composed writable optional keypath chain from optional keypath through Arc<parking_lot::RwLock<T>>
2606#[cfg(feature = "parking_lot")]
2607pub struct OptionalArcParkingRwLockWritableOptionalKeyPathChain<Root, InnerValue, SubValue, F, G>
2608where
2609    F: for<'r> Fn(&'r Root) -> Option<&'r Arc<parking_lot::RwLock<InnerValue>>>,
2610    G: for<'r> Fn(&'r mut InnerValue) -> Option<&'r mut SubValue>,
2611{
2612    outer_keypath: OptionalKeyPath<Root, Arc<parking_lot::RwLock<InnerValue>>, F>,
2613    inner_keypath: WritableOptionalKeyPath<InnerValue, SubValue, G>,
2614}
2615
2616#[cfg(feature = "parking_lot")]
2617impl<Root, InnerValue, SubValue, F, G> OptionalArcParkingRwLockWritableOptionalKeyPathChain<Root, InnerValue, SubValue, F, G>
2618where
2619    F: for<'r> Fn(&'r Root) -> Option<&'r Arc<parking_lot::RwLock<InnerValue>>>,
2620    G: for<'r> Fn(&'r mut InnerValue) -> Option<&'r mut SubValue>,
2621{
2622    /// Apply the composed keypath chain to a container with mutable access (write lock, if value exists)
2623    pub fn get_mut<Callback, R>(self, container: &Root, callback: Callback) -> Option<R>
2624    where
2625        Callback: FnOnce(&mut SubValue) -> R,
2626    {
2627        self.outer_keypath.get(container).and_then(|arc_rwlock_ref| {
2628            let mut guard = arc_rwlock_ref.write();
2629            self.inner_keypath.get_mut(&mut *guard).map(|value_ref| callback(value_ref))
2630        })
2631    }
2632
2633    /// Chain with another writable keypath through another level
2634    pub fn then<NextValue, H>(
2635        self,
2636        next: WritableKeyPath<SubValue, NextValue, H>,
2637    ) -> OptionalArcParkingRwLockWritableOptionalKeyPathChain<Root, InnerValue, NextValue, F, impl for<'r> Fn(&'r mut InnerValue) -> Option<&'r mut NextValue> + 'static>
2638    where
2639        H: for<'r> Fn(&'r mut SubValue) -> &'r mut NextValue,
2640        G: 'static,
2641        H: 'static,
2642        InnerValue: 'static,
2643        SubValue: 'static,
2644        NextValue: 'static,
2645    {
2646        let first = self.inner_keypath;
2647        let second = next;
2648        
2649        let composed = WritableOptionalKeyPath::new(move |inner: &mut InnerValue| {
2650            first.get_mut(inner).map(|sub| second.get_mut(sub))
2651        });
2652        
2653        OptionalArcParkingRwLockWritableOptionalKeyPathChain {
2654            outer_keypath: self.outer_keypath,
2655            inner_keypath: composed,
2656        }
2657    }
2658
2659    /// Chain with an optional writable keypath through another level
2660    pub fn chain_optional<NextValue, H>(
2661        self,
2662        next: WritableOptionalKeyPath<SubValue, NextValue, H>,
2663    ) -> OptionalArcParkingRwLockWritableOptionalKeyPathChain<Root, InnerValue, NextValue, F, impl for<'r> Fn(&'r mut InnerValue) -> Option<&'r mut NextValue> + 'static>
2664    where
2665        H: for<'r> Fn(&'r mut SubValue) -> Option<&'r mut NextValue>,
2666        G: 'static,
2667        H: 'static,
2668        InnerValue: 'static,
2669        SubValue: 'static,
2670        NextValue: 'static,
2671    {
2672        let first = self.inner_keypath;
2673        let second = next;
2674        
2675        let composed = WritableOptionalKeyPath::new(move |inner: &mut InnerValue| {
2676            first.get_mut(inner).and_then(|sub| second.get_mut(sub))
2677        });
2678        
2679        OptionalArcParkingRwLockWritableOptionalKeyPathChain {
2680            outer_keypath: self.outer_keypath,
2681            inner_keypath: composed,
2682        }
2683    }
2684}
2685
2686// ========== TOKIO MUTEX/RWLOCK CHAIN TYPES ==========
2687
2688#[cfg(feature = "tokio")]
2689use tokio::sync::{Mutex as TokioMutex, RwLock as TokioRwLock};
2690
2691/// A composed async keypath chain through Arc<tokio::sync::Mutex<T>> - functional style
2692#[cfg(feature = "tokio")]
2693pub struct ArcTokioMutexKeyPathChain<Root, MutexValue, InnerValue, SubValue, F, G>
2694where
2695    F: for<'r> Fn(&'r Root) -> &'r MutexValue,
2696    G: for<'r> Fn(&'r InnerValue) -> &'r SubValue,
2697{
2698    outer_keypath: KeyPath<Root, MutexValue, F>,
2699    inner_keypath: KeyPath<InnerValue, SubValue, G>,
2700}
2701
2702#[cfg(feature = "tokio")]
2703impl<Root, MutexValue, InnerValue, SubValue, F, G> ArcTokioMutexKeyPathChain<Root, MutexValue, InnerValue, SubValue, F, G>
2704where
2705    MutexValue: std::borrow::Borrow<Arc<TokioMutex<InnerValue>>>,
2706    F: for<'r> Fn(&'r Root) -> &'r MutexValue,
2707    G: for<'r> Fn(&'r InnerValue) -> &'r SubValue,
2708{
2709    /// Apply the composed keypath chain to a container (read, async)
2710    pub async fn get<Callback>(self, container: &Root, callback: Callback)
2711    where
2712        Callback: FnOnce(&SubValue) -> (),
2713    {
2714        let arc_mutex_ref = self.outer_keypath.get(container).borrow();
2715        let guard = arc_mutex_ref.lock().await;
2716        let value = self.inner_keypath.get(&*guard);
2717        callback(value);
2718    }
2719
2720    /// Chain with another readable keypath through another level
2721    pub fn then<NextValue, H>(
2722        self,
2723        next: KeyPath<SubValue, NextValue, H>,
2724    ) -> ArcTokioMutexKeyPathChain<Root, MutexValue, InnerValue, NextValue, F, impl for<'r> Fn(&'r InnerValue) -> &'r NextValue + 'static>
2725    where
2726        H: for<'r> Fn(&'r SubValue) -> &'r NextValue,
2727        G: 'static,
2728        H: 'static,
2729        InnerValue: 'static,
2730        SubValue: 'static,
2731        NextValue: 'static,
2732    {
2733        let first = self.inner_keypath;
2734        let second = next;
2735        
2736        let composed = KeyPath::new(move |inner: &InnerValue| {
2737            let sub = first.get(inner);
2738            second.get(sub)
2739        });
2740        
2741        ArcTokioMutexKeyPathChain {
2742            outer_keypath: self.outer_keypath,
2743            inner_keypath: composed,
2744        }
2745    }
2746
2747    /// Chain with an optional readable keypath through another level
2748    pub fn chain_optional<NextValue, H>(
2749        self,
2750        next: OptionalKeyPath<SubValue, NextValue, H>,
2751    ) -> ArcTokioMutexOptionalKeyPathChain<Root, MutexValue, InnerValue, NextValue, F, impl for<'r> Fn(&'r InnerValue) -> Option<&'r NextValue> + 'static>
2752    where
2753        H: for<'r> Fn(&'r SubValue) -> Option<&'r NextValue>,
2754        G: 'static,
2755        H: 'static,
2756        InnerValue: 'static,
2757        SubValue: 'static,
2758        NextValue: 'static,
2759    {
2760        let first = self.inner_keypath;
2761        let second = next;
2762        
2763        let composed = OptionalKeyPath::new(move |inner: &InnerValue| {
2764            let sub = first.get(inner);
2765            second.get(sub)
2766        });
2767        
2768        ArcTokioMutexOptionalKeyPathChain {
2769            outer_keypath: self.outer_keypath,
2770            inner_keypath: composed,
2771        }
2772    }
2773}
2774
2775/// A composed optional async keypath chain through Arc<tokio::sync::Mutex<T>> - functional style
2776#[cfg(feature = "tokio")]
2777pub struct ArcTokioMutexOptionalKeyPathChain<Root, MutexValue, InnerValue, SubValue, F, G>
2778where
2779    F: for<'r> Fn(&'r Root) -> &'r MutexValue,
2780    G: for<'r> Fn(&'r InnerValue) -> Option<&'r SubValue>,
2781{
2782    outer_keypath: KeyPath<Root, MutexValue, F>,
2783    inner_keypath: OptionalKeyPath<InnerValue, SubValue, G>,
2784}
2785
2786#[cfg(feature = "tokio")]
2787impl<Root, MutexValue, InnerValue, SubValue, F, G> ArcTokioMutexOptionalKeyPathChain<Root, MutexValue, InnerValue, SubValue, F, G>
2788where
2789    MutexValue: std::borrow::Borrow<Arc<TokioMutex<InnerValue>>>,
2790    F: for<'r> Fn(&'r Root) -> &'r MutexValue,
2791    G: for<'r> Fn(&'r InnerValue) -> Option<&'r SubValue>,
2792{
2793    /// Apply the composed keypath chain to a container (read, if value exists, async)
2794    pub async fn get<Callback>(self, container: &Root, callback: Callback) -> Option<()>
2795    where
2796        Callback: FnOnce(&SubValue) -> (),
2797    {
2798        let arc_mutex_ref = self.outer_keypath.get(container).borrow();
2799        let guard = arc_mutex_ref.lock().await;
2800        self.inner_keypath.get(&*guard).map(|value| callback(value))
2801    }
2802
2803    /// Chain with another readable keypath through another level
2804    pub fn then<NextValue, H>(
2805        self,
2806        next: KeyPath<SubValue, NextValue, H>,
2807    ) -> ArcTokioMutexOptionalKeyPathChain<Root, MutexValue, InnerValue, NextValue, F, impl for<'r> Fn(&'r InnerValue) -> Option<&'r NextValue> + 'static>
2808    where
2809        H: for<'r> Fn(&'r SubValue) -> &'r NextValue,
2810        G: 'static,
2811        H: 'static,
2812        InnerValue: 'static,
2813        SubValue: 'static,
2814        NextValue: 'static,
2815    {
2816        let first = self.inner_keypath;
2817        let second = next;
2818        
2819        let composed = OptionalKeyPath::new(move |inner: &InnerValue| {
2820            first.get(inner).map(|sub| second.get(sub))
2821        });
2822        
2823        ArcTokioMutexOptionalKeyPathChain {
2824            outer_keypath: self.outer_keypath,
2825            inner_keypath: composed,
2826        }
2827    }
2828
2829    /// Chain with an optional readable keypath through another level
2830    pub fn chain_optional<NextValue, H>(
2831        self,
2832        next: OptionalKeyPath<SubValue, NextValue, H>,
2833    ) -> ArcTokioMutexOptionalKeyPathChain<Root, MutexValue, InnerValue, NextValue, F, impl for<'r> Fn(&'r InnerValue) -> Option<&'r NextValue> + 'static>
2834    where
2835        H: for<'r> Fn(&'r SubValue) -> Option<&'r NextValue>,
2836        G: 'static,
2837        H: 'static,
2838        InnerValue: 'static,
2839        SubValue: 'static,
2840        NextValue: 'static,
2841    {
2842        let first = self.inner_keypath;
2843        let second = next;
2844        
2845        let composed = OptionalKeyPath::new(move |inner: &InnerValue| {
2846            first.get(inner).and_then(|sub| second.get(sub))
2847        });
2848        
2849        ArcTokioMutexOptionalKeyPathChain {
2850            outer_keypath: self.outer_keypath,
2851            inner_keypath: composed,
2852        }
2853    }
2854}
2855
2856/// A composed writable async keypath chain through Arc<tokio::sync::Mutex<T>> - functional style
2857#[cfg(feature = "tokio")]
2858pub struct ArcTokioMutexWritableKeyPathChain<Root, MutexValue, InnerValue, SubValue, F, G>
2859where
2860    F: for<'r> Fn(&'r Root) -> &'r MutexValue,
2861    G: for<'r> Fn(&'r mut InnerValue) -> &'r mut SubValue,
2862{
2863    outer_keypath: KeyPath<Root, MutexValue, F>,
2864    inner_keypath: WritableKeyPath<InnerValue, SubValue, G>,
2865}
2866
2867#[cfg(feature = "tokio")]
2868impl<Root, MutexValue, InnerValue, SubValue, F, G> ArcTokioMutexWritableKeyPathChain<Root, MutexValue, InnerValue, SubValue, F, G>
2869where
2870    MutexValue: std::borrow::Borrow<Arc<TokioMutex<InnerValue>>>,
2871    F: for<'r> Fn(&'r Root) -> &'r MutexValue,
2872    G: for<'r> Fn(&'r mut InnerValue) -> &'r mut SubValue,
2873{
2874    /// Apply the composed keypath chain to a container with mutable access (async)
2875    pub async fn get_mut<Callback, R>(self, container: &Root, callback: Callback) -> R
2876    where
2877        Callback: FnOnce(&mut SubValue) -> R,
2878    {
2879        let arc_mutex_ref = self.outer_keypath.get(container).borrow();
2880        let mut guard = arc_mutex_ref.lock().await;
2881        let value_ref = self.inner_keypath.get_mut(&mut *guard);
2882        callback(value_ref)
2883    }
2884
2885    /// Chain with another writable keypath through another level
2886    pub fn then<NextValue, H>(
2887        self,
2888        next: WritableKeyPath<SubValue, NextValue, H>,
2889    ) -> ArcTokioMutexWritableKeyPathChain<Root, MutexValue, InnerValue, NextValue, F, impl for<'r> Fn(&'r mut InnerValue) -> &'r mut NextValue + 'static>
2890    where
2891        H: for<'r> Fn(&'r mut SubValue) -> &'r mut NextValue,
2892        G: 'static,
2893        H: 'static,
2894        InnerValue: 'static,
2895        SubValue: 'static,
2896        NextValue: 'static,
2897    {
2898        let first = self.inner_keypath;
2899        let second = next;
2900        
2901        let composed = WritableKeyPath::new(move |inner: &mut InnerValue| {
2902            let sub = first.get_mut(inner);
2903            second.get_mut(sub)
2904        });
2905        
2906        ArcTokioMutexWritableKeyPathChain {
2907            outer_keypath: self.outer_keypath,
2908            inner_keypath: composed,
2909        }
2910    }
2911
2912    /// Chain with an optional writable keypath through another level
2913    pub fn chain_optional<NextValue, H>(
2914        self,
2915        next: WritableOptionalKeyPath<SubValue, NextValue, H>,
2916    ) -> ArcTokioMutexWritableOptionalKeyPathChain<Root, MutexValue, InnerValue, NextValue, F, impl for<'r> Fn(&'r mut InnerValue) -> Option<&'r mut NextValue> + 'static>
2917    where
2918        H: for<'r> Fn(&'r mut SubValue) -> Option<&'r mut NextValue>,
2919        G: 'static,
2920        H: 'static,
2921        InnerValue: 'static,
2922        SubValue: 'static,
2923        NextValue: 'static,
2924    {
2925        let first = self.inner_keypath;
2926        let second = next;
2927        
2928        let composed = WritableOptionalKeyPath::new(move |inner: &mut InnerValue| {
2929            let sub = first.get_mut(inner);
2930            second.get_mut(sub)
2931        });
2932        
2933        ArcTokioMutexWritableOptionalKeyPathChain {
2934            outer_keypath: self.outer_keypath,
2935            inner_keypath: composed,
2936        }
2937    }
2938}
2939
2940/// A composed writable optional async keypath chain through Arc<tokio::sync::Mutex<T>> - functional style
2941#[cfg(feature = "tokio")]
2942pub struct ArcTokioMutexWritableOptionalKeyPathChain<Root, MutexValue, InnerValue, SubValue, F, G>
2943where
2944    F: for<'r> Fn(&'r Root) -> &'r MutexValue,
2945    G: for<'r> Fn(&'r mut InnerValue) -> Option<&'r mut SubValue>,
2946{
2947    outer_keypath: KeyPath<Root, MutexValue, F>,
2948    inner_keypath: WritableOptionalKeyPath<InnerValue, SubValue, G>,
2949}
2950
2951#[cfg(feature = "tokio")]
2952impl<Root, MutexValue, InnerValue, SubValue, F, G> ArcTokioMutexWritableOptionalKeyPathChain<Root, MutexValue, InnerValue, SubValue, F, G>
2953where
2954    MutexValue: std::borrow::Borrow<Arc<TokioMutex<InnerValue>>>,
2955    F: for<'r> Fn(&'r Root) -> &'r MutexValue,
2956    G: for<'r> Fn(&'r mut InnerValue) -> Option<&'r mut SubValue>,
2957{
2958    /// Apply the composed keypath chain to a container with mutable access (if value exists, async)
2959    pub async fn get_mut<Callback, R>(self, container: &Root, callback: Callback) -> Option<R>
2960    where
2961        Callback: FnOnce(&mut SubValue) -> R,
2962    {
2963        let arc_mutex_ref = self.outer_keypath.get(container).borrow();
2964        let mut guard = arc_mutex_ref.lock().await;
2965        self.inner_keypath.get_mut(&mut *guard).map(|value_ref| callback(value_ref))
2966    }
2967
2968    /// Chain with another writable keypath through another level
2969    pub fn then<NextValue, H>(
2970        self,
2971        next: WritableKeyPath<SubValue, NextValue, H>,
2972    ) -> ArcTokioMutexWritableOptionalKeyPathChain<Root, MutexValue, InnerValue, NextValue, F, impl for<'r> Fn(&'r mut InnerValue) -> Option<&'r mut NextValue> + 'static>
2973    where
2974        H: for<'r> Fn(&'r mut SubValue) -> &'r mut NextValue,
2975        G: 'static,
2976        H: 'static,
2977        InnerValue: 'static,
2978        SubValue: 'static,
2979        NextValue: 'static,
2980    {
2981        let first = self.inner_keypath;
2982        let second = next;
2983        
2984        let composed = WritableOptionalKeyPath::new(move |inner: &mut InnerValue| {
2985            first.get_mut(inner).map(|sub| second.get_mut(sub))
2986        });
2987        
2988        ArcTokioMutexWritableOptionalKeyPathChain {
2989            outer_keypath: self.outer_keypath,
2990            inner_keypath: composed,
2991        }
2992    }
2993
2994    /// Chain with an optional writable keypath through another level
2995    pub fn chain_optional<NextValue, H>(
2996        self,
2997        next: WritableOptionalKeyPath<SubValue, NextValue, H>,
2998    ) -> ArcTokioMutexWritableOptionalKeyPathChain<Root, MutexValue, InnerValue, NextValue, F, impl for<'r> Fn(&'r mut InnerValue) -> Option<&'r mut NextValue> + 'static>
2999    where
3000        H: for<'r> Fn(&'r mut SubValue) -> Option<&'r mut NextValue>,
3001        G: 'static,
3002        H: 'static,
3003        InnerValue: 'static,
3004        SubValue: 'static,
3005        NextValue: 'static,
3006    {
3007        let first = self.inner_keypath;
3008        let second = next;
3009        
3010        let composed = WritableOptionalKeyPath::new(move |inner: &mut InnerValue| {
3011            first.get_mut(inner).and_then(|sub| second.get_mut(sub))
3012        });
3013        
3014        ArcTokioMutexWritableOptionalKeyPathChain {
3015            outer_keypath: self.outer_keypath,
3016            inner_keypath: composed,
3017        }
3018    }
3019}
3020
3021/// A composed async keypath chain through Arc<tokio::sync::RwLock<T>> - functional style
3022#[cfg(feature = "tokio")]
3023pub struct ArcTokioRwLockKeyPathChain<Root, RwLockValue, InnerValue, SubValue, F, G>
3024where
3025    RwLockValue: std::borrow::Borrow<Arc<TokioRwLock<InnerValue>>>,
3026    F: for<'r> Fn(&'r Root) -> &'r RwLockValue,
3027    G: for<'r> Fn(&'r InnerValue) -> &'r SubValue,
3028{
3029    outer_keypath: KeyPath<Root, RwLockValue, F>,
3030    inner_keypath: KeyPath<InnerValue, SubValue, G>,
3031}
3032
3033#[cfg(feature = "tokio")]
3034impl<Root, RwLockValue, InnerValue, SubValue, F, G> ArcTokioRwLockKeyPathChain<Root, RwLockValue, InnerValue, SubValue, F, G>
3035where
3036    RwLockValue: std::borrow::Borrow<Arc<TokioRwLock<InnerValue>>>,
3037    F: for<'r> Fn(&'r Root) -> &'r RwLockValue,
3038    G: for<'r> Fn(&'r InnerValue) -> &'r SubValue,
3039{
3040    /// Apply the composed keypath chain to a container (read lock, async)
3041    pub async fn get<Callback>(self, container: &Root, callback: Callback)
3042    where
3043        Callback: FnOnce(&SubValue) -> (),
3044    {
3045        let arc_rwlock_ref = self.outer_keypath.get(container).borrow();
3046        let guard = arc_rwlock_ref.read().await;
3047        let value = self.inner_keypath.get(&*guard);
3048        callback(value);
3049    }
3050
3051    /// Chain with another readable keypath through another level
3052    pub fn then<NextValue, H>(
3053        self,
3054        next: KeyPath<SubValue, NextValue, H>,
3055    ) -> ArcTokioRwLockKeyPathChain<Root, RwLockValue, InnerValue, NextValue, F, impl for<'r> Fn(&'r InnerValue) -> &'r NextValue + 'static>
3056    where
3057        H: for<'r> Fn(&'r SubValue) -> &'r NextValue,
3058        G: 'static,
3059        H: 'static,
3060        InnerValue: 'static,
3061        SubValue: 'static,
3062        NextValue: 'static,
3063    {
3064        let first = self.inner_keypath;
3065        let second = next;
3066        
3067        let composed = KeyPath::new(move |inner: &InnerValue| {
3068            let sub = first.get(inner);
3069            second.get(sub)
3070        });
3071        
3072        ArcTokioRwLockKeyPathChain {
3073            outer_keypath: self.outer_keypath,
3074            inner_keypath: composed,
3075        }
3076    }
3077
3078    /// Chain with an optional readable keypath through another level
3079    pub fn chain_optional<NextValue, H>(
3080        self,
3081        next: OptionalKeyPath<SubValue, NextValue, H>,
3082    ) -> ArcTokioRwLockOptionalKeyPathChain<Root, RwLockValue, InnerValue, NextValue, F, impl for<'r> Fn(&'r InnerValue) -> Option<&'r NextValue> + 'static>
3083    where
3084        H: for<'r> Fn(&'r SubValue) -> Option<&'r NextValue>,
3085        G: 'static,
3086        H: 'static,
3087        InnerValue: 'static,
3088        SubValue: 'static,
3089        NextValue: 'static,
3090    {
3091        let first = self.inner_keypath;
3092        let second = next;
3093        
3094        let composed = OptionalKeyPath::new(move |inner: &InnerValue| {
3095            let sub = first.get(inner);
3096            second.get(sub)
3097        });
3098        
3099        ArcTokioRwLockOptionalKeyPathChain {
3100            outer_keypath: self.outer_keypath,
3101            inner_keypath: composed,
3102        }
3103    }
3104}
3105
3106/// A composed optional async keypath chain through Arc<tokio::sync::RwLock<T>> - functional style
3107#[cfg(feature = "tokio")]
3108pub struct ArcTokioRwLockOptionalKeyPathChain<Root, RwLockValue, InnerValue, SubValue, F, G>
3109where
3110    RwLockValue: std::borrow::Borrow<Arc<TokioRwLock<InnerValue>>>,
3111    F: for<'r> Fn(&'r Root) -> &'r RwLockValue,
3112    G: for<'r> Fn(&'r InnerValue) -> Option<&'r SubValue>,
3113{
3114    outer_keypath: KeyPath<Root, RwLockValue, F>,
3115    inner_keypath: OptionalKeyPath<InnerValue, SubValue, G>,
3116}
3117
3118#[cfg(feature = "tokio")]
3119impl<Root, RwLockValue, InnerValue, SubValue, F, G> ArcTokioRwLockOptionalKeyPathChain<Root, RwLockValue, InnerValue, SubValue, F, G>
3120where
3121    RwLockValue: std::borrow::Borrow<Arc<TokioRwLock<InnerValue>>>,
3122    F: for<'r> Fn(&'r Root) -> &'r RwLockValue,
3123    G: for<'r> Fn(&'r InnerValue) -> Option<&'r SubValue>,
3124{
3125    /// Apply the composed keypath chain to a container (read lock, if value exists, async)
3126    pub async fn get<Callback>(self, container: &Root, callback: Callback) -> Option<()>
3127    where
3128        Callback: FnOnce(&SubValue) -> (),
3129    {
3130        let arc_rwlock_ref = self.outer_keypath.get(container).borrow();
3131        let guard = arc_rwlock_ref.read().await;
3132        self.inner_keypath.get(&*guard).map(|value| callback(value))
3133    }
3134
3135    /// Chain with another readable keypath through another level
3136    pub fn then<NextValue, H>(
3137        self,
3138        next: KeyPath<SubValue, NextValue, H>,
3139    ) -> ArcTokioRwLockOptionalKeyPathChain<Root, RwLockValue, InnerValue, NextValue, F, impl for<'r> Fn(&'r InnerValue) -> Option<&'r NextValue> + 'static>
3140    where
3141        H: for<'r> Fn(&'r SubValue) -> &'r NextValue,
3142        G: 'static,
3143        H: 'static,
3144        InnerValue: 'static,
3145        SubValue: 'static,
3146        NextValue: 'static,
3147    {
3148        let first = self.inner_keypath;
3149        let second = next;
3150        
3151        let composed = OptionalKeyPath::new(move |inner: &InnerValue| {
3152            first.get(inner).map(|sub| second.get(sub))
3153        });
3154        
3155        ArcTokioRwLockOptionalKeyPathChain {
3156            outer_keypath: self.outer_keypath,
3157            inner_keypath: composed,
3158        }
3159    }
3160
3161    /// Chain with an optional readable keypath through another level
3162    pub fn chain_optional<NextValue, H>(
3163        self,
3164        next: OptionalKeyPath<SubValue, NextValue, H>,
3165    ) -> ArcTokioRwLockOptionalKeyPathChain<Root, RwLockValue, InnerValue, NextValue, F, impl for<'r> Fn(&'r InnerValue) -> Option<&'r NextValue> + 'static>
3166    where
3167        H: for<'r> Fn(&'r SubValue) -> Option<&'r NextValue>,
3168        G: 'static,
3169        H: 'static,
3170        InnerValue: 'static,
3171        SubValue: 'static,
3172        NextValue: 'static,
3173    {
3174        let first = self.inner_keypath;
3175        let second = next;
3176        
3177        let composed = OptionalKeyPath::new(move |inner: &InnerValue| {
3178            first.get(inner).and_then(|sub| second.get(sub))
3179        });
3180        
3181        ArcTokioRwLockOptionalKeyPathChain {
3182            outer_keypath: self.outer_keypath,
3183            inner_keypath: composed,
3184        }
3185    }
3186}
3187
3188/// A composed writable async keypath chain through Arc<tokio::sync::RwLock<T>> - functional style
3189#[cfg(feature = "tokio")]
3190pub struct ArcTokioRwLockWritableKeyPathChain<Root, RwLockValue, InnerValue, SubValue, F, G>
3191where
3192    RwLockValue: std::borrow::Borrow<Arc<TokioRwLock<InnerValue>>>,
3193    F: for<'r> Fn(&'r Root) -> &'r RwLockValue,
3194    G: for<'r> Fn(&'r mut InnerValue) -> &'r mut SubValue,
3195{
3196    outer_keypath: KeyPath<Root, RwLockValue, F>,
3197    inner_keypath: WritableKeyPath<InnerValue, SubValue, G>,
3198}
3199
3200#[cfg(feature = "tokio")]
3201impl<Root, RwLockValue, InnerValue, SubValue, F, G> ArcTokioRwLockWritableKeyPathChain<Root, RwLockValue, InnerValue, SubValue, F, G>
3202where
3203    RwLockValue: std::borrow::Borrow<Arc<TokioRwLock<InnerValue>>>,
3204    F: for<'r> Fn(&'r Root) -> &'r RwLockValue,
3205    G: for<'r> Fn(&'r mut InnerValue) -> &'r mut SubValue,
3206{
3207    /// Apply the composed keypath chain to a container with mutable access (write lock, async)
3208    pub async fn get_mut<Callback, R>(self, container: &Root, callback: Callback) -> R
3209    where
3210        Callback: FnOnce(&mut SubValue) -> R,
3211    {
3212        let arc_rwlock_ref = self.outer_keypath.get(container).borrow();
3213        let mut guard = arc_rwlock_ref.write().await;
3214        let value_ref = self.inner_keypath.get_mut(&mut *guard);
3215        callback(value_ref)
3216    }
3217
3218    /// Chain with another writable keypath through another level
3219    pub fn then<NextValue, H>(
3220        self,
3221        next: WritableKeyPath<SubValue, NextValue, H>,
3222    ) -> ArcTokioRwLockWritableKeyPathChain<Root, RwLockValue, InnerValue, NextValue, F, impl for<'r> Fn(&'r mut InnerValue) -> &'r mut NextValue + 'static>
3223    where
3224        H: for<'r> Fn(&'r mut SubValue) -> &'r mut NextValue,
3225        G: 'static,
3226        H: 'static,
3227        InnerValue: 'static,
3228        SubValue: 'static,
3229        NextValue: 'static,
3230    {
3231        let first = self.inner_keypath;
3232        let second = next;
3233        
3234        let composed = WritableKeyPath::new(move |inner: &mut InnerValue| {
3235            let sub = first.get_mut(inner);
3236            second.get_mut(sub)
3237        });
3238        
3239        ArcTokioRwLockWritableKeyPathChain {
3240            outer_keypath: self.outer_keypath,
3241            inner_keypath: composed,
3242        }
3243    }
3244
3245    /// Chain with an optional writable keypath through another level
3246    pub fn chain_optional<NextValue, H>(
3247        self,
3248        next: WritableOptionalKeyPath<SubValue, NextValue, H>,
3249    ) -> ArcTokioRwLockWritableOptionalKeyPathChain<Root, RwLockValue, InnerValue, NextValue, F, impl for<'r> Fn(&'r mut InnerValue) -> Option<&'r mut NextValue> + 'static>
3250    where
3251        H: for<'r> Fn(&'r mut SubValue) -> Option<&'r mut NextValue>,
3252        G: 'static,
3253        H: 'static,
3254        InnerValue: 'static,
3255        SubValue: 'static,
3256        NextValue: 'static,
3257    {
3258        let first = self.inner_keypath;
3259        let second = next;
3260        
3261        let composed = WritableOptionalKeyPath::new(move |inner: &mut InnerValue| {
3262            let sub = first.get_mut(inner);
3263            second.get_mut(sub)
3264        });
3265        
3266        ArcTokioRwLockWritableOptionalKeyPathChain {
3267            outer_keypath: self.outer_keypath,
3268            inner_keypath: composed,
3269        }
3270    }
3271}
3272
3273/// A composed writable optional async keypath chain through Arc<tokio::sync::RwLock<T>> - functional style
3274#[cfg(feature = "tokio")]
3275pub struct ArcTokioRwLockWritableOptionalKeyPathChain<Root, RwLockValue, InnerValue, SubValue, F, G>
3276where
3277    RwLockValue: std::borrow::Borrow<Arc<TokioRwLock<InnerValue>>>,
3278    F: for<'r> Fn(&'r Root) -> &'r RwLockValue,
3279    G: for<'r> Fn(&'r mut InnerValue) -> Option<&'r mut SubValue>,
3280{
3281    outer_keypath: KeyPath<Root, RwLockValue, F>,
3282    inner_keypath: WritableOptionalKeyPath<InnerValue, SubValue, G>,
3283}
3284
3285#[cfg(feature = "tokio")]
3286impl<Root, RwLockValue, InnerValue, SubValue, F, G> ArcTokioRwLockWritableOptionalKeyPathChain<Root, RwLockValue, InnerValue, SubValue, F, G>
3287where
3288    RwLockValue: std::borrow::Borrow<Arc<TokioRwLock<InnerValue>>>,
3289    F: for<'r> Fn(&'r Root) -> &'r RwLockValue,
3290    G: for<'r> Fn(&'r mut InnerValue) -> Option<&'r mut SubValue>,
3291{
3292    /// Apply the composed keypath chain to a container with mutable access (write lock, if value exists, async)
3293    pub async fn get_mut<Callback, R>(self, container: &Root, callback: Callback) -> Option<R>
3294    where
3295        Callback: FnOnce(&mut SubValue) -> R,
3296    {
3297        let arc_rwlock_ref = self.outer_keypath.get(container).borrow();
3298        let mut guard = arc_rwlock_ref.write().await;
3299        self.inner_keypath.get_mut(&mut *guard).map(|value_ref| callback(value_ref))
3300    }
3301
3302    /// Chain with another writable keypath through another level
3303    pub fn then<NextValue, H>(
3304        self,
3305        next: WritableKeyPath<SubValue, NextValue, H>,
3306    ) -> ArcTokioRwLockWritableOptionalKeyPathChain<Root, RwLockValue, InnerValue, NextValue, F, impl for<'r> Fn(&'r mut InnerValue) -> Option<&'r mut NextValue> + 'static>
3307    where
3308        H: for<'r> Fn(&'r mut SubValue) -> &'r mut NextValue,
3309        G: 'static,
3310        H: 'static,
3311        InnerValue: 'static,
3312        SubValue: 'static,
3313        NextValue: 'static,
3314    {
3315        let first = self.inner_keypath;
3316        let second = next;
3317        
3318        let composed = WritableOptionalKeyPath::new(move |inner: &mut InnerValue| {
3319            first.get_mut(inner).map(|sub| second.get_mut(sub))
3320        });
3321        
3322        ArcTokioRwLockWritableOptionalKeyPathChain {
3323            outer_keypath: self.outer_keypath,
3324            inner_keypath: composed,
3325        }
3326    }
3327
3328    /// Chain with an optional writable keypath through another level
3329    pub fn chain_optional<NextValue, H>(
3330        self,
3331        next: WritableOptionalKeyPath<SubValue, NextValue, H>,
3332    ) -> ArcTokioRwLockWritableOptionalKeyPathChain<Root, RwLockValue, InnerValue, NextValue, F, impl for<'r> Fn(&'r mut InnerValue) -> Option<&'r mut NextValue> + 'static>
3333    where
3334        H: for<'r> Fn(&'r mut SubValue) -> Option<&'r mut NextValue>,
3335        G: 'static,
3336        H: 'static,
3337        InnerValue: 'static,
3338        SubValue: 'static,
3339        NextValue: 'static,
3340    {
3341        let first = self.inner_keypath;
3342        let second = next;
3343        
3344        let composed = WritableOptionalKeyPath::new(move |inner: &mut InnerValue| {
3345            first.get_mut(inner).and_then(|sub| second.get_mut(sub))
3346        });
3347        
3348        ArcTokioRwLockWritableOptionalKeyPathChain {
3349            outer_keypath: self.outer_keypath,
3350            inner_keypath: composed,
3351        }
3352    }
3353}
3354
3355// ========== OPTIONAL TOKIO MUTEX KEYPATH CHAINS (from OptionalKeyPath) ==========
3356
3357/// A composed async keypath chain from optional keypath through Arc<tokio::sync::Mutex<T>> - functional style
3358#[cfg(feature = "tokio")]
3359pub struct OptionalArcTokioMutexKeyPathChain<Root, MutexValue, InnerValue, SubValue, F, G>
3360where
3361    MutexValue: std::borrow::Borrow<Arc<TokioMutex<InnerValue>>>,
3362    F: for<'r> Fn(&'r Root) -> Option<&'r MutexValue>,
3363    G: for<'r> Fn(&'r InnerValue) -> &'r SubValue,
3364{
3365    outer_keypath: OptionalKeyPath<Root, MutexValue, F>,
3366    inner_keypath: KeyPath<InnerValue, SubValue, G>,
3367}
3368
3369#[cfg(feature = "tokio")]
3370impl<Root, MutexValue, InnerValue, SubValue, F, G> OptionalArcTokioMutexKeyPathChain<Root, MutexValue, InnerValue, SubValue, F, G>
3371where
3372    MutexValue: std::borrow::Borrow<Arc<TokioMutex<InnerValue>>>,
3373    F: for<'r> Fn(&'r Root) -> Option<&'r MutexValue>,
3374    G: for<'r> Fn(&'r InnerValue) -> &'r SubValue,
3375{
3376    /// Apply the composed keypath chain to a container (async)
3377    pub async fn get<Callback>(self, container: &Root, callback: Callback) -> Option<()>
3378    where
3379        Callback: FnOnce(&SubValue) -> (),
3380    {
3381        if let Some(arc_mutex_ref) = self.outer_keypath.get(container) { let arc_mutex_ref = arc_mutex_ref.borrow();
3382            let guard = arc_mutex_ref.lock().await;
3383            let value = self.inner_keypath.get(&*guard);
3384            callback(value);
3385            Some(())
3386        } else {
3387            None
3388        }
3389    }
3390
3391    /// Chain with another readable keypath through another level
3392    pub fn then<NextValue, H>(
3393        self,
3394        next: KeyPath<SubValue, NextValue, H>,
3395    ) -> OptionalArcTokioMutexKeyPathChain<Root, MutexValue, InnerValue, NextValue, F, impl for<'r> Fn(&'r InnerValue) -> &'r NextValue + 'static>
3396    where
3397        H: for<'r> Fn(&'r SubValue) -> &'r NextValue,
3398        G: 'static,
3399        H: 'static,
3400        InnerValue: 'static,
3401        SubValue: 'static,
3402        NextValue: 'static,
3403    {
3404        let first = self.inner_keypath;
3405        let second = next;
3406        
3407        let composed = KeyPath::new(move |inner: &InnerValue| {
3408            let sub = first.get(inner);
3409            second.get(sub)
3410        });
3411        
3412        OptionalArcTokioMutexKeyPathChain {
3413            outer_keypath: self.outer_keypath,
3414            inner_keypath: composed,
3415        }
3416    }
3417
3418    /// Chain with an optional readable keypath through another level
3419    pub fn chain_optional<NextValue, H>(
3420        self,
3421        next: OptionalKeyPath<SubValue, NextValue, H>,
3422    ) -> OptionalArcTokioMutexOptionalKeyPathChain<Root, MutexValue, InnerValue, NextValue, F, impl for<'r> Fn(&'r InnerValue) -> Option<&'r NextValue> + 'static>
3423    where
3424        H: for<'r> Fn(&'r SubValue) -> Option<&'r NextValue>,
3425        G: 'static,
3426        H: 'static,
3427        InnerValue: 'static,
3428        SubValue: 'static,
3429        NextValue: 'static,
3430    {
3431        let first = self.inner_keypath;
3432        let second = next;
3433        
3434        let composed = OptionalKeyPath::new(move |inner: &InnerValue| {
3435            let sub = first.get(inner);
3436            second.get(sub)
3437        });
3438        
3439        OptionalArcTokioMutexOptionalKeyPathChain {
3440            outer_keypath: self.outer_keypath,
3441            inner_keypath: composed,
3442        }
3443    }
3444}
3445
3446/// A composed optional async keypath chain from optional keypath through Arc<tokio::sync::Mutex<T>>
3447#[cfg(feature = "tokio")]
3448pub struct OptionalArcTokioMutexOptionalKeyPathChain<Root, MutexValue, InnerValue, SubValue, F, G>
3449where
3450    MutexValue: std::borrow::Borrow<Arc<TokioMutex<InnerValue>>>,
3451    F: for<'r> Fn(&'r Root) -> Option<&'r MutexValue>,
3452    G: for<'r> Fn(&'r InnerValue) -> Option<&'r SubValue>,
3453{
3454    outer_keypath: OptionalKeyPath<Root, MutexValue, F>,
3455    inner_keypath: OptionalKeyPath<InnerValue, SubValue, G>,
3456}
3457
3458#[cfg(feature = "tokio")]
3459impl<Root, MutexValue, InnerValue, SubValue, F, G> OptionalArcTokioMutexOptionalKeyPathChain<Root, MutexValue, InnerValue, SubValue, F, G>
3460where
3461    MutexValue: std::borrow::Borrow<Arc<TokioMutex<InnerValue>>>,
3462    F: for<'r> Fn(&'r Root) -> Option<&'r MutexValue>,
3463    G: for<'r> Fn(&'r InnerValue) -> Option<&'r SubValue>,
3464{
3465    /// Apply the composed keypath chain to a container (async)
3466    pub async fn get<Callback>(self, container: &Root, callback: Callback) -> Option<()>
3467    where
3468        Callback: FnOnce(&SubValue) -> (),
3469    {
3470        if let Some(arc_mutex_ref) = self.outer_keypath.get(container) { let arc_mutex_ref = arc_mutex_ref.borrow();
3471            let guard = arc_mutex_ref.lock().await;
3472            self.inner_keypath.get(&*guard).map(|value| callback(value))
3473        } else {
3474            None
3475        }
3476    }
3477
3478    /// Chain with another readable keypath through another level
3479    pub fn then<NextValue, H>(
3480        self,
3481        next: KeyPath<SubValue, NextValue, H>,
3482    ) -> OptionalArcTokioMutexOptionalKeyPathChain<Root, MutexValue, InnerValue, NextValue, F, impl for<'r> Fn(&'r InnerValue) -> Option<&'r NextValue> + 'static>
3483    where
3484        H: for<'r> Fn(&'r SubValue) -> &'r NextValue,
3485        G: 'static,
3486        H: 'static,
3487        InnerValue: 'static,
3488        SubValue: 'static,
3489        NextValue: 'static,
3490    {
3491        let first = self.inner_keypath;
3492        let second = next;
3493        
3494        let composed = OptionalKeyPath::new(move |inner: &InnerValue| {
3495            first.get(inner).map(|sub| second.get(sub))
3496        });
3497        
3498        OptionalArcTokioMutexOptionalKeyPathChain {
3499            outer_keypath: self.outer_keypath,
3500            inner_keypath: composed,
3501        }
3502    }
3503
3504    /// Chain with an optional readable keypath through another level
3505    pub fn chain_optional<NextValue, H>(
3506        self,
3507        next: OptionalKeyPath<SubValue, NextValue, H>,
3508    ) -> OptionalArcTokioMutexOptionalKeyPathChain<Root, MutexValue, InnerValue, NextValue, F, impl for<'r> Fn(&'r InnerValue) -> Option<&'r NextValue> + 'static>
3509    where
3510        H: for<'r> Fn(&'r SubValue) -> Option<&'r NextValue>,
3511        G: 'static,
3512        H: 'static,
3513        InnerValue: 'static,
3514        SubValue: 'static,
3515        NextValue: 'static,
3516    {
3517        let first = self.inner_keypath;
3518        let second = next;
3519        
3520        let composed = OptionalKeyPath::new(move |inner: &InnerValue| {
3521            first.get(inner).and_then(|sub| second.get(sub))
3522        });
3523        
3524        OptionalArcTokioMutexOptionalKeyPathChain {
3525            outer_keypath: self.outer_keypath,
3526            inner_keypath: composed,
3527        }
3528    }
3529}
3530
3531/// A composed writable async keypath chain from optional keypath through Arc<tokio::sync::Mutex<T>>
3532#[cfg(feature = "tokio")]
3533pub struct OptionalArcTokioMutexWritableKeyPathChain<Root, MutexValue, InnerValue, SubValue, F, G>
3534where
3535    MutexValue: std::borrow::Borrow<Arc<TokioMutex<InnerValue>>>,
3536    F: for<'r> Fn(&'r Root) -> Option<&'r MutexValue>,
3537    G: for<'r> Fn(&'r mut InnerValue) -> &'r mut SubValue,
3538{
3539    outer_keypath: OptionalKeyPath<Root, MutexValue, F>,
3540    inner_keypath: WritableKeyPath<InnerValue, SubValue, G>,
3541}
3542
3543#[cfg(feature = "tokio")]
3544impl<Root, MutexValue, InnerValue, SubValue, F, G> OptionalArcTokioMutexWritableKeyPathChain<Root, MutexValue, InnerValue, SubValue, F, G>
3545where
3546    MutexValue: std::borrow::Borrow<Arc<TokioMutex<InnerValue>>>,
3547    F: for<'r> Fn(&'r Root) -> Option<&'r MutexValue>,
3548    G: for<'r> Fn(&'r mut InnerValue) -> &'r mut SubValue,
3549{
3550    /// Apply the composed keypath chain to a container with mutable access (async)
3551    pub async fn get_mut<Callback, R>(self, container: &Root, callback: Callback) -> Option<R>
3552    where
3553        Callback: FnOnce(&mut SubValue) -> R,
3554    {
3555        if let Some(arc_mutex_ref) = self.outer_keypath.get(container) { let arc_mutex_ref = arc_mutex_ref.borrow();
3556            let mut guard = arc_mutex_ref.lock().await;
3557            let value_ref = self.inner_keypath.get_mut(&mut *guard);
3558            Some(callback(value_ref))
3559        } else {
3560            None
3561        }
3562    }
3563
3564    /// Chain with another writable keypath through another level
3565    pub fn then<NextValue, H>(
3566        self,
3567        next: WritableKeyPath<SubValue, NextValue, H>,
3568    ) -> OptionalArcTokioMutexWritableKeyPathChain<Root, MutexValue, InnerValue, NextValue, F, impl for<'r> Fn(&'r mut InnerValue) -> &'r mut NextValue + 'static>
3569    where
3570        H: for<'r> Fn(&'r mut SubValue) -> &'r mut NextValue,
3571        G: 'static,
3572        H: 'static,
3573        InnerValue: 'static,
3574        SubValue: 'static,
3575        NextValue: 'static,
3576    {
3577        let first = self.inner_keypath;
3578        let second = next;
3579        
3580        let composed = WritableKeyPath::new(move |inner: &mut InnerValue| {
3581            let sub = first.get_mut(inner);
3582            second.get_mut(sub)
3583        });
3584        
3585        OptionalArcTokioMutexWritableKeyPathChain {
3586            outer_keypath: self.outer_keypath,
3587            inner_keypath: composed,
3588        }
3589    }
3590
3591    /// Chain with an optional writable keypath through another level
3592    pub fn chain_optional<NextValue, H>(
3593        self,
3594        next: WritableOptionalKeyPath<SubValue, NextValue, H>,
3595    ) -> OptionalArcTokioMutexWritableOptionalKeyPathChain<Root, MutexValue, InnerValue, NextValue, F, impl for<'r> Fn(&'r mut InnerValue) -> Option<&'r mut NextValue> + 'static>
3596    where
3597        H: for<'r> Fn(&'r mut SubValue) -> Option<&'r mut NextValue>,
3598        G: 'static,
3599        H: 'static,
3600        InnerValue: 'static,
3601        SubValue: 'static,
3602        NextValue: 'static,
3603    {
3604        let first = self.inner_keypath;
3605        let second = next;
3606        
3607        let composed = WritableOptionalKeyPath::new(move |inner: &mut InnerValue| {
3608            let sub = first.get_mut(inner);
3609            second.get_mut(sub)
3610        });
3611        
3612        OptionalArcTokioMutexWritableOptionalKeyPathChain {
3613            outer_keypath: self.outer_keypath,
3614            inner_keypath: composed,
3615        }
3616    }
3617}
3618
3619/// A composed writable optional async keypath chain from optional keypath through Arc<tokio::sync::Mutex<T>>
3620#[cfg(feature = "tokio")]
3621pub struct OptionalArcTokioMutexWritableOptionalKeyPathChain<Root, MutexValue, InnerValue, SubValue, F, G>
3622where
3623    MutexValue: std::borrow::Borrow<Arc<TokioMutex<InnerValue>>>,
3624    F: for<'r> Fn(&'r Root) -> Option<&'r MutexValue>,
3625    G: for<'r> Fn(&'r mut InnerValue) -> Option<&'r mut SubValue>,
3626{
3627    outer_keypath: OptionalKeyPath<Root, MutexValue, F>,
3628    inner_keypath: WritableOptionalKeyPath<InnerValue, SubValue, G>,
3629}
3630
3631#[cfg(feature = "tokio")]
3632impl<Root, MutexValue, InnerValue, SubValue, F, G> OptionalArcTokioMutexWritableOptionalKeyPathChain<Root, MutexValue, InnerValue, SubValue, F, G>
3633where
3634    MutexValue: std::borrow::Borrow<Arc<TokioMutex<InnerValue>>>,
3635    F: for<'r> Fn(&'r Root) -> Option<&'r MutexValue>,
3636    G: for<'r> Fn(&'r mut InnerValue) -> Option<&'r mut SubValue>,
3637{
3638    /// Apply the composed keypath chain to a container with mutable access (if value exists, async)
3639    pub async fn get_mut<Callback, R>(self, container: &Root, callback: Callback) -> Option<R>
3640    where
3641        Callback: FnOnce(&mut SubValue) -> R,
3642    {
3643        if let Some(arc_mutex_ref) = self.outer_keypath.get(container) { let arc_mutex_ref = arc_mutex_ref.borrow();
3644            let mut guard = arc_mutex_ref.lock().await;
3645            self.inner_keypath.get_mut(&mut *guard).map(|value_ref| callback(value_ref))
3646        } else {
3647            None
3648        }
3649    }
3650
3651    /// Chain with another writable keypath through another level
3652    pub fn then<NextValue, H>(
3653        self,
3654        next: WritableKeyPath<SubValue, NextValue, H>,
3655    ) -> OptionalArcTokioMutexWritableOptionalKeyPathChain<Root, MutexValue, InnerValue, NextValue, F, impl for<'r> Fn(&'r mut InnerValue) -> Option<&'r mut NextValue> + 'static>
3656    where
3657        H: for<'r> Fn(&'r mut SubValue) -> &'r mut NextValue,
3658        G: 'static,
3659        H: 'static,
3660        InnerValue: 'static,
3661        SubValue: 'static,
3662        NextValue: 'static,
3663    {
3664        let first = self.inner_keypath;
3665        let second = next;
3666        
3667        let composed = WritableOptionalKeyPath::new(move |inner: &mut InnerValue| {
3668            first.get_mut(inner).map(|sub| second.get_mut(sub))
3669        });
3670        
3671        OptionalArcTokioMutexWritableOptionalKeyPathChain {
3672            outer_keypath: self.outer_keypath,
3673            inner_keypath: composed,
3674        }
3675    }
3676
3677    /// Chain with an optional writable keypath through another level
3678    pub fn chain_optional<NextValue, H>(
3679        self,
3680        next: WritableOptionalKeyPath<SubValue, NextValue, H>,
3681    ) -> OptionalArcTokioMutexWritableOptionalKeyPathChain<Root, MutexValue, InnerValue, NextValue, F, impl for<'r> Fn(&'r mut InnerValue) -> Option<&'r mut NextValue> + 'static>
3682    where
3683        H: for<'r> Fn(&'r mut SubValue) -> Option<&'r mut NextValue>,
3684        G: 'static,
3685        H: 'static,
3686        InnerValue: 'static,
3687        SubValue: 'static,
3688        NextValue: 'static,
3689    {
3690        let first = self.inner_keypath;
3691        let second = next;
3692        
3693        let composed = WritableOptionalKeyPath::new(move |inner: &mut InnerValue| {
3694            first.get_mut(inner).and_then(|sub| second.get_mut(sub))
3695        });
3696        
3697        OptionalArcTokioMutexWritableOptionalKeyPathChain {
3698            outer_keypath: self.outer_keypath,
3699            inner_keypath: composed,
3700        }
3701    }
3702}
3703
3704// ========== OPTIONAL TOKIO RWLOCK KEYPATH CHAINS (from OptionalKeyPath) ==========
3705
3706/// A composed async keypath chain from optional keypath through Arc<tokio::sync::RwLock<T>> - functional style
3707#[cfg(feature = "tokio")]
3708pub struct OptionalArcTokioRwLockKeyPathChain<Root, RwLockValue, InnerValue, SubValue, F, G>
3709where
3710    RwLockValue: std::borrow::Borrow<Arc<TokioRwLock<InnerValue>>>,
3711    F: for<'r> Fn(&'r Root) -> Option<&'r RwLockValue>,
3712    G: for<'r> Fn(&'r InnerValue) -> &'r SubValue,
3713{
3714    outer_keypath: OptionalKeyPath<Root, RwLockValue, F>,
3715    inner_keypath: KeyPath<InnerValue, SubValue, G>,
3716}
3717
3718#[cfg(feature = "tokio")]
3719impl<Root, RwLockValue, InnerValue, SubValue, F, G> OptionalArcTokioRwLockKeyPathChain<Root, RwLockValue, InnerValue, SubValue, F, G>
3720where
3721    RwLockValue: std::borrow::Borrow<Arc<TokioRwLock<InnerValue>>>,
3722    F: for<'r> Fn(&'r Root) -> Option<&'r RwLockValue>,
3723    G: for<'r> Fn(&'r InnerValue) -> &'r SubValue,
3724{
3725    /// Apply the composed keypath chain to a container (read lock, async)
3726    pub async fn get<Callback>(self, container: &Root, callback: Callback) -> Option<()>
3727    where
3728        Callback: FnOnce(&SubValue) -> (),
3729    {
3730        if let Some(arc_rwlock_ref) = self.outer_keypath.get(container) { let arc_rwlock_ref = arc_rwlock_ref.borrow();
3731            let guard = arc_rwlock_ref.read().await;
3732            let value = self.inner_keypath.get(&*guard);
3733            callback(value);
3734            Some(())
3735        } else {
3736            None
3737        }
3738    }
3739
3740    /// Chain with another readable keypath through another level
3741    pub fn then<NextValue, H>(
3742        self,
3743        next: KeyPath<SubValue, NextValue, H>,
3744    ) -> OptionalArcTokioRwLockKeyPathChain<Root, RwLockValue, InnerValue, NextValue, F, impl for<'r> Fn(&'r InnerValue) -> &'r NextValue + 'static>
3745    where
3746        H: for<'r> Fn(&'r SubValue) -> &'r NextValue,
3747        G: 'static,
3748        H: 'static,
3749        InnerValue: 'static,
3750        SubValue: 'static,
3751        NextValue: 'static,
3752    {
3753        let first = self.inner_keypath;
3754        let second = next;
3755        
3756        let composed = KeyPath::new(move |inner: &InnerValue| {
3757            let sub = first.get(inner);
3758            second.get(sub)
3759        });
3760        
3761        OptionalArcTokioRwLockKeyPathChain {
3762            outer_keypath: self.outer_keypath,
3763            inner_keypath: composed,
3764        }
3765    }
3766
3767    /// Chain with an optional readable keypath through another level
3768    pub fn chain_optional<NextValue, H>(
3769        self,
3770        next: OptionalKeyPath<SubValue, NextValue, H>,
3771    ) -> OptionalArcTokioRwLockOptionalKeyPathChain<Root, RwLockValue, InnerValue, NextValue, F, impl for<'r> Fn(&'r InnerValue) -> Option<&'r NextValue> + 'static>
3772    where
3773        H: for<'r> Fn(&'r SubValue) -> Option<&'r NextValue>,
3774        G: 'static,
3775        H: 'static,
3776        InnerValue: 'static,
3777        SubValue: 'static,
3778        NextValue: 'static,
3779    {
3780        let first = self.inner_keypath;
3781        let second = next;
3782        
3783        let composed = OptionalKeyPath::new(move |inner: &InnerValue| {
3784            let sub = first.get(inner);
3785            second.get(sub)
3786        });
3787        
3788        OptionalArcTokioRwLockOptionalKeyPathChain {
3789            outer_keypath: self.outer_keypath,
3790            inner_keypath: composed,
3791        }
3792    }
3793}
3794
3795/// A composed optional async keypath chain from optional keypath through Arc<tokio::sync::RwLock<T>>
3796#[cfg(feature = "tokio")]
3797pub struct OptionalArcTokioRwLockOptionalKeyPathChain<Root, RwLockValue, InnerValue, SubValue, F, G>
3798where
3799    RwLockValue: std::borrow::Borrow<Arc<TokioRwLock<InnerValue>>>,
3800    F: for<'r> Fn(&'r Root) -> Option<&'r RwLockValue>,
3801    G: for<'r> Fn(&'r InnerValue) -> Option<&'r SubValue>,
3802{
3803    outer_keypath: OptionalKeyPath<Root, RwLockValue, F>,
3804    inner_keypath: OptionalKeyPath<InnerValue, SubValue, G>,
3805}
3806
3807#[cfg(feature = "tokio")]
3808impl<Root, RwLockValue, InnerValue, SubValue, F, G> OptionalArcTokioRwLockOptionalKeyPathChain<Root, RwLockValue, InnerValue, SubValue, F, G>
3809where
3810    RwLockValue: std::borrow::Borrow<Arc<TokioRwLock<InnerValue>>>,
3811    F: for<'r> Fn(&'r Root) -> Option<&'r RwLockValue>,
3812    G: for<'r> Fn(&'r InnerValue) -> Option<&'r SubValue>,
3813{
3814    /// Apply the composed keypath chain to a container (read lock, async)
3815    pub async fn get<Callback>(self, container: &Root, callback: Callback) -> Option<()>
3816    where
3817        Callback: FnOnce(&SubValue) -> (),
3818    {
3819        if let Some(arc_rwlock_ref) = self.outer_keypath.get(container) { let arc_rwlock_ref = arc_rwlock_ref.borrow();
3820            let guard = arc_rwlock_ref.read().await;
3821            self.inner_keypath.get(&*guard).map(|value| callback(value))
3822        } else {
3823            None
3824        }
3825    }
3826
3827    /// Chain with another readable keypath through another level
3828    pub fn then<NextValue, H>(
3829        self,
3830        next: KeyPath<SubValue, NextValue, H>,
3831    ) -> OptionalArcTokioRwLockOptionalKeyPathChain<Root, RwLockValue, InnerValue, NextValue, F, impl for<'r> Fn(&'r InnerValue) -> Option<&'r NextValue> + 'static>
3832    where
3833        H: for<'r> Fn(&'r SubValue) -> &'r NextValue,
3834        G: 'static,
3835        H: 'static,
3836        InnerValue: 'static,
3837        SubValue: 'static,
3838        NextValue: 'static,
3839    {
3840        let first = self.inner_keypath;
3841        let second = next;
3842        
3843        let composed = OptionalKeyPath::new(move |inner: &InnerValue| {
3844            first.get(inner).map(|sub| second.get(sub))
3845        });
3846        
3847        OptionalArcTokioRwLockOptionalKeyPathChain {
3848            outer_keypath: self.outer_keypath,
3849            inner_keypath: composed,
3850        }
3851    }
3852
3853    /// Chain with an optional readable keypath through another level
3854    pub fn chain_optional<NextValue, H>(
3855        self,
3856        next: OptionalKeyPath<SubValue, NextValue, H>,
3857    ) -> OptionalArcTokioRwLockOptionalKeyPathChain<Root, RwLockValue, InnerValue, NextValue, F, impl for<'r> Fn(&'r InnerValue) -> Option<&'r NextValue> + 'static>
3858    where
3859        H: for<'r> Fn(&'r SubValue) -> Option<&'r NextValue>,
3860        G: 'static,
3861        H: 'static,
3862        InnerValue: 'static,
3863        SubValue: 'static,
3864        NextValue: 'static,
3865    {
3866        let first = self.inner_keypath;
3867        let second = next;
3868        
3869        let composed = OptionalKeyPath::new(move |inner: &InnerValue| {
3870            first.get(inner).and_then(|sub| second.get(sub))
3871        });
3872        
3873        OptionalArcTokioRwLockOptionalKeyPathChain {
3874            outer_keypath: self.outer_keypath,
3875            inner_keypath: composed,
3876        }
3877    }
3878}
3879
3880/// A composed writable async keypath chain from optional keypath through Arc<tokio::sync::RwLock<T>>
3881#[cfg(feature = "tokio")]
3882pub struct OptionalArcTokioRwLockWritableKeyPathChain<Root, RwLockValue, InnerValue, SubValue, F, G>
3883where
3884    RwLockValue: std::borrow::Borrow<Arc<TokioRwLock<InnerValue>>>,
3885    F: for<'r> Fn(&'r Root) -> Option<&'r RwLockValue>,
3886    G: for<'r> Fn(&'r mut InnerValue) -> &'r mut SubValue,
3887{
3888    outer_keypath: OptionalKeyPath<Root, RwLockValue, F>,
3889    inner_keypath: WritableKeyPath<InnerValue, SubValue, G>,
3890}
3891
3892#[cfg(feature = "tokio")]
3893impl<Root, RwLockValue, InnerValue, SubValue, F, G> OptionalArcTokioRwLockWritableKeyPathChain<Root, RwLockValue, InnerValue, SubValue, F, G>
3894where
3895    RwLockValue: std::borrow::Borrow<Arc<TokioRwLock<InnerValue>>>,
3896    F: for<'r> Fn(&'r Root) -> Option<&'r RwLockValue>,
3897    G: for<'r> Fn(&'r mut InnerValue) -> &'r mut SubValue,
3898{
3899    /// Apply the composed keypath chain to a container with mutable access (write lock, async)
3900    pub async fn get_mut<Callback, R>(self, container: &Root, callback: Callback) -> Option<R>
3901    where
3902        Callback: FnOnce(&mut SubValue) -> R,
3903    {
3904        if let Some(arc_rwlock_ref) = self.outer_keypath.get(container) { let arc_rwlock_ref = arc_rwlock_ref.borrow();
3905            let mut guard = arc_rwlock_ref.write().await;
3906            let value_ref = self.inner_keypath.get_mut(&mut *guard);
3907            Some(callback(value_ref))
3908        } else {
3909            None
3910        }
3911    }
3912
3913    /// Chain with another writable keypath through another level
3914    pub fn then<NextValue, H>(
3915        self,
3916        next: WritableKeyPath<SubValue, NextValue, H>,
3917    ) -> OptionalArcTokioRwLockWritableKeyPathChain<Root, RwLockValue, InnerValue, NextValue, F, impl for<'r> Fn(&'r mut InnerValue) -> &'r mut NextValue + 'static>
3918    where
3919        H: for<'r> Fn(&'r mut SubValue) -> &'r mut NextValue,
3920        G: 'static,
3921        H: 'static,
3922        InnerValue: 'static,
3923        SubValue: 'static,
3924        NextValue: 'static,
3925    {
3926        let first = self.inner_keypath;
3927        let second = next;
3928        
3929        let composed = WritableKeyPath::new(move |inner: &mut InnerValue| {
3930            let sub = first.get_mut(inner);
3931            second.get_mut(sub)
3932        });
3933        
3934        OptionalArcTokioRwLockWritableKeyPathChain {
3935            outer_keypath: self.outer_keypath,
3936            inner_keypath: composed,
3937        }
3938    }
3939
3940    /// Chain with an optional writable keypath through another level
3941    pub fn chain_optional<NextValue, H>(
3942        self,
3943        next: WritableOptionalKeyPath<SubValue, NextValue, H>,
3944    ) -> OptionalArcTokioRwLockWritableOptionalKeyPathChain<Root, RwLockValue, InnerValue, NextValue, F, impl for<'r> Fn(&'r mut InnerValue) -> Option<&'r mut NextValue> + 'static>
3945    where
3946        H: for<'r> Fn(&'r mut SubValue) -> Option<&'r mut NextValue>,
3947        G: 'static,
3948        H: 'static,
3949        InnerValue: 'static,
3950        SubValue: 'static,
3951        NextValue: 'static,
3952    {
3953        let first = self.inner_keypath;
3954        let second = next;
3955        
3956        let composed = WritableOptionalKeyPath::new(move |inner: &mut InnerValue| {
3957            let sub = first.get_mut(inner);
3958            second.get_mut(sub)
3959        });
3960        
3961        OptionalArcTokioRwLockWritableOptionalKeyPathChain {
3962            outer_keypath: self.outer_keypath,
3963            inner_keypath: composed,
3964        }
3965    }
3966}
3967
3968/// A composed writable optional async keypath chain from optional keypath through Arc<tokio::sync::RwLock<T>>
3969#[cfg(feature = "tokio")]
3970pub struct OptionalArcTokioRwLockWritableOptionalKeyPathChain<Root, RwLockValue, InnerValue, SubValue, F, G>
3971where
3972    RwLockValue: std::borrow::Borrow<Arc<TokioRwLock<InnerValue>>>,
3973    F: for<'r> Fn(&'r Root) -> Option<&'r RwLockValue>,
3974    G: for<'r> Fn(&'r mut InnerValue) -> Option<&'r mut SubValue>,
3975{
3976    outer_keypath: OptionalKeyPath<Root, RwLockValue, F>,
3977    inner_keypath: WritableOptionalKeyPath<InnerValue, SubValue, G>,
3978}
3979
3980#[cfg(feature = "tokio")]
3981impl<Root, RwLockValue, InnerValue, SubValue, F, G> OptionalArcTokioRwLockWritableOptionalKeyPathChain<Root, RwLockValue, InnerValue, SubValue, F, G>
3982where
3983    RwLockValue: std::borrow::Borrow<Arc<TokioRwLock<InnerValue>>>,
3984    F: for<'r> Fn(&'r Root) -> Option<&'r RwLockValue>,
3985    G: for<'r> Fn(&'r mut InnerValue) -> Option<&'r mut SubValue>,
3986{
3987    /// Apply the composed keypath chain to a container with mutable access (write lock, if value exists, async)
3988    pub async fn get_mut<Callback, R>(self, container: &Root, callback: Callback) -> Option<R>
3989    where
3990        Callback: FnOnce(&mut SubValue) -> R,
3991    {
3992        if let Some(arc_rwlock_ref) = self.outer_keypath.get(container) { let arc_rwlock_ref = arc_rwlock_ref.borrow();
3993            let mut guard = arc_rwlock_ref.write().await;
3994            self.inner_keypath.get_mut(&mut *guard).map(|value_ref| callback(value_ref))
3995        } else {
3996            None
3997        }
3998    }
3999
4000    /// Chain with another writable keypath through another level
4001    pub fn then<NextValue, H>(
4002        self,
4003        next: WritableKeyPath<SubValue, NextValue, H>,
4004    ) -> OptionalArcTokioRwLockWritableOptionalKeyPathChain<Root, RwLockValue, InnerValue, NextValue, F, impl for<'r> Fn(&'r mut InnerValue) -> Option<&'r mut NextValue> + 'static>
4005    where
4006        H: for<'r> Fn(&'r mut SubValue) -> &'r mut NextValue,
4007        G: 'static,
4008        H: 'static,
4009        InnerValue: 'static,
4010        SubValue: 'static,
4011        NextValue: 'static,
4012    {
4013        let first = self.inner_keypath;
4014        let second = next;
4015        
4016        let composed = WritableOptionalKeyPath::new(move |inner: &mut InnerValue| {
4017            first.get_mut(inner).map(|sub| second.get_mut(sub))
4018        });
4019        
4020        OptionalArcTokioRwLockWritableOptionalKeyPathChain {
4021            outer_keypath: self.outer_keypath,
4022            inner_keypath: composed,
4023        }
4024    }
4025
4026    /// Chain with an optional writable keypath through another level
4027    pub fn chain_optional<NextValue, H>(
4028        self,
4029        next: WritableOptionalKeyPath<SubValue, NextValue, H>,
4030    ) -> OptionalArcTokioRwLockWritableOptionalKeyPathChain<Root, RwLockValue, InnerValue, NextValue, F, impl for<'r> Fn(&'r mut InnerValue) -> Option<&'r mut NextValue> + 'static>
4031    where
4032        H: for<'r> Fn(&'r mut SubValue) -> Option<&'r mut NextValue>,
4033        G: 'static,
4034        H: 'static,
4035        InnerValue: 'static,
4036        SubValue: 'static,
4037        NextValue: 'static,
4038    {
4039        let first = self.inner_keypath;
4040        let second = next;
4041        
4042        let composed = WritableOptionalKeyPath::new(move |inner: &mut InnerValue| {
4043            first.get_mut(inner).and_then(|sub| second.get_mut(sub))
4044        });
4045        
4046        OptionalArcTokioRwLockWritableOptionalKeyPathChain {
4047            outer_keypath: self.outer_keypath,
4048            inner_keypath: composed,
4049        }
4050    }
4051}
4052
4053#[cfg(feature = "tagged")]
4054use tagged_core::Tagged;
4055
4056
4057// ========== HELPER MACROS FOR KEYPATH CREATION ==========
4058
4059/// Macro to create a `KeyPath` (readable, non-optional)
4060/// 
4061/// # Examples
4062/// 
4063/// ```rust
4064/// use rust_keypaths::keypath;
4065/// 
4066/// struct User { name: String, address: Address }
4067/// struct Address { street: String }
4068/// 
4069/// // Using a closure with type annotation
4070/// let kp = keypath!(|u: &User| &u.name);
4071/// 
4072/// // Nested field access
4073/// let kp = keypath!(|u: &User| &u.address.street);
4074/// 
4075/// // Or with automatic type inference
4076/// let kp = keypath!(|u| &u.name);
4077/// ```
4078#[macro_export]
4079macro_rules! keypath {
4080    // Accept a closure directly
4081    ($closure:expr) => {
4082        $crate::KeyPath::new($closure)
4083    };
4084}
4085
4086/// Macro to create an `OptionalKeyPath` (readable, optional)
4087/// 
4088/// # Examples
4089/// 
4090/// ```rust
4091/// use rust_keypaths::opt_keypath;
4092/// 
4093/// struct User { metadata: Option<String>, address: Option<Address> }
4094/// struct Address { street: String }
4095/// 
4096/// // Using a closure with type annotation
4097/// let kp = opt_keypath!(|u: &User| u.metadata.as_ref());
4098/// 
4099/// // Nested field access through Option
4100/// let kp = opt_keypath!(|u: &User| u.address.as_ref().map(|a| &a.street));
4101/// 
4102/// // Or with automatic type inference
4103/// let kp = opt_keypath!(|u| u.metadata.as_ref());
4104/// ```
4105#[macro_export]
4106macro_rules! opt_keypath {
4107    // Accept a closure directly
4108    ($closure:expr) => {
4109        $crate::OptionalKeyPath::new($closure)
4110    };
4111}
4112
4113/// Macro to create a `WritableKeyPath` (writable, non-optional)
4114/// 
4115/// # Examples
4116/// 
4117/// ```rust
4118/// use rust_keypaths::writable_keypath;
4119/// 
4120/// struct User { name: String, address: Address }
4121/// struct Address { street: String }
4122/// 
4123/// // Using a closure with type annotation
4124/// let kp = writable_keypath!(|u: &mut User| &mut u.name);
4125/// 
4126/// // Nested field access
4127/// let kp = writable_keypath!(|u: &mut User| &mut u.address.street);
4128/// 
4129/// // Or with automatic type inference
4130/// let kp = writable_keypath!(|u| &mut u.name);
4131/// ```
4132#[macro_export]
4133macro_rules! writable_keypath {
4134    // Accept a closure directly
4135    ($closure:expr) => {
4136        $crate::WritableKeyPath::new($closure)
4137    };
4138}
4139
4140/// Macro to create a `WritableOptionalKeyPath` (writable, optional)
4141/// 
4142/// # Examples
4143/// 
4144/// ```rust
4145/// use rust_keypaths::writable_opt_keypath;
4146/// 
4147/// struct User { metadata: Option<String>, address: Option<Address> }
4148/// struct Address { street: String }
4149/// 
4150/// // Using a closure with type annotation
4151/// let kp = writable_opt_keypath!(|u: &mut User| u.metadata.as_mut());
4152/// 
4153/// // Nested field access through Option
4154/// let kp = writable_opt_keypath!(|u: &mut User| u.address.as_mut().map(|a| &mut a.street));
4155/// 
4156/// // Or with automatic type inference
4157/// let kp = writable_opt_keypath!(|u| u.metadata.as_mut());
4158/// ```
4159#[macro_export]
4160macro_rules! writable_opt_keypath {
4161    // Accept a closure directly
4162    ($closure:expr) => {
4163        $crate::WritableOptionalKeyPath::new($closure)
4164    };
4165}
4166
4167// ========== BASE KEYPATH TYPES ==========
4168
4169// Base KeyPath
4170#[derive(Clone)]
4171pub struct KeyPath<Root, Value, F>
4172where
4173    F: for<'r> Fn(&'r Root) -> &'r Value,
4174{
4175    getter: F,
4176    _phantom: PhantomData<(Root, Value)>,
4177}
4178
4179impl<Root, Value, F> fmt::Display for KeyPath<Root, Value, F>
4180where
4181    F: for<'r> Fn(&'r Root) -> &'r Value,
4182{
4183    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
4184        let root_name = std::any::type_name::<Root>();
4185        let value_name = std::any::type_name::<Value>();
4186        // Simplify type names by removing module paths for cleaner output
4187        let root_short = root_name.split("::").last().unwrap_or(root_name);
4188        let value_short = value_name.split("::").last().unwrap_or(value_name);
4189        write!(f, "KeyPath<{} -> {}>", root_short, value_short)
4190    }
4191}
4192
4193impl<Root, Value, F> fmt::Debug for KeyPath<Root, Value, F>
4194where
4195    F: for<'r> Fn(&'r Root) -> &'r Value,
4196{
4197    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
4198        fmt::Display::fmt(self, f)
4199    }
4200}
4201
4202impl<Root, Value, F> KeyPath<Root, Value, F>
4203where
4204    F: for<'r> Fn(&'r Root) -> &'r Value,
4205{
4206    pub fn new(getter: F) -> Self {
4207        Self {
4208            getter,
4209            _phantom: PhantomData,
4210        }
4211    }
4212    
4213    pub fn get<'r>(&self, root: &'r Root) -> &'r Value {
4214        (self.getter)(root)
4215    }
4216    
4217    /// Chain this keypath with an inner keypath through Arc<Mutex<T>> - functional style
4218    /// Compose first, then apply container at get() time
4219    /// 
4220    /// # Example
4221    /// ```rust
4222    /// let container = ContainerTest { mutex_data: Arc::new(Mutex::new(SomeStruct { data: "test".to_string() })) };
4223    /// 
4224    /// // Functional style: compose first, apply container at get()
4225    /// ContainerTest::mutex_data_r()
4226    ///     .chain_arc_mutex_at_kp(SomeStruct::data_r())
4227    ///     .get(&container, |value| println!("Data: {}", value));
4228    /// ```
4229    pub fn chain_arc_mutex_at_kp<InnerValue, SubValue, G>(
4230        self,
4231        inner_keypath: KeyPath<InnerValue, SubValue, G>,
4232    ) -> ArcMutexKeyPathChain<Root, Value, InnerValue, SubValue, F, G>
4233    where
4234        G: for<'r> Fn(&'r InnerValue) -> &'r SubValue,
4235    {
4236        ArcMutexKeyPathChain {
4237            outer_keypath: self,
4238            inner_keypath,
4239        }
4240    }
4241    
4242    /// Chain this keypath with an optional inner keypath through Arc<Mutex<T>> - functional style
4243    /// Compose first, then apply container at get() time
4244    /// 
4245    /// # Example
4246    /// ```rust
4247    /// let container = ContainerTest { mutex_data: Arc::new(Mutex::new(SomeStruct { optional_field: Some("test".to_string()) })) };
4248    /// 
4249    /// // Functional style: compose first, apply container at get()
4250    /// ContainerTest::mutex_data_r()
4251    ///     .chain_arc_mutex_optional_at_kp(SomeStruct::optional_field_fr())
4252    ///     .get(&container, |value| println!("Value: {}", value));
4253    /// ```
4254    pub fn chain_arc_mutex_optional_at_kp<InnerValue, SubValue, G>(
4255        self,
4256        inner_keypath: OptionalKeyPath<InnerValue, SubValue, G>,
4257    ) -> ArcMutexOptionalKeyPathChain<Root, Value, InnerValue, SubValue, F, G>
4258    where
4259        G: for<'r> Fn(&'r InnerValue) -> Option<&'r SubValue>,
4260    {
4261        ArcMutexOptionalKeyPathChain {
4262            outer_keypath: self,
4263            inner_keypath,
4264        }
4265    }
4266    
4267    /// Chain this keypath with an inner keypath through Arc<RwLock<T>> - functional style
4268    /// Compose first, then apply container at get() time (uses read lock)
4269    /// 
4270    /// # Example
4271    /// ```rust
4272    /// let container = ContainerTest { rwlock_data: Arc::new(RwLock::new(SomeStruct { data: "test".to_string() })) };
4273    /// 
4274    /// // Functional style: compose first, apply container at get()
4275    /// ContainerTest::rwlock_data_r()
4276    ///     .chain_arc_rwlock_at_kp(SomeStruct::data_r())
4277    ///     .get(&container, |value| println!("Data: {}", value));
4278    /// ```
4279    pub fn chain_arc_rwlock_at_kp<InnerValue, SubValue, G>(
4280        self,
4281        inner_keypath: KeyPath<InnerValue, SubValue, G>,
4282    ) -> ArcRwLockKeyPathChain<Root, Value, InnerValue, SubValue, F, G>
4283    where
4284        G: for<'r> Fn(&'r InnerValue) -> &'r SubValue,
4285    {
4286        ArcRwLockKeyPathChain {
4287            outer_keypath: self,
4288            inner_keypath,
4289        }
4290    }
4291    
4292    /// Chain this keypath with an optional inner keypath through Arc<RwLock<T>> - functional style
4293    /// Compose first, then apply container at get() time (uses read lock)
4294    /// 
4295    /// # Example
4296    /// ```rust
4297    /// let container = ContainerTest { rwlock_data: Arc::new(RwLock::new(SomeStruct { optional_field: Some("test".to_string()) })) };
4298    /// 
4299    /// // Functional style: compose first, apply container at get()
4300    /// ContainerTest::rwlock_data_r()
4301    ///     .chain_arc_rwlock_optional_at_kp(SomeStruct::optional_field_fr())
4302    ///     .get(&container, |value| println!("Value: {}", value));
4303    /// ```
4304    pub fn chain_arc_rwlock_optional_at_kp<InnerValue, SubValue, G>(
4305        self,
4306        inner_keypath: OptionalKeyPath<InnerValue, SubValue, G>,
4307    ) -> ArcRwLockOptionalKeyPathChain<Root, Value, InnerValue, SubValue, F, G>
4308    where
4309        G: for<'r> Fn(&'r InnerValue) -> Option<&'r SubValue>,
4310    {
4311        ArcRwLockOptionalKeyPathChain {
4312            outer_keypath: self,
4313            inner_keypath,
4314        }
4315    }
4316    
4317    /// Chain this keypath with a writable inner keypath through Arc<Mutex<T>> - functional style
4318    /// Compose first, then apply container at get_mut() time
4319    /// 
4320    /// # Example
4321    /// ```rust
4322    /// ContainerTest::mutex_data_r()
4323    ///     .chain_arc_mutex_writable_at_kp(SomeStruct::data_w())
4324    ///     .get_mut(&container, |value| *value = "new".to_string());
4325    /// ```
4326    pub fn chain_arc_mutex_writable_at_kp<InnerValue, SubValue, G>(
4327        self,
4328        inner_keypath: WritableKeyPath<InnerValue, SubValue, G>,
4329    ) -> ArcMutexWritableKeyPathChain<Root, Value, InnerValue, SubValue, F, G>
4330    where
4331        G: for<'r> Fn(&'r mut InnerValue) -> &'r mut SubValue,
4332    {
4333        ArcMutexWritableKeyPathChain {
4334            outer_keypath: self,
4335            inner_keypath,
4336        }
4337    }
4338    
4339    /// Chain this keypath with a writable optional inner keypath through Arc<Mutex<T>> - functional style
4340    /// Compose first, then apply container at get_mut() time
4341    /// 
4342    /// # Example
4343    /// ```rust
4344    /// ContainerTest::mutex_data_r()
4345    ///     .chain_arc_mutex_writable_optional_at_kp(SomeStruct::optional_field_fw())
4346    ///     .get_mut(&container, |value| *value = "new".to_string());
4347    /// ```
4348    pub fn chain_arc_mutex_writable_optional_at_kp<InnerValue, SubValue, G>(
4349        self,
4350        inner_keypath: WritableOptionalKeyPath<InnerValue, SubValue, G>,
4351    ) -> ArcMutexWritableOptionalKeyPathChain<Root, Value, InnerValue, SubValue, F, G>
4352    where
4353        G: for<'r> Fn(&'r mut InnerValue) -> Option<&'r mut SubValue>,
4354    {
4355        ArcMutexWritableOptionalKeyPathChain {
4356            outer_keypath: self,
4357            inner_keypath,
4358        }
4359    }
4360    
4361    /// Chain this keypath with a writable inner keypath through Arc<RwLock<T>> - functional style
4362    /// Compose first, then apply container at get_mut() time (uses write lock)
4363    /// 
4364    /// # Example
4365    /// ```rust
4366    /// ContainerTest::rwlock_data_r()
4367    ///     .chain_arc_rwlock_writable_at_kp(SomeStruct::data_w())
4368    ///     .get_mut(&container, |value| *value = "new".to_string());
4369    /// ```
4370    pub fn chain_arc_rwlock_writable_at_kp<InnerValue, SubValue, G>(
4371        self,
4372        inner_keypath: WritableKeyPath<InnerValue, SubValue, G>,
4373    ) -> ArcRwLockWritableKeyPathChain<Root, Value, InnerValue, SubValue, F, G>
4374    where
4375        G: for<'r> Fn(&'r mut InnerValue) -> &'r mut SubValue,
4376    {
4377        ArcRwLockWritableKeyPathChain {
4378            outer_keypath: self,
4379            inner_keypath,
4380        }
4381    }
4382    
4383    /// Chain this keypath with a writable optional inner keypath through Arc<RwLock<T>> - functional style
4384    /// Compose first, then apply container at get_mut() time (uses write lock)
4385    /// 
4386    /// # Example
4387    /// ```rust
4388    /// ContainerTest::rwlock_data_r()
4389    ///     .chain_arc_rwlock_writable_optional_at_kp(SomeStruct::optional_field_fw())
4390    ///     .get_mut(&container, |value| *value = "new".to_string());
4391    /// ```
4392    pub fn chain_arc_rwlock_writable_optional_at_kp<InnerValue, SubValue, G>(
4393        self,
4394        inner_keypath: WritableOptionalKeyPath<InnerValue, SubValue, G>,
4395    ) -> ArcRwLockWritableOptionalKeyPathChain<Root, Value, InnerValue, SubValue, F, G>
4396    where
4397        G: for<'r> Fn(&'r mut InnerValue) -> Option<&'r mut SubValue>,
4398    {
4399        ArcRwLockWritableOptionalKeyPathChain {
4400            outer_keypath: self,
4401            inner_keypath,
4402        }
4403    }
4404
4405    #[cfg(feature = "tokio")]
4406    /// Chain this keypath with an inner keypath through Arc<tokio::sync::Mutex<T>> - functional style (async)
4407    /// Compose first, then apply container at get() time
4408    pub fn chain_arc_tokio_mutex_at_kp<InnerValue, SubValue, G>(
4409        self,
4410        inner_keypath: KeyPath<InnerValue, SubValue, G>,
4411    ) -> ArcTokioMutexKeyPathChain<Root, Value, InnerValue, SubValue, F, G>
4412    where
4413        G: for<'r> Fn(&'r InnerValue) -> &'r SubValue,
4414    {
4415        ArcTokioMutexKeyPathChain {
4416            outer_keypath: self,
4417            inner_keypath,
4418        }
4419    }
4420
4421    #[cfg(feature = "tokio")]
4422    /// Chain this keypath with an optional inner keypath through Arc<tokio::sync::Mutex<T>> - functional style (async)
4423    pub fn chain_arc_tokio_mutex_optional_at_kp<InnerValue, SubValue, G>(
4424        self,
4425        inner_keypath: OptionalKeyPath<InnerValue, SubValue, G>,
4426    ) -> ArcTokioMutexOptionalKeyPathChain<Root, Value, InnerValue, SubValue, F, G>
4427    where
4428        Value: std::borrow::Borrow<Arc<tokio::sync::Mutex<InnerValue>>>,
4429        G: for<'r> Fn(&'r InnerValue) -> Option<&'r SubValue>,
4430    {
4431        ArcTokioMutexOptionalKeyPathChain {
4432            outer_keypath: self,
4433            inner_keypath,
4434        }
4435    }
4436
4437    #[cfg(feature = "tokio")]
4438    /// Chain this keypath with a writable inner keypath through Arc<tokio::sync::Mutex<T>> - functional style (async)
4439    pub fn chain_arc_tokio_mutex_writable_at_kp<InnerValue, SubValue, G>(
4440        self,
4441        inner_keypath: WritableKeyPath<InnerValue, SubValue, G>,
4442    ) -> ArcTokioMutexWritableKeyPathChain<Root, Value, InnerValue, SubValue, F, G>
4443    where
4444        Value: std::borrow::Borrow<Arc<tokio::sync::Mutex<InnerValue>>>,
4445        G: for<'r> Fn(&'r mut InnerValue) -> &'r mut SubValue,
4446    {
4447        ArcTokioMutexWritableKeyPathChain {
4448            outer_keypath: self,
4449            inner_keypath,
4450        }
4451    }
4452
4453    #[cfg(feature = "tokio")]
4454    /// Chain this keypath with a writable optional inner keypath through Arc<tokio::sync::Mutex<T>> - functional style (async)
4455    pub fn chain_arc_tokio_mutex_writable_optional_at_kp<InnerValue, SubValue, G>(
4456        self,
4457        inner_keypath: WritableOptionalKeyPath<InnerValue, SubValue, G>,
4458    ) -> ArcTokioMutexWritableOptionalKeyPathChain<Root, Value, InnerValue, SubValue, F, G>
4459    where
4460        Value: std::borrow::Borrow<Arc<tokio::sync::Mutex<InnerValue>>>,
4461        G: for<'r> Fn(&'r mut InnerValue) -> Option<&'r mut SubValue>,
4462    {
4463        ArcTokioMutexWritableOptionalKeyPathChain {
4464            outer_keypath: self,
4465            inner_keypath,
4466        }
4467    }
4468
4469    #[cfg(feature = "tokio")]
4470    /// Chain this keypath with an inner keypath through Arc<tokio::sync::RwLock<T>> - functional style (async, read lock)
4471    pub fn chain_arc_tokio_rwlock_at_kp<InnerValue, SubValue, G>(
4472        self,
4473        inner_keypath: KeyPath<InnerValue, SubValue, G>,
4474    ) -> ArcTokioRwLockKeyPathChain<Root, Value, InnerValue, SubValue, F, G>
4475    where
4476        Value: std::borrow::Borrow<Arc<tokio::sync::RwLock<InnerValue>>>,
4477        G: for<'r> Fn(&'r InnerValue) -> &'r SubValue,
4478    {
4479        ArcTokioRwLockKeyPathChain {
4480            outer_keypath: self,
4481            inner_keypath,
4482        }
4483    }
4484
4485    #[cfg(feature = "tokio")]
4486    /// Chain this keypath with an optional inner keypath through Arc<tokio::sync::RwLock<T>> - functional style (async, read lock)
4487    pub fn chain_arc_tokio_rwlock_optional_at_kp<InnerValue, SubValue, G>(
4488        self,
4489        inner_keypath: OptionalKeyPath<InnerValue, SubValue, G>,
4490    ) -> ArcTokioRwLockOptionalKeyPathChain<Root, Value, InnerValue, SubValue, F, G>
4491    where
4492        Value: std::borrow::Borrow<Arc<tokio::sync::RwLock<InnerValue>>>,
4493        G: for<'r> Fn(&'r InnerValue) -> Option<&'r SubValue>,
4494    {
4495        ArcTokioRwLockOptionalKeyPathChain {
4496            outer_keypath: self,
4497            inner_keypath,
4498        }
4499    }
4500
4501    #[cfg(feature = "tokio")]
4502    /// Chain this keypath with a writable inner keypath through Arc<tokio::sync::RwLock<T>> - functional style (async, write lock)
4503    pub fn chain_arc_tokio_rwlock_writable_at_kp<InnerValue, SubValue, G>(
4504        self,
4505        inner_keypath: WritableKeyPath<InnerValue, SubValue, G>,
4506    ) -> ArcTokioRwLockWritableKeyPathChain<Root, Value, InnerValue, SubValue, F, G>
4507    where
4508        Value: std::borrow::Borrow<Arc<tokio::sync::RwLock<InnerValue>>>,
4509        G: for<'r> Fn(&'r mut InnerValue) -> &'r mut SubValue,
4510    {
4511        ArcTokioRwLockWritableKeyPathChain {
4512            outer_keypath: self,
4513            inner_keypath,
4514        }
4515    }
4516
4517    #[cfg(feature = "tokio")]
4518    /// Chain this keypath with a writable optional inner keypath through Arc<tokio::sync::RwLock<T>> - functional style (async, write lock)
4519    pub fn chain_arc_tokio_rwlock_writable_optional_at_kp<InnerValue, SubValue, G>(
4520        self,
4521        inner_keypath: WritableOptionalKeyPath<InnerValue, SubValue, G>,
4522    ) -> ArcTokioRwLockWritableOptionalKeyPathChain<Root, Value, InnerValue, SubValue, F, G>
4523    where
4524        Value: std::borrow::Borrow<Arc<tokio::sync::RwLock<InnerValue>>>,
4525        G: for<'r> Fn(&'r mut InnerValue) -> Option<&'r mut SubValue>,
4526    {
4527        ArcTokioRwLockWritableOptionalKeyPathChain {
4528            outer_keypath: self,
4529            inner_keypath,
4530        }
4531    }
4532
4533    /// Monadic helper: shorthand for chain_arc_rwlock_writable_at_kp when Value is Arc<RwLock<T>>
4534    /// This allows chaining with .then().then().then() pattern for Arc<RwLock<T>> structures
4535    /// 
4536    /// # Example
4537    /// ```rust,ignore
4538    /// ContainerTest::rwlock_data_r()
4539    ///     .then_rwlock(SomeStruct::data_w())
4540    ///     .then(OtherStruct::field_w())
4541    ///     .get_mut(&container, |value| *value = "new".to_string());
4542    /// ```
4543    pub fn then_rwlock<InnerValue, SubValue, G>(
4544        self,
4545        inner_keypath: WritableKeyPath<InnerValue, SubValue, G>,
4546    ) -> ArcRwLockWritableKeyPathChain<Root, Value, InnerValue, SubValue, F, G>
4547    where
4548        Value: std::borrow::Borrow<Arc<RwLock<InnerValue>>>,
4549        G: for<'r> Fn(&'r mut InnerValue) -> &'r mut SubValue,
4550    {
4551        self.chain_arc_rwlock_writable_at_kp(inner_keypath)
4552    }
4553
4554    // ========== LOCK KEYPATH CONVERSION METHODS ==========
4555    // These methods convert keypaths pointing to lock types into chain-ready keypaths
4556
4557    /// Convert this keypath to an Arc<RwLock> chain-ready keypath
4558    /// Returns self, but serves as a marker for intent and enables chaining
4559    /// 
4560    /// # Example
4561    /// ```rust,ignore
4562    /// Container::rwlock_data_r()
4563    ///     .to_arc_rwlock_kp()
4564    ///     .chain_arc_rwlock_at_kp(InnerStruct::field_r());
4565    /// ```
4566    pub fn to_arc_rwlock_kp<InnerValue>(self) -> Self
4567    where
4568        Value: std::borrow::Borrow<Arc<RwLock<InnerValue>>>,
4569    {
4570        self
4571    }
4572
4573    /// Convert this keypath to an Arc<Mutex> chain-ready keypath
4574    /// Returns self, but serves as a marker for intent and enables chaining
4575    pub fn to_arc_mutex_kp<InnerValue>(self) -> Self
4576    where
4577        Value: std::borrow::Borrow<Arc<Mutex<InnerValue>>>,
4578    {
4579        self
4580    }
4581
4582    #[cfg(feature = "parking_lot")]
4583    /// Convert this keypath to an Arc<parking_lot::RwLock> chain-ready keypath
4584    /// Returns self, but serves as a marker for intent and enables chaining
4585    /// 
4586    /// # Example
4587    /// ```rust,ignore
4588    /// Container::rwlock_data_r()
4589    ///     .to_arc_parking_rwlock_kp()
4590    ///     .then_arc_parking_rwlock_at_kp(InnerStruct::field_r());
4591    /// ```
4592    pub fn to_arc_parking_rwlock_kp<InnerValue>(self) -> Self
4593    where
4594        Value: std::borrow::Borrow<Arc<parking_lot::RwLock<InnerValue>>>,
4595    {
4596        self
4597    }
4598
4599    #[cfg(feature = "parking_lot")]
4600    /// Convert this keypath to an Arc<parking_lot::Mutex> chain-ready keypath
4601    /// Returns self, but serves as a marker for intent and enables chaining
4602    pub fn to_arc_parking_mutex_kp<InnerValue>(self) -> Self
4603    where
4604        Value: std::borrow::Borrow<Arc<parking_lot::Mutex<InnerValue>>>,
4605    {
4606        self
4607    }
4608
4609    /// Convert this keypath to an Arc<RwLock> chain keypath
4610    /// Creates a chain with an identity inner keypath, ready for further chaining
4611    /// 
4612    /// # Example
4613    /// ```rust,ignore
4614    /// Container::rwlock_data_r()
4615    ///     .to_arc_rwlock_chain()
4616    ///     .then(InnerStruct::field_r());
4617    /// ```
4618    /// Convert this keypath to an Arc<RwLock> chain keypath
4619    /// Creates a chain with an identity inner keypath, ready for further chaining
4620    /// Type inference automatically determines InnerValue from Value
4621    /// 
4622    /// # Example
4623    /// ```rust,ignore
4624    /// Container::rwlock_data_r()
4625    ///     .to_arc_rwlock_chain()
4626    ///     .then(InnerStruct::field_r());
4627    /// ```
4628    pub fn to_arc_rwlock_chain<InnerValue>(self) -> ArcRwLockKeyPathChain<Root, Value, InnerValue, InnerValue, F, impl for<'r> Fn(&'r InnerValue) -> &'r InnerValue + 'static>
4629    where
4630        Value: std::borrow::Borrow<Arc<RwLock<InnerValue>>>,
4631        F: 'static,
4632        InnerValue: 'static,
4633    {
4634        let identity = KeyPath::new(|inner: &InnerValue| inner);
4635        ArcRwLockKeyPathChain {
4636            outer_keypath: self,
4637            inner_keypath: identity,
4638        }
4639    }
4640
4641    /// Convert this keypath to an Arc<Mutex> chain keypath
4642    /// Creates a chain with an identity inner keypath, ready for further chaining
4643    /// Type inference automatically determines InnerValue from Value
4644    pub fn to_arc_mutex_chain<InnerValue>(self) -> ArcMutexKeyPathChain<Root, Value, InnerValue, InnerValue, F, impl for<'r> Fn(&'r InnerValue) -> &'r InnerValue + 'static>
4645    where
4646        Value: std::borrow::Borrow<Arc<Mutex<InnerValue>>>,
4647        F: 'static,
4648        InnerValue: 'static,
4649    {
4650        let identity = KeyPath::new(|inner: &InnerValue| inner);
4651        ArcMutexKeyPathChain {
4652            outer_keypath: self,
4653            inner_keypath: identity,
4654        }
4655    }
4656
4657    // #[cfg(feature = "parking_lot")]
4658    // /// Convert this keypath to an Arc<parking_lot::RwLock> chain keypath
4659    // /// Creates a chain with an identity inner keypath, ready for further chaining
4660    // /// Type inference automatically determines InnerValue from Value
4661    // /// 
4662    // /// # Example
4663    // /// ```rust,ignore
4664    // /// Container::rwlock_data_r()
4665    // ///     .to_arc_parking_rwlock_chain()
4666    // ///     .then(InnerStruct::field_r());
4667    // /// ```
4668    // pub fn to_arc_parking_rwlock_chain<InnerValue>(self) -> ArcParkingRwLockKeyPathChain<Root, InnerValue, InnerValue, impl for<'r> Fn(&'r Root) -> &'r Arc<parking_lot::RwLock<InnerValue>> + 'static, impl for<'r> Fn(&'r InnerValue) -> &'r InnerValue + 'static>
4669    // where
4670    //     Value: std::borrow::Borrow<Arc<parking_lot::RwLock<InnerValue>>>,
4671    //     F: 'static + Clone,
4672    //     InnerValue: 'static,
4673    // {
4674    //     let identity = KeyPath::new(|inner: &InnerValue| inner);
4675    //     let getter = self.getter.clone();
4676    //     // Create a new keypath with the exact type needed, following the proc macro pattern
4677    //     // KeyPath::new(|s: &Root| &s.field).then_arc_parking_rwlock_at_kp(inner_kp)
4678    //     let lock_kp: KeyPath<Root, Arc<parking_lot::RwLock<InnerValue>>, _> = KeyPath::new(move |root: &Root| {
4679    //         // Safe: Value is Arc<parking_lot::RwLock<InnerValue>> at call site, enforced by Borrow bound
4680    //         unsafe {
4681    //             std::mem::transmute::<&Value, &Arc<parking_lot::RwLock<InnerValue>>>(getter(root))
4682    //         }
4683    //     });
4684    //     lock_kp.then_arc_parking_rwlock_at_kp(identity)
4685    // }
4686
4687    // #[cfg(feature = "parking_lot")]
4688    // /// Convert this keypath to an Arc<parking_lot::Mutex> chain keypath
4689    // /// Creates a chain with an identity inner keypath, ready for further chaining
4690    // /// Type inference automatically determines InnerValue from Value
4691    // pub fn to_arc_parking_mutex_chain<InnerValue>(self) -> ArcParkingMutexKeyPathChain<Root, InnerValue, InnerValue, impl for<'r> Fn(&'r Root) -> &'r Arc<parking_lot::Mutex<InnerValue>> + 'static, impl for<'r> Fn(&'r InnerValue) -> &'r InnerValue + 'static>
4692    // where
4693    //     Value: std::borrow::Borrow<Arc<parking_lot::Mutex<InnerValue>>>,
4694    //     F: 'static + Clone,
4695    //     InnerValue: 'static,
4696    // {
4697    //     let identity = KeyPath::new(|inner: &InnerValue| inner);
4698    //     let getter = self.getter.clone();
4699    //     let lock_kp: KeyPath<Root, Arc<parking_lot::Mutex<InnerValue>>, _> = KeyPath::new(move |root: &Root| {
4700    //         unsafe {
4701    //             std::mem::transmute::<&Value, &Arc<parking_lot::Mutex<InnerValue>>>(getter(root))
4702    //         }
4703    //     });
4704    //     lock_kp.then_arc_parking_mutex_at_kp(identity)
4705    // }
4706
4707    // Instance methods for unwrapping containers (automatically infers Target from Value::Target)
4708    // Box<T> -> T
4709    pub fn for_box<Target>(self) -> KeyPath<Root, Target, impl for<'r> Fn(&'r Root) -> &'r Target + 'static>
4710    where
4711        Value: std::ops::Deref<Target = Target>,
4712        F: 'static,
4713        Value: 'static,
4714    {
4715        let getter = self.getter;
4716        
4717        KeyPath {
4718            getter: move |root: &Root| {
4719                getter(root).deref()
4720            },
4721            _phantom: PhantomData,
4722        }
4723    }
4724    
4725    // Arc<T> -> T
4726    pub fn for_arc<Target>(self) -> KeyPath<Root, Target, impl for<'r> Fn(&'r Root) -> &'r Target + 'static>
4727    where
4728        Value: std::ops::Deref<Target = Target>,
4729        F: 'static,
4730        Value: 'static,
4731    {
4732        let getter = self.getter;
4733        
4734        KeyPath {
4735            getter: move |root: &Root| {
4736                getter(root).deref()
4737            },
4738            _phantom: PhantomData,
4739        }
4740    }
4741    
4742    // Rc<T> -> T
4743    pub fn for_rc<Target>(self) -> KeyPath<Root, Target, impl for<'r> Fn(&'r Root) -> &'r Target + 'static>
4744    where
4745        Value: std::ops::Deref<Target = Target>,
4746        F: 'static,
4747        Value: 'static,
4748    {
4749        let getter = self.getter;
4750        
4751        KeyPath {
4752            getter: move |root: &Root| {
4753                getter(root).deref()
4754            },
4755            _phantom: PhantomData,
4756        }
4757    }
4758    
4759    // Overload: Adapt root type to Arc<Root> when Value is Sized (not a container)
4760    pub fn for_arc_root(self) -> OptionalKeyPath<Arc<Root>, Value, impl for<'r> Fn(&'r Arc<Root>) -> Option<&'r Value> + 'static>
4761    where
4762        Value: Sized,
4763        F: 'static,
4764        Root: 'static,
4765        Value: 'static,
4766    {
4767        let getter = self.getter;
4768        
4769        OptionalKeyPath {
4770            getter: move |arc: &Arc<Root>| {
4771                Some(getter(arc.as_ref()))
4772            },
4773            _phantom: PhantomData,
4774        }
4775    }
4776    
4777    // Overload: Adapt root type to Box<Root> when Value is Sized (not a container)
4778    pub fn for_box_root(self) -> OptionalKeyPath<Box<Root>, Value, impl for<'r> Fn(&'r Box<Root>) -> Option<&'r Value> + 'static>
4779    where
4780        Value: Sized,
4781        F: 'static,
4782        Root: 'static,
4783        Value: 'static,
4784    {
4785        let getter = self.getter;
4786        
4787        OptionalKeyPath {
4788            getter: move |boxed: &Box<Root>| {
4789                Some(getter(boxed.as_ref()))
4790            },
4791            _phantom: PhantomData,
4792        }
4793    }
4794    
4795    // Overload: Adapt root type to Rc<Root> when Value is Sized (not a container)
4796    pub fn for_rc_root(self) -> OptionalKeyPath<Rc<Root>, Value, impl for<'r> Fn(&'r Rc<Root>) -> Option<&'r Value> + 'static>
4797    where
4798        Value: Sized,
4799        F: 'static,
4800        Root: 'static,
4801        Value: 'static,
4802    {
4803        let getter = self.getter;
4804        
4805        OptionalKeyPath {
4806            getter: move |rc: &Rc<Root>| {
4807                Some(getter(rc.as_ref()))
4808            },
4809            _phantom: PhantomData,
4810        }
4811    }
4812    
4813    /// Adapt this keypath to work with Result<Root, E> instead of Root
4814    /// This unwraps the Result and applies the keypath to the Ok value
4815    pub fn for_result<E>(self) -> OptionalKeyPath<Result<Root, E>, Value, impl for<'r> Fn(&'r Result<Root, E>) -> Option<&'r Value> + 'static>
4816    where
4817        F: 'static,
4818        Root: 'static,
4819        Value: 'static,
4820        E: 'static,
4821    {
4822        let getter = self.getter;
4823        
4824        OptionalKeyPath {
4825            getter: move |result: &Result<Root, E>| {
4826                result.as_ref().ok().map(|root| getter(root))
4827            },
4828            _phantom: PhantomData,
4829        }
4830    }
4831    
4832    /// Convert a KeyPath to OptionalKeyPath for chaining
4833    /// This allows non-optional keypaths to be chained with then()
4834    pub fn to_optional(self) -> OptionalKeyPath<Root, Value, impl for<'r> Fn(&'r Root) -> Option<&'r Value> + 'static>
4835    where
4836        F: 'static,
4837    {
4838        let getter = self.getter;
4839        OptionalKeyPath::new(move |root: &Root| Some(getter(root)))
4840    }
4841    
4842    /// Execute a closure with a reference to the value inside an Option
4843    pub fn with_option<Callback, R>(&self, option: &Option<Root>, f: Callback) -> Option<R>
4844    where
4845        F: Clone,
4846        Callback: FnOnce(&Value) -> R,
4847    {
4848        option.as_ref().map(|root| {
4849            let value = self.get(root);
4850            f(value)
4851        })
4852    }
4853    
4854    /// Execute a closure with a reference to the value inside a Result
4855    pub fn with_result<Callback, R, E>(&self, result: &Result<Root, E>, f: Callback) -> Option<R>
4856    where
4857        F: Clone,
4858        Callback: FnOnce(&Value) -> R,
4859    {
4860        result.as_ref().ok().map(|root| {
4861            let value = self.get(root);
4862            f(value)
4863        })
4864    }
4865    
4866    /// Execute a closure with a reference to the value inside a Box
4867    pub fn with_box<Callback, R>(&self, boxed: &Box<Root>, f: Callback) -> R
4868    where
4869        F: Clone,
4870        Callback: FnOnce(&Value) -> R,
4871    {
4872        let value = self.get(boxed);
4873        f(value)
4874    }
4875    
4876    /// Execute a closure with a reference to the value inside an Arc
4877    pub fn with_arc<Callback, R>(&self, arc: &Arc<Root>, f: Callback) -> R
4878    where
4879        F: Clone,
4880        Callback: FnOnce(&Value) -> R,
4881    {
4882        let value = self.get(arc);
4883        f(value)
4884    }
4885    
4886    /// Execute a closure with a reference to the value inside an Rc
4887    pub fn with_rc<Callback, R>(&self, rc: &Rc<Root>, f: Callback) -> R
4888    where
4889        F: Clone,
4890        Callback: FnOnce(&Value) -> R,
4891    {
4892        let value = self.get(rc);
4893        f(value)
4894    }
4895    
4896    /// Execute a closure with a reference to the value inside a RefCell
4897    pub fn with_refcell<Callback, R>(&self, refcell: &RefCell<Root>, f: Callback) -> Option<R>
4898    where
4899        F: Clone,
4900        Callback: FnOnce(&Value) -> R,
4901    {
4902        refcell.try_borrow().ok().map(|borrow| {
4903            let value = self.get(&*borrow);
4904            f(value)
4905        })
4906    }
4907    
4908    /// Execute a closure with a reference to the value inside a Mutex
4909    pub fn with_mutex<Callback, R>(&self, mutex: &Mutex<Root>, f: Callback) -> Option<R>
4910    where
4911        F: Clone,
4912        Callback: FnOnce(&Value) -> R,
4913    {
4914        mutex.lock().ok().map(|guard| {
4915            let value = self.get(&*guard);
4916            f(value)
4917        })
4918    }
4919    
4920    /// Execute a closure with a reference to the value inside an RwLock
4921    pub fn with_rwlock<Callback, R>(&self, rwlock: &RwLock<Root>, f: Callback) -> Option<R>
4922    where
4923        F: Clone,
4924        Callback: FnOnce(&Value) -> R,
4925    {
4926        rwlock.read().ok().map(|guard| {
4927            let value = self.get(&*guard);
4928            f(value)
4929        })
4930    }
4931    
4932    /// Execute a closure with a reference to the value inside an Arc<RwLock<Root>>
4933    pub fn with_arc_rwlock<Callback, R>(&self, arc_rwlock: &Arc<RwLock<Root>>, f: Callback) -> Option<R>
4934    where
4935        F: Clone,
4936        Callback: FnOnce(&Value) -> R,
4937    {
4938        arc_rwlock.read().ok().map(|guard| {
4939            let value = self.get(&*guard);
4940            f(value)
4941        })
4942    }
4943    
4944    /// Execute a closure with a reference to the value inside an Arc<Mutex<Root>>
4945    pub fn with_arc_mutex<Callback, R>(&self, arc_mutex: &Arc<Mutex<Root>>, f: Callback) -> Option<R>
4946    where
4947        F: Clone,
4948        Callback: FnOnce(&Value) -> R,
4949    {
4950        arc_mutex.lock().ok().map(|guard| {
4951            let value = self.get(&*guard);
4952            f(value)
4953        })
4954    }
4955    
4956    #[cfg(feature = "tagged")]
4957    /// Adapt this keypath to work with Tagged<Root, Tag> instead of Root
4958    /// This unwraps the Tagged wrapper and applies the keypath to the inner value
4959    pub fn for_tagged<Tag>(self) -> KeyPath<Tagged<Root, Tag>, Value, impl for<'r> Fn(&'r Tagged<Root, Tag>) -> &'r Value + 'static>
4960    where
4961        Tagged<Root, Tag>: std::ops::Deref<Target = Root>,
4962        F: 'static,
4963        Root: 'static,
4964        Value: 'static,
4965        Tag: 'static,
4966    {
4967        use std::ops::Deref;
4968        let getter = self.getter;
4969        
4970        KeyPath {
4971            getter: move |tagged: &Tagged<Root, Tag>| {
4972                getter(tagged.deref())
4973            },
4974            _phantom: PhantomData,
4975        }
4976    }
4977    
4978    #[cfg(feature = "tagged")]
4979    /// Execute a closure with a reference to the value inside a Tagged
4980    /// This avoids cloning by working with references directly
4981    pub fn with_tagged<Tag, Callback, R>(&self, tagged: &Tagged<Root, Tag>, f: Callback) -> R
4982    where
4983        Tagged<Root, Tag>: std::ops::Deref<Target = Root>,
4984        Callback: FnOnce(&Value) -> R,
4985    {
4986        use std::ops::Deref;
4987        let value = self.get(tagged.deref());
4988        f(value)
4989    }
4990    
4991    /// Adapt this keypath to work with Option<Root> instead of Root
4992    /// This converts the KeyPath to an OptionalKeyPath and unwraps the Option
4993    pub fn for_option(self) -> OptionalKeyPath<Option<Root>, Value, impl for<'r> Fn(&'r Option<Root>) -> Option<&'r Value> + 'static>
4994    where
4995        F: 'static,
4996        Root: 'static,
4997        Value: 'static,
4998    {
4999        let getter = self.getter;
5000        
5001        OptionalKeyPath {
5002            getter: move |opt: &Option<Root>| {
5003                opt.as_ref().map(|root| getter(root))
5004            },
5005            _phantom: PhantomData,
5006        }
5007    }
5008    
5009    /// Get an iterator over a Vec when Value is Vec<T>
5010    /// Returns Some(iterator) if the value is a Vec, None otherwise
5011    pub fn iter<'r, T>(&self, root: &'r Root) -> Option<std::slice::Iter<'r, T>>
5012    where
5013        Value: AsRef<[T]> + 'r,
5014    {
5015        let value_ref: &'r Value = self.get(root);
5016        Some(value_ref.as_ref().iter())
5017    }
5018    
5019    /// Extract values from a slice of owned values
5020    /// Returns a Vec of references to the extracted values
5021    pub fn extract_from_slice<'r>(&self, slice: &'r [Root]) -> Vec<&'r Value> {
5022        slice.iter().map(|item| self.get(item)).collect()
5023    }
5024    
5025    /// Extract values from a slice of references
5026    /// Returns a Vec of references to the extracted values
5027    pub fn extract_from_ref_slice<'r>(&self, slice: &'r [&Root]) -> Vec<&'r Value> {
5028        slice.iter().map(|item| self.get(item)).collect()
5029    }
5030    
5031    /// Chain this keypath with another keypath
5032    /// Returns a KeyPath that chains both keypaths
5033    pub fn then<SubValue, G>(
5034        self,
5035        next: KeyPath<Value, SubValue, G>,
5036    ) -> KeyPath<Root, SubValue, impl for<'r> Fn(&'r Root) -> &'r SubValue>
5037    where
5038        G: for<'r> Fn(&'r Value) -> &'r SubValue,
5039        F: 'static,
5040        G: 'static,
5041        Value: 'static,
5042    {
5043        let first = self.getter;
5044        let second = next.getter;
5045        
5046        KeyPath::new(move |root: &Root| {
5047            let value = first(root);
5048            second(value)
5049        })
5050    }
5051    
5052    /// Chain this keypath with an optional keypath
5053    /// Returns an OptionalKeyPath that chains both keypaths
5054    pub fn chain_optional<SubValue, G>(
5055        self,
5056        next: OptionalKeyPath<Value, SubValue, G>,
5057    ) -> OptionalKeyPath<Root, SubValue, impl for<'r> Fn(&'r Root) -> Option<&'r SubValue>>
5058    where
5059        G: for<'r> Fn(&'r Value) -> Option<&'r SubValue>,
5060        F: 'static,
5061        G: 'static,
5062        Value: 'static,
5063    {
5064        let first = self.getter;
5065        let second = next.getter;
5066        
5067        OptionalKeyPath::new(move |root: &Root| {
5068            let value = first(root);
5069            second(value)
5070        })
5071    }
5072    
5073}
5074
5075// Extension methods for KeyPath to support Arc<RwLock> and Arc<Mutex> directly
5076impl<Root, Value, F> KeyPath<Root, Value, F>
5077where
5078    F: for<'r> Fn(&'r Root) -> &'r Value,
5079{
5080    /// Execute a closure with a reference to the value inside an Arc<RwLock<Root>>
5081    /// This is a convenience method that works directly with Arc<RwLock<T>>
5082    pub fn with_arc_rwlock_direct<Callback, R>(&self, arc_rwlock: &Arc<RwLock<Root>>, f: Callback) -> Option<R>
5083    where
5084        Callback: FnOnce(&Value) -> R,
5085    {
5086        arc_rwlock.read().ok().map(|guard| {
5087            let value = self.get(&*guard);
5088            f(value)
5089        })
5090    }
5091    
5092    /// Execute a closure with a reference to the value inside an Arc<Mutex<Root>>
5093    /// This is a convenience method that works directly with Arc<Mutex<T>>
5094    pub fn with_arc_mutex_direct<Callback, R>(&self, arc_mutex: &Arc<Mutex<Root>>, f: Callback) -> Option<R>
5095    where
5096        Callback: FnOnce(&Value) -> R,
5097    {
5098        arc_mutex.lock().ok().map(|guard| {
5099            let value = self.get(&*guard);
5100            f(value)
5101        })
5102    }
5103}
5104
5105// Utility function for slice access (kept as standalone function)
5106pub fn for_slice<T>() -> impl for<'r> Fn(&'r [T], usize) -> Option<&'r T> {
5107    |slice: &[T], index: usize| slice.get(index)
5108}
5109
5110// Container access utilities
5111pub mod containers {
5112    use super::{OptionalKeyPath, WritableOptionalKeyPath, KeyPath, WritableKeyPath};
5113    use std::collections::{HashMap, BTreeMap, HashSet, BTreeSet, VecDeque, LinkedList, BinaryHeap};
5114    use std::sync::{Mutex, RwLock, Weak as StdWeak, Arc};
5115    use std::rc::{Weak as RcWeak, Rc};
5116    use std::ops::{Deref, DerefMut};
5117
5118    #[cfg(feature = "parking_lot")]
5119    use parking_lot::{Mutex as ParkingMutex, RwLock as ParkingRwLock};
5120
5121    #[cfg(feature = "tagged")]
5122    use tagged_core::Tagged;
5123
5124    /// Create a keypath for indexed access in Vec<T>
5125    pub fn for_vec_index<T>(index: usize) -> OptionalKeyPath<Vec<T>, T, impl for<'r> Fn(&'r Vec<T>) -> Option<&'r T>> {
5126        OptionalKeyPath::new(move |vec: &Vec<T>| vec.get(index))
5127    }
5128
5129    /// Create a keypath for indexed access in VecDeque<T>
5130    pub fn for_vecdeque_index<T>(index: usize) -> OptionalKeyPath<VecDeque<T>, T, impl for<'r> Fn(&'r VecDeque<T>) -> Option<&'r T>> {
5131        OptionalKeyPath::new(move |deque: &VecDeque<T>| deque.get(index))
5132    }
5133
5134    /// Create a keypath for indexed access in LinkedList<T>
5135    pub fn for_linkedlist_index<T>(index: usize) -> OptionalKeyPath<LinkedList<T>, T, impl for<'r> Fn(&'r LinkedList<T>) -> Option<&'r T>> {
5136        OptionalKeyPath::new(move |list: &LinkedList<T>| {
5137            list.iter().nth(index)
5138        })
5139    }
5140
5141    /// Create a keypath for key-based access in HashMap<K, V>
5142    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>>
5143    where
5144        K: std::hash::Hash + Eq + Clone + 'static,
5145        V: 'static,
5146    {
5147        OptionalKeyPath::new(move |map: &HashMap<K, V>| map.get(&key))
5148    }
5149
5150    /// Create a keypath for key-based access in BTreeMap<K, V>
5151    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>>
5152    where
5153        K: Ord + Clone + 'static,
5154        V: 'static,
5155    {
5156        OptionalKeyPath::new(move |map: &BTreeMap<K, V>| map.get(&key))
5157    }
5158
5159    /// Create a keypath for getting a value from HashSet<T> (returns Option<&T>)
5160    pub fn for_hashset_get<T>(value: T) -> OptionalKeyPath<HashSet<T>, T, impl for<'r> Fn(&'r HashSet<T>) -> Option<&'r T>>
5161    where
5162        T: std::hash::Hash + Eq + Clone + 'static,
5163    {
5164        OptionalKeyPath::new(move |set: &HashSet<T>| set.get(&value))
5165    }
5166
5167    /// Create a keypath for checking membership in BTreeSet<T>
5168    pub fn for_btreeset_get<T>(value: T) -> OptionalKeyPath<BTreeSet<T>, T, impl for<'r> Fn(&'r BTreeSet<T>) -> Option<&'r T>>
5169    where
5170        T: Ord + Clone + 'static,
5171    {
5172        OptionalKeyPath::new(move |set: &BTreeSet<T>| set.get(&value))
5173    }
5174
5175    /// Create a keypath for peeking at the top of BinaryHeap<T>
5176    pub fn for_binaryheap_peek<T>() -> OptionalKeyPath<BinaryHeap<T>, T, impl for<'r> Fn(&'r BinaryHeap<T>) -> Option<&'r T>>
5177    where
5178        T: Ord + 'static,
5179    {
5180        OptionalKeyPath::new(|heap: &BinaryHeap<T>| heap.peek())
5181    }
5182
5183    // ========== WRITABLE VERSIONS ==========
5184
5185    /// Create a writable keypath for indexed access in Vec<T>
5186    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>> {
5187        WritableOptionalKeyPath::new(move |vec: &mut Vec<T>| vec.get_mut(index))
5188    }
5189
5190    /// Create a writable keypath for indexed access in VecDeque<T>
5191    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>> {
5192        WritableOptionalKeyPath::new(move |deque: &mut VecDeque<T>| deque.get_mut(index))
5193    }
5194
5195    /// Create a writable keypath for indexed access in LinkedList<T>
5196    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>> {
5197        WritableOptionalKeyPath::new(move |list: &mut LinkedList<T>| {
5198            // LinkedList doesn't have get_mut, so we need to iterate
5199            let mut iter = list.iter_mut();
5200            iter.nth(index)
5201        })
5202    }
5203
5204    /// Create a writable keypath for key-based access in HashMap<K, V>
5205    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>>
5206    where
5207        K: std::hash::Hash + Eq + Clone + 'static,
5208        V: 'static,
5209    {
5210        WritableOptionalKeyPath::new(move |map: &mut HashMap<K, V>| map.get_mut(&key))
5211    }
5212
5213    /// Create a writable keypath for key-based access in BTreeMap<K, V>
5214    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>>
5215    where
5216        K: Ord + Clone + 'static,
5217        V: 'static,
5218    {
5219        WritableOptionalKeyPath::new(move |map: &mut BTreeMap<K, V>| map.get_mut(&key))
5220    }
5221
5222    /// Create a writable keypath for getting a mutable value from HashSet<T>
5223    /// Note: HashSet doesn't support mutable access to elements, but we provide it for consistency
5224    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>>
5225    where
5226        T: std::hash::Hash + Eq + Clone + 'static,
5227    {
5228        WritableOptionalKeyPath::new(move |set: &mut HashSet<T>| {
5229            // HashSet doesn't have get_mut, so we need to check and return None
5230            // This is a limitation of HashSet's design
5231            if set.contains(&value) {
5232                // We can't return a mutable reference to the value in the set
5233                // This is a fundamental limitation of HashSet
5234                None
5235            } else {
5236                None
5237            }
5238        })
5239    }
5240
5241    /// Create a writable keypath for getting a mutable value from BTreeSet<T>
5242    /// Note: BTreeSet doesn't support mutable access to elements, but we provide it for consistency
5243    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>>
5244    where
5245        T: Ord + Clone + 'static,
5246    {
5247        WritableOptionalKeyPath::new(move |set: &mut BTreeSet<T>| {
5248            // BTreeSet doesn't have get_mut, so we need to check and return None
5249            // This is a limitation of BTreeSet's design
5250            if set.contains(&value) {
5251                // We can't return a mutable reference to the value in the set
5252                // This is a fundamental limitation of BTreeSet
5253                None
5254            } else {
5255                None
5256            }
5257        })
5258    }
5259
5260    /// Create a writable keypath for peeking at the top of BinaryHeap<T>
5261    /// Note: BinaryHeap.peek_mut() returns PeekMut which is a guard type.
5262    /// Due to Rust's borrowing rules, we cannot return &mut T directly from PeekMut.
5263    /// This function returns None as BinaryHeap doesn't support direct mutable access
5264    /// through keypaths. Use heap.peek_mut() directly for mutable access.
5265    pub fn for_binaryheap_peek_mut<T>() -> WritableOptionalKeyPath<BinaryHeap<T>, T, impl for<'r> Fn(&'r mut BinaryHeap<T>) -> Option<&'r mut T>>
5266    where
5267        T: Ord + 'static,
5268    {
5269        // BinaryHeap.peek_mut() returns PeekMut which is a guard type that owns the mutable reference.
5270        // We cannot return &mut T from it due to lifetime constraints.
5271        // This is a fundamental limitation - use heap.peek_mut() directly instead.
5272        WritableOptionalKeyPath::new(|_heap: &mut BinaryHeap<T>| {
5273            None
5274        })
5275    }
5276
5277    // ========== SYNCHRONIZATION PRIMITIVES ==========
5278    // Note: Mutex and RwLock return guards that own the lock, not references.
5279    // We cannot create keypaths that return references from guards due to lifetime constraints.
5280    // These helper functions are provided for convenience, but direct lock()/read()/write() calls are recommended.
5281
5282    /// Helper function to lock a Mutex<T> and access its value
5283    /// Returns None if the mutex is poisoned
5284    /// Note: This returns a guard, not a reference, so it cannot be used in keypaths directly
5285    pub fn lock_mutex<T>(mutex: &Mutex<T>) -> Option<std::sync::MutexGuard<'_, T>> {
5286        mutex.lock().ok()
5287    }
5288
5289    /// Helper function to read-lock an RwLock<T> and access its value
5290    /// Returns None if the lock is poisoned
5291    /// Note: This returns a guard, not a reference, so it cannot be used in keypaths directly
5292    pub fn read_rwlock<T>(rwlock: &RwLock<T>) -> Option<std::sync::RwLockReadGuard<'_, T>> {
5293        rwlock.read().ok()
5294    }
5295
5296    /// Helper function to write-lock an RwLock<T> and access its value
5297    /// Returns None if the lock is poisoned
5298    /// Note: This returns a guard, not a reference, so it cannot be used in keypaths directly
5299    pub fn write_rwlock<T>(rwlock: &RwLock<T>) -> Option<std::sync::RwLockWriteGuard<'_, T>> {
5300        rwlock.write().ok()
5301    }
5302
5303    /// Helper function to lock an Arc<Mutex<T>> and access its value
5304    /// Returns None if the mutex is poisoned
5305    /// Note: This returns a guard, not a reference, so it cannot be used in keypaths directly
5306    pub fn lock_arc_mutex<T>(arc_mutex: &Arc<Mutex<T>>) -> Option<std::sync::MutexGuard<'_, T>> {
5307        arc_mutex.lock().ok()
5308    }
5309
5310    /// Helper function to read-lock an Arc<RwLock<T>> and access its value
5311    /// Returns None if the lock is poisoned
5312    /// Note: This returns a guard, not a reference, so it cannot be used in keypaths directly
5313    pub fn read_arc_rwlock<T>(arc_rwlock: &Arc<RwLock<T>>) -> Option<std::sync::RwLockReadGuard<'_, T>> {
5314        arc_rwlock.read().ok()
5315    }
5316
5317    /// Helper function to write-lock an Arc<RwLock<T>> and access its value
5318    /// Returns None if the lock is poisoned
5319    /// Note: This returns a guard, not a reference, so it cannot be used in keypaths directly
5320    pub fn write_arc_rwlock<T>(arc_rwlock: &Arc<RwLock<T>>) -> Option<std::sync::RwLockWriteGuard<'_, T>> {
5321        arc_rwlock.write().ok()
5322    }
5323
5324    /// Helper function to upgrade a Weak<T> to Arc<T>
5325    /// Returns None if the Arc has been dropped
5326    /// Note: This returns an owned Arc, not a reference, so it cannot be used in keypaths directly
5327    pub fn upgrade_weak<T>(weak: &StdWeak<T>) -> Option<Arc<T>> {
5328        weak.upgrade()
5329    }
5330
5331    /// Helper function to upgrade an Rc::Weak<T> to Rc<T>
5332    /// Returns None if the Rc has been dropped
5333    /// Note: This returns an owned Rc, not a reference, so it cannot be used in keypaths directly
5334    pub fn upgrade_rc_weak<T>(weak: &RcWeak<T>) -> Option<Rc<T>> {
5335        weak.upgrade()
5336    }
5337
5338    #[cfg(feature = "parking_lot")]
5339    /// Helper function to lock a parking_lot::Mutex<T> and access its value
5340    /// Note: This returns a guard, not a reference, so it cannot be used in keypaths directly
5341    pub fn lock_parking_mutex<T>(mutex: &ParkingMutex<T>) -> parking_lot::MutexGuard<'_, T> {
5342        mutex.lock()
5343    }
5344
5345    #[cfg(feature = "parking_lot")]
5346    /// Helper function to read-lock a parking_lot::RwLock<T> and access its value
5347    /// Note: This returns a guard, not a reference, so it cannot be used in keypaths directly
5348    pub fn read_parking_rwlock<T>(rwlock: &ParkingRwLock<T>) -> parking_lot::RwLockReadGuard<'_, T> {
5349        rwlock.read()
5350    }
5351
5352    #[cfg(feature = "parking_lot")]
5353    /// Helper function to write-lock a parking_lot::RwLock<T> and access its value
5354    /// Note: This returns a guard, not a reference, so it cannot be used in keypaths directly
5355    pub fn write_parking_rwlock<T>(rwlock: &ParkingRwLock<T>) -> parking_lot::RwLockWriteGuard<'_, T> {
5356        rwlock.write()
5357    }
5358
5359    #[cfg(feature = "tagged")]
5360    /// Create a keypath for accessing the inner value of Tagged<Tag, T>
5361    /// Tagged implements Deref, so we can access the inner value directly
5362    pub fn for_tagged<Tag, T>() -> KeyPath<Tagged<Tag, T>, T, impl for<'r> Fn(&'r Tagged<Tag, T>) -> &'r T>
5363    where
5364        Tagged<Tag, T>: std::ops::Deref<Target = T>,
5365        Tag: 'static,
5366        T: 'static,
5367    {
5368        KeyPath::new(|tagged: &Tagged<Tag, T>| tagged.deref())
5369    }
5370
5371    #[cfg(feature = "tagged")]
5372    /// Create a writable keypath for accessing the inner value of Tagged<Tag, T>
5373    /// Tagged implements DerefMut, so we can access the inner value directly
5374    pub fn for_tagged_mut<Tag, T>() -> WritableKeyPath<Tagged<Tag, T>, T, impl for<'r> Fn(&'r mut Tagged<Tag, T>) -> &'r mut T>
5375    where
5376        Tagged<Tag, T>: std::ops::DerefMut<Target = T>,
5377        Tag: 'static,
5378        T: 'static,
5379    {
5380        WritableKeyPath::new(|tagged: &mut Tagged<Tag, T>| tagged.deref_mut())
5381    }
5382}
5383
5384// ========== PARKING_LOT CHAIN METHODS FOR KEYPATH ==========
5385
5386#[cfg(feature = "parking_lot")]
5387impl<Root, InnerValue, F> KeyPath<Root, Arc<parking_lot::Mutex<InnerValue>>, F>
5388where
5389    F: for<'r> Fn(&'r Root) -> &'r Arc<parking_lot::Mutex<InnerValue>>,
5390{
5391    /// Chain this keypath with an inner keypath through Arc<parking_lot::Mutex<T>> - functional style
5392    pub fn then_arc_parking_mutex_at_kp<SubValue, G>(
5393        self,
5394        inner_keypath: KeyPath<InnerValue, SubValue, G>,
5395    ) -> ArcParkingMutexKeyPathChain<Root, InnerValue, SubValue, F, G>
5396    where
5397        G: for<'r> Fn(&'r InnerValue) -> &'r SubValue,
5398    {
5399        ArcParkingMutexKeyPathChain {
5400            outer_keypath: self,
5401            inner_keypath,
5402        }
5403    }
5404    
5405    /// Chain this keypath with an optional inner keypath through Arc<parking_lot::Mutex<T>>
5406    pub fn then_arc_parking_mutex_optional_at_kp<SubValue, G>(
5407        self,
5408        inner_keypath: OptionalKeyPath<InnerValue, SubValue, G>,
5409    ) -> ArcParkingMutexOptionalKeyPathChain<Root, InnerValue, SubValue, F, G>
5410    where
5411        G: for<'r> Fn(&'r InnerValue) -> Option<&'r SubValue>,
5412    {
5413        ArcParkingMutexOptionalKeyPathChain {
5414            outer_keypath: self,
5415            inner_keypath,
5416        }
5417    }
5418    
5419    /// Chain this keypath with a writable inner keypath through Arc<parking_lot::Mutex<T>>
5420    pub fn then_arc_parking_mutex_writable_at_kp<SubValue, G>(
5421        self,
5422        inner_keypath: WritableKeyPath<InnerValue, SubValue, G>,
5423    ) -> ArcParkingMutexWritableKeyPathChain<Root, InnerValue, SubValue, F, G>
5424    where
5425        G: for<'r> Fn(&'r mut InnerValue) -> &'r mut SubValue,
5426    {
5427        ArcParkingMutexWritableKeyPathChain {
5428            outer_keypath: self,
5429            inner_keypath,
5430        }
5431    }
5432    
5433    /// Chain this keypath with a writable optional inner keypath through Arc<parking_lot::Mutex<T>>
5434    pub fn then_arc_parking_mutex_writable_optional_at_kp<SubValue, G>(
5435        self,
5436        inner_keypath: WritableOptionalKeyPath<InnerValue, SubValue, G>,
5437    ) -> ArcParkingMutexWritableOptionalKeyPathChain<Root, InnerValue, SubValue, F, G>
5438    where
5439        G: for<'r> Fn(&'r mut InnerValue) -> Option<&'r mut SubValue>,
5440    {
5441        ArcParkingMutexWritableOptionalKeyPathChain {
5442            outer_keypath: self,
5443            inner_keypath,
5444        }
5445    }
5446}
5447
5448#[cfg(feature = "parking_lot")]
5449impl<Root, InnerValue, F> KeyPath<Root, Arc<parking_lot::RwLock<InnerValue>>, F>
5450where
5451    F: for<'r> Fn(&'r Root) -> &'r Arc<parking_lot::RwLock<InnerValue>>,
5452{
5453    /// Chain this keypath with an inner keypath through Arc<parking_lot::RwLock<T>> - functional style
5454    pub fn then_arc_parking_rwlock_at_kp<SubValue, G>(
5455        self,
5456        inner_keypath: KeyPath<InnerValue, SubValue, G>,
5457    ) -> ArcParkingRwLockKeyPathChain<Root, InnerValue, SubValue, F, G>
5458    where
5459        G: for<'r> Fn(&'r InnerValue) -> &'r SubValue,
5460    {
5461        ArcParkingRwLockKeyPathChain {
5462            outer_keypath: self,
5463            inner_keypath,
5464        }
5465    }
5466    
5467    /// Chain this keypath with an optional inner keypath through Arc<parking_lot::RwLock<T>>
5468    pub fn then_arc_parking_rwlock_optional_at_kp<SubValue, G>(
5469        self,
5470        inner_keypath: OptionalKeyPath<InnerValue, SubValue, G>,
5471    ) -> ArcParkingRwLockOptionalKeyPathChain<Root, InnerValue, SubValue, F, G>
5472    where
5473        G: for<'r> Fn(&'r InnerValue) -> Option<&'r SubValue>,
5474    {
5475        ArcParkingRwLockOptionalKeyPathChain {
5476            outer_keypath: self,
5477            inner_keypath,
5478        }
5479    }
5480    
5481    /// Chain this keypath with a writable inner keypath through Arc<parking_lot::RwLock<T>>
5482    pub fn then_arc_parking_rwlock_writable_at_kp<SubValue, G>(
5483        self,
5484        inner_keypath: WritableKeyPath<InnerValue, SubValue, G>,
5485    ) -> ArcParkingRwLockWritableKeyPathChain<Root, InnerValue, SubValue, F, G>
5486    where
5487        G: for<'r> Fn(&'r mut InnerValue) -> &'r mut SubValue,
5488    {
5489        ArcParkingRwLockWritableKeyPathChain {
5490            outer_keypath: self,
5491            inner_keypath,
5492        }
5493    }
5494    
5495    /// Chain this keypath with a writable optional inner keypath through Arc<parking_lot::RwLock<T>>
5496    pub fn then_arc_parking_rwlock_writable_optional_at_kp<SubValue, G>(
5497        self,
5498        inner_keypath: WritableOptionalKeyPath<InnerValue, SubValue, G>,
5499    ) -> ArcParkingRwLockWritableOptionalKeyPathChain<Root, InnerValue, SubValue, F, G>
5500    where
5501        G: for<'r> Fn(&'r mut InnerValue) -> Option<&'r mut SubValue>,
5502    {
5503        ArcParkingRwLockWritableOptionalKeyPathChain {
5504            outer_keypath: self,
5505            inner_keypath,
5506        }
5507    }
5508}
5509
5510// OptionalKeyPath for Option<T>
5511#[derive(Clone)]
5512pub struct OptionalKeyPath<Root, Value, F>
5513where
5514    F: for<'r> Fn(&'r Root) -> Option<&'r Value>,
5515{
5516    getter: F,
5517    _phantom: PhantomData<(Root, Value)>,
5518}
5519
5520impl<Root, Value, F> fmt::Display for OptionalKeyPath<Root, Value, F>
5521where
5522    F: for<'r> Fn(&'r Root) -> Option<&'r Value>,
5523{
5524    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
5525        let root_name = std::any::type_name::<Root>();
5526        let value_name = std::any::type_name::<Value>();
5527        // Simplify type names by removing module paths for cleaner output
5528        let root_short = root_name.split("::").last().unwrap_or(root_name);
5529        let value_short = value_name.split("::").last().unwrap_or(value_name);
5530        write!(f, "OptionalKeyPath<{} -> Option<{}>>", root_short, value_short)
5531    }
5532}
5533
5534impl<Root, Value, F> fmt::Debug for OptionalKeyPath<Root, Value, F>
5535where
5536    F: for<'r> Fn(&'r Root) -> Option<&'r Value>,
5537{
5538    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
5539        fmt::Display::fmt(self, f)
5540    }
5541}
5542
5543impl<Root, Value, F> OptionalKeyPath<Root, Value, F>
5544where
5545    F: for<'r> Fn(&'r Root) -> Option<&'r Value>,
5546{
5547    pub fn new(getter: F) -> Self {
5548        Self {
5549            getter,
5550            _phantom: PhantomData,
5551        }
5552    }
5553    
5554    pub fn get<'r>(&self, root: &'r Root) -> Option<&'r Value> {
5555        (self.getter)(root)
5556    }
5557    
5558    /// Chain this optional keypath with an inner keypath through Arc<Mutex<T>> - functional style
5559    /// Compose first, then apply container at get() time
5560    /// 
5561    /// # Example
5562    /// ```rust
5563    /// let container = ContainerTest { mutex_data: Some(Arc::new(Mutex::new(SomeStruct { data: "test".to_string() }))) };
5564    /// 
5565    /// // Functional style: compose first, apply container at get()
5566    /// ContainerTest::mutex_data_fr()
5567    ///     .chain_arc_mutex_at_kp(SomeStruct::data_r())
5568    ///     .get(&container, |value| println!("Data: {}", value));
5569    /// ```
5570    pub fn chain_arc_mutex_at_kp<InnerValue, SubValue, G>(
5571        self,
5572        inner_keypath: KeyPath<InnerValue, SubValue, G>,
5573    ) -> OptionalArcMutexKeyPathChain<Root, Value, InnerValue, SubValue, F, G>
5574    where
5575        G: for<'r> Fn(&'r InnerValue) -> &'r SubValue,
5576    {
5577        OptionalArcMutexKeyPathChain {
5578            outer_keypath: self,
5579            inner_keypath,
5580        }
5581    }
5582    
5583    /// Chain this optional keypath with an optional inner keypath through Arc<Mutex<T>> - functional style
5584    /// Compose first, then apply container at get() time
5585    /// 
5586    /// # Example
5587    /// ```rust
5588    /// let container = ContainerTest { mutex_data: Some(Arc::new(Mutex::new(SomeStruct { optional_field: Some("test".to_string()) }))) };
5589    /// 
5590    /// // Functional style: compose first, apply container at get()
5591    /// ContainerTest::mutex_data_fr()
5592    ///     .chain_arc_mutex_optional_at_kp(SomeStruct::optional_field_fr())
5593    ///     .get(&container, |value| println!("Value: {}", value));
5594    /// ```
5595    pub fn chain_arc_mutex_optional_at_kp<InnerValue, SubValue, G>(
5596        self,
5597        inner_keypath: OptionalKeyPath<InnerValue, SubValue, G>,
5598    ) -> OptionalArcMutexOptionalKeyPathChain<Root, Value, InnerValue, SubValue, F, G>
5599    where
5600        G: for<'r> Fn(&'r InnerValue) -> Option<&'r SubValue>,
5601    {
5602        OptionalArcMutexOptionalKeyPathChain {
5603            outer_keypath: self,
5604            inner_keypath,
5605        }
5606    }
5607    
5608    /// Chain this optional keypath with an inner keypath through Arc<RwLock<T>> - functional style
5609    /// Compose first, then apply container at get() time (uses read lock)
5610    /// 
5611    /// # Example
5612    /// ```rust
5613    /// let container = ContainerTest { rwlock_data: Some(Arc::new(RwLock::new(SomeStruct { data: "test".to_string() }))) };
5614    /// 
5615    /// // Functional style: compose first, apply container at get()
5616    /// ContainerTest::rwlock_data_fr()
5617    ///     .chain_arc_rwlock_at_kp(SomeStruct::data_r())
5618    ///     .get(&container, |value| println!("Data: {}", value));
5619    /// ```
5620    pub fn chain_arc_rwlock_at_kp<InnerValue, SubValue, G>(
5621        self,
5622        inner_keypath: KeyPath<InnerValue, SubValue, G>,
5623    ) -> OptionalArcRwLockKeyPathChain<Root, Value, InnerValue, SubValue, F, G>
5624    where
5625        G: for<'r> Fn(&'r InnerValue) -> &'r SubValue,
5626    {
5627        OptionalArcRwLockKeyPathChain {
5628            outer_keypath: self,
5629            inner_keypath,
5630        }
5631    }
5632    
5633    /// Chain this optional keypath with an optional inner keypath through Arc<RwLock<T>> - functional style
5634    /// Compose first, then apply container at get() time (uses read lock)
5635    /// 
5636    /// # Example
5637    /// ```rust
5638    /// let container = ContainerTest { rwlock_data: Some(Arc::new(RwLock::new(SomeStruct { optional_field: Some("test".to_string()) }))) };
5639    /// 
5640    /// // Functional style: compose first, apply container at get()
5641    /// ContainerTest::rwlock_data_fr()
5642    ///     .chain_arc_rwlock_optional_at_kp(SomeStruct::optional_field_fr())
5643    ///     .get(&container, |value| println!("Value: {}", value));
5644    /// ```
5645    pub fn chain_arc_rwlock_optional_at_kp<InnerValue, SubValue, G>(
5646        self,
5647        inner_keypath: OptionalKeyPath<InnerValue, SubValue, G>,
5648    ) -> OptionalArcRwLockOptionalKeyPathChain<Root, Value, InnerValue, SubValue, F, G>
5649    where
5650        G: for<'r> Fn(&'r InnerValue) -> Option<&'r SubValue>,
5651    {
5652        OptionalArcRwLockOptionalKeyPathChain {
5653            outer_keypath: self,
5654            inner_keypath,
5655        }
5656    }
5657    
5658    /// Chain this optional keypath with a writable inner keypath through Arc<Mutex<T>> - functional style
5659    /// Compose first, then apply container at get_mut() time
5660    /// 
5661    /// # Example
5662    /// ```rust
5663    /// let container = ContainerTest { mutex_data: Some(Arc::new(Mutex::new(SomeStruct { data: "test".to_string() }))) };
5664    /// 
5665    /// // Functional style: compose first, apply container at get_mut()
5666    /// ContainerTest::mutex_data_fr()
5667    ///     .chain_arc_mutex_writable_at_kp(SomeStruct::data_w())
5668    ///     .get_mut(&container, |value| *value = "new".to_string());
5669    /// ```
5670    pub fn chain_arc_mutex_writable_at_kp<InnerValue, SubValue, G>(
5671        self,
5672        inner_keypath: WritableKeyPath<InnerValue, SubValue, G>,
5673    ) -> OptionalArcMutexWritableKeyPathChain<Root, Value, InnerValue, SubValue, F, G>
5674    where
5675        G: for<'r> Fn(&'r mut InnerValue) -> &'r mut SubValue,
5676    {
5677        OptionalArcMutexWritableKeyPathChain {
5678            outer_keypath: self,
5679            inner_keypath,
5680        }
5681    }
5682    
5683    /// Chain this optional keypath with a writable optional inner keypath through Arc<Mutex<T>> - functional style
5684    /// Compose first, then apply container at get_mut() time
5685    /// 
5686    /// # Example
5687    /// ```rust
5688    /// let container = ContainerTest { mutex_data: Some(Arc::new(Mutex::new(SomeStruct { optional_field: Some("test".to_string()) }))) };
5689    /// 
5690    /// // Functional style: compose first, apply container at get_mut()
5691    /// ContainerTest::mutex_data_fr()
5692    ///     .chain_arc_mutex_writable_optional_at_kp(SomeStruct::optional_field_fw())
5693    ///     .get_mut(&container, |value| *value = "new".to_string());
5694    /// ```
5695    pub fn chain_arc_mutex_writable_optional_at_kp<InnerValue, SubValue, G>(
5696        self,
5697        inner_keypath: WritableOptionalKeyPath<InnerValue, SubValue, G>,
5698    ) -> OptionalArcMutexWritableOptionalKeyPathChain<Root, Value, InnerValue, SubValue, F, G>
5699    where
5700        G: for<'r> Fn(&'r mut InnerValue) -> Option<&'r mut SubValue>,
5701    {
5702        OptionalArcMutexWritableOptionalKeyPathChain {
5703            outer_keypath: self,
5704            inner_keypath,
5705        }
5706    }
5707    
5708    /// Chain this optional keypath with a writable inner keypath through Arc<RwLock<T>> - functional style
5709    /// Compose first, then apply container at get_mut() time (uses write lock)
5710    /// 
5711    /// # Example
5712    /// ```rust
5713    /// let container = ContainerTest { rwlock_data: Some(Arc::new(RwLock::new(SomeStruct { data: "test".to_string() }))) };
5714    /// 
5715    /// // Functional style: compose first, apply container at get_mut()
5716    /// ContainerTest::rwlock_data_fr()
5717    ///     .chain_arc_rwlock_writable_at_kp(SomeStruct::data_w())
5718    ///     .get_mut(&container, |value| *value = "new".to_string());
5719    /// ```
5720    pub fn chain_arc_rwlock_writable_at_kp<InnerValue, SubValue, G>(
5721        self,
5722        inner_keypath: WritableKeyPath<InnerValue, SubValue, G>,
5723    ) -> OptionalArcRwLockWritableKeyPathChain<Root, Value, InnerValue, SubValue, F, G>
5724    where
5725        G: for<'r> Fn(&'r mut InnerValue) -> &'r mut SubValue,
5726    {
5727        OptionalArcRwLockWritableKeyPathChain {
5728            outer_keypath: self,
5729            inner_keypath,
5730        }
5731    }
5732    
5733    /// Chain this optional keypath with a writable optional inner keypath through Arc<RwLock<T>> - functional style
5734    /// Compose first, then apply container at get_mut() time (uses write lock)
5735    /// 
5736    /// # Example
5737    /// ```rust
5738    /// let container = ContainerTest { rwlock_data: Some(Arc::new(RwLock::new(SomeStruct { optional_field: Some("test".to_string()) }))) };
5739    /// 
5740    /// // Functional style: compose first, apply container at get_mut()
5741    /// ContainerTest::rwlock_data_fr()
5742    ///     .chain_arc_rwlock_writable_optional_at_kp(SomeStruct::optional_field_fw())
5743    ///     .get_mut(&container, |value| *value = "new".to_string());
5744    /// ```
5745    pub fn chain_arc_rwlock_writable_optional_at_kp<InnerValue, SubValue, G>(
5746        self,
5747        inner_keypath: WritableOptionalKeyPath<InnerValue, SubValue, G>,
5748    ) -> OptionalArcRwLockWritableOptionalKeyPathChain<Root, Value, InnerValue, SubValue, F, G>
5749    where
5750        G: for<'r> Fn(&'r mut InnerValue) -> Option<&'r mut SubValue>,
5751    {
5752        OptionalArcRwLockWritableOptionalKeyPathChain {
5753            outer_keypath: self,
5754            inner_keypath,
5755        }
5756    }
5757
5758    #[cfg(feature = "tokio")]
5759    /// Chain this optional keypath with an inner keypath through Arc<tokio::sync::Mutex<T>> - functional style (async)
5760    pub fn chain_arc_tokio_mutex_at_kp<InnerValue, SubValue, G>(
5761        self,
5762        inner_keypath: KeyPath<InnerValue, SubValue, G>,
5763    ) -> OptionalArcTokioMutexKeyPathChain<Root, Value, InnerValue, SubValue, F, G>
5764    where
5765        Value: std::borrow::Borrow<Arc<tokio::sync::Mutex<InnerValue>>>,
5766        G: for<'r> Fn(&'r InnerValue) -> &'r SubValue,
5767    {
5768        OptionalArcTokioMutexKeyPathChain {
5769            outer_keypath: self,
5770            inner_keypath,
5771        }
5772    }
5773
5774    #[cfg(feature = "tokio")]
5775    /// Chain this optional keypath with an optional inner keypath through Arc<tokio::sync::Mutex<T>> - functional style (async)
5776    pub fn chain_arc_tokio_mutex_optional_at_kp<InnerValue, SubValue, G>(
5777        self,
5778        inner_keypath: OptionalKeyPath<InnerValue, SubValue, G>,
5779    ) -> OptionalArcTokioMutexOptionalKeyPathChain<Root, Value, InnerValue, SubValue, F, G>
5780    where
5781        Value: std::borrow::Borrow<Arc<tokio::sync::Mutex<InnerValue>>>,
5782        G: for<'r> Fn(&'r InnerValue) -> Option<&'r SubValue>,
5783    {
5784        OptionalArcTokioMutexOptionalKeyPathChain {
5785            outer_keypath: self,
5786            inner_keypath,
5787        }
5788    }
5789
5790    #[cfg(feature = "tokio")]
5791    /// Chain this optional keypath with a writable inner keypath through Arc<tokio::sync::Mutex<T>> - functional style (async)
5792    pub fn chain_arc_tokio_mutex_writable_at_kp<InnerValue, SubValue, G>(
5793        self,
5794        inner_keypath: WritableKeyPath<InnerValue, SubValue, G>,
5795    ) -> OptionalArcTokioMutexWritableKeyPathChain<Root, Value, InnerValue, SubValue, F, G>
5796    where
5797        Value: std::borrow::Borrow<Arc<tokio::sync::Mutex<InnerValue>>>,
5798        G: for<'r> Fn(&'r mut InnerValue) -> &'r mut SubValue,
5799    {
5800        OptionalArcTokioMutexWritableKeyPathChain {
5801            outer_keypath: self,
5802            inner_keypath,
5803        }
5804    }
5805
5806    #[cfg(feature = "tokio")]
5807    /// Chain this optional keypath with a writable optional inner keypath through Arc<tokio::sync::Mutex<T>> - functional style (async)
5808    pub fn chain_arc_tokio_mutex_writable_optional_at_kp<InnerValue, SubValue, G>(
5809        self,
5810        inner_keypath: WritableOptionalKeyPath<InnerValue, SubValue, G>,
5811    ) -> OptionalArcTokioMutexWritableOptionalKeyPathChain<Root, Value, InnerValue, SubValue, F, G>
5812    where
5813        Value: std::borrow::Borrow<Arc<tokio::sync::Mutex<InnerValue>>>,
5814        G: for<'r> Fn(&'r mut InnerValue) -> Option<&'r mut SubValue>,
5815    {
5816        OptionalArcTokioMutexWritableOptionalKeyPathChain {
5817            outer_keypath: self,
5818            inner_keypath,
5819        }
5820    }
5821
5822    #[cfg(feature = "tokio")]
5823    /// Chain this optional keypath with an inner keypath through Arc<tokio::sync::RwLock<T>> - functional style (async, read lock)
5824    pub fn chain_arc_tokio_rwlock_at_kp<InnerValue, SubValue, G>(
5825        self,
5826        inner_keypath: KeyPath<InnerValue, SubValue, G>,
5827    ) -> OptionalArcTokioRwLockKeyPathChain<Root, Value, InnerValue, SubValue, F, G>
5828    where
5829        Value: std::borrow::Borrow<Arc<tokio::sync::RwLock<InnerValue>>>,
5830        G: for<'r> Fn(&'r InnerValue) -> &'r SubValue,
5831    {
5832        OptionalArcTokioRwLockKeyPathChain {
5833            outer_keypath: self,
5834            inner_keypath,
5835        }
5836    }
5837
5838    #[cfg(feature = "tokio")]
5839    /// Chain this optional keypath with an optional inner keypath through Arc<tokio::sync::RwLock<T>> - functional style (async, read lock)
5840    pub fn chain_arc_tokio_rwlock_optional_at_kp<InnerValue, SubValue, G>(
5841        self,
5842        inner_keypath: OptionalKeyPath<InnerValue, SubValue, G>,
5843    ) -> OptionalArcTokioRwLockOptionalKeyPathChain<Root, Value, InnerValue, SubValue, F, G>
5844    where
5845        Value: std::borrow::Borrow<Arc<tokio::sync::RwLock<InnerValue>>>,
5846        G: for<'r> Fn(&'r InnerValue) -> Option<&'r SubValue>,
5847    {
5848        OptionalArcTokioRwLockOptionalKeyPathChain {
5849            outer_keypath: self,
5850            inner_keypath,
5851        }
5852    }
5853
5854    #[cfg(feature = "tokio")]
5855    /// Chain this optional keypath with a writable inner keypath through Arc<tokio::sync::RwLock<T>> - functional style (async, write lock)
5856    pub fn chain_arc_tokio_rwlock_writable_at_kp<InnerValue, SubValue, G>(
5857        self,
5858        inner_keypath: WritableKeyPath<InnerValue, SubValue, G>,
5859    ) -> OptionalArcTokioRwLockWritableKeyPathChain<Root, Value, InnerValue, SubValue, F, G>
5860    where
5861        Value: std::borrow::Borrow<Arc<tokio::sync::RwLock<InnerValue>>>,
5862        G: for<'r> Fn(&'r mut InnerValue) -> &'r mut SubValue,
5863    {
5864        OptionalArcTokioRwLockWritableKeyPathChain {
5865            outer_keypath: self,
5866            inner_keypath,
5867        }
5868    }
5869
5870    #[cfg(feature = "tokio")]
5871    /// Chain this optional keypath with a writable optional inner keypath through Arc<tokio::sync::RwLock<T>> - functional style (async, write lock)
5872    pub fn chain_arc_tokio_rwlock_writable_optional_at_kp<InnerValue, SubValue, G>(
5873        self,
5874        inner_keypath: WritableOptionalKeyPath<InnerValue, SubValue, G>,
5875    ) -> OptionalArcTokioRwLockWritableOptionalKeyPathChain<Root, Value, InnerValue, SubValue, F, G>
5876    where
5877        Value: std::borrow::Borrow<Arc<tokio::sync::RwLock<InnerValue>>>,
5878        G: for<'r> Fn(&'r mut InnerValue) -> Option<&'r mut SubValue>,
5879    {
5880        OptionalArcTokioRwLockWritableOptionalKeyPathChain {
5881            outer_keypath: self,
5882            inner_keypath,
5883        }
5884    }
5885    
5886    // Swift-like operator for chaining OptionalKeyPath
5887    pub fn then<SubValue, G>(
5888        self,
5889        next: OptionalKeyPath<Value, SubValue, G>,
5890    ) -> OptionalKeyPath<Root, SubValue, impl for<'r> Fn(&'r Root) -> Option<&'r SubValue>>
5891    where
5892        G: for<'r> Fn(&'r Value) -> Option<&'r SubValue>,
5893        F: 'static,
5894        G: 'static,
5895        Value: 'static,
5896    {
5897        let first = self.getter;
5898        let second = next.getter;
5899        
5900        OptionalKeyPath::new(move |root: &Root| {
5901            first(root).and_then(|value| second(value))
5902        })
5903    }
5904    
5905    // Instance methods for unwrapping containers from Option<Container<T>>
5906    // Option<Box<T>> -> Option<&T> (type automatically inferred from Value::Target)
5907    pub fn for_box<Target>(self) -> OptionalKeyPath<Root, Target, impl for<'r> Fn(&'r Root) -> Option<&'r Target> + 'static>
5908    where
5909        Value: std::ops::Deref<Target = Target>,
5910        F: 'static,
5911        Value: 'static,
5912    {
5913        let getter = self.getter;
5914        
5915        OptionalKeyPath {
5916            getter: move |root: &Root| {
5917                getter(root).map(|boxed| boxed.deref())
5918            },
5919            _phantom: PhantomData,
5920        }
5921    }
5922    
5923    // Option<Arc<T>> -> Option<&T> (type automatically inferred from Value::Target)
5924    pub fn for_arc<Target>(self) -> OptionalKeyPath<Root, Target, impl for<'r> Fn(&'r Root) -> Option<&'r Target> + 'static>
5925    where
5926        Value: std::ops::Deref<Target = Target>,
5927        F: 'static,
5928        Value: 'static,
5929    {
5930        let getter = self.getter;
5931        
5932        OptionalKeyPath {
5933            getter: move |root: &Root| {
5934                getter(root).map(|arc| arc.deref())
5935            },
5936            _phantom: PhantomData,
5937        }
5938    }
5939    
5940    // Option<Rc<T>> -> Option<&T> (type automatically inferred from Value::Target)
5941    pub fn for_rc<Target>(self) -> OptionalKeyPath<Root, Target, impl for<'r> Fn(&'r Root) -> Option<&'r Target> + 'static>
5942    where
5943        Value: std::ops::Deref<Target = Target>,
5944        F: 'static,
5945        Value: 'static,
5946    {
5947        let getter = self.getter;
5948        
5949        OptionalKeyPath {
5950            getter: move |root: &Root| {
5951                getter(root).map(|rc| rc.deref())
5952            },
5953            _phantom: PhantomData,
5954        }
5955    }
5956    
5957    #[cfg(feature = "tagged")]
5958    /// Adapt this keypath to work with Tagged<Root, Tag> instead of Root
5959    /// This unwraps the Tagged wrapper and applies the keypath to the inner value
5960    pub fn for_tagged<Tag>(self) -> OptionalKeyPath<Tagged<Root, Tag>, Value, impl for<'r> Fn(&'r Tagged<Root, Tag>) -> Option<&'r Value> + 'static>
5961    where
5962        Tagged<Root, Tag>: std::ops::Deref<Target = Root>,
5963        F: 'static,
5964        Root: 'static,
5965        Value: 'static,
5966        Tag: 'static,
5967    {
5968        use std::ops::Deref;
5969        let getter = self.getter;
5970        
5971        OptionalKeyPath {
5972            getter: move |tagged: &Tagged<Root, Tag>| {
5973                getter(tagged.deref())
5974            },
5975            _phantom: PhantomData,
5976        }
5977    }
5978    
5979    #[cfg(feature = "tagged")]
5980    /// Execute a closure with a reference to the value inside a Tagged
5981    /// This avoids cloning by working with references directly
5982    pub fn with_tagged<Tag, Callback, R>(&self, tagged: &Tagged<Root, Tag>, f: Callback) -> Option<R>
5983    where
5984        Tagged<Root, Tag>: std::ops::Deref<Target = Root>,
5985        F: Clone,
5986        Callback: FnOnce(&Value) -> R,
5987    {
5988        use std::ops::Deref;
5989        self.get(tagged.deref()).map(|value| f(value))
5990    }
5991    
5992    /// Adapt this keypath to work with Option<Root> instead of Root
5993    /// This unwraps the Option and applies the keypath to the inner value
5994    pub fn for_option(self) -> OptionalKeyPath<Option<Root>, Value, impl for<'r> Fn(&'r Option<Root>) -> Option<&'r Value> + 'static>
5995    where
5996        F: 'static,
5997        Root: 'static,
5998        Value: 'static,
5999    {
6000        let getter = self.getter;
6001        
6002        OptionalKeyPath {
6003            getter: move |opt: &Option<Root>| {
6004                opt.as_ref().and_then(|root| getter(root))
6005            },
6006            _phantom: PhantomData,
6007        }
6008    }
6009    
6010    /// Adapt this keypath to work with Result<Root, E> instead of Root
6011    /// This unwraps the Result and applies the keypath to the Ok value
6012    pub fn for_result<E>(self) -> OptionalKeyPath<Result<Root, E>, Value, impl for<'r> Fn(&'r Result<Root, E>) -> Option<&'r Value> + 'static>
6013    where
6014        F: 'static,
6015        Root: 'static,
6016        Value: 'static,
6017        E: 'static,
6018    {
6019        let getter = self.getter;
6020        
6021        OptionalKeyPath {
6022            getter: move |result: &Result<Root, E>| {
6023                result.as_ref().ok().and_then(|root| getter(root))
6024            },
6025            _phantom: PhantomData,
6026        }
6027    }
6028
6029    // ========== LOCK KEYPATH CONVERSION METHODS ==========
6030    // These methods convert keypaths pointing to lock types into chain-ready keypaths
6031
6032    /// Convert this optional keypath to an Arc<RwLock> chain-ready keypath
6033    /// Returns self, but serves as a marker for intent and enables chaining
6034    pub fn to_arc_rwlock_kp<InnerValue>(self) -> Self
6035    where
6036        Value: std::borrow::Borrow<Arc<RwLock<InnerValue>>>,
6037    {
6038        self
6039    }
6040
6041    /// Convert this optional keypath to an Arc<Mutex> chain-ready keypath
6042    /// Returns self, but serves as a marker for intent and enables chaining
6043    pub fn to_arc_mutex_kp<InnerValue>(self) -> Self
6044    where
6045        Value: std::borrow::Borrow<Arc<Mutex<InnerValue>>>,
6046    {
6047        self
6048    }
6049
6050    #[cfg(feature = "parking_lot")]
6051    /// Convert this optional keypath to an Arc<parking_lot::RwLock> chain-ready keypath
6052    /// Returns self, but serves as a marker for intent and enables chaining
6053    pub fn to_arc_parking_rwlock_kp<InnerValue>(self) -> Self
6054    where
6055        Value: std::borrow::Borrow<Arc<parking_lot::RwLock<InnerValue>>>,
6056    {
6057        self
6058    }
6059
6060    #[cfg(feature = "parking_lot")]
6061    /// Convert this optional keypath to an Arc<parking_lot::Mutex> chain-ready keypath
6062    /// Returns self, but serves as a marker for intent and enables chaining
6063    pub fn to_arc_parking_mutex_kp<InnerValue>(self) -> Self
6064    where
6065        Value: std::borrow::Borrow<Arc<parking_lot::Mutex<InnerValue>>>,
6066    {
6067        self
6068    }
6069
6070    /// Convert this optional keypath to an Arc<RwLock> chain keypath
6071    /// Creates a chain with an identity inner keypath, ready for further chaining
6072    /// Type inference automatically determines InnerValue from Value
6073    pub fn to_arc_rwlock_chain<InnerValue>(self) -> OptionalArcRwLockKeyPathChain<Root, Value, InnerValue, InnerValue, F, impl for<'r> Fn(&'r InnerValue) -> &'r InnerValue + 'static>
6074    where
6075        Value: std::borrow::Borrow<Arc<RwLock<InnerValue>>>,
6076        F: 'static,
6077        InnerValue: 'static,
6078    {
6079        let identity = KeyPath::new(|inner: &InnerValue| inner);
6080        OptionalArcRwLockKeyPathChain {
6081            outer_keypath: self,
6082            inner_keypath: identity,
6083        }
6084    }
6085
6086    /// Convert this optional keypath to an Arc<Mutex> chain keypath
6087    /// Creates a chain with an identity inner keypath, ready for further chaining
6088    /// Type inference automatically determines InnerValue from Value
6089    pub fn to_arc_mutex_chain<InnerValue>(self) -> OptionalArcMutexKeyPathChain<Root, Value, InnerValue, InnerValue, F, impl for<'r> Fn(&'r InnerValue) -> &'r InnerValue + 'static>
6090    where
6091        Value: std::borrow::Borrow<Arc<Mutex<InnerValue>>>,
6092        F: 'static,
6093        InnerValue: 'static,
6094    {
6095        let identity = KeyPath::new(|inner: &InnerValue| inner);
6096        OptionalArcMutexKeyPathChain {
6097            outer_keypath: self,
6098            inner_keypath: identity,
6099        }
6100    }
6101
6102    // #[cfg(feature = "parking_lot")]
6103    // /// Convert this optional keypath to an Arc<parking_lot::RwLock> chain keypath
6104    // /// Creates a chain with an identity inner keypath, ready for further chaining
6105    // /// Type inference automatically determines InnerValue from Value
6106    // pub fn to_arc_parking_rwlock_chain<InnerValue>(self) -> OptionalArcParkingRwLockKeyPathChain<Root, InnerValue, InnerValue, impl for<'r> Fn(&'r Root) -> Option<&'r Arc<parking_lot::RwLock<InnerValue>>> + 'static, impl for<'r> Fn(&'r InnerValue) -> &'r InnerValue + 'static>
6107    // where
6108    //     Value: std::borrow::Borrow<Arc<parking_lot::RwLock<InnerValue>>>,
6109    //     F: 'static + Clone,
6110    //     InnerValue: 'static,
6111    // {
6112    //     let identity = KeyPath::new(|inner: &InnerValue| inner);
6113    //     let getter = self.getter.clone();
6114    //     let lock_kp: OptionalKeyPath<Root, Arc<parking_lot::RwLock<InnerValue>>, _> = OptionalKeyPath::new(move |root: &Root| {
6115    //         getter(root).map(|v| {
6116    //             unsafe {
6117    //                 std::mem::transmute::<&Value, &Arc<parking_lot::RwLock<InnerValue>>>(v)
6118    //             }
6119    //         })
6120    //     });
6121    //     lock_kp.then_arc_parking_rwlock_at_kp(identity)
6122    // }
6123
6124    // #[cfg(feature = "parking_lot")]
6125    // /// Convert this optional keypath to an Arc<parking_lot::Mutex> chain keypath
6126    // /// Creates a chain with an identity inner keypath, ready for further chaining
6127    // /// Type inference automatically determines InnerValue from Value
6128    // pub fn to_arc_parking_mutex_chain<InnerValue>(self) -> OptionalArcParkingMutexKeyPathChain<Root, InnerValue, InnerValue, impl for<'r> Fn(&'r Root) -> Option<&'r Arc<parking_lot::Mutex<InnerValue>>> + 'static, impl for<'r> Fn(&'r InnerValue) -> &'r InnerValue + 'static>
6129    // where
6130    //     Value: std::borrow::Borrow<Arc<parking_lot::Mutex<InnerValue>>>,
6131    //     F: 'static + Clone,
6132    //     InnerValue: 'static,
6133    // {
6134    //     let identity = KeyPath::new(|inner: &InnerValue| inner);
6135    //     let getter = self.getter.clone();
6136    //     let lock_kp: OptionalKeyPath<Root, Arc<parking_lot::Mutex<InnerValue>>, _> = OptionalKeyPath::new(move |root: &Root| {
6137    //         getter(root).map(|v| {
6138    //             unsafe {
6139    //                 std::mem::transmute::<&Value, &Arc<parking_lot::Mutex<InnerValue>>>(v)
6140    //             }
6141    //         })
6142    //     });
6143    //     lock_kp.then_arc_parking_mutex_at_kp(identity)
6144    // }
6145    
6146    // Overload: Adapt root type to Arc<Root> when Value is Sized (not a container)
6147    pub fn for_arc_root(self) -> OptionalKeyPath<Arc<Root>, Value, impl for<'r> Fn(&'r Arc<Root>) -> Option<&'r Value> + 'static>
6148    where
6149        Value: Sized,
6150        F: 'static,
6151        Root: 'static,
6152        Value: 'static,
6153    {
6154        let getter = self.getter;
6155        
6156        OptionalKeyPath {
6157            getter: move |arc: &Arc<Root>| {
6158                getter(arc.as_ref())
6159            },
6160            _phantom: PhantomData,
6161        }
6162    }
6163    
6164    // Overload: Adapt root type to Rc<Root> when Value is Sized (not a container)
6165    pub fn for_rc_root(self) -> OptionalKeyPath<Rc<Root>, Value, impl for<'r> Fn(&'r Rc<Root>) -> Option<&'r Value> + 'static>
6166    where
6167        Value: Sized,
6168        F: 'static,
6169        Root: 'static,
6170        Value: 'static,
6171    {
6172        let getter = self.getter;
6173        
6174        OptionalKeyPath {
6175            getter: move |rc: &Rc<Root>| {
6176                getter(rc.as_ref())
6177            },
6178            _phantom: PhantomData,
6179        }
6180    }
6181    
6182    /// Execute a closure with a reference to the value inside an Option
6183    pub fn with_option<Callback, R>(&self, option: &Option<Root>, f: Callback) -> Option<R>
6184    where
6185        F: Clone,
6186        Callback: FnOnce(&Value) -> R,
6187    {
6188        option.as_ref().and_then(|root| {
6189            self.get(root).map(|value| f(value))
6190        })
6191    }
6192    
6193    /// Execute a closure with a reference to the value inside a Mutex
6194    pub fn with_mutex<Callback, R>(&self, mutex: &Mutex<Root>, f: Callback) -> Option<R>
6195    where
6196        F: Clone,
6197        Callback: FnOnce(&Value) -> R,
6198    {
6199        mutex.lock().ok().and_then(|guard| {
6200            self.get(&*guard).map(|value| f(value))
6201        })
6202    }
6203    
6204    /// Execute a closure with a reference to the value inside an RwLock
6205    pub fn with_rwlock<Callback, R>(&self, rwlock: &RwLock<Root>, f: Callback) -> Option<R>
6206    where
6207        F: Clone,
6208        Callback: FnOnce(&Value) -> R,
6209    {
6210        rwlock.read().ok().and_then(|guard| {
6211            self.get(&*guard).map(|value| f(value))
6212        })
6213    }
6214    
6215    /// Execute a closure with a reference to the value inside an Arc<RwLock<Root>>
6216    pub fn with_arc_rwlock<Callback, R>(&self, arc_rwlock: &Arc<RwLock<Root>>, f: Callback) -> Option<R>
6217    where
6218        F: Clone,
6219        Callback: FnOnce(&Value) -> R,
6220    {
6221        arc_rwlock.read().ok().and_then(|guard| {
6222            self.get(&*guard).map(|value| f(value))
6223        })
6224    }
6225    
6226    /// Execute a closure with a reference to the value inside an Arc<RwLock<Root>>
6227    /// This is a convenience method that works directly with Arc<RwLock<T>>
6228    /// Unlike with_arc_rwlock, this doesn't require F: Clone
6229    pub fn with_arc_rwlock_direct<Callback, R>(&self, arc_rwlock: &Arc<RwLock<Root>>, f: Callback) -> Option<R>
6230    where
6231        Callback: FnOnce(&Value) -> R,
6232    {
6233        arc_rwlock.read().ok().and_then(|guard| {
6234            self.get(&*guard).map(|value| f(value))
6235        })
6236    }
6237    
6238    /// Execute a closure with a reference to the value inside an Arc<Mutex<Root>>
6239    pub fn with_arc_mutex<Callback, R>(&self, arc_mutex: &Arc<Mutex<Root>>, f: Callback) -> Option<R>
6240    where
6241        F: Clone,
6242        Callback: FnOnce(&Value) -> R,
6243    {
6244        arc_mutex.lock().ok().and_then(|guard| {
6245            self.get(&*guard).map(|value| f(value))
6246        })
6247    }
6248}
6249
6250// ========== PARKING_LOT CHAIN METHODS FOR OPTIONAL KEYPATH ==========
6251
6252#[cfg(feature = "parking_lot")]
6253impl<Root, InnerValue, F> OptionalKeyPath<Root, Arc<parking_lot::Mutex<InnerValue>>, F>
6254where
6255    F: for<'r> Fn(&'r Root) -> Option<&'r Arc<parking_lot::Mutex<InnerValue>>>,
6256{
6257    /// Chain this optional keypath with an inner keypath through Arc<parking_lot::Mutex<T>>
6258    pub fn then_arc_parking_mutex_at_kp<SubValue, G>(
6259        self,
6260        inner_keypath: KeyPath<InnerValue, SubValue, G>,
6261    ) -> OptionalArcParkingMutexKeyPathChain<Root, InnerValue, SubValue, F, G>
6262    where
6263        G: for<'r> Fn(&'r InnerValue) -> &'r SubValue,
6264    {
6265        OptionalArcParkingMutexKeyPathChain {
6266            outer_keypath: self,
6267            inner_keypath,
6268        }
6269    }
6270    
6271    /// Chain this optional keypath with an optional inner keypath through Arc<parking_lot::Mutex<T>>
6272    pub fn then_arc_parking_mutex_optional_at_kp<SubValue, G>(
6273        self,
6274        inner_keypath: OptionalKeyPath<InnerValue, SubValue, G>,
6275    ) -> OptionalArcParkingMutexOptionalKeyPathChain<Root, InnerValue, SubValue, F, G>
6276    where
6277        G: for<'r> Fn(&'r InnerValue) -> Option<&'r SubValue>,
6278    {
6279        OptionalArcParkingMutexOptionalKeyPathChain {
6280            outer_keypath: self,
6281            inner_keypath,
6282        }
6283    }
6284    
6285    /// Chain this optional keypath with a writable inner keypath through Arc<parking_lot::Mutex<T>>
6286    pub fn then_arc_parking_mutex_writable_at_kp<SubValue, G>(
6287        self,
6288        inner_keypath: WritableKeyPath<InnerValue, SubValue, G>,
6289    ) -> OptionalArcParkingMutexWritableKeyPathChain<Root, InnerValue, SubValue, F, G>
6290    where
6291        G: for<'r> Fn(&'r mut InnerValue) -> &'r mut SubValue,
6292    {
6293        OptionalArcParkingMutexWritableKeyPathChain {
6294            outer_keypath: self,
6295            inner_keypath,
6296        }
6297    }
6298    
6299    /// Chain this optional keypath with a writable optional inner keypath through Arc<parking_lot::Mutex<T>>
6300    pub fn then_arc_parking_mutex_writable_optional_at_kp<SubValue, G>(
6301        self,
6302        inner_keypath: WritableOptionalKeyPath<InnerValue, SubValue, G>,
6303    ) -> OptionalArcParkingMutexWritableOptionalKeyPathChain<Root, InnerValue, SubValue, F, G>
6304    where
6305        G: for<'r> Fn(&'r mut InnerValue) -> Option<&'r mut SubValue>,
6306    {
6307        OptionalArcParkingMutexWritableOptionalKeyPathChain {
6308            outer_keypath: self,
6309            inner_keypath,
6310        }
6311    }
6312}
6313
6314#[cfg(feature = "parking_lot")]
6315impl<Root, InnerValue, F> OptionalKeyPath<Root, Arc<parking_lot::RwLock<InnerValue>>, F>
6316where
6317    F: for<'r> Fn(&'r Root) -> Option<&'r Arc<parking_lot::RwLock<InnerValue>>>,
6318{
6319    /// Chain this optional keypath with an inner keypath through Arc<parking_lot::RwLock<T>>
6320    pub fn then_arc_parking_rwlock_at_kp<SubValue, G>(
6321        self,
6322        inner_keypath: KeyPath<InnerValue, SubValue, G>,
6323    ) -> OptionalArcParkingRwLockKeyPathChain<Root, InnerValue, SubValue, F, G>
6324    where
6325        G: for<'r> Fn(&'r InnerValue) -> &'r SubValue,
6326    {
6327        OptionalArcParkingRwLockKeyPathChain {
6328            outer_keypath: self,
6329            inner_keypath,
6330        }
6331    }
6332    
6333    /// Chain this optional keypath with an optional inner keypath through Arc<parking_lot::RwLock<T>>
6334    pub fn then_arc_parking_rwlock_optional_at_kp<SubValue, G>(
6335        self,
6336        inner_keypath: OptionalKeyPath<InnerValue, SubValue, G>,
6337    ) -> OptionalArcParkingRwLockOptionalKeyPathChain<Root, InnerValue, SubValue, F, G>
6338    where
6339        G: for<'r> Fn(&'r InnerValue) -> Option<&'r SubValue>,
6340    {
6341        OptionalArcParkingRwLockOptionalKeyPathChain {
6342            outer_keypath: self,
6343            inner_keypath,
6344        }
6345    }
6346    
6347    /// Chain this optional keypath with a writable inner keypath through Arc<parking_lot::RwLock<T>>
6348    pub fn then_arc_parking_rwlock_writable_at_kp<SubValue, G>(
6349        self,
6350        inner_keypath: WritableKeyPath<InnerValue, SubValue, G>,
6351    ) -> OptionalArcParkingRwLockWritableKeyPathChain<Root, InnerValue, SubValue, F, G>
6352    where
6353        G: for<'r> Fn(&'r mut InnerValue) -> &'r mut SubValue,
6354    {
6355        OptionalArcParkingRwLockWritableKeyPathChain {
6356            outer_keypath: self,
6357            inner_keypath,
6358        }
6359    }
6360    
6361    /// Chain this optional keypath with a writable optional inner keypath through Arc<parking_lot::RwLock<T>>
6362    pub fn then_arc_parking_rwlock_writable_optional_at_kp<SubValue, G>(
6363        self,
6364        inner_keypath: WritableOptionalKeyPath<InnerValue, SubValue, G>,
6365    ) -> OptionalArcParkingRwLockWritableOptionalKeyPathChain<Root, InnerValue, SubValue, F, G>
6366    where
6367        G: for<'r> Fn(&'r mut InnerValue) -> Option<&'r mut SubValue>,
6368    {
6369        OptionalArcParkingRwLockWritableOptionalKeyPathChain {
6370            outer_keypath: self,
6371            inner_keypath,
6372        }
6373    }
6374}
6375
6376
6377// WritableKeyPath for mutable access
6378#[derive(Clone)]
6379pub struct WritableKeyPath<Root, Value, F>
6380where
6381    F: for<'r> Fn(&'r mut Root) -> &'r mut Value,
6382{
6383    getter: F,
6384    _phantom: PhantomData<(Root, Value)>,
6385}
6386
6387impl<Root, Value, F> fmt::Display for WritableKeyPath<Root, Value, F>
6388where
6389    F: for<'r> Fn(&'r mut Root) -> &'r mut Value,
6390{
6391    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
6392        let root_name = std::any::type_name::<Root>();
6393        let value_name = std::any::type_name::<Value>();
6394        // Simplify type names by removing module paths for cleaner output
6395        let root_short = root_name.split("::").last().unwrap_or(root_name);
6396        let value_short = value_name.split("::").last().unwrap_or(value_name);
6397        write!(f, "WritableKeyPath<{} -> {}>", root_short, value_short)
6398    }
6399}
6400
6401impl<Root, Value, F> fmt::Debug for WritableKeyPath<Root, Value, F>
6402where
6403    F: for<'r> Fn(&'r mut Root) -> &'r mut Value,
6404{
6405    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
6406        fmt::Display::fmt(self, f)
6407    }
6408}
6409
6410impl<Root, Value, F> WritableKeyPath<Root, Value, F>
6411where
6412    F: for<'r> Fn(&'r mut Root) -> &'r mut Value,
6413{
6414    pub fn new(getter: F) -> Self {
6415        Self {
6416            getter,
6417            _phantom: PhantomData,
6418        }
6419    }
6420    
6421    pub fn get_mut<'r>(&self, root: &'r mut Root) -> &'r mut Value {
6422        (self.getter)(root)
6423    }
6424    
6425    /// Adapt this keypath to work with Result<Root, E> instead of Root
6426    /// This unwraps the Result and applies the keypath to the Ok value
6427    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>
6428    where
6429        F: 'static,
6430        Root: 'static,
6431        Value: 'static,
6432        E: 'static,
6433    {
6434        let getter = self.getter;
6435        
6436        WritableOptionalKeyPath {
6437            getter: move |result: &mut Result<Root, E>| {
6438                result.as_mut().ok().map(|root| getter(root))
6439            },
6440            _phantom: PhantomData,
6441        }
6442    }
6443    
6444    // Overload: Adapt root type to Box<Root> when Value is Sized (not a container)
6445    pub fn for_box_root(self) -> WritableKeyPath<Box<Root>, Value, impl for<'r> Fn(&'r mut Box<Root>) -> &'r mut Value + 'static>
6446    where
6447        Value: Sized,
6448        F: 'static,
6449        Root: 'static,
6450        Value: 'static,
6451    {
6452        let getter = self.getter;
6453        
6454        WritableKeyPath {
6455            getter: move |boxed: &mut Box<Root>| {
6456                getter(boxed.as_mut())
6457            },
6458            _phantom: PhantomData,
6459        }
6460    }
6461    
6462    /// Adapt this keypath to work with Option<Root> instead of Root
6463    /// This unwraps the Option and applies the keypath to the Some value
6464    pub fn for_option(self) -> WritableOptionalKeyPath<Option<Root>, Value, impl for<'r> Fn(&'r mut Option<Root>) -> Option<&'r mut Value> + 'static>
6465    where
6466        F: 'static,
6467        Root: 'static,
6468        Value: 'static,
6469    {
6470        let getter = self.getter;
6471        
6472        WritableOptionalKeyPath {
6473            getter: move |option: &mut Option<Root>| {
6474                option.as_mut().map(|root| getter(root))
6475            },
6476            _phantom: PhantomData,
6477        }
6478    }
6479    
6480    /// Convert a WritableKeyPath to WritableOptionalKeyPath for chaining
6481    /// This allows non-optional writable keypaths to be chained with then()
6482    pub fn to_optional(self) -> WritableOptionalKeyPath<Root, Value, impl for<'r> Fn(&'r mut Root) -> Option<&'r mut Value> + 'static>
6483    where
6484        F: 'static,
6485    {
6486        let getter = self.getter;
6487        WritableOptionalKeyPath::new(move |root: &mut Root| Some(getter(root)))
6488    }
6489    
6490    // Instance methods for unwrapping containers (automatically infers Target from Value::Target)
6491    // Box<T> -> T
6492    pub fn for_box<Target>(self) -> WritableKeyPath<Root, Target, impl for<'r> Fn(&'r mut Root) -> &'r mut Target + 'static>
6493    where
6494        Value: std::ops::DerefMut<Target = Target>,
6495        F: 'static,
6496        Value: 'static,
6497    {
6498        let getter = self.getter;
6499        
6500        WritableKeyPath {
6501            getter: move |root: &mut Root| {
6502                getter(root).deref_mut()
6503            },
6504            _phantom: PhantomData,
6505        }
6506    }
6507    
6508    // Arc<T> -> T (Note: Arc doesn't support mutable access, but we provide it for consistency)
6509    // This will require interior mutability patterns
6510    pub fn for_arc<Target>(self) -> WritableKeyPath<Root, Target, impl for<'r> Fn(&'r mut Root) -> &'r mut Target + 'static>
6511    where
6512        Value: std::ops::DerefMut<Target = Target>,
6513        F: 'static,
6514        Value: 'static,
6515    {
6516        let getter = self.getter;
6517        
6518        WritableKeyPath {
6519            getter: move |root: &mut Root| {
6520                getter(root).deref_mut()
6521            },
6522            _phantom: PhantomData,
6523        }
6524    }
6525    
6526    // Rc<T> -> T (Note: Rc doesn't support mutable access, but we provide it for consistency)
6527    // This will require interior mutability patterns
6528    pub fn for_rc<Target>(self) -> WritableKeyPath<Root, Target, impl for<'r> Fn(&'r mut Root) -> &'r mut Target + 'static>
6529    where
6530        Value: std::ops::DerefMut<Target = Target>,
6531        F: 'static,
6532        Value: 'static,
6533    {
6534        let getter = self.getter;
6535        
6536        WritableKeyPath {
6537            getter: move |root: &mut Root| {
6538                getter(root).deref_mut()
6539            },
6540            _phantom: PhantomData,
6541        }
6542    }
6543    
6544    /// Execute a closure with a mutable reference to the value inside a Box
6545    pub fn with_box_mut<Callback, R>(&self, boxed: &mut Box<Root>, f: Callback) -> R
6546    where
6547        F: Clone,
6548        Callback: FnOnce(&mut Value) -> R,
6549    {
6550        let value = self.get_mut(boxed);
6551        f(value)
6552    }
6553    
6554    /// Execute a closure with a mutable reference to the value inside a Result
6555    pub fn with_result_mut<Callback, R, E>(&self, result: &mut Result<Root, E>, f: Callback) -> Option<R>
6556    where
6557        F: Clone,
6558        Callback: FnOnce(&mut Value) -> R,
6559    {
6560        result.as_mut().ok().map(|root| {
6561            let value = self.get_mut(root);
6562            f(value)
6563        })
6564    }
6565    
6566    /// Execute a closure with a mutable reference to the value inside an Option
6567    pub fn with_option_mut<Callback, R>(&self, option: &mut Option<Root>, f: Callback) -> Option<R>
6568    where
6569        F: Clone,
6570        Callback: FnOnce(&mut Value) -> R,
6571    {
6572        option.as_mut().map(|root| {
6573            let value = self.get_mut(root);
6574            f(value)
6575        })
6576    }
6577    
6578    /// Execute a closure with a mutable reference to the value inside a RefCell
6579    pub fn with_refcell_mut<Callback, R>(&self, refcell: &RefCell<Root>, f: Callback) -> Option<R>
6580    where
6581        F: Clone,
6582        Callback: FnOnce(&mut Value) -> R,
6583    {
6584        refcell.try_borrow_mut().ok().map(|mut borrow| {
6585            let value = self.get_mut(&mut *borrow);
6586            f(value)
6587        })
6588    }
6589    
6590    /// Execute a closure with a mutable reference to the value inside a Mutex
6591    pub fn with_mutex_mut<Callback, R>(&self, mutex: &mut Mutex<Root>, f: Callback) -> Option<R>
6592    where
6593        F: Clone,
6594        Callback: FnOnce(&mut Value) -> R,
6595    {
6596        mutex.get_mut().ok().map(|root| {
6597            let value = self.get_mut(root);
6598            f(value)
6599        })
6600    }
6601    
6602    /// Execute a closure with a mutable reference to the value inside an RwLock
6603    pub fn with_rwlock_mut<Callback, R>(&self, rwlock: &mut RwLock<Root>, f: Callback) -> Option<R>
6604    where
6605        F: Clone,
6606        Callback: FnOnce(&mut Value) -> R,
6607    {
6608        rwlock.write().ok().map(|mut guard| {
6609            let value = self.get_mut(&mut *guard);
6610            f(value)
6611        })
6612    }
6613    
6614    /// Get a mutable iterator over a Vec when Value is Vec<T>
6615    /// Returns Some(iterator) if the value is a Vec, None otherwise
6616    pub fn iter_mut<'r, T>(&self, root: &'r mut Root) -> Option<std::slice::IterMut<'r, T>>
6617    where
6618        Value: AsMut<[T]> + 'r,
6619    {
6620        let value_ref: &'r mut Value = self.get_mut(root);
6621        Some(value_ref.as_mut().iter_mut())
6622    }
6623    
6624    /// Extract mutable values from a slice of owned mutable values
6625    /// Returns a Vec of mutable references to the extracted values
6626    pub fn extract_mut_from_slice<'r>(&self, slice: &'r mut [Root]) -> Vec<&'r mut Value> {
6627        slice.iter_mut().map(|item| self.get_mut(item)).collect()
6628    }
6629    
6630    /// Extract mutable values from a slice of mutable references
6631    /// Returns a Vec of mutable references to the extracted values
6632    pub fn extract_mut_from_ref_slice<'r>(&self, slice: &'r mut [&'r mut Root]) -> Vec<&'r mut Value> {
6633        slice.iter_mut().map(|item| self.get_mut(*item)).collect()
6634    }
6635    
6636    /// Chain this keypath with another writable keypath
6637    /// Returns a WritableKeyPath that chains both keypaths
6638    pub fn then<SubValue, G>(
6639        self,
6640        next: WritableKeyPath<Value, SubValue, G>,
6641    ) -> WritableKeyPath<Root, SubValue, impl for<'r> Fn(&'r mut Root) -> &'r mut SubValue>
6642    where
6643        G: for<'r> Fn(&'r mut Value) -> &'r mut SubValue,
6644        F: 'static,
6645        G: 'static,
6646        Value: 'static,
6647    {
6648        let first = self.getter;
6649        let second = next.getter;
6650        
6651        WritableKeyPath::new(move |root: &mut Root| {
6652            let value = first(root);
6653            second(value)
6654        })
6655    }
6656    
6657    /// Chain this keypath with a writable optional keypath
6658    /// Returns a WritableOptionalKeyPath that chains both keypaths
6659    pub fn chain_optional<SubValue, G>(
6660        self,
6661        next: WritableOptionalKeyPath<Value, SubValue, G>,
6662    ) -> WritableOptionalKeyPath<Root, SubValue, impl for<'r> Fn(&'r mut Root) -> Option<&'r mut SubValue>>
6663    where
6664        G: for<'r> Fn(&'r mut Value) -> Option<&'r mut SubValue>,
6665        F: 'static,
6666        G: 'static,
6667        Value: 'static,
6668    {
6669        let first = self.getter;
6670        let second = next.getter;
6671        
6672        WritableOptionalKeyPath::new(move |root: &mut Root| {
6673            let value = first(root);
6674            second(value)
6675        })
6676    }
6677
6678    // ========== LOCK KEYPATH CONVERSION METHODS ==========
6679    // These methods convert keypaths pointing to lock types into chain-ready keypaths
6680
6681    /// Convert this writable keypath to an Arc<RwLock> chain-ready keypath
6682    /// Returns self, but serves as a marker for intent and enables chaining
6683    pub fn to_arc_rwlock_kp<InnerValue>(self) -> Self
6684    where
6685        Value: std::borrow::Borrow<Arc<RwLock<InnerValue>>>,
6686    {
6687        self
6688    }
6689
6690    /// Convert this writable keypath to an Arc<Mutex> chain-ready keypath
6691    /// Returns self, but serves as a marker for intent and enables chaining
6692    pub fn to_arc_mutex_kp<InnerValue>(self) -> Self
6693    where
6694        Value: std::borrow::Borrow<Arc<Mutex<InnerValue>>>,
6695    {
6696        self
6697    }
6698
6699    #[cfg(feature = "parking_lot")]
6700    /// Convert this writable keypath to an Arc<parking_lot::RwLock> chain-ready keypath
6701    /// Returns self, but serves as a marker for intent and enables chaining
6702    pub fn to_arc_parking_rwlock_kp<InnerValue>(self) -> Self
6703    where
6704        Value: std::borrow::Borrow<Arc<parking_lot::RwLock<InnerValue>>>,
6705    {
6706        self
6707    }
6708
6709    #[cfg(feature = "parking_lot")]
6710    /// Convert this writable keypath to an Arc<parking_lot::Mutex> chain-ready keypath
6711    /// Returns self, but serves as a marker for intent and enables chaining
6712    pub fn to_arc_parking_mutex_kp<InnerValue>(self) -> Self
6713    where
6714        Value: std::borrow::Borrow<Arc<parking_lot::Mutex<InnerValue>>>,
6715    {
6716        self
6717    }
6718
6719}
6720
6721// WritableOptionalKeyPath for failable mutable access
6722#[derive(Clone)]
6723pub struct WritableOptionalKeyPath<Root, Value, F>
6724where
6725    F: for<'r> Fn(&'r mut Root) -> Option<&'r mut Value>,
6726{
6727    getter: F,
6728    _phantom: PhantomData<(Root, Value)>,
6729}
6730
6731impl<Root, Value, F> fmt::Display for WritableOptionalKeyPath<Root, Value, F>
6732where
6733    F: for<'r> Fn(&'r mut Root) -> Option<&'r mut Value>,
6734{
6735    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
6736        let root_name = std::any::type_name::<Root>();
6737        let value_name = std::any::type_name::<Value>();
6738        // Simplify type names by removing module paths for cleaner output
6739        let root_short = root_name.split("::").last().unwrap_or(root_name);
6740        let value_short = value_name.split("::").last().unwrap_or(value_name);
6741        write!(f, "WritableOptionalKeyPath<{} -> Option<{}>>", root_short, value_short)
6742    }
6743}
6744
6745impl<Root, Value, F> fmt::Debug for WritableOptionalKeyPath<Root, Value, F>
6746where
6747    F: for<'r> Fn(&'r mut Root) -> Option<&'r mut Value>,
6748{
6749    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
6750        // Show type information and indicate this is a chain that may fail
6751        let root_name = std::any::type_name::<Root>();
6752        let value_name = std::any::type_name::<Value>();
6753        let root_short = root_name.split("::").last().unwrap_or(root_name);
6754        let value_short = value_name.split("::").last().unwrap_or(value_name);
6755        
6756        // Use alternate format for more detailed debugging
6757        if f.alternate() {
6758            writeln!(f, "WritableOptionalKeyPath<{} -> Option<{}>>", root_short, value_short)?;
6759            writeln!(f, "  âš  Chain may break if any intermediate step returns None")?;
6760            writeln!(f, "  💡 Use trace_chain() to find where the chain breaks")
6761        } else {
6762            write!(f, "WritableOptionalKeyPath<{} -> Option<{}>>", root_short, value_short)
6763        }
6764    }
6765}
6766
6767impl<Root, Value, F> WritableOptionalKeyPath<Root, Value, F>
6768where
6769    F: for<'r> Fn(&'r mut Root) -> Option<&'r mut Value>,
6770{
6771    pub fn new(getter: F) -> Self {
6772        Self {
6773            getter,
6774            _phantom: PhantomData,
6775        }
6776    }
6777    
6778    pub fn get_mut<'r>(&self, root: &'r mut Root) -> Option<&'r mut Value> {
6779        (self.getter)(root)
6780    }
6781    
6782    /// Trace the chain to find where it breaks
6783    /// Returns Ok(()) if the chain succeeds, or Err with diagnostic information
6784    /// 
6785    /// # Example
6786    /// ```rust
6787    /// let path = SomeComplexStruct::scsf_fw()
6788    ///     .then(SomeOtherStruct::sosf_fw())
6789    ///     .then(SomeEnum::b_case_fw());
6790    /// 
6791    /// match path.trace_chain(&mut instance) {
6792    ///     Ok(()) => println!("Chain succeeded"),
6793    ///     Err(msg) => println!("Chain broken: {}", msg),
6794    /// }
6795    /// ```
6796    pub fn trace_chain(&self, root: &mut Root) -> Result<(), String> {
6797        match self.get_mut(root) {
6798            Some(_) => Ok(()),
6799            None => {
6800                let root_name = std::any::type_name::<Root>();
6801                let value_name = std::any::type_name::<Value>();
6802                let root_short = root_name.split("::").last().unwrap_or(root_name);
6803                let value_short = value_name.split("::").last().unwrap_or(value_name);
6804                Err(format!("{} -> Option<{}> returned None (chain broken at this step)", root_short, value_short))
6805            }
6806        }
6807    }
6808    
6809    /// Adapt this keypath to work with Option<Root> instead of Root
6810    /// This unwraps the Option and applies the keypath to the Some value
6811    pub fn for_option(self) -> WritableOptionalKeyPath<Option<Root>, Value, impl for<'r> Fn(&'r mut Option<Root>) -> Option<&'r mut Value> + 'static>
6812    where
6813        F: 'static,
6814        Root: 'static,
6815        Value: 'static,
6816    {
6817        let getter = self.getter;
6818        
6819        WritableOptionalKeyPath {
6820            getter: move |option: &mut Option<Root>| {
6821                option.as_mut().and_then(|root| getter(root))
6822            },
6823            _phantom: PhantomData,
6824        }
6825    }
6826    
6827    // Swift-like operator for chaining WritableOptionalKeyPath
6828    pub fn then<SubValue, G>(
6829        self,
6830        next: WritableOptionalKeyPath<Value, SubValue, G>,
6831    ) -> WritableOptionalKeyPath<Root, SubValue, impl for<'r> Fn(&'r mut Root) -> Option<&'r mut SubValue>>
6832    where
6833        G: for<'r> Fn(&'r mut Value) -> Option<&'r mut SubValue>,
6834        F: 'static,
6835        G: 'static,
6836        Value: 'static,
6837    {
6838        let first = self.getter;
6839        let second = next.getter;
6840        
6841        WritableOptionalKeyPath::new(move |root: &mut Root| {
6842            first(root).and_then(|value| second(value))
6843        })
6844    }
6845    
6846    // Instance methods for unwrapping containers from Option<Container<T>>
6847    // Option<Box<T>> -> Option<&mut T> (type automatically inferred from Value::Target)
6848    pub fn for_box<Target>(self) -> WritableOptionalKeyPath<Root, Target, impl for<'r> Fn(&'r mut Root) -> Option<&'r mut Target> + 'static>
6849    where
6850        Value: std::ops::DerefMut<Target = Target>,
6851        F: 'static,
6852        Value: 'static,
6853    {
6854        let getter = self.getter;
6855        
6856        WritableOptionalKeyPath {
6857            getter: move |root: &mut Root| {
6858                getter(root).map(|boxed| boxed.deref_mut())
6859            },
6860            _phantom: PhantomData,
6861        }
6862    }
6863    
6864    // Option<Arc<T>> -> Option<&mut T> (type automatically inferred from Value::Target)
6865    pub fn for_arc<Target>(self) -> WritableOptionalKeyPath<Root, Target, impl for<'r> Fn(&'r mut Root) -> Option<&'r mut Target> + 'static>
6866    where
6867        Value: std::ops::DerefMut<Target = Target>,
6868        F: 'static,
6869        Value: 'static,
6870    {
6871        let getter = self.getter;
6872        
6873        WritableOptionalKeyPath {
6874            getter: move |root: &mut Root| {
6875                getter(root).map(|arc| arc.deref_mut())
6876            },
6877            _phantom: PhantomData,
6878        }
6879    }
6880    
6881    // Option<Rc<T>> -> Option<&mut T> (type automatically inferred from Value::Target)
6882    pub fn for_rc<Target>(self) -> WritableOptionalKeyPath<Root, Target, impl for<'r> Fn(&'r mut Root) -> Option<&'r mut Target> + 'static>
6883    where
6884        Value: std::ops::DerefMut<Target = Target>,
6885        F: 'static,
6886        Value: 'static,
6887    {
6888        let getter = self.getter;
6889        
6890        WritableOptionalKeyPath {
6891            getter: move |root: &mut Root| {
6892                getter(root).map(|rc| rc.deref_mut())
6893            },
6894            _phantom: PhantomData,
6895        }
6896    }
6897    
6898    /// Adapt this keypath to work with Result<Root, E> instead of Root
6899    /// This unwraps the Result and applies the keypath to the Ok value
6900    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>
6901    where
6902        F: 'static,
6903        Root: 'static,
6904        Value: 'static,
6905        E: 'static,
6906    {
6907        let getter = self.getter;
6908        
6909        WritableOptionalKeyPath {
6910            getter: move |result: &mut Result<Root, E>| {
6911                result.as_mut().ok().and_then(|root| getter(root))
6912            },
6913            _phantom: PhantomData,
6914        }
6915    }
6916    
6917    // Overload: Adapt root type to Box<Root> when Value is Sized (not a container)
6918    pub fn for_box_root(self) -> WritableOptionalKeyPath<Box<Root>, Value, impl for<'r> Fn(&'r mut Box<Root>) -> Option<&'r mut Value> + 'static>
6919    where
6920        Value: Sized,
6921        F: 'static,
6922        Root: 'static,
6923        Value: 'static,
6924    {
6925        let getter = self.getter;
6926        
6927        WritableOptionalKeyPath {
6928            getter: move |boxed: &mut Box<Root>| {
6929                getter(boxed.as_mut())
6930            },
6931            _phantom: PhantomData,
6932        }
6933    }
6934    
6935    // Overload: Adapt root type to Arc<Root> when Value is Sized (not a container)
6936    pub fn for_arc_root(self) -> WritableOptionalKeyPath<Arc<Root>, Value, impl for<'r> Fn(&'r mut Arc<Root>) -> Option<&'r mut Value> + 'static>
6937    where
6938        Value: Sized,
6939        F: 'static,
6940        Root: 'static,
6941        Value: 'static,
6942    {
6943        let getter = self.getter;
6944        
6945        WritableOptionalKeyPath {
6946            getter: move |arc: &mut Arc<Root>| {
6947                // Arc doesn't support mutable access without interior mutability
6948                // This will always return None, but we provide it for API consistency
6949                None
6950            },
6951            _phantom: PhantomData,
6952        }
6953    }
6954    
6955    // Overload: Adapt root type to Rc<Root> when Value is Sized (not a container)
6956    pub fn for_rc_root(self) -> WritableOptionalKeyPath<Rc<Root>, Value, impl for<'r> Fn(&'r mut Rc<Root>) -> Option<&'r mut Value> + 'static>
6957    where
6958        Value: Sized,
6959        F: 'static,
6960        Root: 'static,
6961        Value: 'static,
6962    {
6963        let getter = self.getter;
6964        
6965        WritableOptionalKeyPath {
6966            getter: move |rc: &mut Rc<Root>| {
6967                // Rc doesn't support mutable access without interior mutability
6968                // This will always return None, but we provide it for API consistency
6969                None
6970            },
6971            _phantom: PhantomData,
6972        }
6973    }
6974
6975    // ========== LOCK KEYPATH CONVERSION METHODS ==========
6976    // These methods convert keypaths pointing to lock types into chain-ready keypaths
6977
6978    /// Convert this writable optional keypath to an Arc<RwLock> chain-ready keypath
6979    /// Returns self, but serves as a marker for intent and enables chaining
6980    pub fn to_arc_rwlock_kp<InnerValue>(self) -> Self
6981    where
6982        Value: std::borrow::Borrow<Arc<RwLock<InnerValue>>>,
6983    {
6984        self
6985    }
6986
6987    /// Convert this writable optional keypath to an Arc<Mutex> chain-ready keypath
6988    /// Returns self, but serves as a marker for intent and enables chaining
6989    pub fn to_arc_mutex_kp<InnerValue>(self) -> Self
6990    where
6991        Value: std::borrow::Borrow<Arc<Mutex<InnerValue>>>,
6992    {
6993        self
6994    }
6995
6996    #[cfg(feature = "parking_lot")]
6997    /// Convert this writable optional keypath to an Arc<parking_lot::RwLock> chain-ready keypath
6998    /// Returns self, but serves as a marker for intent and enables chaining
6999    pub fn to_arc_parking_rwlock_kp<InnerValue>(self) -> Self
7000    where
7001        Value: std::borrow::Borrow<Arc<parking_lot::RwLock<InnerValue>>>,
7002    {
7003        self
7004    }
7005
7006    #[cfg(feature = "parking_lot")]
7007    /// Convert this writable optional keypath to an Arc<parking_lot::Mutex> chain-ready keypath
7008    /// Returns self, but serves as a marker for intent and enables chaining
7009    pub fn to_arc_parking_mutex_kp<InnerValue>(self) -> Self
7010    where
7011        Value: std::borrow::Borrow<Arc<parking_lot::Mutex<InnerValue>>>,
7012    {
7013        self
7014    }
7015}
7016
7017// Static factory methods for WritableOptionalKeyPath
7018impl WritableOptionalKeyPath<(), (), fn(&mut ()) -> Option<&mut ()>> {
7019    // Static method for Option<T> -> Option<&mut T>
7020    // Note: This is a factory method. Use instance method `for_option()` to adapt existing keypaths.
7021    pub fn for_option_static<T>() -> WritableOptionalKeyPath<Option<T>, T, impl for<'r> Fn(&'r mut Option<T>) -> Option<&'r mut T>> {
7022        WritableOptionalKeyPath::new(|opt: &mut Option<T>| opt.as_mut())
7023    }
7024    
7025    /// Backword compatibility method for writable enum keypath
7026    // Create a writable enum keypath for enum variants
7027    /// This allows both reading and writing to enum variant fields
7028    /// 
7029    /// # Arguments
7030    /// * `embedder` - Function to embed a value into the enum variant (for API consistency, not used)
7031    /// * `read_extractor` - Function to extract a read reference from the enum (for API consistency, not used)
7032    /// * `write_extractor` - Function to extract a mutable reference from the enum
7033    /// 
7034    /// # Example
7035    /// ```rust
7036    /// enum Color { Other(RGBU8) }
7037    /// struct RGBU8(u8, u8, u8);
7038    /// 
7039    /// let case_path = WritableOptionalKeyPath::writable_enum(
7040    ///     |v| Color::Other(v),
7041    ///     |p: &Color| match p { Color::Other(rgb) => Some(rgb), _ => None },
7042    ///     |p: &mut Color| match p { Color::Other(rgb) => Some(rgb), _ => None },
7043    /// );
7044    /// ```
7045    pub fn writable_enum<Enum, Variant, EmbedFn, ReadExtractFn, WriteExtractFn>(
7046        _embedder: EmbedFn,
7047        _read_extractor: ReadExtractFn,
7048        write_extractor: WriteExtractFn,
7049    ) -> WritableOptionalKeyPath<Enum, Variant, impl for<'r> Fn(&'r mut Enum) -> Option<&'r mut Variant> + 'static>
7050    where
7051        EmbedFn: Fn(Variant) -> Enum + 'static,
7052        ReadExtractFn: for<'r> Fn(&'r Enum) -> Option<&'r Variant> + 'static,
7053        WriteExtractFn: for<'r> Fn(&'r mut Enum) -> Option<&'r mut Variant> + 'static,
7054    {
7055        WritableOptionalKeyPath::new(write_extractor)
7056    }
7057}
7058
7059// Enum-specific keypaths
7060/// EnumKeyPath - A keypath for enum variants that supports both extraction and embedding
7061/// Uses generic type parameters instead of dynamic dispatch for zero-cost abstraction
7062/// 
7063/// This struct serves dual purpose:
7064/// 1. As a concrete keypath instance: `EnumKeyPath<Enum, Variant, ExtractFn, EmbedFn>`
7065/// 2. As a namespace for static factory methods: `EnumKeyPath::readable_enum(...)`
7066pub struct EnumKeyPath<Enum = (), Variant = (), ExtractFn = fn(&()) -> Option<&()>, EmbedFn = fn(()) -> ()> 
7067where
7068    ExtractFn: for<'r> Fn(&'r Enum) -> Option<&'r Variant> + 'static,
7069    EmbedFn: Fn(Variant) -> Enum + 'static,
7070{
7071    extractor: OptionalKeyPath<Enum, Variant, ExtractFn>,
7072    embedder: EmbedFn,
7073}
7074
7075impl<Enum, Variant, ExtractFn, EmbedFn> EnumKeyPath<Enum, Variant, ExtractFn, EmbedFn>
7076where
7077    ExtractFn: for<'r> Fn(&'r Enum) -> Option<&'r Variant> + 'static,
7078    EmbedFn: Fn(Variant) -> Enum + 'static,
7079{
7080    /// Create a new EnumKeyPath with extractor and embedder functions
7081    pub fn new(
7082        extractor: ExtractFn,
7083        embedder: EmbedFn,
7084    ) -> Self {
7085        Self {
7086            extractor: OptionalKeyPath::new(extractor),
7087            embedder,
7088        }
7089    }
7090    
7091    /// Extract the value from an enum variant
7092    pub fn get<'r>(&self, enum_value: &'r Enum) -> Option<&'r Variant> {
7093        self.extractor.get(enum_value)
7094    }
7095    
7096    /// Embed a value into the enum variant
7097    pub fn embed(&self, value: Variant) -> Enum {
7098        (self.embedder)(value)
7099    }
7100    
7101    /// Get the underlying OptionalKeyPath for composition
7102    pub fn as_optional(&self) -> &OptionalKeyPath<Enum, Variant, ExtractFn> {
7103        &self.extractor
7104    }
7105    
7106    /// Convert to OptionalKeyPath (loses embedding capability but gains composition)
7107    pub fn to_optional(self) -> OptionalKeyPath<Enum, Variant, ExtractFn> {
7108        self.extractor
7109    }
7110}
7111
7112// Static factory methods for EnumKeyPath
7113impl EnumKeyPath {
7114    /// Create a readable enum keypath with both extraction and embedding
7115    /// Returns an EnumKeyPath that supports both get() and embed() operations
7116    pub fn readable_enum<Enum, Variant, ExtractFn, EmbedFn>(
7117        embedder: EmbedFn,
7118        extractor: ExtractFn,
7119    ) -> EnumKeyPath<Enum, Variant, ExtractFn, EmbedFn>
7120    where
7121        ExtractFn: for<'r> Fn(&'r Enum) -> Option<&'r Variant> + 'static,
7122        EmbedFn: Fn(Variant) -> Enum + 'static,
7123    {
7124        EnumKeyPath::new(extractor, embedder)
7125    }
7126    
7127    /// Extract from a specific enum variant
7128    pub fn for_variant<Enum, Variant, ExtractFn>(
7129        extractor: ExtractFn
7130    ) -> OptionalKeyPath<Enum, Variant, impl for<'r> Fn(&'r Enum) -> Option<&'r Variant>>
7131    where
7132        ExtractFn: Fn(&Enum) -> Option<&Variant>,
7133    {
7134        OptionalKeyPath::new(extractor)
7135    }
7136    
7137    /// Match against multiple variants (returns a tagged union)
7138    pub fn for_match<Enum, Output, MatchFn>(
7139        matcher: MatchFn
7140    ) -> KeyPath<Enum, Output, impl for<'r> Fn(&'r Enum) -> &'r Output>
7141    where
7142        MatchFn: Fn(&Enum) -> &Output,
7143    {
7144        KeyPath::new(matcher)
7145    }
7146    
7147    /// Extract from Result<T, E> - Ok variant
7148    pub fn for_ok<T, E>() -> OptionalKeyPath<Result<T, E>, T, impl for<'r> Fn(&'r Result<T, E>) -> Option<&'r T>> {
7149        OptionalKeyPath::new(|result: &Result<T, E>| result.as_ref().ok())
7150    }
7151    
7152    /// Extract from Result<T, E> - Err variant
7153    pub fn for_err<T, E>() -> OptionalKeyPath<Result<T, E>, E, impl for<'r> Fn(&'r Result<T, E>) -> Option<&'r E>> {
7154        OptionalKeyPath::new(|result: &Result<T, E>| result.as_ref().err())
7155    }
7156    
7157    /// Extract from Option<T> - Some variant
7158    pub fn for_some<T>() -> OptionalKeyPath<Option<T>, T, impl for<'r> Fn(&'r Option<T>) -> Option<&'r T>> {
7159        OptionalKeyPath::new(|opt: &Option<T>| opt.as_ref())
7160    }
7161    
7162    /// Extract from Option<T> - Some variant (alias for for_some for consistency)
7163    pub fn for_option<T>() -> OptionalKeyPath<Option<T>, T, impl for<'r> Fn(&'r Option<T>) -> Option<&'r T>> {
7164        OptionalKeyPath::new(|opt: &Option<T>| opt.as_ref())
7165    }
7166    
7167    /// Unwrap Box<T> -> T
7168    pub fn for_box<T>() -> KeyPath<Box<T>, T, impl for<'r> Fn(&'r Box<T>) -> &'r T> {
7169        KeyPath::new(|b: &Box<T>| b.as_ref())
7170    }
7171    
7172    /// Unwrap Arc<T> -> T
7173    pub fn for_arc<T>() -> KeyPath<Arc<T>, T, impl for<'r> Fn(&'r Arc<T>) -> &'r T> {
7174        KeyPath::new(|arc: &Arc<T>| arc.as_ref())
7175    }
7176    
7177    /// Unwrap Rc<T> -> T
7178    pub fn for_rc<T>() -> KeyPath<std::rc::Rc<T>, T, impl for<'r> Fn(&'r std::rc::Rc<T>) -> &'r T> {
7179        KeyPath::new(|rc: &std::rc::Rc<T>| rc.as_ref())
7180    }
7181
7182    /// Unwrap Box<T> -> T (mutable)
7183    pub fn for_box_mut<T>() -> WritableKeyPath<Box<T>, T, impl for<'r> Fn(&'r mut Box<T>) -> &'r mut T> {
7184        WritableKeyPath::new(|b: &mut Box<T>| b.as_mut())
7185    }
7186
7187    // Note: Arc<T> and Rc<T> don't support direct mutable access without interior mutability
7188    // (e.g., Arc<Mutex<T>> or Rc<RefCell<T>>). These methods are not provided as they
7189    // would require unsafe code or interior mutability patterns.
7190}
7191
7192// Helper to create enum variant keypaths with type inference
7193pub fn variant_of<Enum, Variant, F>(extractor: F) -> OptionalKeyPath<Enum, Variant, F>
7194where
7195    F: for<'r> Fn(&'r Enum) -> Option<&'r Variant>,
7196{
7197    OptionalKeyPath::new(extractor)
7198}
7199
7200// ========== PARTIAL KEYPATHS (Hide Value Type) ==========
7201
7202/// PartialKeyPath - Hides the Value type but keeps Root visible
7203/// Useful for storing keypaths in collections without knowing the exact Value type
7204/// 
7205/// # Why PhantomData<Root>?
7206/// 
7207/// `PhantomData<Root>` is needed because:
7208/// 1. The `Root` type parameter is not actually stored in the struct (only used in the closure)
7209/// 2. Rust needs to know the generic type parameter for:
7210///    - Type checking at compile time
7211///    - Ensuring correct usage (e.g., `PartialKeyPath<User>` can only be used with `&User`)
7212///    - Preventing mixing different Root types
7213/// 3. Without `PhantomData`, Rust would complain that `Root` is unused
7214/// 4. `PhantomData` is zero-sized - it adds no runtime overhead
7215#[derive(Clone)]
7216pub struct PartialKeyPath<Root> {
7217    getter: Rc<dyn for<'r> Fn(&'r Root) -> &'r dyn Any>,
7218    value_type_id: TypeId,
7219    _phantom: PhantomData<Root>,
7220}
7221
7222impl<Root> PartialKeyPath<Root> {
7223    pub fn new<Value>(keypath: KeyPath<Root, Value, impl for<'r> Fn(&'r Root) -> &'r Value + 'static>) -> Self
7224    where
7225        Value: Any + 'static,
7226        Root: 'static,
7227    {
7228        let value_type_id = TypeId::of::<Value>();
7229        let getter = Rc::new(keypath.getter);
7230        
7231        Self {
7232            getter: Rc::new(move |root: &Root| {
7233                let value: &Value = getter(root);
7234                value as &dyn Any
7235            }),
7236            value_type_id,
7237            _phantom: PhantomData,
7238        }
7239    }
7240    
7241    /// Create a PartialKeyPath from a concrete KeyPath
7242    /// Alias for `new()` for consistency with `from()` pattern
7243    pub fn from<Value>(keypath: KeyPath<Root, Value, impl for<'r> Fn(&'r Root) -> &'r Value + 'static>) -> Self
7244    where
7245        Value: Any + 'static,
7246        Root: 'static,
7247    {
7248        Self::new(keypath)
7249    }
7250    
7251    pub fn get<'r>(&self, root: &'r Root) -> &'r dyn Any {
7252        (self.getter)(root)
7253    }
7254    
7255    /// Get the TypeId of the Value type
7256    pub fn value_type_id(&self) -> TypeId {
7257        self.value_type_id
7258    }
7259    
7260    /// Try to downcast the result to a specific type
7261    pub fn get_as<'a, Value: Any>(&self, root: &'a Root) -> Option<&'a Value> {
7262        if self.value_type_id == TypeId::of::<Value>() {
7263            self.get(root).downcast_ref::<Value>()
7264        } else {
7265            None
7266        }
7267    }
7268    
7269    /// Get a human-readable name for the value type
7270    /// Returns a string representation of the TypeId
7271    pub fn kind_name(&self) -> String {
7272        format!("{:?}", self.value_type_id)
7273    }
7274    
7275    /// Adapt this keypath to work with Arc<Root> instead of Root
7276    pub fn for_arc(&self) -> PartialOptionalKeyPath<Arc<Root>>
7277    where
7278        Root: 'static,
7279    {
7280        let getter = self.getter.clone();
7281        let value_type_id = self.value_type_id;
7282        
7283        PartialOptionalKeyPath {
7284            getter: Rc::new(move |arc: &Arc<Root>| {
7285                Some(getter(arc.as_ref()))
7286            }),
7287            value_type_id,
7288            _phantom: PhantomData,
7289        }
7290    }
7291    
7292    /// Adapt this keypath to work with Box<Root> instead of Root
7293    pub fn for_box(&self) -> PartialOptionalKeyPath<Box<Root>>
7294    where
7295        Root: 'static,
7296    {
7297        let getter = self.getter.clone();
7298        let value_type_id = self.value_type_id;
7299        
7300        PartialOptionalKeyPath {
7301            getter: Rc::new(move |boxed: &Box<Root>| {
7302                Some(getter(boxed.as_ref()))
7303            }),
7304            value_type_id,
7305            _phantom: PhantomData,
7306        }
7307    }
7308    
7309    /// Adapt this keypath to work with Rc<Root> instead of Root
7310    pub fn for_rc(&self) -> PartialOptionalKeyPath<Rc<Root>>
7311    where
7312        Root: 'static,
7313    {
7314        let getter = self.getter.clone();
7315        let value_type_id = self.value_type_id;
7316        
7317        PartialOptionalKeyPath {
7318            getter: Rc::new(move |rc: &Rc<Root>| {
7319                Some(getter(rc.as_ref()))
7320            }),
7321            value_type_id,
7322            _phantom: PhantomData,
7323        }
7324    }
7325    
7326    /// Adapt this keypath to work with Option<Root> instead of Root
7327    pub fn for_option(&self) -> PartialOptionalKeyPath<Option<Root>>
7328    where
7329        Root: 'static,
7330    {
7331        let getter = self.getter.clone();
7332        let value_type_id = self.value_type_id;
7333        
7334        PartialOptionalKeyPath {
7335            getter: Rc::new(move |opt: &Option<Root>| {
7336                opt.as_ref().map(|root| getter(root))
7337            }),
7338            value_type_id,
7339            _phantom: PhantomData,
7340        }
7341    }
7342    
7343    /// Adapt this keypath to work with Result<Root, E> instead of Root
7344    pub fn for_result<E>(&self) -> PartialOptionalKeyPath<Result<Root, E>>
7345    where
7346        Root: 'static,
7347        E: 'static,
7348    {
7349        let getter = self.getter.clone();
7350        let value_type_id = self.value_type_id;
7351        
7352        PartialOptionalKeyPath {
7353            getter: Rc::new(move |result: &Result<Root, E>| {
7354                result.as_ref().ok().map(|root| getter(root))
7355            }),
7356            value_type_id,
7357            _phantom: PhantomData,
7358        }
7359    }
7360    
7361    /// Adapt this keypath to work with Arc<RwLock<Root>> instead of Root
7362    /// Note: This requires the Root to be cloned first, then use the keypath on the cloned value
7363    /// Example: `keypath.get_as::<Value>(&arc_rwlock.read().unwrap().clone())`
7364    pub fn for_arc_rwlock(&self) -> PartialOptionalKeyPath<Arc<RwLock<Root>>>
7365    where
7366        Root: Clone + 'static,
7367    {
7368        // We can't return a reference from a guard, so we return None
7369        // Users should clone the root first: arc_rwlock.read().unwrap().clone()
7370        PartialOptionalKeyPath {
7371            getter: Rc::new(move |_arc_rwlock: &Arc<RwLock<Root>>| {
7372                // Cannot return reference from temporary guard
7373                // User should clone the root first and use the keypath on the cloned value
7374                None
7375            }),
7376            value_type_id: self.value_type_id,
7377            _phantom: PhantomData,
7378        }
7379    }
7380    
7381    /// Adapt this keypath to work with Arc<Mutex<Root>> instead of Root
7382    /// Note: This requires the Root to be cloned first, then use the keypath on the cloned value
7383    /// Example: `keypath.get_as::<Value>(&arc_mutex.lock().unwrap().clone())`
7384    pub fn for_arc_mutex(&self) -> PartialOptionalKeyPath<Arc<Mutex<Root>>>
7385    where
7386        Root: Clone + 'static,
7387    {
7388        // We can't return a reference from a guard, so we return None
7389        // Users should clone the root first: arc_mutex.lock().unwrap().clone()
7390        PartialOptionalKeyPath {
7391            getter: Rc::new(move |_arc_mutex: &Arc<Mutex<Root>>| {
7392                // Cannot return reference from temporary guard
7393                // User should clone the root first and use the keypath on the cloned value
7394                None
7395            }),
7396            value_type_id: self.value_type_id,
7397            _phantom: PhantomData,
7398        }
7399    }
7400}
7401
7402/// PartialOptionalKeyPath - Hides the Value type but keeps Root visible
7403/// Useful for storing optional keypaths in collections without knowing the exact Value type
7404/// 
7405/// # Why PhantomData<Root>?
7406/// 
7407/// See `PartialKeyPath` documentation for explanation of why `PhantomData` is needed.
7408#[derive(Clone)]
7409pub struct PartialOptionalKeyPath<Root> {
7410    getter: Rc<dyn for<'r> Fn(&'r Root) -> Option<&'r dyn Any>>,
7411    value_type_id: TypeId,
7412    _phantom: PhantomData<Root>,
7413}
7414
7415impl<Root> PartialOptionalKeyPath<Root> {
7416    pub fn new<Value>(keypath: OptionalKeyPath<Root, Value, impl for<'r> Fn(&'r Root) -> Option<&'r Value> + 'static>) -> Self
7417    where
7418        Value: Any + 'static,
7419        Root: 'static,
7420    {
7421        let value_type_id = TypeId::of::<Value>();
7422        let getter = Rc::new(keypath.getter);
7423        
7424        Self {
7425            getter: Rc::new(move |root: &Root| {
7426                getter(root).map(|value: &Value| value as &dyn Any)
7427            }),
7428            value_type_id,
7429            _phantom: PhantomData,
7430        }
7431    }
7432    
7433    pub fn get<'r>(&self, root: &'r Root) -> Option<&'r dyn Any> {
7434        (self.getter)(root)
7435    }
7436    
7437    /// Get the TypeId of the Value type
7438    pub fn value_type_id(&self) -> TypeId {
7439        self.value_type_id
7440    }
7441    
7442    /// Try to downcast the result to a specific type
7443    pub fn get_as<'a, Value: Any>(&self, root: &'a Root) -> Option<Option<&'a Value>> {
7444        if self.value_type_id == TypeId::of::<Value>() {
7445            self.get(root).map(|any| any.downcast_ref::<Value>())
7446        } else {
7447            None
7448        }
7449    }
7450    
7451    /// Chain with another PartialOptionalKeyPath
7452    /// Note: This requires the Value type of the first keypath to match the Root type of the second
7453    /// For type-erased chaining, consider using AnyKeyPath instead
7454    pub fn then<MidValue>(
7455        self,
7456        next: PartialOptionalKeyPath<MidValue>,
7457    ) -> PartialOptionalKeyPath<Root>
7458    where
7459        MidValue: Any + 'static,
7460        Root: 'static,
7461    {
7462        let first = self.getter;
7463        let second = next.getter;
7464        let value_type_id = next.value_type_id;
7465        
7466        PartialOptionalKeyPath {
7467            getter: Rc::new(move |root: &Root| {
7468                first(root).and_then(|any| {
7469                    if let Some(mid_value) = any.downcast_ref::<MidValue>() {
7470                        second(mid_value)
7471                    } else {
7472                        None
7473                    }
7474                })
7475            }),
7476            value_type_id,
7477            _phantom: PhantomData,
7478        }
7479    }
7480}
7481
7482/// PartialWritableKeyPath - Hides the Value type but keeps Root visible (writable)
7483/// 
7484/// # Why PhantomData<Root>?
7485/// 
7486/// See `PartialKeyPath` documentation for explanation of why `PhantomData` is needed.
7487#[derive(Clone)]
7488pub struct PartialWritableKeyPath<Root> {
7489    getter: Rc<dyn for<'r> Fn(&'r mut Root) -> &'r mut dyn Any>,
7490    value_type_id: TypeId,
7491    _phantom: PhantomData<Root>,
7492}
7493
7494impl<Root> PartialWritableKeyPath<Root> {
7495    pub fn new<Value>(keypath: WritableKeyPath<Root, Value, impl for<'r> Fn(&'r mut Root) -> &'r mut Value + 'static>) -> Self
7496    where
7497        Value: Any + 'static,
7498        Root: 'static,
7499    {
7500        let value_type_id = TypeId::of::<Value>();
7501        let getter = Rc::new(keypath.getter);
7502        
7503        Self {
7504            getter: Rc::new(move |root: &mut Root| {
7505                let value: &mut Value = getter(root);
7506                value as &mut dyn Any
7507            }),
7508            value_type_id,
7509            _phantom: PhantomData,
7510        }
7511    }
7512    
7513    /// Create a PartialWritableKeyPath from a concrete WritableKeyPath
7514    /// Alias for `new()` for consistency with `from()` pattern
7515    pub fn from<Value>(keypath: WritableKeyPath<Root, Value, impl for<'r> Fn(&'r mut Root) -> &'r mut Value + 'static>) -> Self
7516    where
7517        Value: Any + 'static,
7518        Root: 'static,
7519    {
7520        Self::new(keypath)
7521    }
7522    
7523    pub fn get_mut<'r>(&self, root: &'r mut Root) -> &'r mut dyn Any {
7524        (self.getter)(root)
7525    }
7526    
7527    /// Get the TypeId of the Value type
7528    pub fn value_type_id(&self) -> TypeId {
7529        self.value_type_id
7530    }
7531    
7532    /// Try to downcast the result to a specific type
7533    pub fn get_mut_as<'a, Value: Any>(&self, root: &'a mut Root) -> Option<&'a mut Value> {
7534        if self.value_type_id == TypeId::of::<Value>() {
7535            self.get_mut(root).downcast_mut::<Value>()
7536        } else {
7537            None
7538        }
7539    }
7540}
7541
7542/// PartialWritableOptionalKeyPath - Hides the Value type but keeps Root visible (writable optional)
7543/// 
7544/// # Why PhantomData<Root>?
7545/// 
7546/// See `PartialKeyPath` documentation for explanation of why `PhantomData` is needed.
7547#[derive(Clone)]
7548pub struct PartialWritableOptionalKeyPath<Root> {
7549    getter: Rc<dyn for<'r> Fn(&'r mut Root) -> Option<&'r mut dyn Any>>,
7550    value_type_id: TypeId,
7551    _phantom: PhantomData<Root>,
7552}
7553
7554impl<Root> PartialWritableOptionalKeyPath<Root> {
7555    pub fn new<Value>(keypath: WritableOptionalKeyPath<Root, Value, impl for<'r> Fn(&'r mut Root) -> Option<&'r mut Value> + 'static>) -> Self
7556    where
7557        Value: Any + 'static,
7558        Root: 'static,
7559    {
7560        let value_type_id = TypeId::of::<Value>();
7561        let getter = Rc::new(keypath.getter);
7562        
7563        Self {
7564            getter: Rc::new(move |root: &mut Root| {
7565                getter(root).map(|value: &mut Value| value as &mut dyn Any)
7566            }),
7567            value_type_id,
7568            _phantom: PhantomData,
7569        }
7570    }
7571    
7572    pub fn get_mut<'r>(&self, root: &'r mut Root) -> Option<&'r mut dyn Any> {
7573        (self.getter)(root)
7574    }
7575    
7576    /// Get the TypeId of the Value type
7577    pub fn value_type_id(&self) -> TypeId {
7578        self.value_type_id
7579    }
7580    
7581    /// Try to downcast the result to a specific type
7582    pub fn get_mut_as<'a, Value: Any>(&self, root: &'a mut Root) -> Option<Option<&'a mut Value>> {
7583        if self.value_type_id == TypeId::of::<Value>() {
7584            self.get_mut(root).map(|any| any.downcast_mut::<Value>())
7585        } else {
7586            None
7587        }
7588    }
7589}
7590
7591// ========== ANY KEYPATHS (Hide Both Root and Value Types) ==========
7592
7593/// AnyKeyPath - Hides both Root and Value types
7594/// Equivalent to Swift's AnyKeyPath
7595/// Useful for storing keypaths in collections without knowing either type
7596/// 
7597/// # Why No PhantomData?
7598/// 
7599/// Unlike `PartialKeyPath`, `AnyKeyPath` doesn't need `PhantomData` because:
7600/// - Both `Root` and `Value` types are completely erased
7601/// - We store `TypeId` instead for runtime type checking
7602/// - The type information is encoded in the closure's behavior, not the struct
7603/// - There's no generic type parameter to track at compile time
7604#[derive(Clone)]
7605pub struct AnyKeyPath {
7606    getter: Rc<dyn for<'r> Fn(&'r dyn Any) -> Option<&'r dyn Any>>,
7607    root_type_id: TypeId,
7608    value_type_id: TypeId,
7609}
7610
7611impl AnyKeyPath {
7612    pub fn new<Root, Value>(keypath: OptionalKeyPath<Root, Value, impl for<'r> Fn(&'r Root) -> Option<&'r Value> + 'static>) -> Self
7613    where
7614        Root: Any + 'static,
7615        Value: Any + 'static,
7616    {
7617        let root_type_id = TypeId::of::<Root>();
7618        let value_type_id = TypeId::of::<Value>();
7619        let getter = keypath.getter;
7620        
7621        Self {
7622            getter: Rc::new(move |any: &dyn Any| {
7623                if let Some(root) = any.downcast_ref::<Root>() {
7624                    getter(root).map(|value: &Value| value as &dyn Any)
7625                } else {
7626                    None
7627                }
7628            }),
7629            root_type_id,
7630            value_type_id,
7631        }
7632    }
7633    
7634    /// Create an AnyKeyPath from a concrete OptionalKeyPath
7635    /// Alias for `new()` for consistency with `from()` pattern
7636    pub fn from<Root, Value>(keypath: OptionalKeyPath<Root, Value, impl for<'r> Fn(&'r Root) -> Option<&'r Value> + 'static>) -> Self
7637    where
7638        Root: Any + 'static,
7639        Value: Any + 'static,
7640    {
7641        Self::new(keypath)
7642    }
7643    
7644    pub fn get<'r>(&self, root: &'r dyn Any) -> Option<&'r dyn Any> {
7645        (self.getter)(root)
7646    }
7647    
7648    /// Get the TypeId of the Root type
7649    pub fn root_type_id(&self) -> TypeId {
7650        self.root_type_id
7651    }
7652    
7653    /// Get the TypeId of the Value type
7654    pub fn value_type_id(&self) -> TypeId {
7655        self.value_type_id
7656    }
7657    
7658    /// Try to get the value with type checking
7659    pub fn get_as<'a, Root: Any, Value: Any>(&self, root: &'a Root) -> Option<Option<&'a Value>> {
7660        if self.root_type_id == TypeId::of::<Root>() && self.value_type_id == TypeId::of::<Value>() {
7661            self.get(root as &dyn Any).map(|any| any.downcast_ref::<Value>())
7662        } else {
7663            None
7664        }
7665    }
7666    
7667    /// Get a human-readable name for the value type
7668    /// Returns a string representation of the TypeId
7669    pub fn kind_name(&self) -> String {
7670        format!("{:?}", self.value_type_id)
7671    }
7672    
7673    /// Adapt this keypath to work with Arc<Root> instead of Root
7674    pub fn for_arc<Root>(&self) -> AnyKeyPath
7675    where
7676        Root: Any + 'static,
7677    {
7678        let root_type_id = self.root_type_id;
7679        let value_type_id = self.value_type_id;
7680        let getter = self.getter.clone();
7681        
7682        AnyKeyPath {
7683            getter: Rc::new(move |any: &dyn Any| {
7684                if let Some(arc) = any.downcast_ref::<Arc<Root>>() {
7685                    getter(arc.as_ref() as &dyn Any)
7686                } else {
7687                    None
7688                }
7689            }),
7690            root_type_id: TypeId::of::<Arc<Root>>(),
7691            value_type_id,
7692        }
7693    }
7694    
7695    /// Adapt this keypath to work with Box<Root> instead of Root
7696    pub fn for_box<Root>(&self) -> AnyKeyPath
7697    where
7698        Root: Any + 'static,
7699    {
7700        let root_type_id = self.root_type_id;
7701        let value_type_id = self.value_type_id;
7702        let getter = self.getter.clone();
7703        
7704        AnyKeyPath {
7705            getter: Rc::new(move |any: &dyn Any| {
7706                if let Some(boxed) = any.downcast_ref::<Box<Root>>() {
7707                    getter(boxed.as_ref() as &dyn Any)
7708                } else {
7709                    None
7710                }
7711            }),
7712            root_type_id: TypeId::of::<Box<Root>>(),
7713            value_type_id,
7714        }
7715    }
7716    
7717    /// Adapt this keypath to work with Rc<Root> instead of Root
7718    pub fn for_rc<Root>(&self) -> AnyKeyPath
7719    where
7720        Root: Any + 'static,
7721    {
7722        let root_type_id = self.root_type_id;
7723        let value_type_id = self.value_type_id;
7724        let getter = self.getter.clone();
7725        
7726        AnyKeyPath {
7727            getter: Rc::new(move |any: &dyn Any| {
7728                if let Some(rc) = any.downcast_ref::<Rc<Root>>() {
7729                    getter(rc.as_ref() as &dyn Any)
7730                } else {
7731                    None
7732                }
7733            }),
7734            root_type_id: TypeId::of::<Rc<Root>>(),
7735            value_type_id,
7736        }
7737    }
7738    
7739    /// Adapt this keypath to work with Option<Root> instead of Root
7740    pub fn for_option<Root>(&self) -> AnyKeyPath
7741    where
7742        Root: Any + 'static,
7743    {
7744        let root_type_id = self.root_type_id;
7745        let value_type_id = self.value_type_id;
7746        let getter = self.getter.clone();
7747        
7748        AnyKeyPath {
7749            getter: Rc::new(move |any: &dyn Any| {
7750                if let Some(opt) = any.downcast_ref::<Option<Root>>() {
7751                    opt.as_ref().and_then(|root| getter(root as &dyn Any))
7752                } else {
7753                    None
7754                }
7755            }),
7756            root_type_id: TypeId::of::<Option<Root>>(),
7757            value_type_id,
7758        }
7759    }
7760    
7761    /// Adapt this keypath to work with Result<Root, E> instead of Root
7762    pub fn for_result<Root, E>(&self) -> AnyKeyPath
7763    where
7764        Root: Any + 'static,
7765        E: Any + 'static,
7766    {
7767        let root_type_id = self.root_type_id;
7768        let value_type_id = self.value_type_id;
7769        let getter = self.getter.clone();
7770        
7771        AnyKeyPath {
7772            getter: Rc::new(move |any: &dyn Any| {
7773                if let Some(result) = any.downcast_ref::<Result<Root, E>>() {
7774                    result.as_ref().ok().and_then(|root| getter(root as &dyn Any))
7775                } else {
7776                    None
7777                }
7778            }),
7779            root_type_id: TypeId::of::<Result<Root, E>>(),
7780            value_type_id,
7781        }
7782    }
7783    
7784    /// Adapt this keypath to work with Arc<RwLock<Root>> instead of Root
7785    /// Note: This requires the Root to be cloned first, then use the keypath on the cloned value
7786    pub fn for_arc_rwlock<Root>(&self) -> AnyKeyPath
7787    where
7788        Root: Any + Clone + 'static,
7789    {
7790        // We can't return a reference from a guard, so we return None
7791        // Users should clone the root first
7792        AnyKeyPath {
7793            getter: Rc::new(move |_any: &dyn Any| {
7794                // Cannot return reference from temporary guard
7795                // User should clone the root first and use the keypath on the cloned value
7796                None
7797            }),
7798            root_type_id: TypeId::of::<Arc<RwLock<Root>>>(),
7799            value_type_id: self.value_type_id,
7800        }
7801    }
7802    
7803    /// Adapt this keypath to work with Arc<Mutex<Root>> instead of Root
7804    /// Note: This requires the Root to be cloned first, then use the keypath on the cloned value
7805    pub fn for_arc_mutex<Root>(&self) -> AnyKeyPath
7806    where
7807        Root: Any + Clone + 'static,
7808    {
7809        // We can't return a reference from a guard, so we return None
7810        // Users should clone the root first
7811        AnyKeyPath {
7812            getter: Rc::new(move |_any: &dyn Any| {
7813                // Cannot return reference from temporary guard
7814                // User should clone the root first and use the keypath on the cloned value
7815                None
7816            }),
7817            root_type_id: TypeId::of::<Arc<Mutex<Root>>>(),
7818            value_type_id: self.value_type_id,
7819        }
7820    }
7821}
7822
7823/// AnyWritableKeyPath - Hides both Root and Value types (writable)
7824#[derive(Clone)]
7825pub struct AnyWritableKeyPath {
7826    getter: Rc<dyn for<'r> Fn(&'r mut dyn Any) -> Option<&'r mut dyn Any>>,
7827    root_type_id: TypeId,
7828    value_type_id: TypeId,
7829}
7830
7831/// FailableCombinedKeyPath - A keypath that supports readable, writable, and owned access patterns
7832/// 
7833/// This keypath type combines the functionality of OptionalKeyPath, WritableOptionalKeyPath,
7834/// and adds owned access. It's useful when you need all three access patterns for the same field.
7835#[derive(Clone)]
7836pub struct FailableCombinedKeyPath<Root, Value, ReadFn, WriteFn, OwnedFn>
7837where
7838    ReadFn: for<'r> Fn(&'r Root) -> Option<&'r Value> + 'static,
7839    WriteFn: for<'r> Fn(&'r mut Root) -> Option<&'r mut Value> + 'static,
7840    OwnedFn: Fn(Root) -> Option<Value> + 'static,
7841{
7842    readable: ReadFn,
7843    writable: WriteFn,
7844    owned: OwnedFn,
7845    _phantom: PhantomData<(Root, Value)>,
7846}
7847
7848impl<Root, Value, ReadFn, WriteFn, OwnedFn> FailableCombinedKeyPath<Root, Value, ReadFn, WriteFn, OwnedFn>
7849where
7850    ReadFn: for<'r> Fn(&'r Root) -> Option<&'r Value> + 'static,
7851    WriteFn: for<'r> Fn(&'r mut Root) -> Option<&'r mut Value> + 'static,
7852    OwnedFn: Fn(Root) -> Option<Value> + 'static,
7853{
7854    /// Create a new FailableCombinedKeyPath with all three access patterns
7855    pub fn new(readable: ReadFn, writable: WriteFn, owned: OwnedFn) -> Self {
7856        Self {
7857            readable,
7858            writable,
7859            owned,
7860            _phantom: PhantomData,
7861        }
7862    }
7863    
7864    /// Get an immutable reference to the value (readable access)
7865    pub fn get<'r>(&self, root: &'r Root) -> Option<&'r Value> {
7866        (self.readable)(root)
7867    }
7868    
7869    /// Get a mutable reference to the value (writable access)
7870    pub fn get_mut<'r>(&self, root: &'r mut Root) -> Option<&'r mut Value> {
7871        (self.writable)(root)
7872    }
7873    
7874    /// Get an owned value (owned access) - consumes the root
7875    pub fn get_failable_owned(&self, root: Root) -> Option<Value> {
7876        (self.owned)(root)
7877    }
7878    
7879    /// Convert to OptionalKeyPath (loses writable and owned capabilities)
7880    pub fn to_optional(self) -> OptionalKeyPath<Root, Value, ReadFn> {
7881        OptionalKeyPath::new(self.readable)
7882    }
7883    
7884    /// Convert to WritableOptionalKeyPath (loses owned capability)
7885    pub fn to_writable_optional(self) -> WritableOptionalKeyPath<Root, Value, WriteFn> {
7886        WritableOptionalKeyPath::new(self.writable)
7887    }
7888    
7889    /// Compose this keypath with another FailableCombinedKeyPath
7890    /// Returns a new FailableCombinedKeyPath that chains both keypaths
7891    pub fn then<SubValue, SubReadFn, SubWriteFn, SubOwnedFn>(
7892        self,
7893        next: FailableCombinedKeyPath<Value, SubValue, SubReadFn, SubWriteFn, SubOwnedFn>,
7894    ) -> 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>
7895    where
7896        SubReadFn: for<'r> Fn(&'r Value) -> Option<&'r SubValue> + 'static,
7897        SubWriteFn: for<'r> Fn(&'r mut Value) -> Option<&'r mut SubValue> + 'static,
7898        SubOwnedFn: Fn(Value) -> Option<SubValue> + 'static,
7899        ReadFn: 'static,
7900        WriteFn: 'static,
7901        OwnedFn: 'static,
7902        Value: 'static,
7903        Root: 'static,
7904        SubValue: 'static,
7905    {
7906        let first_read = self.readable;
7907        let first_write = self.writable;
7908        let first_owned = self.owned;
7909        let second_read = next.readable;
7910        let second_write = next.writable;
7911        let second_owned = next.owned;
7912        
7913        FailableCombinedKeyPath::new(
7914            move |root: &Root| {
7915                first_read(root).and_then(|value| second_read(value))
7916            },
7917            move |root: &mut Root| {
7918                first_write(root).and_then(|value| second_write(value))
7919            },
7920            move |root: Root| {
7921                first_owned(root).and_then(|value| second_owned(value))
7922            },
7923        )
7924    }
7925    
7926    /// Compose with OptionalKeyPath (readable only)
7927    /// Returns a FailableCombinedKeyPath that uses the readable from OptionalKeyPath
7928    /// and creates dummy writable/owned closures that return None
7929    pub fn chain_optional<SubValue, SubReadFn>(
7930        self,
7931        next: OptionalKeyPath<Value, SubValue, SubReadFn>,
7932    ) -> 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>
7933    where
7934        SubReadFn: for<'r> Fn(&'r Value) -> Option<&'r SubValue> + 'static,
7935        ReadFn: 'static,
7936        WriteFn: 'static,
7937        OwnedFn: 'static,
7938        Value: 'static,
7939        Root: 'static,
7940        SubValue: 'static,
7941    {
7942        let first_read = self.readable;
7943        let first_write = self.writable;
7944        let first_owned = self.owned;
7945        let second_read = next.getter;
7946        
7947        FailableCombinedKeyPath::new(
7948            move |root: &Root| {
7949                first_read(root).and_then(|value| second_read(value))
7950            },
7951            move |_root: &mut Root| {
7952                None // Writable not supported when composing with OptionalKeyPath
7953            },
7954            move |root: Root| {
7955                first_owned(root).and_then(|value| {
7956                    // Try to get owned value, but OptionalKeyPath doesn't support owned
7957                    None
7958                })
7959            },
7960        )
7961    }
7962}
7963
7964// Factory function for FailableCombinedKeyPath
7965impl FailableCombinedKeyPath<(), (), fn(&()) -> Option<&()>, fn(&mut ()) -> Option<&mut ()>, fn(()) -> Option<()>> {
7966    /// Create a FailableCombinedKeyPath with all three access patterns
7967    pub fn failable_combined<Root, Value, ReadFn, WriteFn, OwnedFn>(
7968        readable: ReadFn,
7969        writable: WriteFn,
7970        owned: OwnedFn,
7971    ) -> FailableCombinedKeyPath<Root, Value, ReadFn, WriteFn, OwnedFn>
7972    where
7973        ReadFn: for<'r> Fn(&'r Root) -> Option<&'r Value> + 'static,
7974        WriteFn: for<'r> Fn(&'r mut Root) -> Option<&'r mut Value> + 'static,
7975        OwnedFn: Fn(Root) -> Option<Value> + 'static,
7976    {
7977        FailableCombinedKeyPath::new(readable, writable, owned)
7978    }
7979}
7980
7981impl AnyWritableKeyPath {
7982    pub fn new<Root, Value>(keypath: WritableOptionalKeyPath<Root, Value, impl for<'r> Fn(&'r mut Root) -> Option<&'r mut Value> + 'static>) -> Self
7983    where
7984        Root: Any + 'static,
7985        Value: Any + 'static,
7986    {
7987        let root_type_id = TypeId::of::<Root>();
7988        let value_type_id = TypeId::of::<Value>();
7989        let getter = keypath.getter;
7990        
7991        Self {
7992            getter: Rc::new(move |any: &mut dyn Any| {
7993                if let Some(root) = any.downcast_mut::<Root>() {
7994                    getter(root).map(|value: &mut Value| value as &mut dyn Any)
7995                } else {
7996                    None
7997                }
7998            }),
7999            root_type_id,
8000            value_type_id,
8001        }
8002    }
8003    
8004    pub fn get_mut<'r>(&self, root: &'r mut dyn Any) -> Option<&'r mut dyn Any> {
8005        (self.getter)(root)
8006    }
8007    
8008    /// Get the TypeId of the Root type
8009    pub fn root_type_id(&self) -> TypeId {
8010        self.root_type_id
8011    }
8012    
8013    /// Get the TypeId of the Value type
8014    pub fn value_type_id(&self) -> TypeId {
8015        self.value_type_id
8016    }
8017    
8018    /// Try to get the value with type checking
8019    pub fn get_mut_as<'a, Root: Any, Value: Any>(&self, root: &'a mut Root) -> Option<Option<&'a mut Value>> {
8020        if self.root_type_id == TypeId::of::<Root>() && self.value_type_id == TypeId::of::<Value>() {
8021            self.get_mut(root as &mut dyn Any).map(|any| any.downcast_mut::<Value>())
8022        } else {
8023            None
8024        }
8025    }
8026}
8027
8028// Conversion methods from concrete keypaths to partial/any keypaths
8029impl<Root, Value, F> KeyPath<Root, Value, F>
8030where
8031    F: for<'r> Fn(&'r Root) -> &'r Value + 'static,
8032    Root: 'static,
8033    Value: Any + 'static,
8034{
8035    /// Convert to PartialKeyPath (hides Value type)
8036    pub fn to_partial(self) -> PartialKeyPath<Root> {
8037        PartialKeyPath::new(self)
8038    }
8039    
8040    /// Alias for `to_partial()` - converts to PartialKeyPath
8041    pub fn to(self) -> PartialKeyPath<Root> {
8042        self.to_partial()
8043    }
8044}
8045
8046impl<Root, Value, F> OptionalKeyPath<Root, Value, F>
8047where
8048    F: for<'r> Fn(&'r Root) -> Option<&'r Value> + 'static,
8049    Root: Any + 'static,
8050    Value: Any + 'static,
8051{
8052    /// Convert to PartialOptionalKeyPath (hides Value type)
8053    pub fn to_partial(self) -> PartialOptionalKeyPath<Root> {
8054        PartialOptionalKeyPath::new(self)
8055    }
8056    
8057    /// Convert to AnyKeyPath (hides both Root and Value types)
8058    pub fn to_any(self) -> AnyKeyPath {
8059        AnyKeyPath::new(self)
8060    }
8061    
8062    /// Convert to PartialOptionalKeyPath (alias for `to_partial()`)
8063    pub fn to(self) -> PartialOptionalKeyPath<Root> {
8064        self.to_partial()
8065    }
8066}
8067
8068impl<Root, Value, F> WritableKeyPath<Root, Value, F>
8069where
8070    F: for<'r> Fn(&'r mut Root) -> &'r mut Value + 'static,
8071    Root: 'static,
8072    Value: Any + 'static,
8073{
8074    /// Convert to PartialWritableKeyPath (hides Value type)
8075    pub fn to_partial(self) -> PartialWritableKeyPath<Root> {
8076        PartialWritableKeyPath::new(self)
8077    }
8078    
8079    /// Alias for `to_partial()` - converts to PartialWritableKeyPath
8080    pub fn to(self) -> PartialWritableKeyPath<Root> {
8081        self.to_partial()
8082    }
8083}
8084
8085impl<Root, Value, F> WritableOptionalKeyPath<Root, Value, F>
8086where
8087    F: for<'r> Fn(&'r mut Root) -> Option<&'r mut Value> + 'static,
8088    Root: Any + 'static,
8089    Value: Any + 'static,
8090{
8091    /// Convert to PartialWritableOptionalKeyPath (hides Value type)
8092    pub fn to_partial(self) -> PartialWritableOptionalKeyPath<Root> {
8093        PartialWritableOptionalKeyPath::new(self)
8094    }
8095    
8096    /// Convert to AnyWritableKeyPath (hides both Root and Value types)
8097    pub fn to_any(self) -> AnyWritableKeyPath {
8098        AnyWritableKeyPath::new(self)
8099    }
8100    
8101    /// Convert to PartialWritableOptionalKeyPath (alias for `to_partial()`)
8102    pub fn to(self) -> PartialWritableOptionalKeyPath<Root> {
8103        self.to_partial()
8104    }
8105}
8106
8107// ========== SHR OPERATOR IMPLEMENTATIONS (>> operator) ==========
8108// 
8109// The `>>` operator provides the same functionality as `then()` methods.
8110// It requires nightly Rust with the `nightly` feature enabled.
8111//
8112// Usage example (requires nightly):
8113// ```rust
8114// #![feature(impl_trait_in_assoc_type)]  // Must be in YOUR code
8115// use rust_keypaths::{keypath, KeyPath};
8116// 
8117// struct User { address: Address }
8118// struct Address { street: String }
8119// 
8120// let kp1 = keypath!(|u: &User| &u.address);
8121// let kp2 = keypath!(|a: &Address| &a.street);
8122// let chained = kp1 >> kp2; // Works with nightly feature
8123// ```
8124//
8125// On stable Rust, use `keypath1.then(keypath2)` instead.
8126//
8127// Supported combinations (same as `then()` methods):
8128// - `KeyPath >> KeyPath` → `KeyPath`
8129// - `KeyPath >> OptionalKeyPath` → `OptionalKeyPath`
8130// - `OptionalKeyPath >> OptionalKeyPath` → `OptionalKeyPath`
8131// - `WritableKeyPath >> WritableKeyPath` → `WritableKeyPath`
8132// - `WritableKeyPath >> WritableOptionalKeyPath` → `WritableOptionalKeyPath`
8133// - `WritableOptionalKeyPath >> WritableOptionalKeyPath` → `WritableOptionalKeyPath`
8134
8135// #[cfg(feature = "nightly")]
8136// mod shr_impls {
8137//     use super::*;
8138//
8139//     // Implement Shr for KeyPath >> KeyPath: returns KeyPath
8140//     impl<Root, Value, F, SubValue, G> Shr<KeyPath<Value, SubValue, G>> for KeyPath<Root, Value, F>
8141//     where
8142//         F: for<'r> Fn(&'r Root) -> &'r Value + 'static,
8143//         G: for<'r> Fn(&'r Value) -> &'r SubValue + 'static,
8144//         Value: 'static,
8145//     {
8146//         type Output = KeyPath<Root, SubValue, impl for<'r> Fn(&'r Root) -> &'r SubValue>;
8147//
8148//         fn shr(self, rhs: KeyPath<Value, SubValue, G>) -> Self::Output {
8149//             self.then(rhs)
8150//         }
8151//     }
8152//
8153//     // Implement Shr for KeyPath >> OptionalKeyPath: returns OptionalKeyPath
8154//     impl<Root, Value, F, SubValue, G> Shr<OptionalKeyPath<Value, SubValue, G>> for KeyPath<Root, Value, F>
8155//     where
8156//         F: for<'r> Fn(&'r Root) -> &'r Value + 'static,
8157//         G: for<'r> Fn(&'r Value) -> Option<&'r SubValue> + 'static,
8158//         Value: 'static,
8159//     {
8160//         type Output = OptionalKeyPath<Root, SubValue, impl for<'r> Fn(&'r Root) -> Option<&'r SubValue>>;
8161//
8162//         fn shr(self, rhs: OptionalKeyPath<Value, SubValue, G>) -> Self::Output {
8163//             self.chain_optional(rhs)
8164//         }
8165//     }
8166//
8167//     // Implement Shr for OptionalKeyPath >> OptionalKeyPath: returns OptionalKeyPath
8168//     impl<Root, Value, F, SubValue, G> Shr<OptionalKeyPath<Value, SubValue, G>> for OptionalKeyPath<Root, Value, F>
8169//     where
8170//         F: for<'r> Fn(&'r Root) -> Option<&'r Value> + 'static,
8171//         G: for<'r> Fn(&'r Value) -> Option<&'r SubValue> + 'static,
8172//         Value: 'static,
8173//     {
8174//         type Output = OptionalKeyPath<Root, SubValue, impl for<'r> Fn(&'r Root) -> Option<&'r SubValue>>;
8175//
8176//         fn shr(self, rhs: OptionalKeyPath<Value, SubValue, G>) -> Self::Output {
8177//             self.then(rhs)
8178//         }
8179//     }
8180//
8181//     // Implement Shr for WritableKeyPath >> WritableKeyPath: returns WritableKeyPath
8182//     impl<Root, Value, F, SubValue, G> Shr<WritableKeyPath<Value, SubValue, G>> for WritableKeyPath<Root, Value, F>
8183//     where
8184//         F: for<'r> Fn(&'r mut Root) -> &'r mut Value + 'static,
8185//         G: for<'r> Fn(&'r mut Value) -> &'r mut SubValue + 'static,
8186//         Value: 'static,
8187//     {
8188//         type Output = WritableKeyPath<Root, SubValue, impl for<'r> Fn(&'r mut Root) -> &'r mut SubValue>;
8189//
8190//         fn shr(self, rhs: WritableKeyPath<Value, SubValue, G>) -> Self::Output {
8191//             self.then(rhs)
8192//         }
8193//     }
8194//
8195//     // Implement Shr for WritableKeyPath >> WritableOptionalKeyPath: returns WritableOptionalKeyPath
8196//     impl<Root, Value, F, SubValue, G> Shr<WritableOptionalKeyPath<Value, SubValue, G>> for WritableKeyPath<Root, Value, F>
8197//     where
8198//         F: for<'r> Fn(&'r mut Root) -> &'r mut Value + 'static,
8199//         G: for<'r> Fn(&'r mut Value) -> Option<&'r mut SubValue> + 'static,
8200//         Value: 'static,
8201//     {
8202//         type Output = WritableOptionalKeyPath<Root, SubValue, impl for<'r> Fn(&'r mut Root) -> Option<&'r mut SubValue>>;
8203//
8204//         fn shr(self, rhs: WritableOptionalKeyPath<Value, SubValue, G>) -> Self::Output {
8205//             self.chain_optional(rhs)
8206//         }
8207//     }
8208//
8209//     // Implement Shr for WritableOptionalKeyPath >> WritableOptionalKeyPath: returns WritableOptionalKeyPath
8210//     impl<Root, Value, F, SubValue, G> Shr<WritableOptionalKeyPath<Value, SubValue, G>> for WritableOptionalKeyPath<Root, Value, F>
8211//     where
8212//         F: for<'r> Fn(&'r mut Root) -> Option<&'r mut Value> + 'static,
8213//         G: for<'r> Fn(&'r mut Value) -> Option<&'r mut SubValue> + 'static,
8214//         Value: 'static,
8215//     {
8216//         type Output = WritableOptionalKeyPath<Root, SubValue, impl for<'r> Fn(&'r mut Root) -> Option<&'r mut SubValue>>;
8217//
8218//         fn shr(self, rhs: WritableOptionalKeyPath<Value, SubValue, G>) -> Self::Output {
8219//             self.then(rhs)
8220//         }
8221//     }
8222// }
8223
8224#[cfg(test)]
8225mod tests {
8226    use super::*;
8227    use std::sync::atomic::{AtomicUsize, Ordering};
8228    use std::rc::Rc;
8229
8230    // Global counter to track memory allocations/deallocations
8231    static ALLOC_COUNT: AtomicUsize = AtomicUsize::new(0);
8232    static DEALLOC_COUNT: AtomicUsize = AtomicUsize::new(0);
8233
8234    // Type that panics on clone to detect unwanted cloning
8235    #[derive(Debug)]
8236    struct NoCloneType {
8237        id: usize,
8238        data: String,
8239    }
8240
8241    impl NoCloneType {
8242        fn new(data: String) -> Self {
8243            ALLOC_COUNT.fetch_add(1, Ordering::SeqCst);
8244            Self {
8245                id: ALLOC_COUNT.load(Ordering::SeqCst),
8246                data,
8247            }
8248        }
8249    }
8250
8251    impl Clone for NoCloneType {
8252        fn clone(&self) -> Self {
8253            eprintln!("[DEBUG] NoCloneType should not be cloned! ID: {}", self.id);
8254            unreachable!("NoCloneType should not be cloned! ID: {}", self.id);
8255        }
8256    }
8257
8258    impl Drop for NoCloneType {
8259        fn drop(&mut self) {
8260            DEALLOC_COUNT.fetch_add(1, Ordering::SeqCst);
8261        }
8262    }
8263
8264    // Helper functions for testing memory management
8265    fn reset_memory_counters() {
8266        ALLOC_COUNT.store(0, Ordering::SeqCst);
8267        DEALLOC_COUNT.store(0, Ordering::SeqCst);
8268    }
8269
8270    fn get_alloc_count() -> usize {
8271        ALLOC_COUNT.load(Ordering::SeqCst)
8272    }
8273
8274    fn get_dealloc_count() -> usize {
8275        DEALLOC_COUNT.load(Ordering::SeqCst)
8276    }
8277
8278// Usage example
8279#[derive(Debug)]
8280struct User {
8281    name: String,
8282    metadata: Option<Box<UserMetadata>>,
8283    friends: Vec<Arc<User>>,
8284}
8285
8286#[derive(Debug)]
8287struct UserMetadata {
8288    created_at: String,
8289}
8290
8291fn some_fn() {
8292        let akash = User {
8293        name: "Alice".to_string(),
8294        metadata: Some(Box::new(UserMetadata {
8295            created_at: "2024-01-01".to_string(),
8296        })),
8297        friends: vec![
8298            Arc::new(User {
8299                name: "Bob".to_string(),
8300                metadata: None,
8301                friends: vec![],
8302            }),
8303        ],
8304    };
8305    
8306    // Create keypaths
8307    let name_kp = KeyPath::new(|u: &User| &u.name);
8308    let metadata_kp = OptionalKeyPath::new(|u: &User| u.metadata.as_ref());
8309    let friends_kp = KeyPath::new(|u: &User| &u.friends);
8310    
8311    // Use them
8312        println!("Name: {}", name_kp.get(&akash));
8313    
8314        if let Some(metadata) = metadata_kp.get(&akash) {
8315        println!("Has metadata: {:?}", metadata);
8316    }
8317    
8318    // Access first friend's name
8319        if let Some(first_friend) = akash.friends.get(0) {
8320        println!("First friend: {}", name_kp.get(first_friend));
8321    }
8322    
8323        // Access metadata through Box using for_box()
8324    let created_at_kp = KeyPath::new(|m: &UserMetadata| &m.created_at);
8325    
8326        if let Some(metadata) = akash.metadata.as_ref() {
8327            // Use for_box() to unwrap Box<UserMetadata> to &UserMetadata
8328            let boxed_metadata: &Box<UserMetadata> = metadata;
8329            let unwrapped = boxed_metadata.as_ref();
8330            println!("Created at: {:?}", created_at_kp.get(unwrapped));
8331        }
8332    }
8333
8334    #[test]
8335    fn test_name() {
8336        some_fn();
8337    }
8338    
8339    #[test]
8340    fn test_no_cloning_on_keypath_operations() {
8341        reset_memory_counters();
8342        
8343        // Create a value that panics on clone
8344        let value = NoCloneType::new("test".to_string());
8345        let boxed = Box::new(value);
8346        
8347        // Create keypath - should not clone
8348        let kp = KeyPath::new(|b: &Box<NoCloneType>| b.as_ref());
8349        
8350        // Access value - should not clone
8351        let _ref = kp.get(&boxed);
8352        
8353        // Clone the keypath itself (this is allowed)
8354        let _kp_clone = kp.clone();
8355        
8356        // Access again - should not clone the value
8357        let _ref2 = _kp_clone.get(&boxed);
8358        
8359        // Verify no panics occurred (if we got here, no cloning happened)
8360        assert_eq!(get_alloc_count(), 1);
8361    }
8362    
8363    #[test]
8364    fn test_no_cloning_on_optional_keypath_operations() {
8365        reset_memory_counters();
8366        
8367        let value = NoCloneType::new("test".to_string());
8368        let opt = Some(Box::new(value));
8369        
8370        // Create optional keypath
8371        let okp = OptionalKeyPath::new(|o: &Option<Box<NoCloneType>>| o.as_ref());
8372        
8373        // Access - should not clone
8374        let _ref = okp.get(&opt);
8375        
8376        // Clone keypath (allowed)
8377        let _okp_clone = okp.clone();
8378        
8379        // Chain operations - should not clone values
8380        let chained = okp.then(OptionalKeyPath::new(|b: &Box<NoCloneType>| Some(b.as_ref())));
8381        let _ref2 = chained.get(&opt);
8382        
8383        assert_eq!(get_alloc_count(), 1);
8384    }
8385    
8386    #[test]
8387    fn test_memory_release() {
8388        reset_memory_counters();
8389        
8390        {
8391            let value = NoCloneType::new("test".to_string());
8392            let boxed = Box::new(value);
8393            let kp = KeyPath::new(|b: &Box<NoCloneType>| b.as_ref());
8394            
8395            // Use the keypath
8396            let _ref = kp.get(&boxed);
8397            
8398            // boxed goes out of scope here
8399        }
8400        
8401        // After drop, memory should be released
8402        // Note: This is a best-effort check since drop timing can vary
8403        assert_eq!(get_alloc_count(), 1);
8404        // Deallocation happens when the value is dropped
8405        // We can't reliably test exact timing, but we verify the counter exists
8406    }
8407    
8408    #[test]
8409    fn test_keypath_clone_does_not_clone_underlying_data() {
8410        reset_memory_counters();
8411        
8412        let value = NoCloneType::new("data".to_string());
8413        let rc_value = Rc::new(value);
8414        
8415        // Create keypath
8416        let kp = KeyPath::new(|r: &Rc<NoCloneType>| r.as_ref());
8417        
8418        // Clone keypath multiple times
8419        let kp1 = kp.clone();
8420        let kp2 = kp.clone();
8421        let kp3 = kp1.clone();
8422        
8423        // All should work without cloning the underlying data
8424        let _ref1 = kp.get(&rc_value);
8425        let _ref2 = kp1.get(&rc_value);
8426        let _ref3 = kp2.get(&rc_value);
8427        let _ref4 = kp3.get(&rc_value);
8428        
8429        // Only one allocation should have happened
8430        assert_eq!(get_alloc_count(), 1);
8431    }
8432    
8433    #[test]
8434    fn test_optional_keypath_chaining_no_clone() {
8435        reset_memory_counters();
8436        
8437        let value = NoCloneType::new("value1".to_string());
8438        
8439        struct Container {
8440            inner: Option<Box<NoCloneType>>,
8441        }
8442        
8443        let container = Container {
8444            inner: Some(Box::new(value)),
8445        };
8446        
8447        // Create chained keypath
8448        let kp1 = OptionalKeyPath::new(|c: &Container| c.inner.as_ref());
8449        let kp2 = OptionalKeyPath::new(|b: &Box<NoCloneType>| Some(b.as_ref()));
8450        
8451        // Chain them - should not clone
8452        let chained = kp1.then(kp2);
8453        
8454        // Use chained keypath
8455        let _result = chained.get(&container);
8456        
8457        // Should only have one allocation
8458        assert_eq!(get_alloc_count(), 1);
8459    }
8460    
8461    #[test]
8462    fn test_for_box_no_clone() {
8463        reset_memory_counters();
8464        
8465        let value = NoCloneType::new("test".to_string());
8466        let boxed = Box::new(value);
8467        let opt_boxed = Some(boxed);
8468        
8469        // Create keypath with for_box
8470        let kp = OptionalKeyPath::new(|o: &Option<Box<NoCloneType>>| o.as_ref());
8471        let unwrapped = kp.for_box();
8472        
8473        // Access - should not clone
8474        let _ref = unwrapped.get(&opt_boxed);
8475        
8476        assert_eq!(get_alloc_count(), 1);
8477    }
8478    
8479    // ========== MACRO USAGE EXAMPLES ==========
8480    
8481    #[derive(Debug, PartialEq)]
8482    struct TestUser {
8483        name: String,
8484        age: u32,
8485        metadata: Option<String>,
8486        address: Option<TestAddress>,
8487    }
8488    
8489    #[derive(Debug, PartialEq)]
8490    struct TestAddress {
8491        street: String,
8492        city: String,
8493        country: Option<TestCountry>,
8494    }
8495    
8496    #[derive(Debug, PartialEq)]
8497    struct TestCountry {
8498        name: String,
8499    }
8500    
8501    #[test]
8502    fn test_keypath_macro() {
8503        let user = TestUser {
8504            name: "Alice".to_string(),
8505            age: 30,
8506            metadata: None,
8507            address: None,
8508        };
8509        
8510        // Simple field access using closure
8511        let name_kp = keypath!(|u: &TestUser| &u.name);
8512        assert_eq!(name_kp.get(&user), "Alice");
8513        
8514        // Nested field access
8515        let user_with_address = TestUser {
8516            name: "Bob".to_string(),
8517            age: 25,
8518            metadata: None,
8519            address: Some(TestAddress {
8520                street: "123 Main St".to_string(),
8521                city: "New York".to_string(),
8522                country: None,
8523            }),
8524        };
8525        
8526        let street_kp = keypath!(|u: &TestUser| &u.address.as_ref().unwrap().street);
8527        assert_eq!(street_kp.get(&user_with_address), "123 Main St");
8528        
8529        // Deeper nesting
8530        let user_with_country = TestUser {
8531            name: "Charlie".to_string(),
8532            age: 35,
8533            metadata: None,
8534            address: Some(TestAddress {
8535                street: "456 Oak Ave".to_string(),
8536                city: "London".to_string(),
8537                country: Some(TestCountry {
8538                    name: "UK".to_string(),
8539                }),
8540            }),
8541        };
8542        
8543        let country_name_kp = keypath!(|u: &TestUser| &u.address.as_ref().unwrap().country.as_ref().unwrap().name);
8544        assert_eq!(country_name_kp.get(&user_with_country), "UK");
8545        
8546        // Fallback: using closure
8547        let age_kp = keypath!(|u: &TestUser| &u.age);
8548        assert_eq!(age_kp.get(&user), &30);
8549    }
8550    
8551    #[test]
8552    fn test_opt_keypath_macro() {
8553        let user = TestUser {
8554            name: "Alice".to_string(),
8555            age: 30,
8556            metadata: Some("admin".to_string()),
8557            address: None,
8558        };
8559        
8560        // Simple Option field access using closure
8561        let metadata_kp = opt_keypath!(|u: &TestUser| u.metadata.as_ref());
8562        assert_eq!(metadata_kp.get(&user), Some(&"admin".to_string()));
8563        
8564        // None case
8565        let user_no_metadata = TestUser {
8566            name: "Bob".to_string(),
8567            age: 25,
8568            metadata: None,
8569            address: None,
8570        };
8571        assert_eq!(metadata_kp.get(&user_no_metadata), None);
8572        
8573        // Nested Option access
8574        let user_with_address = TestUser {
8575            name: "Charlie".to_string(),
8576            age: 35,
8577            metadata: None,
8578            address: Some(TestAddress {
8579                street: "789 Pine Rd".to_string(),
8580                city: "Paris".to_string(),
8581                country: None,
8582            }),
8583        };
8584        
8585        let street_kp = opt_keypath!(|u: &TestUser| u.address.as_ref().map(|a| &a.street));
8586        assert_eq!(street_kp.get(&user_with_address), Some(&"789 Pine Rd".to_string()));
8587        
8588        // Deeper nesting through Options
8589        let user_with_country = TestUser {
8590            name: "David".to_string(),
8591            age: 40,
8592            metadata: None,
8593            address: Some(TestAddress {
8594                street: "321 Elm St".to_string(),
8595                city: "Tokyo".to_string(),
8596                country: Some(TestCountry {
8597                    name: "Japan".to_string(),
8598                }),
8599            }),
8600        };
8601        
8602        let country_name_kp = opt_keypath!(|u: &TestUser| u.address.as_ref().and_then(|a| a.country.as_ref().map(|c| &c.name)));
8603        assert_eq!(country_name_kp.get(&user_with_country), Some(&"Japan".to_string()));
8604        
8605        // Fallback: using closure
8606        let metadata_kp2 = opt_keypath!(|u: &TestUser| u.metadata.as_ref());
8607        assert_eq!(metadata_kp2.get(&user), Some(&"admin".to_string()));
8608    }
8609    
8610    #[test]
8611    fn test_writable_keypath_macro() {
8612        let mut user = TestUser {
8613            name: "Alice".to_string(),
8614            age: 30,
8615            metadata: None,
8616            address: None,
8617        };
8618        
8619        // Simple field mutation using closure
8620        let name_kp = writable_keypath!(|u: &mut TestUser| &mut u.name);
8621        *name_kp.get_mut(&mut user) = "Bob".to_string();
8622        assert_eq!(user.name, "Bob");
8623        
8624        // Nested field mutation
8625        let mut user_with_address = TestUser {
8626            name: "Charlie".to_string(),
8627            age: 25,
8628            metadata: None,
8629            address: Some(TestAddress {
8630                street: "123 Main St".to_string(),
8631                city: "New York".to_string(),
8632                country: None,
8633            }),
8634        };
8635        
8636        let street_kp = writable_keypath!(|u: &mut TestUser| &mut u.address.as_mut().unwrap().street);
8637        *street_kp.get_mut(&mut user_with_address) = "456 Oak Ave".to_string();
8638        assert_eq!(user_with_address.address.as_ref().unwrap().street, "456 Oak Ave");
8639        
8640        // Deeper nesting
8641        let mut user_with_country = TestUser {
8642            name: "David".to_string(),
8643            age: 35,
8644            metadata: None,
8645            address: Some(TestAddress {
8646                street: "789 Pine Rd".to_string(),
8647                city: "London".to_string(),
8648                country: Some(TestCountry {
8649                    name: "UK".to_string(),
8650                }),
8651            }),
8652        };
8653        
8654        let country_name_kp = writable_keypath!(|u: &mut TestUser| &mut u.address.as_mut().unwrap().country.as_mut().unwrap().name);
8655        *country_name_kp.get_mut(&mut user_with_country) = "United Kingdom".to_string();
8656        assert_eq!(user_with_country.address.as_ref().unwrap().country.as_ref().unwrap().name, "United Kingdom");
8657        
8658        // Fallback: using closure
8659        let age_kp = writable_keypath!(|u: &mut TestUser| &mut u.age);
8660        *age_kp.get_mut(&mut user) = 31;
8661        assert_eq!(user.age, 31);
8662    }
8663    
8664    #[test]
8665    fn test_writable_opt_keypath_macro() {
8666        let mut user = TestUser {
8667            name: "Alice".to_string(),
8668            age: 30,
8669            metadata: Some("user".to_string()),
8670            address: None,
8671        };
8672        
8673        // Simple Option field mutation using closure
8674        let metadata_kp = writable_opt_keypath!(|u: &mut TestUser| u.metadata.as_mut());
8675        if let Some(metadata) = metadata_kp.get_mut(&mut user) {
8676            *metadata = "admin".to_string();
8677        }
8678        assert_eq!(user.metadata, Some("admin".to_string()));
8679        
8680        // None case - should return None
8681        let mut user_no_metadata = TestUser {
8682            name: "Bob".to_string(),
8683            age: 25,
8684            metadata: None,
8685            address: None,
8686        };
8687        assert_eq!(metadata_kp.get_mut(&mut user_no_metadata), None);
8688        
8689        // Nested Option access
8690        let mut user_with_address = TestUser {
8691            name: "Charlie".to_string(),
8692            age: 35,
8693            metadata: None,
8694            address: Some(TestAddress {
8695                street: "123 Main St".to_string(),
8696                city: "New York".to_string(),
8697                country: None,
8698            }),
8699        };
8700        
8701        let street_kp = writable_opt_keypath!(|u: &mut TestUser| u.address.as_mut().map(|a| &mut a.street));
8702        if let Some(street) = street_kp.get_mut(&mut user_with_address) {
8703            *street = "456 Oak Ave".to_string();
8704        }
8705        assert_eq!(user_with_address.address.as_ref().unwrap().street, "456 Oak Ave");
8706        
8707        // Deeper nesting through Options
8708        let mut user_with_country = TestUser {
8709            name: "David".to_string(),
8710            age: 40,
8711            metadata: None,
8712            address: Some(TestAddress {
8713                street: "789 Pine Rd".to_string(),
8714                city: "Tokyo".to_string(),
8715                country: Some(TestCountry {
8716                    name: "Japan".to_string(),
8717                }),
8718            }),
8719        };
8720        
8721        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)));
8722        if let Some(country_name) = country_name_kp.get_mut(&mut user_with_country) {
8723            *country_name = "Nippon".to_string();
8724        }
8725        assert_eq!(user_with_country.address.as_ref().unwrap().country.as_ref().unwrap().name, "Nippon");
8726        
8727        // Fallback: using closure
8728        let metadata_kp2 = writable_opt_keypath!(|u: &mut TestUser| u.metadata.as_mut());
8729        if let Some(metadata) = metadata_kp2.get_mut(&mut user) {
8730            *metadata = "super_admin".to_string();
8731        }
8732        assert_eq!(user.metadata, Some("super_admin".to_string()));
8733    }
8734}
8735
8736// ========== WithContainer Trait ==========
8737
8738/// Trait for no-clone callback-based access to container types
8739/// Provides methods to execute closures with references to values inside containers
8740/// without requiring cloning of the values
8741pub trait WithContainer<Root, Value> {
8742    /// Execute a closure with a reference to the value inside an Arc
8743    fn with_arc<F, R>(&self, arc: &Arc<Root>, f: F) -> R
8744    where
8745        F: FnOnce(&Value) -> R;
8746
8747    /// Execute a closure with a reference to the value inside a Box
8748    fn with_box<F, R>(&self, boxed: &Box<Root>, f: F) -> R
8749    where
8750        F: FnOnce(&Value) -> R;
8751
8752    /// Execute a closure with a mutable reference to the value inside a Box
8753    fn with_box_mut<F, R>(&self, boxed: &mut Box<Root>, f: F) -> R
8754    where
8755        F: FnOnce(&mut Value) -> R;
8756
8757    /// Execute a closure with a reference to the value inside an Rc
8758    fn with_rc<F, R>(&self, rc: &Rc<Root>, f: F) -> R
8759    where
8760        F: FnOnce(&Value) -> R;
8761
8762    /// Execute a closure with a reference to the value inside a Result
8763    fn with_result<F, R, E>(&self, result: &Result<Root, E>, f: F) -> Option<R>
8764    where
8765        F: FnOnce(&Value) -> R;
8766
8767    /// Execute a closure with a mutable reference to the value inside a Result
8768    fn with_result_mut<F, R, E>(&self, result: &mut Result<Root, E>, f: F) -> Option<R>
8769    where
8770        F: FnOnce(&mut Value) -> R;
8771
8772    /// Execute a closure with a reference to the value inside an Option
8773    fn with_option<F, R>(&self, option: &Option<Root>, f: F) -> Option<R>
8774    where
8775        F: FnOnce(&Value) -> R;
8776
8777    /// Execute a closure with a mutable reference to the value inside an Option
8778    fn with_option_mut<F, R>(&self, option: &mut Option<Root>, f: F) -> Option<R>
8779    where
8780        F: FnOnce(&mut Value) -> R;
8781
8782    /// Execute a closure with a reference to the value inside a RefCell
8783    fn with_refcell<F, R>(&self, refcell: &RefCell<Root>, f: F) -> Option<R>
8784    where
8785        F: FnOnce(&Value) -> R;
8786
8787    /// Execute a closure with a mutable reference to the value inside a RefCell
8788    fn with_refcell_mut<F, R>(&self, refcell: &RefCell<Root>, f: F) -> Option<R>
8789    where
8790        F: FnOnce(&mut Value) -> R;
8791
8792    #[cfg(feature = "tagged")]
8793    /// Execute a closure with a reference to the value inside a Tagged
8794    fn with_tagged<F, R, Tag>(&self, tagged: &Tagged<Root, Tag>, f: F) -> R
8795    where
8796        Tagged<Root, Tag>: std::ops::Deref<Target = Root>,
8797        F: FnOnce(&Value) -> R;
8798
8799    /// Execute a closure with a reference to the value inside a Mutex
8800    fn with_mutex<F, R>(&self, mutex: &Mutex<Root>, f: F) -> Option<R>
8801    where
8802        F: FnOnce(&Value) -> R;
8803
8804    /// Execute a closure with a mutable reference to the value inside a Mutex
8805    fn with_mutex_mut<F, R>(&self, mutex: &mut Mutex<Root>, f: F) -> Option<R>
8806    where
8807        F: FnOnce(&mut Value) -> R;
8808
8809    /// Execute a closure with a reference to the value inside an RwLock
8810    fn with_rwlock<F, R>(&self, rwlock: &RwLock<Root>, f: F) -> Option<R>
8811    where
8812        F: FnOnce(&Value) -> R;
8813
8814    /// Execute a closure with a mutable reference to the value inside an RwLock
8815    fn with_rwlock_mut<F, R>(&self, rwlock: &mut RwLock<Root>, f: F) -> Option<R>
8816    where
8817        F: FnOnce(&mut Value) -> R;
8818
8819    /// Execute a closure with a reference to the value inside an Arc<RwLock<Root>>
8820    fn with_arc_rwlock<F, R>(&self, arc_rwlock: &Arc<RwLock<Root>>, f: F) -> Option<R>
8821    where
8822        F: FnOnce(&Value) -> R;
8823
8824    /// Execute a closure with a mutable reference to the value inside an Arc<RwLock<Root>>
8825    fn with_arc_rwlock_mut<F, R>(&self, arc_rwlock: &Arc<RwLock<Root>>, f: F) -> Option<R>
8826    where
8827        F: FnOnce(&mut Value) -> R;
8828}
8829
8830// Implement WithContainer for KeyPath
8831impl<Root, Value, F> WithContainer<Root, Value> for KeyPath<Root, Value, F>
8832where
8833    F: for<'r> Fn(&'r Root) -> &'r Value + Clone,
8834{
8835    fn with_arc<Callback, R>(&self, arc: &Arc<Root>, f: Callback) -> R
8836    where
8837        Callback: FnOnce(&Value) -> R,
8838    {
8839        self.with_arc(arc, f)
8840    }
8841
8842    fn with_box<Callback, R>(&self, boxed: &Box<Root>, f: Callback) -> R
8843    where
8844        Callback: FnOnce(&Value) -> R,
8845    {
8846        self.with_box(boxed, f)
8847    }
8848
8849    fn with_box_mut<Callback, R>(&self, _boxed: &mut Box<Root>, _f: Callback) -> R
8850    where
8851        Callback: FnOnce(&mut Value) -> R,
8852    {
8853        eprintln!("[DEBUG] KeyPath does not support mutable access - use WritableKeyPath instead");
8854        unreachable!("KeyPath does not support mutable access - use WritableKeyPath instead")
8855    }
8856
8857    fn with_rc<Callback, R>(&self, rc: &Rc<Root>, f: Callback) -> R
8858    where
8859        Callback: FnOnce(&Value) -> R,
8860    {
8861        self.with_rc(rc, f)
8862    }
8863
8864    fn with_result<Callback, R, E>(&self, result: &Result<Root, E>, f: Callback) -> Option<R>
8865    where
8866        Callback: FnOnce(&Value) -> R,
8867    {
8868        self.with_result(result, f)
8869    }
8870
8871    fn with_result_mut<Callback, R, E>(&self, _result: &mut Result<Root, E>, _f: Callback) -> Option<R>
8872    where
8873        Callback: FnOnce(&mut Value) -> R,
8874    {
8875        None
8876    }
8877
8878    fn with_option<Callback, R>(&self, option: &Option<Root>, f: Callback) -> Option<R>
8879    where
8880        Callback: FnOnce(&Value) -> R,
8881    {
8882        self.with_option(option, f)
8883    }
8884
8885    fn with_option_mut<Callback, R>(&self, _option: &mut Option<Root>, _f: Callback) -> Option<R>
8886    where
8887        Callback: FnOnce(&mut Value) -> R,
8888    {
8889        None
8890    }
8891
8892    fn with_refcell<Callback, R>(&self, refcell: &RefCell<Root>, f: Callback) -> Option<R>
8893    where
8894        Callback: FnOnce(&Value) -> R,
8895    {
8896        self.with_refcell(refcell, f)
8897    }
8898
8899    fn with_refcell_mut<Callback, R>(&self, _refcell: &RefCell<Root>, _f: Callback) -> Option<R>
8900    where
8901        Callback: FnOnce(&mut Value) -> R,
8902    {
8903        None
8904    }
8905
8906    #[cfg(feature = "tagged")]
8907    fn with_tagged<Callback, R, Tag>(&self, tagged: &Tagged<Root, Tag>, f: Callback) -> R
8908    where
8909        Tagged<Root, Tag>: std::ops::Deref<Target = Root>,
8910        Callback: FnOnce(&Value) -> R,
8911    {
8912        self.with_tagged(tagged, f)
8913    }
8914
8915    fn with_mutex<Callback, R>(&self, mutex: &Mutex<Root>, f: Callback) -> Option<R>
8916    where
8917        Callback: FnOnce(&Value) -> R,
8918    {
8919        self.with_mutex(mutex, f)
8920    }
8921
8922    fn with_mutex_mut<Callback, R>(&self, _mutex: &mut Mutex<Root>, _f: Callback) -> Option<R>
8923    where
8924        Callback: FnOnce(&mut Value) -> R,
8925    {
8926        None
8927    }
8928
8929    fn with_rwlock<Callback, R>(&self, rwlock: &RwLock<Root>, f: Callback) -> Option<R>
8930    where
8931        Callback: FnOnce(&Value) -> R,
8932    {
8933        self.with_rwlock(rwlock, f)
8934    }
8935
8936    fn with_rwlock_mut<Callback, R>(&self, _rwlock: &mut RwLock<Root>, _f: Callback) -> Option<R>
8937    where
8938        Callback: FnOnce(&mut Value) -> R,
8939    {
8940        None
8941    }
8942
8943    fn with_arc_rwlock<Callback, R>(&self, arc_rwlock: &Arc<RwLock<Root>>, f: Callback) -> Option<R>
8944    where
8945        Callback: FnOnce(&Value) -> R,
8946    {
8947        self.with_arc_rwlock(arc_rwlock, f)
8948    }
8949
8950    fn with_arc_rwlock_mut<Callback, R>(&self, _arc_rwlock: &Arc<RwLock<Root>>, _f: Callback) -> Option<R>
8951    where
8952        Callback: FnOnce(&mut Value) -> R,
8953    {
8954        None
8955    }
8956}
8957
8958// Implement WithContainer for OptionalKeyPath - read-only operations only
8959impl<Root, Value, F> WithContainer<Root, Value> for OptionalKeyPath<Root, Value, F>
8960where
8961    F: for<'r> Fn(&'r Root) -> Option<&'r Value> + Clone,
8962{
8963    fn with_arc<Callback, R>(&self, arc: &Arc<Root>, f: Callback) -> R
8964    where
8965        Callback: FnOnce(&Value) -> R,
8966    {
8967        self.with_arc(arc, f)
8968    }
8969
8970    fn with_box<Callback, R>(&self, boxed: &Box<Root>, f: Callback) -> R
8971    where
8972        Callback: FnOnce(&Value) -> R,
8973    {
8974        self.with_box(boxed, f)
8975    }
8976
8977    fn with_box_mut<Callback, R>(&self, _boxed: &mut Box<Root>, _f: Callback) -> R
8978    where
8979        Callback: FnOnce(&mut Value) -> R,
8980    {
8981        eprintln!("[DEBUG] OptionalKeyPath does not support mutable access - use WritableOptionalKeyPath instead");
8982        unreachable!("OptionalKeyPath does not support mutable access - use WritableOptionalKeyPath instead")
8983    }
8984
8985    fn with_rc<Callback, R>(&self, rc: &Rc<Root>, f: Callback) -> R
8986    where
8987        Callback: FnOnce(&Value) -> R,
8988    {
8989        self.with_rc(rc, f)
8990    }
8991
8992    fn with_result<Callback, R, E>(&self, result: &Result<Root, E>, f: Callback) -> Option<R>
8993    where
8994        Callback: FnOnce(&Value) -> R,
8995    {
8996        self.with_result(result, f)
8997    }
8998
8999    fn with_result_mut<Callback, R, E>(&self, _result: &mut Result<Root, E>, _f: Callback) -> Option<R>
9000    where
9001        Callback: FnOnce(&mut Value) -> R,
9002    {
9003        None // OptionalKeyPath doesn't support mutable access
9004    }
9005
9006    fn with_option<Callback, R>(&self, option: &Option<Root>, f: Callback) -> Option<R>
9007    where
9008        Callback: FnOnce(&Value) -> R,
9009    {
9010        self.with_option(option, f)
9011    }
9012
9013    fn with_option_mut<Callback, R>(&self, _option: &mut Option<Root>, _f: Callback) -> Option<R>
9014    where
9015        Callback: FnOnce(&mut Value) -> R,
9016    {
9017        None // OptionalKeyPath doesn't support mutable access
9018    }
9019
9020    fn with_refcell<Callback, R>(&self, refcell: &RefCell<Root>, f: Callback) -> Option<R>
9021    where
9022        Callback: FnOnce(&Value) -> R,
9023    {
9024        self.with_refcell(refcell, f)
9025    }
9026
9027    fn with_refcell_mut<Callback, R>(&self, _refcell: &RefCell<Root>, _f: Callback) -> Option<R>
9028    where
9029        Callback: FnOnce(&mut Value) -> R,
9030    {
9031        None // OptionalKeyPath doesn't support mutable access
9032    }
9033
9034    #[cfg(feature = "tagged")]
9035    fn with_tagged<Callback, R, Tag>(&self, tagged: &Tagged<Root, Tag>, f: Callback) -> R
9036    where
9037        Tagged<Root, Tag>: std::ops::Deref<Target = Root>,
9038        Callback: FnOnce(&Value) -> R,
9039    {
9040        use std::ops::Deref;
9041        self.get(tagged.deref())
9042            .map(|value| f(value))
9043            .expect("OptionalKeyPath::with_tagged: Tagged should always contain a value that matches the keypath")
9044    }
9045
9046    fn with_mutex<Callback, R>(&self, mutex: &Mutex<Root>, f: Callback) -> Option<R>
9047    where
9048        Callback: FnOnce(&Value) -> R,
9049    {
9050        self.with_mutex(mutex, f)
9051    }
9052
9053    fn with_mutex_mut<Callback, R>(&self, _mutex: &mut Mutex<Root>, _f: Callback) -> Option<R>
9054    where
9055        Callback: FnOnce(&mut Value) -> R,
9056    {
9057        None // OptionalKeyPath doesn't support mutable access
9058    }
9059
9060    fn with_rwlock<Callback, R>(&self, rwlock: &RwLock<Root>, f: Callback) -> Option<R>
9061    where
9062        Callback: FnOnce(&Value) -> R,
9063    {
9064        self.with_rwlock(rwlock, f)
9065    }
9066
9067    fn with_rwlock_mut<Callback, R>(&self, _rwlock: &mut RwLock<Root>, _f: Callback) -> Option<R>
9068    where
9069        Callback: FnOnce(&mut Value) -> R,
9070    {
9071        None // OptionalKeyPath doesn't support mutable access
9072    }
9073
9074    fn with_arc_rwlock<Callback, R>(&self, arc_rwlock: &Arc<RwLock<Root>>, f: Callback) -> Option<R>
9075    where
9076        Callback: FnOnce(&Value) -> R,
9077    {
9078        self.with_arc_rwlock(arc_rwlock, f)
9079    }
9080
9081    fn with_arc_rwlock_mut<Callback, R>(&self, _arc_rwlock: &Arc<RwLock<Root>>, _f: Callback) -> Option<R>
9082    where
9083        Callback: FnOnce(&mut Value) -> R,
9084    {
9085        None // OptionalKeyPath doesn't support mutable access - use WritableOptionalKeyPath instead
9086    }
9087}
9088
9089// Implement WithContainer for WritableKeyPath - supports all mutable operations
9090impl<Root, Value, F> WithContainer<Root, Value> for WritableKeyPath<Root, Value, F>
9091where
9092    F: for<'r> Fn(&'r mut Root) -> &'r mut Value,
9093{
9094    fn with_arc<Callback, R>(&self, _arc: &Arc<Root>, _f: Callback) -> R
9095    where
9096        Callback: FnOnce(&Value) -> R,
9097    {
9098        // Arc doesn't support mutable access without interior mutability
9099        // This method requires &mut Arc<Root> which we don't have
9100        eprintln!("[DEBUG] WritableKeyPath::with_arc requires &mut Arc<Root> or interior mutability");
9101        unreachable!("WritableKeyPath::with_arc requires &mut Arc<Root> or interior mutability")
9102    }
9103
9104    fn with_box<Callback, R>(&self, boxed: &Box<Root>, f: Callback) -> R
9105    where
9106        Callback: FnOnce(&Value) -> R,
9107    {
9108        // Box doesn't support getting mutable reference from immutable reference
9109        // This is a limitation - we'd need &mut Box<Root> for mutable access
9110        eprintln!("[DEBUG] WritableKeyPath::with_box requires &mut Box<Root> - use with_box_mut instead");
9111        unreachable!("WritableKeyPath::with_box requires &mut Box<Root> - use with_box_mut instead")
9112    }
9113
9114    fn with_box_mut<Callback, R>(&self, boxed: &mut Box<Root>, f: Callback) -> R
9115    where
9116        Callback: FnOnce(&mut Value) -> R,
9117    {
9118        let value = self.get_mut(boxed.as_mut());
9119        f(value)
9120    }
9121
9122    fn with_rc<Callback, R>(&self, _rc: &Rc<Root>, _f: Callback) -> R
9123    where
9124        Callback: FnOnce(&Value) -> R,
9125    {
9126        // Rc doesn't support mutable access without interior mutability
9127        // This method requires &mut Rc<Root> which we don't have
9128        eprintln!("[DEBUG] WritableKeyPath::with_rc requires &mut Rc<Root> or interior mutability");
9129        unreachable!("WritableKeyPath::with_rc requires &mut Rc<Root> or interior mutability")
9130    }
9131
9132    fn with_result<Callback, R, E>(&self, _result: &Result<Root, E>, _f: Callback) -> Option<R>
9133    where
9134        Callback: FnOnce(&Value) -> R,
9135    {
9136        // WritableKeyPath requires &mut Root, but we only have &Result<Root, E>
9137        // This is a limitation - use with_result_mut for mutable access
9138        None
9139    }
9140
9141    fn with_result_mut<Callback, R, E>(&self, result: &mut Result<Root, E>, f: Callback) -> Option<R>
9142    where
9143        Callback: FnOnce(&mut Value) -> R,
9144    {
9145        result.as_mut().ok().map(|root| {
9146            let value = self.get_mut(root);
9147            f(value)
9148        })
9149    }
9150
9151    fn with_option<Callback, R>(&self, _option: &Option<Root>, _f: Callback) -> Option<R>
9152    where
9153        Callback: FnOnce(&Value) -> R,
9154    {
9155        // WritableKeyPath requires &mut Root, but we only have &Option<Root>
9156        // This is a limitation - use with_option_mut for mutable access
9157        None
9158    }
9159
9160    fn with_option_mut<Callback, R>(&self, option: &mut Option<Root>, f: Callback) -> Option<R>
9161    where
9162        Callback: FnOnce(&mut Value) -> R,
9163    {
9164        option.as_mut().map(|root| {
9165            let value = self.get_mut(root);
9166            f(value)
9167        })
9168    }
9169
9170    fn with_refcell<Callback, R>(&self, refcell: &RefCell<Root>, f: Callback) -> Option<R>
9171    where
9172        Callback: FnOnce(&Value) -> R,
9173    {
9174        // RefCell doesn't allow getting mutable reference from immutable borrow
9175        // This is a limitation - we'd need try_borrow_mut for mutable access
9176        None
9177    }
9178
9179    fn with_refcell_mut<Callback, R>(&self, refcell: &RefCell<Root>, f: Callback) -> Option<R>
9180    where
9181        Callback: FnOnce(&mut Value) -> R,
9182    {
9183        refcell.try_borrow_mut().ok().map(|mut borrow| {
9184            let value = self.get_mut(&mut *borrow);
9185            f(value)
9186        })
9187    }
9188
9189    #[cfg(feature = "tagged")]
9190    fn with_tagged<Callback, R, Tag>(&self, _tagged: &Tagged<Root, Tag>, _f: Callback) -> R
9191    where
9192        Tagged<Root, Tag>: std::ops::Deref<Target = Root>,
9193        Callback: FnOnce(&Value) -> R,
9194    {
9195        // WritableKeyPath requires &mut Root, but we only have &Tagged<Root, Tag>
9196        // This is a limitation - Tagged doesn't support mutable access without interior mutability
9197        eprintln!("[DEBUG] WritableKeyPath::with_tagged requires &mut Tagged<Root, Tag> or interior mutability");
9198        unreachable!("WritableKeyPath::with_tagged requires &mut Tagged<Root, Tag> or interior mutability")
9199    }
9200
9201    fn with_mutex<Callback, R>(&self, mutex: &Mutex<Root>, f: Callback) -> Option<R>
9202    where
9203        Callback: FnOnce(&Value) -> R,
9204    {
9205        mutex.lock().ok().map(|mut guard| {
9206            let value = self.get_mut(&mut *guard);
9207            f(value)
9208        })
9209    }
9210
9211    fn with_mutex_mut<Callback, R>(&self, mutex: &mut Mutex<Root>, f: Callback) -> Option<R>
9212    where
9213        Callback: FnOnce(&mut Value) -> R,
9214    {
9215        // Mutex::get_mut returns Result<&mut Root, PoisonError>
9216        mutex.get_mut().ok().map(|root| {
9217            let value = self.get_mut(root);
9218            f(value)
9219        })
9220    }
9221
9222    fn with_rwlock<Callback, R>(&self, rwlock: &RwLock<Root>, f: Callback) -> Option<R>
9223    where
9224        Callback: FnOnce(&Value) -> R,
9225    {
9226        // RwLock read guard doesn't allow mutable access
9227        // This is a limitation - we'd need write() for mutable access
9228        None
9229    }
9230
9231    fn with_rwlock_mut<Callback, R>(&self, rwlock: &mut RwLock<Root>, f: Callback) -> Option<R>
9232    where
9233        Callback: FnOnce(&mut Value) -> R,
9234    {
9235        // RwLock::get_mut returns Result<&mut Root, PoisonError>
9236        rwlock.get_mut().ok().map(|root| {
9237            let value = self.get_mut(root);
9238            f(value)
9239        })
9240    }
9241
9242    fn with_arc_rwlock<Callback, R>(&self, arc_rwlock: &Arc<RwLock<Root>>, f: Callback) -> Option<R>
9243    where
9244        Callback: FnOnce(&Value) -> R,
9245    {
9246        // Arc<RwLock> read guard doesn't allow mutable access
9247        // This is a limitation - we'd need write() for mutable access
9248        None
9249    }
9250
9251    fn with_arc_rwlock_mut<Callback, R>(&self, arc_rwlock: &Arc<RwLock<Root>>, f: Callback) -> Option<R>
9252    where
9253        Callback: FnOnce(&mut Value) -> R,
9254    {
9255        arc_rwlock.write().ok().map(|mut guard| {
9256            let value = self.get_mut(&mut *guard);
9257            f(value)
9258        })
9259    }
9260}
9261
9262// Implement WithContainer for WritableOptionalKeyPath - supports all mutable operations
9263impl<Root, Value, F> WithContainer<Root, Value> for WritableOptionalKeyPath<Root, Value, F>
9264where
9265    F: for<'r> Fn(&'r mut Root) -> Option<&'r mut Value>,
9266{
9267    fn with_arc<Callback, R>(&self, _arc: &Arc<Root>, _f: Callback) -> R
9268    where
9269        Callback: FnOnce(&Value) -> R,
9270    {
9271        // Arc doesn't support mutable access without interior mutability
9272        // This method requires &mut Arc<Root> which we don't have
9273        eprintln!("[DEBUG] WritableOptionalKeyPath::with_arc requires &mut Arc<Root> or interior mutability");
9274        unreachable!("WritableOptionalKeyPath::with_arc requires &mut Arc<Root> or interior mutability")
9275    }
9276
9277    fn with_box<Callback, R>(&self, _boxed: &Box<Root>, _f: Callback) -> R
9278    where
9279        Callback: FnOnce(&Value) -> R,
9280    {
9281        // WritableOptionalKeyPath requires &mut Root, but we only have &Box<Root>
9282        // This is a limitation - use with_box_mut for mutable access
9283        eprintln!("[DEBUG] WritableOptionalKeyPath::with_box requires &mut Box<Root> - use with_box_mut instead");
9284        unreachable!("WritableOptionalKeyPath::with_box requires &mut Box<Root> - use with_box_mut instead")
9285    }
9286
9287    fn with_box_mut<Callback, R>(&self, boxed: &mut Box<Root>, f: Callback) -> R
9288    where
9289        Callback: FnOnce(&mut Value) -> R,
9290    {
9291        if let Some(value) = self.get_mut(boxed.as_mut()) {
9292            f(value)
9293        } else {
9294            eprintln!("[DEBUG] WritableOptionalKeyPath failed to get value from Box");
9295            unreachable!("WritableOptionalKeyPath failed to get value from Box")
9296        }
9297    }
9298
9299    fn with_rc<Callback, R>(&self, _rc: &Rc<Root>, _f: Callback) -> R
9300    where
9301        Callback: FnOnce(&Value) -> R,
9302    {
9303        // Rc doesn't support mutable access without interior mutability
9304        // This method requires &mut Rc<Root> which we don't have
9305        eprintln!("[DEBUG] WritableOptionalKeyPath::with_rc requires &mut Rc<Root> or interior mutability");
9306        unreachable!("WritableOptionalKeyPath::with_rc requires &mut Rc<Root> or interior mutability")
9307    }
9308
9309    fn with_result<Callback, R, E>(&self, _result: &Result<Root, E>, _f: Callback) -> Option<R>
9310    where
9311        Callback: FnOnce(&Value) -> R,
9312    {
9313        // WritableOptionalKeyPath requires &mut Root, but we only have &Result<Root, E>
9314        // This is a limitation - use with_result_mut for mutable access
9315        None
9316    }
9317
9318    fn with_result_mut<Callback, R, E>(&self, result: &mut Result<Root, E>, f: Callback) -> Option<R>
9319    where
9320        Callback: FnOnce(&mut Value) -> R,
9321    {
9322        result.as_mut().ok().and_then(|root| {
9323            self.get_mut(root).map(|value| f(value))
9324        })
9325    }
9326
9327    fn with_option<Callback, R>(&self, _option: &Option<Root>, _f: Callback) -> Option<R>
9328    where
9329        Callback: FnOnce(&Value) -> R,
9330    {
9331        // WritableOptionalKeyPath requires &mut Root, but we only have &Option<Root>
9332        // This is a limitation - use with_option_mut for mutable access
9333        None
9334    }
9335
9336    fn with_option_mut<Callback, R>(&self, option: &mut Option<Root>, f: Callback) -> Option<R>
9337    where
9338        Callback: FnOnce(&mut Value) -> R,
9339    {
9340        option.as_mut().and_then(|root| {
9341            self.get_mut(root).map(|value| f(value))
9342        })
9343    }
9344
9345    fn with_refcell<Callback, R>(&self, _refcell: &RefCell<Root>, _f: Callback) -> Option<R>
9346    where
9347        Callback: FnOnce(&Value) -> R,
9348    {
9349        // RefCell doesn't allow getting mutable reference from immutable borrow
9350        // This is a limitation - we'd need try_borrow_mut for mutable access
9351        None
9352    }
9353
9354    fn with_refcell_mut<Callback, R>(&self, refcell: &RefCell<Root>, f: Callback) -> Option<R>
9355    where
9356        Callback: FnOnce(&mut Value) -> R,
9357    {
9358        refcell.try_borrow_mut().ok().and_then(|mut borrow| {
9359            self.get_mut(&mut *borrow).map(|value| f(value))
9360        })
9361    }
9362
9363    #[cfg(feature = "tagged")]
9364    fn with_tagged<Callback, R, Tag>(&self, _tagged: &Tagged<Root, Tag>, _f: Callback) -> R
9365    where
9366        Tagged<Root, Tag>: std::ops::Deref<Target = Root>,
9367        Callback: FnOnce(&Value) -> R,
9368    {
9369        // WritableOptionalKeyPath requires &mut Root, but we only have &Tagged<Root, Tag>
9370        // This is a limitation - Tagged doesn't support mutable access without interior mutability
9371        eprintln!("[DEBUG] WritableOptionalKeyPath::with_tagged requires &mut Tagged<Root, Tag> or interior mutability");
9372        unreachable!("WritableOptionalKeyPath::with_tagged requires &mut Tagged<Root, Tag> or interior mutability")
9373    }
9374
9375    fn with_mutex<Callback, R>(&self, mutex: &Mutex<Root>, f: Callback) -> Option<R>
9376    where
9377        Callback: FnOnce(&Value) -> R,
9378    {
9379        mutex.lock().ok().and_then(|mut guard| {
9380            self.get_mut(&mut *guard).map(|value| f(value))
9381        })
9382    }
9383
9384    fn with_mutex_mut<Callback, R>(&self, mutex: &mut Mutex<Root>, f: Callback) -> Option<R>
9385    where
9386        Callback: FnOnce(&mut Value) -> R,
9387    {
9388        // Mutex::get_mut returns Result<&mut Root, PoisonError>
9389        mutex.get_mut().ok().and_then(|root| {
9390            self.get_mut(root).map(|value| f(value))
9391        })
9392    }
9393
9394    fn with_rwlock<Callback, R>(&self, _rwlock: &RwLock<Root>, _f: Callback) -> Option<R>
9395    where
9396        Callback: FnOnce(&Value) -> R,
9397    {
9398        // RwLock read guard doesn't allow mutable access
9399        // This is a limitation - we'd need write() for mutable access
9400        None
9401    }
9402
9403    fn with_rwlock_mut<Callback, R>(&self, rwlock: &mut RwLock<Root>, f: Callback) -> Option<R>
9404    where
9405        Callback: FnOnce(&mut Value) -> R,
9406    {
9407        // RwLock::get_mut returns Result<&mut Root, PoisonError>
9408        rwlock.get_mut().ok().and_then(|root| {
9409            self.get_mut(root).map(|value| f(value))
9410        })
9411    }
9412
9413    fn with_arc_rwlock<Callback, R>(&self, _arc_rwlock: &Arc<RwLock<Root>>, _f: Callback) -> Option<R>
9414    where
9415        Callback: FnOnce(&Value) -> R,
9416    {
9417        // Arc<RwLock> read guard doesn't allow mutable access
9418        // This is a limitation - we'd need write() for mutable access
9419        None
9420    }
9421
9422    fn with_arc_rwlock_mut<Callback, R>(&self, arc_rwlock: &Arc<RwLock<Root>>, f: Callback) -> Option<R>
9423    where
9424        Callback: FnOnce(&mut Value) -> R,
9425    {
9426        arc_rwlock.write().ok().and_then(|mut guard| {
9427            self.get_mut(&mut *guard).map(|value| f(value))
9428        })
9429    }
9430}
9431