Skip to main content

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::any::{Any, TypeId};
6use std::cell::RefCell;
7use std::marker::PhantomData;
8use std::ops::{Deref, DerefMut};
9use std::rc::Rc;
10use std::sync::{Arc, Mutex, MutexGuard, RwLock};
11// use std::ops::Shr;
12use std::fmt;
13
14// ========== FUNCTIONAL KEYPATH CHAIN (Compose first, apply container at get) ==========
15
16#[derive(Debug)]
17pub struct LKp<Root, MutexValue, InnerValue, SubValue, G, S>
18where
19    G: for<'r> Fn(&'r InnerValue) -> Option<&'r SubValue>,
20    S: for<'r> Fn(&'r mut InnerValue) -> Option<&'r mut SubValue>,
21{
22    o: Kp<Root, MutexValue>,
23    i: KpType<InnerValue, SubValue, G, S>,
24}
25
26// Helper function to create LKp from simple keypaths
27impl<Root, MutexValue, InnerValue, SubValue, G, S> LKp<Root, MutexValue, InnerValue, SubValue, G, S>
28where
29    MutexValue: std::borrow::Borrow<Arc<Mutex<InnerValue>>>,
30    G: for<'r> Fn(&'r InnerValue) -> Option<&'r SubValue>,
31    S: for<'r> Fn(&'r mut InnerValue) -> Option<&'r mut SubValue>,
32{
33    /// Create an LKp from two simple keypaths
34    /// - outer: keypath from Root to Arc<Mutex<InnerValue>>
35    /// - inner: keypath from InnerValue to SubValue
36    pub fn new(outer: Kp<Root, MutexValue>, inner: KpType<InnerValue, SubValue, G, S>) -> Self {
37        Self { o: outer, i: inner }
38    }
39
40    pub fn then<NextValue, G2, S2>(
41        self,
42        next: KpType<SubValue, NextValue, G2, S2>,
43    ) -> LKp<
44        Root,
45        MutexValue,
46        InnerValue,
47        NextValue,
48        impl for<'r> Fn(&'r InnerValue) -> Option<&'r NextValue>,
49        impl for<'r> Fn(&'r mut InnerValue) -> Option<&'r mut NextValue>,
50    >
51    where
52        InnerValue: 'static,
53        SubValue: 'static,
54        NextValue: 'static,
55        G2: for<'r> Fn(&'r SubValue) -> Option<&'r NextValue>,
56        S2: for<'r> Fn(&'r mut SubValue) -> Option<&'r mut NextValue>,
57    {
58        LKp {
59            o: self.o,
60            i: self.i.then(next),
61        }
62    }
63
64    /// Consider using the fn only when value is of type Rc or Arc else it will clone.
65    pub fn get_cloned(&self, root: &Root) -> Option<SubValue>
66    where
67        SubValue: Clone,
68    {
69        self.o.get(root).and_then(|mutex_value| {
70            let arc_mutex = mutex_value.borrow();
71            let guard = arc_mutex.lock().ok()?;
72            let sub_value = self.i.get(&*guard)?;
73            Some(sub_value.clone())
74        })
75    }
76
77    pub fn get_arc(&self, root: &Root) -> Option<Arc<SubValue>>
78    where
79        SubValue: Clone,
80    {
81        self.o.get(root).and_then(|mutex_value| {
82            let arc_mutex = mutex_value.borrow();
83            let guard = arc_mutex.lock().ok()?;
84            let sub_value = self.i.get(&*guard)?;
85            Some(Arc::new(sub_value.clone()))
86        })
87    }
88
89    pub fn get_mut<F, SubSubValue>(&self, root: &mut Root, f: F) -> Option<SubSubValue>
90    where
91        F: FnOnce(&mut SubValue) -> SubSubValue,
92    {
93        self.o.get_mut(root).and_then(|mutex_value| {
94            let arc_mutex = mutex_value.borrow();
95            let mut guard = arc_mutex.lock().ok()?;
96            let sub_value = self.i.get_mut(&mut *guard)?;
97            Some(f(sub_value))
98        })
99    }
100
101    pub fn get<F, SubSubValue>(&self, root: &Root, f: F) -> Option<SubSubValue>
102    where
103        F: FnOnce(&SubValue) -> SubSubValue,
104    {
105        self.o.get(root).and_then(|mutex_value| {
106            let arc_mutex = mutex_value.borrow();
107            let mut guard = arc_mutex.lock().ok()?;
108            let sub_value = self.i.get(&mut *guard)?;
109            Some(f(sub_value))
110        })
111    }
112}
113
114impl<Root, MutexValue, InnerValue, SubValue, G, S> LKp<Root, MutexValue, InnerValue, SubValue, G, S>
115where
116    MutexValue: std::borrow::Borrow<Arc<Mutex<InnerValue>>>,
117    G: for<'r> Fn(&'r InnerValue) -> Option<&'r SubValue>,
118    S: for<'r> Fn(&'r mut InnerValue) -> Option<&'r mut SubValue>,
119{
120    // ... existing methods ...
121
122    // /// Chain through another mutex layer
123    // /// SubValue must be Arc<Mutex<NextInner>> to go through another mutex
124    // pub fn and_then<NextInner, NextValue, G2, S2>(
125    //     self,
126    //     next_inner: KpType<NextInner, NextValue, G2, S2>,
127    // ) -> LKp
128    // <
129    //     Root,
130    //     MutexValue,
131    //     InnerValue,
132    //     NextValue,
133    //     impl for<'r> Fn(&'r InnerValue) -> Option<&'r NextValue>,
134    //     impl for<'r> Fn(&'r mut InnerValue) -> Option<&'r mut NextValue>,
135    // >
136    // where
137    //     SubValue: std::borrow::Borrow<Arc<Mutex<NextInner>>>,
138    //     InnerValue: 'static,
139    //     SubValue: 'static,
140    //     NextInner: 'static,
141    //     NextValue: 'static,
142    //     G2: for<'r> Fn(&'r NextInner) -> Option<&'r NextValue> + 'static,
143    //     S2: for<'r> Fn(&'r mut NextInner) -> Option<&'r mut NextValue> + 'static,
144    // {
145    //     let outer_get = self.i.g;
146    //     let outer_set = self.i.s;
147    //     let inner_get = next_inner.g;
148    //     let inner_set = next_inner.s;
149
150    //     let composed = KpType::new(
151    //         move |inner: &InnerValue| -> Option<&NextValue> {
152    //             // Navigate to SubValue (which is Arc<Mutex<NextInner>>)
153    //             let sub_value = outer_get(inner)?;
154    //             // Borrow as Arc<Mutex<NextInner>> and lock it
155    //             let arc_mutex = sub_value.borrow();
156    //             let guard = arc_mutex.lock().ok()?;
157    //             // Navigate through the locked NextInner to get NextValue
158    //             inner_get(&*guard)
159    //         },
160    //         move |inner: &mut InnerValue| -> Option<&mut NextValue> {
161    //             let sub_value = outer_set(inner)?;
162    //             let arc_mutex = sub_value.borrow();
163    //             let mut guard = arc_mutex.lock().ok()?;
164    //             inner_set(&mut *guard)
165    //         },
166    //     );
167
168    //     LKp {
169    //         o: self.o,
170    //         i: composed,
171    //     }
172    // }
173
174    /// Chain through another mutex layer with callback-based access (safer)
175    pub fn and_then_with<NextInner, NextValue, G2, S2, F, R>(
176        &self,
177        next_inner: &KpType<NextInner, NextValue, G2, S2>,
178        root: &Root,
179        callback: F,
180    ) -> Option<R>
181    where
182        SubValue: std::borrow::Borrow<Arc<Mutex<NextInner>>>,
183        G2: for<'r> Fn(&'r NextInner) -> Option<&'r NextValue>,
184        S2: for<'r> Fn(&'r mut NextInner) -> Option<&'r mut NextValue>,
185        F: FnOnce(&NextValue) -> R,
186    {
187        self.o.get(root).and_then(|mutex_value| {
188            let arc_mutex = mutex_value.borrow();
189            let guard = arc_mutex.lock().ok()?;
190            let sub_value = self.i.get(&*guard)?;
191
192            // Now sub_value is Arc<Mutex<NextInner>>
193            let next_arc_mutex = sub_value.borrow();
194            let next_guard = next_arc_mutex.lock().ok()?;
195            let next_value = next_inner.get(&*next_guard)?;
196
197            Some(callback(next_value))
198        })
199    }
200
201    /// Mutable version of and_then_with
202    pub fn and_then_with_mut<NextInner, NextValue, G2, S2, F, R>(
203        &self,
204        next_inner: &KpType<NextInner, NextValue, G2, S2>,
205        root: &mut Root,
206        callback: F,
207    ) -> Option<R>
208    where
209        SubValue: std::borrow::Borrow<Arc<Mutex<NextInner>>>,
210        G2: for<'r> Fn(&'r NextInner) -> Option<&'r NextValue>,
211        S2: for<'r> Fn(&'r mut NextInner) -> Option<&'r mut NextValue>,
212        F: FnOnce(&mut NextValue) -> R,
213    {
214        self.o.get_mut(root).and_then(|mutex_value| {
215            let arc_mutex = mutex_value.borrow();
216            let mut guard = arc_mutex.lock().ok()?;
217            let sub_value = self.i.get_mut(&mut *guard)?;
218
219            let next_arc_mutex = sub_value.borrow();
220            let mut next_guard = next_arc_mutex.lock().ok()?;
221            let next_value = next_inner.get_mut(&mut *next_guard)?;
222
223            Some(callback(next_value))
224        })
225    }
226}
227
228// Add helper identity methods for common types
229// impl<T> Kp<T, T> {
230//     pub fn identity() -> Self {
231//         Kp {
232//             g: |r: &T| Some(r),
233//             s: |r: &mut T| Some(r),
234//             _p: PhantomData,
235//         }
236//     }
237// }
238
239impl<T> Kp<Arc<Mutex<T>>, Arc<Mutex<T>>> {
240    pub fn identity_arc_mutex() -> Self {
241        Kp {
242            g: |r: &Arc<Mutex<T>>| Some(r),
243            s: |r: &mut Arc<Mutex<T>>| Some(r),
244            _p: PhantomData,
245        }
246    }
247}
248
249/// A composed keypath chain through Arc<Mutex<T>> - functional style
250/// Build the chain first, then apply container at get() time
251///
252/// # Example
253/// ```rust
254/// // Functional style: compose first, then apply container at get()
255/// ContainerTest::mutex_data_r()
256///     .chain_arc_mutex_at_kp(SomeStruct::data_r())
257///     .get(&container, |value| println!("Value: {}", value));
258/// ```
259pub struct ArcMutexKeyPathChain<Root, MutexValue, InnerValue, SubValue, F, G>
260where
261    F: for<'r> Fn(&'r Root) -> &'r MutexValue,
262    G: for<'r> Fn(&'r InnerValue) -> &'r SubValue,
263{
264    outer_keypath: KeyPath<Root, MutexValue, F>,
265    inner_keypath: KeyPath<InnerValue, SubValue, G>,
266}
267
268impl<Root, MutexValue, InnerValue, SubValue, F, G>
269    ArcMutexKeyPathChain<Root, MutexValue, InnerValue, SubValue, F, G>
270where
271    F: for<'r> Fn(&'r Root) -> &'r MutexValue,
272    G: for<'r> Fn(&'r InnerValue) -> &'r SubValue,
273    MutexValue: std::borrow::Borrow<Arc<Mutex<InnerValue>>>,
274{
275    /// Apply the composed keypath chain to a container, executing callback with the value (read)
276    /// Consumes self - functional style (compose once, apply once)
277    pub fn get<Callback>(self, container: &Root, callback: Callback) -> Option<()>
278    where
279        Callback: FnOnce(&SubValue) -> (),
280    {
281        let arc_mutex_ref = self.outer_keypath.get(container);
282        arc_mutex_ref.borrow().lock().ok().map(|guard| {
283            let value = self.inner_keypath.get(&*guard);
284            callback(value)
285        })
286    }
287
288    /// Chain with another readable keypath through another level
289    pub fn then<NextValue, H>(
290        self,
291        next: KeyPath<SubValue, NextValue, H>,
292    ) -> ArcMutexKeyPathChain<
293        Root,
294        MutexValue,
295        InnerValue,
296        NextValue,
297        F,
298        impl for<'r> Fn(&'r InnerValue) -> &'r NextValue + 'static,
299    >
300    where
301        H: for<'r> Fn(&'r SubValue) -> &'r NextValue,
302        G: 'static,
303        H: 'static,
304        InnerValue: 'static,
305        SubValue: 'static,
306        NextValue: 'static,
307    {
308        let first = self.inner_keypath;
309        let second = next;
310
311        let composed = KeyPath::new(move |inner: &InnerValue| {
312            let sub = first.get(inner);
313            second.get(sub)
314        });
315
316        ArcMutexKeyPathChain {
317            outer_keypath: self.outer_keypath,
318            inner_keypath: composed,
319        }
320    }
321
322    /// Chain with an optional readable keypath through another level
323    pub fn chain_optional<NextValue, H>(
324        self,
325        next: OptionalKeyPath<SubValue, NextValue, H>,
326    ) -> ArcMutexOptionalKeyPathChain<
327        Root,
328        MutexValue,
329        InnerValue,
330        NextValue,
331        F,
332        impl for<'r> Fn(&'r InnerValue) -> Option<&'r NextValue> + 'static,
333    >
334    where
335        H: for<'r> Fn(&'r SubValue) -> Option<&'r NextValue>,
336        G: 'static,
337        H: 'static,
338        InnerValue: 'static,
339        SubValue: 'static,
340        NextValue: 'static,
341    {
342        let first = self.inner_keypath;
343        let second = next;
344
345        let composed = OptionalKeyPath::new(move |inner: &InnerValue| {
346            let sub = first.get(inner);
347            second.get(sub)
348        });
349
350        ArcMutexOptionalKeyPathChain {
351            outer_keypath: self.outer_keypath,
352            inner_keypath: composed,
353        }
354    }
355}
356
357// ========== WRITABLE MUTEX KEYPATH CHAINS ==========
358
359/// A composed writable keypath chain through Arc<Mutex<T>> - functional style
360/// Build the chain first, then apply container at get_mut() time
361pub struct ArcMutexWritableKeyPathChain<Root, MutexValue, InnerValue, SubValue, F, G>
362where
363    F: for<'r> Fn(&'r Root) -> &'r MutexValue,
364    G: for<'r> Fn(&'r mut InnerValue) -> &'r mut SubValue,
365{
366    outer_keypath: KeyPath<Root, MutexValue, F>,
367    inner_keypath: WritableKeyPath<InnerValue, SubValue, G>,
368}
369
370impl<Root, MutexValue, InnerValue, SubValue, F, G>
371    ArcMutexWritableKeyPathChain<Root, MutexValue, InnerValue, SubValue, F, G>
372where
373    F: for<'r> Fn(&'r Root) -> &'r MutexValue,
374    G: for<'r> Fn(&'r mut InnerValue) -> &'r mut SubValue,
375    MutexValue: std::borrow::Borrow<Arc<Mutex<InnerValue>>>,
376{
377    /// Apply the composed keypath chain to a container with mutable access
378    /// Consumes self - functional style (compose once, apply once)
379    pub fn get_mut<Callback, R>(self, container: &Root, callback: Callback) -> Option<R>
380    where
381        Callback: FnOnce(&mut SubValue) -> R,
382    {
383        let arc_mutex_ref = self.outer_keypath.get(container);
384        arc_mutex_ref.borrow().lock().ok().map(|mut guard| {
385            let value_ref = self.inner_keypath.get_mut(&mut *guard);
386            callback(value_ref)
387        })
388    }
389
390    /// Chain with another writable keypath through another level
391    pub fn then<NextValue, H>(
392        self,
393        next: WritableKeyPath<SubValue, NextValue, H>,
394    ) -> ArcMutexWritableKeyPathChain<
395        Root,
396        MutexValue,
397        InnerValue,
398        NextValue,
399        F,
400        impl for<'r> Fn(&'r mut InnerValue) -> &'r mut NextValue + 'static,
401    >
402    where
403        H: for<'r> Fn(&'r mut SubValue) -> &'r mut NextValue,
404        G: 'static,
405        H: 'static,
406        InnerValue: 'static,
407        SubValue: 'static,
408        NextValue: 'static,
409    {
410        let first = self.inner_keypath;
411        let second = next;
412
413        let composed = WritableKeyPath::new(move |inner: &mut InnerValue| {
414            let sub = first.get_mut(inner);
415            second.get_mut(sub)
416        });
417
418        ArcMutexWritableKeyPathChain {
419            outer_keypath: self.outer_keypath,
420            inner_keypath: composed,
421        }
422    }
423
424    /// Chain with an optional writable keypath through another level
425    pub fn chain_optional<NextValue, H>(
426        self,
427        next: WritableOptionalKeyPath<SubValue, NextValue, H>,
428    ) -> ArcMutexWritableOptionalKeyPathChain<
429        Root,
430        MutexValue,
431        InnerValue,
432        NextValue,
433        F,
434        impl for<'r> Fn(&'r mut InnerValue) -> Option<&'r mut NextValue> + 'static,
435    >
436    where
437        H: for<'r> Fn(&'r mut SubValue) -> Option<&'r mut NextValue>,
438        G: 'static,
439        H: 'static,
440        InnerValue: 'static,
441        SubValue: 'static,
442        NextValue: 'static,
443    {
444        let first = self.inner_keypath;
445        let second = next;
446
447        let composed = WritableOptionalKeyPath::new(move |inner: &mut InnerValue| {
448            let sub = first.get_mut(inner);
449            second.get_mut(sub)
450        });
451
452        ArcMutexWritableOptionalKeyPathChain {
453            outer_keypath: self.outer_keypath,
454            inner_keypath: composed,
455        }
456    }
457}
458
459/// A composed writable optional keypath chain through Arc<Mutex<T>> - functional style
460pub struct ArcMutexWritableOptionalKeyPathChain<Root, MutexValue, InnerValue, SubValue, F, G>
461where
462    F: for<'r> Fn(&'r Root) -> &'r MutexValue,
463    G: for<'r> Fn(&'r mut InnerValue) -> Option<&'r mut SubValue>,
464{
465    outer_keypath: KeyPath<Root, MutexValue, F>,
466    inner_keypath: WritableOptionalKeyPath<InnerValue, SubValue, G>,
467}
468
469impl<Root, MutexValue, InnerValue, SubValue, F, G>
470    ArcMutexWritableOptionalKeyPathChain<Root, MutexValue, InnerValue, SubValue, F, G>
471where
472    F: for<'r> Fn(&'r Root) -> &'r MutexValue,
473    G: for<'r> Fn(&'r mut InnerValue) -> Option<&'r mut SubValue>,
474    MutexValue: std::borrow::Borrow<Arc<Mutex<InnerValue>>>,
475{
476    /// Apply the composed keypath chain to a container with mutable access (if value exists)
477    /// Consumes self - functional style (compose once, apply once)
478    pub fn get_mut<Callback, R>(self, container: &Root, callback: Callback) -> Option<R>
479    where
480        Callback: FnOnce(&mut SubValue) -> R,
481    {
482        let arc_mutex_ref = self.outer_keypath.get(container);
483        arc_mutex_ref.borrow().lock().ok().and_then(|mut guard| {
484            self.inner_keypath
485                .get_mut(&mut *guard)
486                .map(|value_ref| callback(value_ref))
487        })
488    }
489
490    /// Chain with another writable keypath through another level
491    pub fn then<NextValue, H>(
492        self,
493        next: WritableKeyPath<SubValue, NextValue, H>,
494    ) -> ArcMutexWritableOptionalKeyPathChain<
495        Root,
496        MutexValue,
497        InnerValue,
498        NextValue,
499        F,
500        impl for<'r> Fn(&'r mut InnerValue) -> Option<&'r mut NextValue> + 'static,
501    >
502    where
503        H: for<'r> Fn(&'r mut SubValue) -> &'r mut 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 = WritableOptionalKeyPath::new(move |inner: &mut InnerValue| {
514            first.get_mut(inner).map(|sub| second.get_mut(sub))
515        });
516
517        ArcMutexWritableOptionalKeyPathChain {
518            outer_keypath: self.outer_keypath,
519            inner_keypath: composed,
520        }
521    }
522
523    /// Chain with an optional writable keypath through another level
524    pub fn chain_optional<NextValue, H>(
525        self,
526        next: WritableOptionalKeyPath<SubValue, NextValue, H>,
527    ) -> ArcMutexWritableOptionalKeyPathChain<
528        Root,
529        MutexValue,
530        InnerValue,
531        NextValue,
532        F,
533        impl for<'r> Fn(&'r mut InnerValue) -> Option<&'r mut NextValue> + 'static,
534    >
535    where
536        H: for<'r> Fn(&'r mut SubValue) -> Option<&'r mut NextValue>,
537        G: 'static,
538        H: 'static,
539        InnerValue: 'static,
540        SubValue: 'static,
541        NextValue: 'static,
542    {
543        let first = self.inner_keypath;
544        let second = next;
545
546        let composed = WritableOptionalKeyPath::new(move |inner: &mut InnerValue| {
547            first.get_mut(inner).and_then(|sub| second.get_mut(sub))
548        });
549
550        ArcMutexWritableOptionalKeyPathChain {
551            outer_keypath: self.outer_keypath,
552            inner_keypath: composed,
553        }
554    }
555}
556
557/// A composed optional keypath chain through Arc<Mutex<T>> - functional style
558pub struct ArcMutexOptionalKeyPathChain<Root, MutexValue, InnerValue, SubValue, F, G>
559where
560    F: for<'r> Fn(&'r Root) -> &'r MutexValue,
561    G: for<'r> Fn(&'r InnerValue) -> Option<&'r SubValue>,
562{
563    outer_keypath: KeyPath<Root, MutexValue, F>,
564    inner_keypath: OptionalKeyPath<InnerValue, SubValue, G>,
565}
566
567impl<Root, MutexValue, InnerValue, SubValue, F, G>
568    ArcMutexOptionalKeyPathChain<Root, MutexValue, InnerValue, SubValue, F, G>
569where
570    F: for<'r> Fn(&'r Root) -> &'r MutexValue,
571    G: for<'r> Fn(&'r InnerValue) -> Option<&'r SubValue>,
572    MutexValue: std::borrow::Borrow<Arc<Mutex<InnerValue>>>,
573{
574    /// Apply the composed keypath chain to a container, executing callback with the value
575    /// Consumes self - functional style (compose once, apply once)
576    pub fn get<Callback>(self, container: &Root, callback: Callback) -> Option<()>
577    where
578        Callback: FnOnce(&SubValue) -> (),
579    {
580        let arc_mutex_ref = self.outer_keypath.get(container);
581        arc_mutex_ref
582            .borrow()
583            .lock()
584            .ok()
585            .and_then(|guard| self.inner_keypath.get(&*guard).map(|value| callback(value)))
586    }
587
588    /// Chain with another readable keypath through another level
589    pub fn then<NextValue, H>(
590        self,
591        next: KeyPath<SubValue, NextValue, H>,
592    ) -> ArcMutexOptionalKeyPathChain<
593        Root,
594        MutexValue,
595        InnerValue,
596        NextValue,
597        F,
598        impl for<'r> Fn(&'r InnerValue) -> Option<&'r NextValue> + 'static,
599    >
600    where
601        H: for<'r> Fn(&'r SubValue) -> &'r NextValue,
602        G: 'static,
603        H: 'static,
604        InnerValue: 'static,
605        SubValue: 'static,
606        NextValue: 'static,
607    {
608        let first = self.inner_keypath;
609        let second = next;
610
611        let composed = OptionalKeyPath::new(move |inner: &InnerValue| {
612            first.get(inner).map(|sub| second.get(sub))
613        });
614
615        ArcMutexOptionalKeyPathChain {
616            outer_keypath: self.outer_keypath,
617            inner_keypath: composed,
618        }
619    }
620
621    /// Chain with an optional readable keypath through another level
622    pub fn chain_optional<NextValue, H>(
623        self,
624        next: OptionalKeyPath<SubValue, NextValue, H>,
625    ) -> ArcMutexOptionalKeyPathChain<
626        Root,
627        MutexValue,
628        InnerValue,
629        NextValue,
630        F,
631        impl for<'r> Fn(&'r InnerValue) -> Option<&'r NextValue> + 'static,
632    >
633    where
634        H: for<'r> Fn(&'r SubValue) -> Option<&'r NextValue>,
635        G: 'static,
636        H: 'static,
637        InnerValue: 'static,
638        SubValue: 'static,
639        NextValue: 'static,
640    {
641        let first = self.inner_keypath;
642        let second = next;
643
644        let composed = OptionalKeyPath::new(move |inner: &InnerValue| {
645            first.get(inner).and_then(|sub| second.get(sub))
646        });
647
648        ArcMutexOptionalKeyPathChain {
649            outer_keypath: self.outer_keypath,
650            inner_keypath: composed,
651        }
652    }
653}
654
655/// A composed keypath chain from OptionalKeyPath through Arc<Mutex<T>> - functional style
656pub struct OptionalArcMutexKeyPathChain<Root, MutexValue, InnerValue, SubValue, F, G>
657where
658    F: for<'r> Fn(&'r Root) -> Option<&'r MutexValue>,
659    G: for<'r> Fn(&'r InnerValue) -> &'r SubValue,
660{
661    outer_keypath: OptionalKeyPath<Root, MutexValue, F>,
662    inner_keypath: KeyPath<InnerValue, SubValue, G>,
663}
664
665impl<Root, MutexValue, InnerValue, SubValue, F, G>
666    OptionalArcMutexKeyPathChain<Root, MutexValue, InnerValue, SubValue, F, G>
667where
668    F: for<'r> Fn(&'r Root) -> Option<&'r MutexValue>,
669    G: for<'r> Fn(&'r InnerValue) -> &'r SubValue,
670    MutexValue: std::borrow::Borrow<Arc<Mutex<InnerValue>>>,
671{
672    /// Apply the composed keypath chain to a container, executing callback with the value
673    /// Consumes self - functional style (compose once, apply once)
674    pub fn get<Callback>(self, container: &Root, callback: Callback) -> Option<()>
675    where
676        Callback: FnOnce(&SubValue) -> (),
677    {
678        self.outer_keypath.get(container).and_then(|arc_mutex_ref| {
679            arc_mutex_ref.borrow().lock().ok().map(|guard| {
680                let value = self.inner_keypath.get(&*guard);
681                callback(value)
682            })
683        })
684    }
685
686    /// Chain with another readable keypath through another level
687    pub fn then<NextValue, H>(
688        self,
689        next: KeyPath<SubValue, NextValue, H>,
690    ) -> OptionalArcMutexKeyPathChain<
691        Root,
692        MutexValue,
693        InnerValue,
694        NextValue,
695        F,
696        impl for<'r> Fn(&'r InnerValue) -> &'r NextValue + 'static,
697    >
698    where
699        H: for<'r> Fn(&'r SubValue) -> &'r NextValue,
700        G: 'static,
701        H: 'static,
702        InnerValue: 'static,
703        SubValue: 'static,
704        NextValue: 'static,
705    {
706        let first = self.inner_keypath;
707        let second = next;
708
709        let composed = KeyPath::new(move |inner: &InnerValue| {
710            let sub = first.get(inner);
711            second.get(sub)
712        });
713
714        OptionalArcMutexKeyPathChain {
715            outer_keypath: self.outer_keypath,
716            inner_keypath: composed,
717        }
718    }
719
720    /// Chain with an optional readable keypath through another level
721    pub fn chain_optional<NextValue, H>(
722        self,
723        next: OptionalKeyPath<SubValue, NextValue, H>,
724    ) -> OptionalArcMutexOptionalKeyPathChain<
725        Root,
726        MutexValue,
727        InnerValue,
728        NextValue,
729        F,
730        impl for<'r> Fn(&'r InnerValue) -> Option<&'r NextValue> + 'static,
731    >
732    where
733        H: for<'r> Fn(&'r SubValue) -> Option<&'r NextValue>,
734        G: 'static,
735        H: 'static,
736        InnerValue: 'static,
737        SubValue: 'static,
738        NextValue: 'static,
739    {
740        let first = self.inner_keypath;
741        let second = next;
742
743        let composed = OptionalKeyPath::new(move |inner: &InnerValue| {
744            let sub = first.get(inner);
745            second.get(sub)
746        });
747
748        OptionalArcMutexOptionalKeyPathChain {
749            outer_keypath: self.outer_keypath,
750            inner_keypath: composed,
751        }
752    }
753}
754
755/// A composed optional keypath chain from OptionalKeyPath through Arc<Mutex<T>> - functional style
756pub struct OptionalArcMutexOptionalKeyPathChain<Root, MutexValue, InnerValue, SubValue, F, G>
757where
758    F: for<'r> Fn(&'r Root) -> Option<&'r MutexValue>,
759    G: for<'r> Fn(&'r InnerValue) -> Option<&'r SubValue>,
760{
761    outer_keypath: OptionalKeyPath<Root, MutexValue, F>,
762    inner_keypath: OptionalKeyPath<InnerValue, SubValue, G>,
763}
764
765impl<Root, MutexValue, InnerValue, SubValue, F, G>
766    OptionalArcMutexOptionalKeyPathChain<Root, MutexValue, InnerValue, SubValue, F, G>
767where
768    F: for<'r> Fn(&'r Root) -> Option<&'r MutexValue>,
769    G: for<'r> Fn(&'r InnerValue) -> Option<&'r SubValue>,
770    MutexValue: std::borrow::Borrow<Arc<Mutex<InnerValue>>>,
771{
772    /// Apply the composed keypath chain to a container, executing callback with the value
773    /// Consumes self - functional style (compose once, apply once)
774    pub fn get<Callback>(self, container: &Root, callback: Callback) -> Option<()>
775    where
776        Callback: FnOnce(&SubValue) -> (),
777    {
778        self.outer_keypath.get(container).and_then(|arc_mutex_ref| {
779            arc_mutex_ref
780                .borrow()
781                .lock()
782                .ok()
783                .and_then(|guard| self.inner_keypath.get(&*guard).map(|value| callback(value)))
784        })
785    }
786
787    /// Chain with another readable keypath through another level
788    pub fn then<NextValue, H>(
789        self,
790        next: KeyPath<SubValue, NextValue, H>,
791    ) -> OptionalArcMutexOptionalKeyPathChain<
792        Root,
793        MutexValue,
794        InnerValue,
795        NextValue,
796        F,
797        impl for<'r> Fn(&'r InnerValue) -> Option<&'r NextValue> + 'static,
798    >
799    where
800        H: for<'r> Fn(&'r SubValue) -> &'r NextValue,
801        G: 'static,
802        H: 'static,
803        InnerValue: 'static,
804        SubValue: 'static,
805        NextValue: 'static,
806    {
807        let first = self.inner_keypath;
808        let second = next;
809
810        let composed = OptionalKeyPath::new(move |inner: &InnerValue| {
811            first.get(inner).map(|sub| second.get(sub))
812        });
813
814        OptionalArcMutexOptionalKeyPathChain {
815            outer_keypath: self.outer_keypath,
816            inner_keypath: composed,
817        }
818    }
819
820    /// Chain with an optional readable keypath through another level
821    pub fn chain_optional<NextValue, H>(
822        self,
823        next: OptionalKeyPath<SubValue, NextValue, H>,
824    ) -> OptionalArcMutexOptionalKeyPathChain<
825        Root,
826        MutexValue,
827        InnerValue,
828        NextValue,
829        F,
830        impl for<'r> Fn(&'r InnerValue) -> Option<&'r NextValue> + 'static,
831    >
832    where
833        H: for<'r> Fn(&'r SubValue) -> Option<&'r NextValue>,
834        G: 'static,
835        H: 'static,
836        InnerValue: 'static,
837        SubValue: 'static,
838        NextValue: 'static,
839    {
840        let first = self.inner_keypath;
841        let second = next;
842
843        let composed = OptionalKeyPath::new(move |inner: &InnerValue| {
844            first.get(inner).and_then(|sub| second.get(sub))
845        });
846
847        OptionalArcMutexOptionalKeyPathChain {
848            outer_keypath: self.outer_keypath,
849            inner_keypath: composed,
850        }
851    }
852}
853
854// ========== FUNCTIONAL RWLOCK KEYPATH CHAINS ==========
855
856/// A composed keypath chain through Arc<RwLock<T>> - functional style
857/// Build the chain first, then apply container at get() time
858///
859/// # Example
860/// ```rust
861/// // Functional style: compose first, then apply container at get()
862/// ContainerTest::rwlock_data_r()
863///     .chain_arc_rwlock_at_kp(SomeStruct::data_r())
864///     .get(&container, |value| println!("Value: {}", value));
865/// ```
866pub struct ArcRwLockKeyPathChain<Root, RwLockValue, InnerValue, SubValue, F, G>
867where
868    F: for<'r> Fn(&'r Root) -> &'r RwLockValue,
869    G: for<'r> Fn(&'r InnerValue) -> &'r SubValue,
870{
871    outer_keypath: KeyPath<Root, RwLockValue, F>,
872    inner_keypath: KeyPath<InnerValue, SubValue, G>,
873}
874
875impl<Root, RwLockValue, InnerValue, SubValue, F, G>
876    ArcRwLockKeyPathChain<Root, RwLockValue, InnerValue, SubValue, F, G>
877where
878    F: for<'r> Fn(&'r Root) -> &'r RwLockValue,
879    G: for<'r> Fn(&'r InnerValue) -> &'r SubValue,
880    RwLockValue: std::borrow::Borrow<Arc<RwLock<InnerValue>>>,
881{
882    /// Apply the composed keypath chain to a container, executing callback with the value (read lock)
883    /// Consumes self - functional style (compose once, apply once)
884    pub fn get<Callback>(self, container: &Root, callback: Callback) -> Option<()>
885    where
886        Callback: FnOnce(&SubValue) -> (),
887    {
888        let arc_rwlock_ref = self.outer_keypath.get(container);
889        arc_rwlock_ref.borrow().read().ok().map(|guard| {
890            let value = self.inner_keypath.get(&*guard);
891            callback(value)
892        })
893    }
894
895    /// Chain with another readable keypath through another level
896    /// This allows composing deeper keypaths through the same Arc<RwLock<T>> structure
897    pub fn then<NextValue, H>(
898        self,
899        next: KeyPath<SubValue, NextValue, H>,
900    ) -> ArcRwLockKeyPathChain<
901        Root,
902        RwLockValue,
903        InnerValue,
904        NextValue,
905        F,
906        impl for<'r> Fn(&'r InnerValue) -> &'r NextValue + 'static,
907    >
908    where
909        H: for<'r> Fn(&'r SubValue) -> &'r NextValue,
910        G: 'static,
911        H: 'static,
912        InnerValue: 'static,
913        SubValue: 'static,
914        NextValue: 'static,
915    {
916        let first = self.inner_keypath;
917        let second = next;
918
919        let composed = KeyPath::new(move |inner: &InnerValue| {
920            let sub = first.get(inner);
921            second.get(sub)
922        });
923
924        ArcRwLockKeyPathChain {
925            outer_keypath: self.outer_keypath,
926            inner_keypath: composed,
927        }
928    }
929
930    /// Chain with an optional readable keypath through another level
931    pub fn chain_optional<NextValue, H>(
932        self,
933        next: OptionalKeyPath<SubValue, NextValue, H>,
934    ) -> ArcRwLockOptionalKeyPathChain<
935        Root,
936        RwLockValue,
937        InnerValue,
938        NextValue,
939        F,
940        impl for<'r> Fn(&'r InnerValue) -> Option<&'r NextValue> + 'static,
941    >
942    where
943        H: for<'r> Fn(&'r SubValue) -> Option<&'r NextValue>,
944        G: 'static,
945        H: 'static,
946        InnerValue: 'static,
947        SubValue: 'static,
948        NextValue: 'static,
949    {
950        let first = self.inner_keypath;
951        let second = next;
952
953        let composed = OptionalKeyPath::new(move |inner: &InnerValue| {
954            let sub = first.get(inner);
955            second.get(sub)
956        });
957
958        ArcRwLockOptionalKeyPathChain {
959            outer_keypath: self.outer_keypath,
960            inner_keypath: composed,
961        }
962    }
963}
964
965/// A composed optional keypath chain through Arc<RwLock<T>> - functional style
966pub struct ArcRwLockOptionalKeyPathChain<Root, RwLockValue, InnerValue, SubValue, F, G>
967where
968    F: for<'r> Fn(&'r Root) -> &'r RwLockValue,
969    G: for<'r> Fn(&'r InnerValue) -> Option<&'r SubValue>,
970{
971    outer_keypath: KeyPath<Root, RwLockValue, F>,
972    inner_keypath: OptionalKeyPath<InnerValue, SubValue, G>,
973}
974
975impl<Root, RwLockValue, InnerValue, SubValue, F, G>
976    ArcRwLockOptionalKeyPathChain<Root, RwLockValue, InnerValue, SubValue, F, G>
977where
978    F: for<'r> Fn(&'r Root) -> &'r RwLockValue,
979    G: for<'r> Fn(&'r InnerValue) -> Option<&'r SubValue>,
980    RwLockValue: std::borrow::Borrow<Arc<RwLock<InnerValue>>>,
981{
982    /// Apply the composed keypath chain to a container, executing callback with the value (read lock)
983    /// Consumes self - functional style (compose once, apply once)
984    pub fn get<Callback>(self, container: &Root, callback: Callback) -> Option<()>
985    where
986        Callback: FnOnce(&SubValue) -> (),
987    {
988        let arc_rwlock_ref = self.outer_keypath.get(container);
989        arc_rwlock_ref
990            .borrow()
991            .read()
992            .ok()
993            .and_then(|guard| self.inner_keypath.get(&*guard).map(|value| callback(value)))
994    }
995}
996
997/// A composed keypath chain from OptionalKeyPath through Arc<RwLock<T>> - functional style
998pub struct OptionalArcRwLockKeyPathChain<Root, RwLockValue, InnerValue, SubValue, F, G>
999where
1000    F: for<'r> Fn(&'r Root) -> Option<&'r RwLockValue>,
1001    G: for<'r> Fn(&'r InnerValue) -> &'r SubValue,
1002{
1003    outer_keypath: OptionalKeyPath<Root, RwLockValue, F>,
1004    inner_keypath: KeyPath<InnerValue, SubValue, G>,
1005}
1006
1007impl<Root, RwLockValue, InnerValue, SubValue, F, G>
1008    OptionalArcRwLockKeyPathChain<Root, RwLockValue, InnerValue, SubValue, F, G>
1009where
1010    F: for<'r> Fn(&'r Root) -> Option<&'r RwLockValue>,
1011    G: for<'r> Fn(&'r InnerValue) -> &'r SubValue,
1012    RwLockValue: std::borrow::Borrow<Arc<RwLock<InnerValue>>>,
1013{
1014    /// Apply the composed keypath chain to a container, executing callback with the value (read lock)
1015    /// Consumes self - functional style (compose once, apply once)
1016    pub fn get<Callback>(self, container: &Root, callback: Callback) -> Option<()>
1017    where
1018        Callback: FnOnce(&SubValue) -> (),
1019    {
1020        self.outer_keypath
1021            .get(container)
1022            .and_then(|arc_rwlock_ref| {
1023                arc_rwlock_ref.borrow().read().ok().map(|guard| {
1024                    let value = self.inner_keypath.get(&*guard);
1025                    callback(value)
1026                })
1027            })
1028    }
1029
1030    /// Chain with another readable keypath through another level
1031    pub fn then<NextValue, H>(
1032        self,
1033        next: KeyPath<SubValue, NextValue, H>,
1034    ) -> OptionalArcRwLockKeyPathChain<
1035        Root,
1036        RwLockValue,
1037        InnerValue,
1038        NextValue,
1039        F,
1040        impl for<'r> Fn(&'r InnerValue) -> &'r NextValue + 'static,
1041    >
1042    where
1043        H: for<'r> Fn(&'r SubValue) -> &'r NextValue,
1044        G: 'static,
1045        H: 'static,
1046        InnerValue: 'static,
1047        SubValue: 'static,
1048        NextValue: 'static,
1049    {
1050        let first = self.inner_keypath;
1051        let second = next;
1052
1053        let composed = KeyPath::new(move |inner: &InnerValue| {
1054            let sub = first.get(inner);
1055            second.get(sub)
1056        });
1057
1058        OptionalArcRwLockKeyPathChain {
1059            outer_keypath: self.outer_keypath,
1060            inner_keypath: composed,
1061        }
1062    }
1063
1064    /// Chain with an optional readable keypath through another level
1065    pub fn chain_optional<NextValue, H>(
1066        self,
1067        next: OptionalKeyPath<SubValue, NextValue, H>,
1068    ) -> OptionalArcRwLockOptionalKeyPathChain<
1069        Root,
1070        RwLockValue,
1071        InnerValue,
1072        NextValue,
1073        F,
1074        impl for<'r> Fn(&'r InnerValue) -> Option<&'r NextValue> + 'static,
1075    >
1076    where
1077        H: for<'r> Fn(&'r SubValue) -> Option<&'r NextValue>,
1078        G: 'static,
1079        H: 'static,
1080        InnerValue: 'static,
1081        SubValue: 'static,
1082        NextValue: 'static,
1083    {
1084        let first = self.inner_keypath;
1085        let second = next;
1086
1087        let composed = OptionalKeyPath::new(move |inner: &InnerValue| {
1088            let sub = first.get(inner);
1089            second.get(sub)
1090        });
1091
1092        OptionalArcRwLockOptionalKeyPathChain {
1093            outer_keypath: self.outer_keypath,
1094            inner_keypath: composed,
1095        }
1096    }
1097}
1098
1099/// A composed optional keypath chain from OptionalKeyPath through Arc<RwLock<T>> - functional style
1100pub struct OptionalArcRwLockOptionalKeyPathChain<Root, RwLockValue, InnerValue, SubValue, F, G>
1101where
1102    F: for<'r> Fn(&'r Root) -> Option<&'r RwLockValue>,
1103    G: for<'r> Fn(&'r InnerValue) -> Option<&'r SubValue>,
1104{
1105    outer_keypath: OptionalKeyPath<Root, RwLockValue, F>,
1106    inner_keypath: OptionalKeyPath<InnerValue, SubValue, G>,
1107}
1108
1109impl<Root, RwLockValue, InnerValue, SubValue, F, G>
1110    OptionalArcRwLockOptionalKeyPathChain<Root, RwLockValue, InnerValue, SubValue, F, G>
1111where
1112    F: for<'r> Fn(&'r Root) -> Option<&'r RwLockValue>,
1113    G: for<'r> Fn(&'r InnerValue) -> Option<&'r SubValue>,
1114    RwLockValue: std::borrow::Borrow<Arc<RwLock<InnerValue>>>,
1115{
1116    /// Apply the composed keypath chain to a container, executing callback with the value (read lock)
1117    /// Consumes self - functional style (compose once, apply once)
1118    pub fn get<Callback>(self, container: &Root, callback: Callback) -> Option<()>
1119    where
1120        Callback: FnOnce(&SubValue) -> (),
1121    {
1122        self.outer_keypath
1123            .get(container)
1124            .and_then(|arc_rwlock_ref| {
1125                arc_rwlock_ref
1126                    .borrow()
1127                    .read()
1128                    .ok()
1129                    .and_then(|guard| self.inner_keypath.get(&*guard).map(|value| callback(value)))
1130            })
1131    }
1132
1133    /// Chain with another readable keypath through another level
1134    pub fn then<NextValue, H>(
1135        self,
1136        next: KeyPath<SubValue, NextValue, H>,
1137    ) -> OptionalArcRwLockOptionalKeyPathChain<
1138        Root,
1139        RwLockValue,
1140        InnerValue,
1141        NextValue,
1142        F,
1143        impl for<'r> Fn(&'r InnerValue) -> Option<&'r NextValue> + 'static,
1144    >
1145    where
1146        H: for<'r> Fn(&'r SubValue) -> &'r NextValue,
1147        G: 'static,
1148        H: 'static,
1149        InnerValue: 'static,
1150        SubValue: 'static,
1151        NextValue: 'static,
1152    {
1153        let first = self.inner_keypath;
1154        let second = next;
1155
1156        let composed = OptionalKeyPath::new(move |inner: &InnerValue| {
1157            first.get(inner).map(|sub| second.get(sub))
1158        });
1159
1160        OptionalArcRwLockOptionalKeyPathChain {
1161            outer_keypath: self.outer_keypath,
1162            inner_keypath: composed,
1163        }
1164    }
1165
1166    /// Chain with an optional readable keypath through another level
1167    pub fn chain_optional<NextValue, H>(
1168        self,
1169        next: OptionalKeyPath<SubValue, NextValue, H>,
1170    ) -> OptionalArcRwLockOptionalKeyPathChain<
1171        Root,
1172        RwLockValue,
1173        InnerValue,
1174        NextValue,
1175        F,
1176        impl for<'r> Fn(&'r InnerValue) -> Option<&'r NextValue> + 'static,
1177    >
1178    where
1179        H: for<'r> Fn(&'r SubValue) -> Option<&'r NextValue>,
1180        G: 'static,
1181        H: 'static,
1182        InnerValue: 'static,
1183        SubValue: 'static,
1184        NextValue: 'static,
1185    {
1186        let first = self.inner_keypath;
1187        let second = next;
1188
1189        let composed = OptionalKeyPath::new(move |inner: &InnerValue| {
1190            first.get(inner).and_then(|sub| second.get(sub))
1191        });
1192
1193        OptionalArcRwLockOptionalKeyPathChain {
1194            outer_keypath: self.outer_keypath,
1195            inner_keypath: composed,
1196        }
1197    }
1198}
1199
1200// ========== WRITABLE MUTEX KEYPATH CHAINS FROM OPTIONAL KEYPATHS ==========
1201
1202/// A composed writable keypath chain from optional keypath through Arc<Mutex<T>> - functional style
1203/// Build the chain first, then apply container at get_mut() time
1204pub struct OptionalArcMutexWritableKeyPathChain<Root, MutexValue, InnerValue, SubValue, F, G>
1205where
1206    F: for<'r> Fn(&'r Root) -> Option<&'r MutexValue>,
1207    G: for<'r> Fn(&'r mut InnerValue) -> &'r mut SubValue,
1208{
1209    outer_keypath: OptionalKeyPath<Root, MutexValue, F>,
1210    inner_keypath: WritableKeyPath<InnerValue, SubValue, G>,
1211}
1212
1213impl<Root, MutexValue, InnerValue, SubValue, F, G>
1214    OptionalArcMutexWritableKeyPathChain<Root, MutexValue, InnerValue, SubValue, F, G>
1215where
1216    F: for<'r> Fn(&'r Root) -> Option<&'r MutexValue>,
1217    G: for<'r> Fn(&'r mut InnerValue) -> &'r mut SubValue,
1218    MutexValue: std::borrow::Borrow<Arc<Mutex<InnerValue>>>,
1219{
1220    /// Apply the composed keypath chain to a container with mutable access
1221    /// Consumes self - functional style (compose once, apply once)
1222    pub fn get_mut<Callback, R>(self, container: &Root, callback: Callback) -> Option<R>
1223    where
1224        Callback: FnOnce(&mut SubValue) -> R,
1225    {
1226        self.outer_keypath.get(container).and_then(|arc_mutex_ref| {
1227            arc_mutex_ref.borrow().lock().ok().map(|mut guard| {
1228                let value_ref = self.inner_keypath.get_mut(&mut *guard);
1229                callback(value_ref)
1230            })
1231        })
1232    }
1233
1234    /// Chain with another writable keypath through another level
1235    pub fn then<NextValue, H>(
1236        self,
1237        next: WritableKeyPath<SubValue, NextValue, H>,
1238    ) -> OptionalArcMutexWritableKeyPathChain<
1239        Root,
1240        MutexValue,
1241        InnerValue,
1242        NextValue,
1243        F,
1244        impl for<'r> Fn(&'r mut InnerValue) -> &'r mut NextValue + 'static,
1245    >
1246    where
1247        H: for<'r> Fn(&'r mut SubValue) -> &'r mut NextValue,
1248        G: 'static,
1249        H: 'static,
1250        InnerValue: 'static,
1251        SubValue: 'static,
1252        NextValue: 'static,
1253    {
1254        let first = self.inner_keypath;
1255        let second = next;
1256
1257        let composed = WritableKeyPath::new(move |inner: &mut InnerValue| {
1258            let sub = first.get_mut(inner);
1259            second.get_mut(sub)
1260        });
1261
1262        OptionalArcMutexWritableKeyPathChain {
1263            outer_keypath: self.outer_keypath,
1264            inner_keypath: composed,
1265        }
1266    }
1267
1268    /// Chain with an optional writable keypath through another level
1269    pub fn chain_optional<NextValue, H>(
1270        self,
1271        next: WritableOptionalKeyPath<SubValue, NextValue, H>,
1272    ) -> OptionalArcMutexWritableOptionalKeyPathChain<
1273        Root,
1274        MutexValue,
1275        InnerValue,
1276        NextValue,
1277        F,
1278        impl for<'r> Fn(&'r mut InnerValue) -> Option<&'r mut NextValue> + 'static,
1279    >
1280    where
1281        H: for<'r> Fn(&'r mut SubValue) -> Option<&'r mut NextValue>,
1282        G: 'static,
1283        H: 'static,
1284        InnerValue: 'static,
1285        SubValue: 'static,
1286        NextValue: 'static,
1287    {
1288        let first = self.inner_keypath;
1289        let second = next;
1290
1291        let composed = WritableOptionalKeyPath::new(move |inner: &mut InnerValue| {
1292            let sub = first.get_mut(inner);
1293            second.get_mut(sub)
1294        });
1295
1296        OptionalArcMutexWritableOptionalKeyPathChain {
1297            outer_keypath: self.outer_keypath,
1298            inner_keypath: composed,
1299        }
1300    }
1301}
1302
1303/// A composed writable optional keypath chain from optional keypath through Arc<Mutex<T>> - functional style
1304/// Build the chain first, then apply container at get_mut() time
1305pub struct OptionalArcMutexWritableOptionalKeyPathChain<
1306    Root,
1307    MutexValue,
1308    InnerValue,
1309    SubValue,
1310    F,
1311    G,
1312> where
1313    F: for<'r> Fn(&'r Root) -> Option<&'r MutexValue>,
1314    G: for<'r> Fn(&'r mut InnerValue) -> Option<&'r mut SubValue>,
1315{
1316    outer_keypath: OptionalKeyPath<Root, MutexValue, F>,
1317    inner_keypath: WritableOptionalKeyPath<InnerValue, SubValue, G>,
1318}
1319
1320impl<Root, MutexValue, InnerValue, SubValue, F, G>
1321    OptionalArcMutexWritableOptionalKeyPathChain<Root, MutexValue, InnerValue, SubValue, F, G>
1322where
1323    F: for<'r> Fn(&'r Root) -> Option<&'r MutexValue>,
1324    G: for<'r> Fn(&'r mut InnerValue) -> Option<&'r mut SubValue>,
1325    MutexValue: std::borrow::Borrow<Arc<Mutex<InnerValue>>>,
1326{
1327    /// Apply the composed keypath chain to a container with mutable access (if value exists)
1328    /// Consumes self - functional style (compose once, apply once)
1329    pub fn get_mut<Callback, R>(self, container: &Root, callback: Callback) -> Option<R>
1330    where
1331        Callback: FnOnce(&mut SubValue) -> R,
1332    {
1333        self.outer_keypath.get(container).and_then(|arc_mutex_ref| {
1334            arc_mutex_ref.borrow().lock().ok().and_then(|mut guard| {
1335                self.inner_keypath
1336                    .get_mut(&mut *guard)
1337                    .map(|value_ref| callback(value_ref))
1338            })
1339        })
1340    }
1341
1342    /// Chain with another writable keypath through another level
1343    pub fn then<NextValue, H>(
1344        self,
1345        next: WritableKeyPath<SubValue, NextValue, H>,
1346    ) -> OptionalArcMutexWritableOptionalKeyPathChain<
1347        Root,
1348        MutexValue,
1349        InnerValue,
1350        NextValue,
1351        F,
1352        impl for<'r> Fn(&'r mut InnerValue) -> Option<&'r mut NextValue> + 'static,
1353    >
1354    where
1355        H: for<'r> Fn(&'r mut SubValue) -> &'r mut NextValue,
1356        G: 'static,
1357        H: 'static,
1358        InnerValue: 'static,
1359        SubValue: 'static,
1360        NextValue: 'static,
1361    {
1362        let first = self.inner_keypath;
1363        let second = next;
1364
1365        let composed = WritableOptionalKeyPath::new(move |inner: &mut InnerValue| {
1366            first.get_mut(inner).map(|sub| second.get_mut(sub))
1367        });
1368
1369        OptionalArcMutexWritableOptionalKeyPathChain {
1370            outer_keypath: self.outer_keypath,
1371            inner_keypath: composed,
1372        }
1373    }
1374
1375    /// Chain with an optional writable keypath through another level
1376    pub fn chain_optional<NextValue, H>(
1377        self,
1378        next: WritableOptionalKeyPath<SubValue, NextValue, H>,
1379    ) -> OptionalArcMutexWritableOptionalKeyPathChain<
1380        Root,
1381        MutexValue,
1382        InnerValue,
1383        NextValue,
1384        F,
1385        impl for<'r> Fn(&'r mut InnerValue) -> Option<&'r mut NextValue> + 'static,
1386    >
1387    where
1388        H: for<'r> Fn(&'r mut SubValue) -> Option<&'r mut NextValue>,
1389        G: 'static,
1390        H: 'static,
1391        InnerValue: 'static,
1392        SubValue: 'static,
1393        NextValue: 'static,
1394    {
1395        let first = self.inner_keypath;
1396        let second = next;
1397
1398        let composed = WritableOptionalKeyPath::new(move |inner: &mut InnerValue| {
1399            first.get_mut(inner).and_then(|sub| second.get_mut(sub))
1400        });
1401
1402        OptionalArcMutexWritableOptionalKeyPathChain {
1403            outer_keypath: self.outer_keypath,
1404            inner_keypath: composed,
1405        }
1406    }
1407}
1408
1409// ========== WRITABLE RWLOCK KEYPATH CHAINS FROM OPTIONAL KEYPATHS ==========
1410
1411/// A composed writable keypath chain from optional keypath through Arc<RwLock<T>> - functional style
1412/// Build the chain first, then apply container at get_mut() time (uses write lock)
1413pub struct OptionalArcRwLockWritableKeyPathChain<Root, RwLockValue, InnerValue, SubValue, F, G>
1414where
1415    F: for<'r> Fn(&'r Root) -> Option<&'r RwLockValue>,
1416    G: for<'r> Fn(&'r mut InnerValue) -> &'r mut SubValue,
1417{
1418    outer_keypath: OptionalKeyPath<Root, RwLockValue, F>,
1419    inner_keypath: WritableKeyPath<InnerValue, SubValue, G>,
1420}
1421
1422impl<Root, RwLockValue, InnerValue, SubValue, F, G>
1423    OptionalArcRwLockWritableKeyPathChain<Root, RwLockValue, InnerValue, SubValue, F, G>
1424where
1425    F: for<'r> Fn(&'r Root) -> Option<&'r RwLockValue>,
1426    G: for<'r> Fn(&'r mut InnerValue) -> &'r mut SubValue,
1427    RwLockValue: std::borrow::Borrow<Arc<RwLock<InnerValue>>>,
1428{
1429    /// Apply the composed keypath chain to a container with mutable access (write lock)
1430    /// Consumes self - functional style (compose once, apply once)
1431    pub fn get_mut<Callback, R>(self, container: &Root, callback: Callback) -> Option<R>
1432    where
1433        Callback: FnOnce(&mut SubValue) -> R,
1434    {
1435        self.outer_keypath
1436            .get(container)
1437            .and_then(|arc_rwlock_ref| {
1438                arc_rwlock_ref.borrow().write().ok().map(|mut guard| {
1439                    let value_ref = self.inner_keypath.get_mut(&mut *guard);
1440                    callback(value_ref)
1441                })
1442            })
1443    }
1444
1445    /// Chain with another writable keypath through another level
1446    pub fn then<NextValue, H>(
1447        self,
1448        next: WritableKeyPath<SubValue, NextValue, H>,
1449    ) -> OptionalArcRwLockWritableKeyPathChain<
1450        Root,
1451        RwLockValue,
1452        InnerValue,
1453        NextValue,
1454        F,
1455        impl for<'r> Fn(&'r mut InnerValue) -> &'r mut NextValue + 'static,
1456    >
1457    where
1458        H: for<'r> Fn(&'r mut SubValue) -> &'r mut NextValue,
1459        G: 'static,
1460        H: 'static,
1461        InnerValue: 'static,
1462        SubValue: 'static,
1463        NextValue: 'static,
1464    {
1465        let first = self.inner_keypath;
1466        let second = next;
1467
1468        let composed = WritableKeyPath::new(move |inner: &mut InnerValue| {
1469            let sub = first.get_mut(inner);
1470            second.get_mut(sub)
1471        });
1472
1473        OptionalArcRwLockWritableKeyPathChain {
1474            outer_keypath: self.outer_keypath,
1475            inner_keypath: composed,
1476        }
1477    }
1478
1479    /// Chain with an optional writable keypath through another level
1480    pub fn chain_optional<NextValue, H>(
1481        self,
1482        next: WritableOptionalKeyPath<SubValue, NextValue, H>,
1483    ) -> OptionalArcRwLockWritableOptionalKeyPathChain<
1484        Root,
1485        RwLockValue,
1486        InnerValue,
1487        NextValue,
1488        F,
1489        impl for<'r> Fn(&'r mut InnerValue) -> Option<&'r mut NextValue> + 'static,
1490    >
1491    where
1492        H: for<'r> Fn(&'r mut SubValue) -> Option<&'r mut NextValue>,
1493        G: 'static,
1494        H: 'static,
1495        InnerValue: 'static,
1496        SubValue: 'static,
1497        NextValue: 'static,
1498    {
1499        let first = self.inner_keypath;
1500        let second = next;
1501
1502        let composed = WritableOptionalKeyPath::new(move |inner: &mut InnerValue| {
1503            let sub = first.get_mut(inner);
1504            second.get_mut(sub)
1505        });
1506
1507        OptionalArcRwLockWritableOptionalKeyPathChain {
1508            outer_keypath: self.outer_keypath,
1509            inner_keypath: composed,
1510        }
1511    }
1512}
1513
1514/// A composed writable optional keypath chain from optional keypath through Arc<RwLock<T>> - functional style
1515/// Build the chain first, then apply container at get_mut() time (uses write lock)
1516pub struct OptionalArcRwLockWritableOptionalKeyPathChain<
1517    Root,
1518    RwLockValue,
1519    InnerValue,
1520    SubValue,
1521    F,
1522    G,
1523> where
1524    F: for<'r> Fn(&'r Root) -> Option<&'r RwLockValue>,
1525    G: for<'r> Fn(&'r mut InnerValue) -> Option<&'r mut SubValue>,
1526{
1527    outer_keypath: OptionalKeyPath<Root, RwLockValue, F>,
1528    inner_keypath: WritableOptionalKeyPath<InnerValue, SubValue, G>,
1529}
1530
1531impl<Root, RwLockValue, InnerValue, SubValue, F, G>
1532    OptionalArcRwLockWritableOptionalKeyPathChain<Root, RwLockValue, InnerValue, SubValue, F, G>
1533where
1534    F: for<'r> Fn(&'r Root) -> Option<&'r RwLockValue>,
1535    G: for<'r> Fn(&'r mut InnerValue) -> Option<&'r mut SubValue>,
1536    RwLockValue: std::borrow::Borrow<Arc<RwLock<InnerValue>>>,
1537{
1538    /// Apply the composed keypath chain to a container with mutable access (write lock, if value exists)
1539    /// Consumes self - functional style (compose once, apply once)
1540    pub fn get_mut<Callback, R>(self, container: &Root, callback: Callback) -> Option<R>
1541    where
1542        Callback: FnOnce(&mut SubValue) -> R,
1543    {
1544        self.outer_keypath
1545            .get(container)
1546            .and_then(|arc_rwlock_ref| {
1547                arc_rwlock_ref.borrow().write().ok().and_then(|mut guard| {
1548                    self.inner_keypath
1549                        .get_mut(&mut *guard)
1550                        .map(|value_ref| callback(value_ref))
1551                })
1552            })
1553    }
1554
1555    /// Chain with another writable keypath through another level
1556    pub fn then<NextValue, H>(
1557        self,
1558        next: WritableKeyPath<SubValue, NextValue, H>,
1559    ) -> OptionalArcRwLockWritableOptionalKeyPathChain<
1560        Root,
1561        RwLockValue,
1562        InnerValue,
1563        NextValue,
1564        F,
1565        impl for<'r> Fn(&'r mut InnerValue) -> Option<&'r mut NextValue> + 'static,
1566    >
1567    where
1568        H: for<'r> Fn(&'r mut SubValue) -> &'r mut NextValue,
1569        G: 'static,
1570        H: 'static,
1571        InnerValue: 'static,
1572        SubValue: 'static,
1573        NextValue: 'static,
1574    {
1575        let first = self.inner_keypath;
1576        let second = next;
1577
1578        let composed = WritableOptionalKeyPath::new(move |inner: &mut InnerValue| {
1579            first.get_mut(inner).map(|sub| second.get_mut(sub))
1580        });
1581
1582        OptionalArcRwLockWritableOptionalKeyPathChain {
1583            outer_keypath: self.outer_keypath,
1584            inner_keypath: composed,
1585        }
1586    }
1587
1588    /// Chain with an optional writable keypath through another level
1589    pub fn chain_optional<NextValue, H>(
1590        self,
1591        next: WritableOptionalKeyPath<SubValue, NextValue, H>,
1592    ) -> OptionalArcRwLockWritableOptionalKeyPathChain<
1593        Root,
1594        RwLockValue,
1595        InnerValue,
1596        NextValue,
1597        F,
1598        impl for<'r> Fn(&'r mut InnerValue) -> Option<&'r mut NextValue> + 'static,
1599    >
1600    where
1601        H: for<'r> Fn(&'r mut SubValue) -> Option<&'r mut NextValue>,
1602        G: 'static,
1603        H: 'static,
1604        InnerValue: 'static,
1605        SubValue: 'static,
1606        NextValue: 'static,
1607    {
1608        let first = self.inner_keypath;
1609        let second = next;
1610
1611        let composed = WritableOptionalKeyPath::new(move |inner: &mut InnerValue| {
1612            first.get_mut(inner).and_then(|sub| second.get_mut(sub))
1613        });
1614
1615        OptionalArcRwLockWritableOptionalKeyPathChain {
1616            outer_keypath: self.outer_keypath,
1617            inner_keypath: composed,
1618        }
1619    }
1620}
1621
1622// ========== WRITABLE RWLOCK KEYPATH CHAINS ==========
1623
1624/// A composed writable keypath chain through Arc<RwLock<T>> - functional style
1625/// Build the chain first, then apply container at get_mut() time (uses write lock)
1626pub struct ArcRwLockWritableKeyPathChain<Root, RwLockValue, InnerValue, SubValue, F, G>
1627where
1628    F: for<'r> Fn(&'r Root) -> &'r RwLockValue,
1629    G: for<'r> Fn(&'r mut InnerValue) -> &'r mut SubValue,
1630{
1631    outer_keypath: KeyPath<Root, RwLockValue, F>,
1632    inner_keypath: WritableKeyPath<InnerValue, SubValue, G>,
1633}
1634
1635impl<Root, RwLockValue, InnerValue, SubValue, F, G>
1636    ArcRwLockWritableKeyPathChain<Root, RwLockValue, InnerValue, SubValue, F, G>
1637where
1638    F: for<'r> Fn(&'r Root) -> &'r RwLockValue,
1639    G: for<'r> Fn(&'r mut InnerValue) -> &'r mut SubValue,
1640    RwLockValue: std::borrow::Borrow<Arc<RwLock<InnerValue>>>,
1641{
1642    /// Apply the composed keypath chain to a container with mutable access (write lock)
1643    /// Consumes self - functional style (compose once, apply once)
1644    pub fn get_mut<Callback, R>(self, container: &Root, callback: Callback) -> Option<R>
1645    where
1646        Callback: FnOnce(&mut SubValue) -> R,
1647    {
1648        let arc_rwlock_ref = self.outer_keypath.get(container);
1649        arc_rwlock_ref.borrow().write().ok().map(|mut guard| {
1650            let value_ref = self.inner_keypath.get_mut(&mut *guard);
1651            callback(value_ref)
1652        })
1653    }
1654
1655    /// Monadic composition: chain with another writable keypath
1656    /// This allows composing deeper keypaths through the same Arc<RwLock<T>> structure
1657    ///
1658    /// # Example
1659    /// ```rust,ignore
1660    /// // Compose: Root -> Arc<RwLock<InnerValue>> -> InnerValue -> SubValue -> NextValue
1661    /// let chain = root_keypath
1662    ///     .chain_arc_rwlock_writable_at_kp(inner_keypath)
1663    ///     .then(next_keypath);
1664    /// ```
1665    pub fn then<NextValue, H>(
1666        self,
1667        next: WritableKeyPath<SubValue, NextValue, H>,
1668    ) -> ArcRwLockWritableKeyPathChain<
1669        Root,
1670        RwLockValue,
1671        InnerValue,
1672        NextValue,
1673        F,
1674        impl for<'r> Fn(&'r mut InnerValue) -> &'r mut NextValue + 'static,
1675    >
1676    where
1677        H: for<'r> Fn(&'r mut SubValue) -> &'r mut NextValue,
1678        G: 'static,
1679        H: 'static,
1680        InnerValue: 'static,
1681        SubValue: 'static,
1682        NextValue: 'static,
1683    {
1684        let first = self.inner_keypath;
1685        let second = next;
1686
1687        // Create a new composed writable keypath
1688        let composed = WritableKeyPath::new(move |inner: &mut InnerValue| {
1689            let sub = first.get_mut(inner);
1690            second.get_mut(sub)
1691        });
1692
1693        ArcRwLockWritableKeyPathChain {
1694            outer_keypath: self.outer_keypath,
1695            inner_keypath: composed,
1696        }
1697    }
1698
1699    /// Monadic composition: chain with a writable optional keypath (for Option fields)
1700    /// This allows composing through Option types within the same Arc<RwLock<T>> structure
1701    ///
1702    /// # Example
1703    /// ```rust,ignore
1704    /// // Compose: Root -> Arc<RwLock<InnerValue>> -> InnerValue -> Option<SubValue> -> NextValue
1705    /// let chain = root_keypath
1706    ///     .chain_arc_rwlock_writable_at_kp(inner_keypath)
1707    ///     .chain_optional(optional_keypath);
1708    /// ```
1709    pub fn chain_optional<NextValue, H>(
1710        self,
1711        next: WritableOptionalKeyPath<SubValue, NextValue, H>,
1712    ) -> ArcRwLockWritableOptionalKeyPathChain<
1713        Root,
1714        RwLockValue,
1715        InnerValue,
1716        NextValue,
1717        F,
1718        impl for<'r> Fn(&'r mut InnerValue) -> Option<&'r mut NextValue> + 'static,
1719    >
1720    where
1721        H: for<'r> Fn(&'r mut SubValue) -> Option<&'r mut NextValue>,
1722        G: 'static,
1723        H: 'static,
1724        InnerValue: 'static,
1725        SubValue: 'static,
1726        NextValue: 'static,
1727    {
1728        let first = self.inner_keypath;
1729        let second = next;
1730
1731        // Create a new composed writable optional keypath
1732        let composed = WritableOptionalKeyPath::new(move |inner: &mut InnerValue| {
1733            let sub = first.get_mut(inner);
1734            second.get_mut(sub)
1735        });
1736
1737        ArcRwLockWritableOptionalKeyPathChain {
1738            outer_keypath: self.outer_keypath,
1739            inner_keypath: composed,
1740        }
1741    }
1742}
1743
1744/// A composed writable optional keypath chain through Arc<RwLock<T>> - functional style
1745/// Build the chain first, then apply container at get_mut() time (uses write lock)
1746pub struct ArcRwLockWritableOptionalKeyPathChain<Root, RwLockValue, InnerValue, SubValue, F, G>
1747where
1748    F: for<'r> Fn(&'r Root) -> &'r RwLockValue,
1749    G: for<'r> Fn(&'r mut InnerValue) -> Option<&'r mut SubValue>,
1750{
1751    outer_keypath: KeyPath<Root, RwLockValue, F>,
1752    inner_keypath: WritableOptionalKeyPath<InnerValue, SubValue, G>,
1753}
1754
1755impl<Root, RwLockValue, InnerValue, SubValue, F, G>
1756    ArcRwLockWritableOptionalKeyPathChain<Root, RwLockValue, InnerValue, SubValue, F, G>
1757where
1758    F: for<'r> Fn(&'r Root) -> &'r RwLockValue,
1759    G: for<'r> Fn(&'r mut InnerValue) -> Option<&'r mut SubValue>,
1760    RwLockValue: std::borrow::Borrow<Arc<RwLock<InnerValue>>>,
1761{
1762    /// Apply the composed keypath chain to a container with mutable access (write lock, if value exists)
1763    /// Consumes self - functional style (compose once, apply once)
1764    pub fn get_mut<Callback, R>(self, container: &Root, callback: Callback) -> Option<R>
1765    where
1766        Callback: FnOnce(&mut SubValue) -> R,
1767    {
1768        let arc_rwlock_ref = self.outer_keypath.get(container);
1769        arc_rwlock_ref.borrow().write().ok().and_then(|mut guard| {
1770            self.inner_keypath
1771                .get_mut(&mut *guard)
1772                .map(|value_ref| callback(value_ref))
1773        })
1774    }
1775
1776    /// Monadic composition: chain with another writable keypath
1777    /// This allows composing deeper keypaths through the same Arc<RwLock<T>> structure
1778    pub fn then<NextValue, H>(
1779        self,
1780        next: WritableKeyPath<SubValue, NextValue, H>,
1781    ) -> ArcRwLockWritableOptionalKeyPathChain<
1782        Root,
1783        RwLockValue,
1784        InnerValue,
1785        NextValue,
1786        F,
1787        impl for<'r> Fn(&'r mut InnerValue) -> Option<&'r mut NextValue> + 'static,
1788    >
1789    where
1790        H: for<'r> Fn(&'r mut SubValue) -> &'r mut NextValue,
1791        G: 'static,
1792        H: 'static,
1793        InnerValue: 'static,
1794        SubValue: 'static,
1795        NextValue: 'static,
1796    {
1797        let first = self.inner_keypath;
1798        let second = next;
1799
1800        // Create a new composed writable optional keypath
1801        let composed = WritableOptionalKeyPath::new(move |inner: &mut InnerValue| {
1802            if let Some(sub) = first.get_mut(inner) {
1803                Some(second.get_mut(sub))
1804            } else {
1805                None
1806            }
1807        });
1808
1809        ArcRwLockWritableOptionalKeyPathChain {
1810            outer_keypath: self.outer_keypath,
1811            inner_keypath: composed,
1812        }
1813    }
1814
1815    /// Monadic composition: chain with another writable optional keypath (for Option fields)
1816    /// This allows composing through Option types within the same Arc<RwLock<T>> structure
1817    pub fn chain_optional<NextValue, H>(
1818        self,
1819        next: WritableOptionalKeyPath<SubValue, NextValue, H>,
1820    ) -> ArcRwLockWritableOptionalKeyPathChain<
1821        Root,
1822        RwLockValue,
1823        InnerValue,
1824        NextValue,
1825        F,
1826        impl for<'r> Fn(&'r mut InnerValue) -> Option<&'r mut NextValue> + 'static,
1827    >
1828    where
1829        H: for<'r> Fn(&'r mut SubValue) -> Option<&'r mut NextValue>,
1830        G: 'static,
1831        H: 'static,
1832        InnerValue: 'static,
1833        SubValue: 'static,
1834        NextValue: 'static,
1835    {
1836        let first = self.inner_keypath;
1837        let second = next;
1838
1839        // Create a new composed writable optional keypath
1840        let composed = WritableOptionalKeyPath::new(move |inner: &mut InnerValue| {
1841            first.get_mut(inner).and_then(|sub| second.get_mut(sub))
1842        });
1843
1844        ArcRwLockWritableOptionalKeyPathChain {
1845            outer_keypath: self.outer_keypath,
1846            inner_keypath: composed,
1847        }
1848    }
1849}
1850
1851// ========== PARKING_LOT MUTEX/RWLOCK CHAIN TYPES ==========
1852
1853#[cfg(feature = "parking_lot")]
1854use parking_lot::{Mutex as ParkingMutex, RwLock as ParkingRwLock};
1855
1856/// A composed keypath chain through Arc<parking_lot::Mutex<T>> - functional style
1857#[cfg(feature = "parking_lot")]
1858pub struct ArcParkingMutexKeyPathChain<Root, InnerValue, SubValue, F, G>
1859where
1860    F: for<'r> Fn(&'r Root) -> &'r Arc<parking_lot::Mutex<InnerValue>>,
1861    G: for<'r> Fn(&'r InnerValue) -> &'r SubValue,
1862{
1863    outer_keypath: KeyPath<Root, Arc<parking_lot::Mutex<InnerValue>>, F>,
1864    inner_keypath: KeyPath<InnerValue, SubValue, G>,
1865}
1866
1867#[cfg(feature = "parking_lot")]
1868impl<Root, InnerValue, SubValue, F, G> ArcParkingMutexKeyPathChain<Root, InnerValue, SubValue, F, G>
1869where
1870    F: for<'r> Fn(&'r Root) -> &'r Arc<parking_lot::Mutex<InnerValue>>,
1871    G: for<'r> Fn(&'r InnerValue) -> &'r SubValue,
1872{
1873    /// Apply the composed keypath chain to a container (read)
1874    pub fn get<Callback>(self, container: &Root, callback: Callback)
1875    where
1876        Callback: FnOnce(&SubValue) -> (),
1877    {
1878        let arc_mutex_ref = self.outer_keypath.get(container);
1879        let guard = arc_mutex_ref.lock();
1880        let value = self.inner_keypath.get(&*guard);
1881        callback(value);
1882    }
1883
1884    /// Chain with another readable keypath through another level
1885    pub fn then<NextValue, H>(
1886        self,
1887        next: KeyPath<SubValue, NextValue, H>,
1888    ) -> ArcParkingMutexKeyPathChain<
1889        Root,
1890        InnerValue,
1891        NextValue,
1892        F,
1893        impl for<'r> Fn(&'r InnerValue) -> &'r NextValue + 'static,
1894    >
1895    where
1896        H: for<'r> Fn(&'r SubValue) -> &'r NextValue,
1897        G: 'static,
1898        H: 'static,
1899        InnerValue: 'static,
1900        SubValue: 'static,
1901        NextValue: 'static,
1902    {
1903        let first = self.inner_keypath;
1904        let second = next;
1905
1906        let composed = KeyPath::new(move |inner: &InnerValue| {
1907            let sub = first.get(inner);
1908            second.get(sub)
1909        });
1910
1911        ArcParkingMutexKeyPathChain {
1912            outer_keypath: self.outer_keypath,
1913            inner_keypath: composed,
1914        }
1915    }
1916
1917    /// Chain with an optional readable keypath through another level
1918    pub fn chain_optional<NextValue, H>(
1919        self,
1920        next: OptionalKeyPath<SubValue, NextValue, H>,
1921    ) -> ArcParkingMutexOptionalKeyPathChain<
1922        Root,
1923        InnerValue,
1924        NextValue,
1925        F,
1926        impl for<'r> Fn(&'r InnerValue) -> Option<&'r NextValue> + 'static,
1927    >
1928    where
1929        H: for<'r> Fn(&'r SubValue) -> Option<&'r NextValue>,
1930        G: 'static,
1931        H: 'static,
1932        InnerValue: 'static,
1933        SubValue: 'static,
1934        NextValue: 'static,
1935    {
1936        let first = self.inner_keypath;
1937        let second = next;
1938
1939        let composed = OptionalKeyPath::new(move |inner: &InnerValue| {
1940            let sub = first.get(inner);
1941            second.get(sub)
1942        });
1943
1944        ArcParkingMutexOptionalKeyPathChain {
1945            outer_keypath: self.outer_keypath,
1946            inner_keypath: composed,
1947        }
1948    }
1949}
1950
1951/// A composed optional keypath chain through Arc<parking_lot::Mutex<T>> - functional style
1952#[cfg(feature = "parking_lot")]
1953pub struct ArcParkingMutexOptionalKeyPathChain<Root, InnerValue, SubValue, F, G>
1954where
1955    F: for<'r> Fn(&'r Root) -> &'r Arc<parking_lot::Mutex<InnerValue>>,
1956    G: for<'r> Fn(&'r InnerValue) -> Option<&'r SubValue>,
1957{
1958    outer_keypath: KeyPath<Root, Arc<parking_lot::Mutex<InnerValue>>, F>,
1959    inner_keypath: OptionalKeyPath<InnerValue, SubValue, G>,
1960}
1961
1962#[cfg(feature = "parking_lot")]
1963impl<Root, InnerValue, SubValue, F, G>
1964    ArcParkingMutexOptionalKeyPathChain<Root, InnerValue, SubValue, F, G>
1965where
1966    F: for<'r> Fn(&'r Root) -> &'r Arc<parking_lot::Mutex<InnerValue>>,
1967    G: for<'r> Fn(&'r InnerValue) -> Option<&'r SubValue>,
1968{
1969    /// Apply the composed keypath chain to a container (read, if value exists)
1970    pub fn get<Callback>(self, container: &Root, callback: Callback) -> Option<()>
1971    where
1972        Callback: FnOnce(&SubValue) -> (),
1973    {
1974        let arc_mutex_ref = self.outer_keypath.get(container);
1975        let guard = arc_mutex_ref.lock();
1976        self.inner_keypath.get(&*guard).map(|value| callback(value))
1977    }
1978
1979    /// Chain with another readable keypath through another level
1980    pub fn then<NextValue, H>(
1981        self,
1982        next: KeyPath<SubValue, NextValue, H>,
1983    ) -> ArcParkingMutexOptionalKeyPathChain<
1984        Root,
1985        InnerValue,
1986        NextValue,
1987        F,
1988        impl for<'r> Fn(&'r InnerValue) -> Option<&'r NextValue> + 'static,
1989    >
1990    where
1991        H: for<'r> Fn(&'r SubValue) -> &'r NextValue,
1992        G: 'static,
1993        H: 'static,
1994        InnerValue: 'static,
1995        SubValue: 'static,
1996        NextValue: 'static,
1997    {
1998        let first = self.inner_keypath;
1999        let second = next;
2000
2001        let composed = OptionalKeyPath::new(move |inner: &InnerValue| {
2002            first.get(inner).map(|sub| second.get(sub))
2003        });
2004
2005        ArcParkingMutexOptionalKeyPathChain {
2006            outer_keypath: self.outer_keypath,
2007            inner_keypath: composed,
2008        }
2009    }
2010
2011    /// Chain with an optional readable keypath through another level
2012    pub fn chain_optional<NextValue, H>(
2013        self,
2014        next: OptionalKeyPath<SubValue, NextValue, H>,
2015    ) -> ArcParkingMutexOptionalKeyPathChain<
2016        Root,
2017        InnerValue,
2018        NextValue,
2019        F,
2020        impl for<'r> Fn(&'r InnerValue) -> Option<&'r NextValue> + 'static,
2021    >
2022    where
2023        H: for<'r> Fn(&'r SubValue) -> Option<&'r NextValue>,
2024        G: 'static,
2025        H: 'static,
2026        InnerValue: 'static,
2027        SubValue: 'static,
2028        NextValue: 'static,
2029    {
2030        let first = self.inner_keypath;
2031        let second = next;
2032
2033        let composed = OptionalKeyPath::new(move |inner: &InnerValue| {
2034            first.get(inner).and_then(|sub| second.get(sub))
2035        });
2036
2037        ArcParkingMutexOptionalKeyPathChain {
2038            outer_keypath: self.outer_keypath,
2039            inner_keypath: composed,
2040        }
2041    }
2042}
2043
2044/// A composed writable keypath chain through Arc<parking_lot::Mutex<T>> - functional style
2045#[cfg(feature = "parking_lot")]
2046pub struct ArcParkingMutexWritableKeyPathChain<Root, InnerValue, SubValue, F, G>
2047where
2048    F: for<'r> Fn(&'r Root) -> &'r Arc<parking_lot::Mutex<InnerValue>>,
2049    G: for<'r> Fn(&'r mut InnerValue) -> &'r mut SubValue,
2050{
2051    outer_keypath: KeyPath<Root, Arc<parking_lot::Mutex<InnerValue>>, F>,
2052    inner_keypath: WritableKeyPath<InnerValue, SubValue, G>,
2053}
2054
2055#[cfg(feature = "parking_lot")]
2056impl<Root, InnerValue, SubValue, F, G>
2057    ArcParkingMutexWritableKeyPathChain<Root, InnerValue, SubValue, F, G>
2058where
2059    F: for<'r> Fn(&'r Root) -> &'r Arc<parking_lot::Mutex<InnerValue>>,
2060    G: for<'r> Fn(&'r mut InnerValue) -> &'r mut SubValue,
2061{
2062    /// Apply the composed keypath chain to a container with mutable access
2063    pub fn get_mut<Callback, R>(self, container: &Root, callback: Callback) -> R
2064    where
2065        Callback: FnOnce(&mut SubValue) -> R,
2066    {
2067        let arc_mutex_ref = self.outer_keypath.get(container);
2068        let mut guard = arc_mutex_ref.lock();
2069        let value_ref = self.inner_keypath.get_mut(&mut *guard);
2070        callback(value_ref)
2071    }
2072
2073    /// Chain with another writable keypath through another level
2074    pub fn then<NextValue, H>(
2075        self,
2076        next: WritableKeyPath<SubValue, NextValue, H>,
2077    ) -> ArcParkingMutexWritableKeyPathChain<
2078        Root,
2079        InnerValue,
2080        NextValue,
2081        F,
2082        impl for<'r> Fn(&'r mut InnerValue) -> &'r mut NextValue + 'static,
2083    >
2084    where
2085        H: for<'r> Fn(&'r mut SubValue) -> &'r mut NextValue,
2086        G: 'static,
2087        H: 'static,
2088        InnerValue: 'static,
2089        SubValue: 'static,
2090        NextValue: 'static,
2091    {
2092        let first = self.inner_keypath;
2093        let second = next;
2094
2095        let composed = WritableKeyPath::new(move |inner: &mut InnerValue| {
2096            let sub = first.get_mut(inner);
2097            second.get_mut(sub)
2098        });
2099
2100        ArcParkingMutexWritableKeyPathChain {
2101            outer_keypath: self.outer_keypath,
2102            inner_keypath: composed,
2103        }
2104    }
2105
2106    /// Chain with an optional writable keypath through another level
2107    pub fn chain_optional<NextValue, H>(
2108        self,
2109        next: WritableOptionalKeyPath<SubValue, NextValue, H>,
2110    ) -> ArcParkingMutexWritableOptionalKeyPathChain<
2111        Root,
2112        InnerValue,
2113        NextValue,
2114        F,
2115        impl for<'r> Fn(&'r mut InnerValue) -> Option<&'r mut NextValue> + 'static,
2116    >
2117    where
2118        H: for<'r> Fn(&'r mut SubValue) -> Option<&'r mut NextValue>,
2119        G: 'static,
2120        H: 'static,
2121        InnerValue: 'static,
2122        SubValue: 'static,
2123        NextValue: 'static,
2124    {
2125        let first = self.inner_keypath;
2126        let second = next;
2127
2128        let composed = WritableOptionalKeyPath::new(move |inner: &mut InnerValue| {
2129            let sub = first.get_mut(inner);
2130            second.get_mut(sub)
2131        });
2132
2133        ArcParkingMutexWritableOptionalKeyPathChain {
2134            outer_keypath: self.outer_keypath,
2135            inner_keypath: composed,
2136        }
2137    }
2138}
2139
2140/// A composed writable optional keypath chain through Arc<parking_lot::Mutex<T>> - functional style
2141#[cfg(feature = "parking_lot")]
2142pub struct ArcParkingMutexWritableOptionalKeyPathChain<Root, InnerValue, SubValue, F, G>
2143where
2144    F: for<'r> Fn(&'r Root) -> &'r Arc<parking_lot::Mutex<InnerValue>>,
2145    G: for<'r> Fn(&'r mut InnerValue) -> Option<&'r mut SubValue>,
2146{
2147    outer_keypath: KeyPath<Root, Arc<parking_lot::Mutex<InnerValue>>, F>,
2148    inner_keypath: WritableOptionalKeyPath<InnerValue, SubValue, G>,
2149}
2150
2151#[cfg(feature = "parking_lot")]
2152impl<Root, InnerValue, SubValue, F, G>
2153    ArcParkingMutexWritableOptionalKeyPathChain<Root, InnerValue, SubValue, F, G>
2154where
2155    F: for<'r> Fn(&'r Root) -> &'r Arc<parking_lot::Mutex<InnerValue>>,
2156    G: for<'r> Fn(&'r mut InnerValue) -> Option<&'r mut SubValue>,
2157{
2158    /// Apply the composed keypath chain to a container with mutable access (if value exists)
2159    pub fn get_mut<Callback, R>(self, container: &Root, callback: Callback) -> Option<R>
2160    where
2161        Callback: FnOnce(&mut SubValue) -> R,
2162    {
2163        let arc_mutex_ref = self.outer_keypath.get(container);
2164        let mut guard = arc_mutex_ref.lock();
2165        self.inner_keypath
2166            .get_mut(&mut *guard)
2167            .map(|value_ref| callback(value_ref))
2168    }
2169
2170    /// Chain with another writable keypath through another level
2171    pub fn then<NextValue, H>(
2172        self,
2173        next: WritableKeyPath<SubValue, NextValue, H>,
2174    ) -> ArcParkingMutexWritableOptionalKeyPathChain<
2175        Root,
2176        InnerValue,
2177        NextValue,
2178        F,
2179        impl for<'r> Fn(&'r mut InnerValue) -> Option<&'r mut NextValue> + 'static,
2180    >
2181    where
2182        H: for<'r> Fn(&'r mut SubValue) -> &'r mut NextValue,
2183        G: 'static,
2184        H: 'static,
2185        InnerValue: 'static,
2186        SubValue: 'static,
2187        NextValue: 'static,
2188    {
2189        let first = self.inner_keypath;
2190        let second = next;
2191
2192        let composed = WritableOptionalKeyPath::new(move |inner: &mut InnerValue| {
2193            first.get_mut(inner).map(|sub| second.get_mut(sub))
2194        });
2195
2196        ArcParkingMutexWritableOptionalKeyPathChain {
2197            outer_keypath: self.outer_keypath,
2198            inner_keypath: composed,
2199        }
2200    }
2201
2202    /// Chain with an optional writable keypath through another level
2203    pub fn chain_optional<NextValue, H>(
2204        self,
2205        next: WritableOptionalKeyPath<SubValue, NextValue, H>,
2206    ) -> ArcParkingMutexWritableOptionalKeyPathChain<
2207        Root,
2208        InnerValue,
2209        NextValue,
2210        F,
2211        impl for<'r> Fn(&'r mut InnerValue) -> Option<&'r mut NextValue> + 'static,
2212    >
2213    where
2214        H: for<'r> Fn(&'r mut SubValue) -> Option<&'r mut NextValue>,
2215        G: 'static,
2216        H: 'static,
2217        InnerValue: 'static,
2218        SubValue: 'static,
2219        NextValue: 'static,
2220    {
2221        let first = self.inner_keypath;
2222        let second = next;
2223
2224        let composed = WritableOptionalKeyPath::new(move |inner: &mut InnerValue| {
2225            first.get_mut(inner).and_then(|sub| second.get_mut(sub))
2226        });
2227
2228        ArcParkingMutexWritableOptionalKeyPathChain {
2229            outer_keypath: self.outer_keypath,
2230            inner_keypath: composed,
2231        }
2232    }
2233}
2234
2235/// A composed keypath chain through Arc<parking_lot::RwLock<T>> - functional style
2236#[cfg(feature = "parking_lot")]
2237pub struct ArcParkingRwLockKeyPathChain<Root, InnerValue, SubValue, F, G>
2238where
2239    F: for<'r> Fn(&'r Root) -> &'r Arc<parking_lot::RwLock<InnerValue>>,
2240    G: for<'r> Fn(&'r InnerValue) -> &'r SubValue,
2241{
2242    outer_keypath: KeyPath<Root, Arc<parking_lot::RwLock<InnerValue>>, F>,
2243    inner_keypath: KeyPath<InnerValue, SubValue, G>,
2244}
2245
2246#[cfg(feature = "parking_lot")]
2247impl<Root, InnerValue, SubValue, F, G>
2248    ArcParkingRwLockKeyPathChain<Root, InnerValue, SubValue, F, G>
2249where
2250    F: for<'r> Fn(&'r Root) -> &'r Arc<parking_lot::RwLock<InnerValue>>,
2251    G: for<'r> Fn(&'r InnerValue) -> &'r SubValue,
2252{
2253    /// Apply the composed keypath chain to a container (read lock)
2254    pub fn get<Callback>(self, container: &Root, callback: Callback)
2255    where
2256        Callback: FnOnce(&SubValue) -> (),
2257    {
2258        let arc_rwlock_ref = self.outer_keypath.get(container);
2259        let guard = arc_rwlock_ref.read();
2260        let value = self.inner_keypath.get(&*guard);
2261        callback(value);
2262    }
2263
2264    /// Chain with another readable keypath through another level
2265    pub fn then<NextValue, H>(
2266        self,
2267        next: KeyPath<SubValue, NextValue, H>,
2268    ) -> ArcParkingRwLockKeyPathChain<
2269        Root,
2270        InnerValue,
2271        NextValue,
2272        F,
2273        impl for<'r> Fn(&'r InnerValue) -> &'r NextValue + 'static,
2274    >
2275    where
2276        H: for<'r> Fn(&'r SubValue) -> &'r NextValue,
2277        G: 'static,
2278        H: 'static,
2279        InnerValue: 'static,
2280        SubValue: 'static,
2281        NextValue: 'static,
2282    {
2283        let first = self.inner_keypath;
2284        let second = next;
2285
2286        let composed = KeyPath::new(move |inner: &InnerValue| {
2287            let sub = first.get(inner);
2288            second.get(sub)
2289        });
2290
2291        ArcParkingRwLockKeyPathChain {
2292            outer_keypath: self.outer_keypath,
2293            inner_keypath: composed,
2294        }
2295    }
2296
2297    /// Chain with an optional readable keypath through another level
2298    pub fn chain_optional<NextValue, H>(
2299        self,
2300        next: OptionalKeyPath<SubValue, NextValue, H>,
2301    ) -> ArcParkingRwLockOptionalKeyPathChain<
2302        Root,
2303        InnerValue,
2304        NextValue,
2305        F,
2306        impl for<'r> Fn(&'r InnerValue) -> Option<&'r NextValue> + 'static,
2307    >
2308    where
2309        H: for<'r> Fn(&'r SubValue) -> Option<&'r NextValue>,
2310        G: 'static,
2311        H: 'static,
2312        InnerValue: 'static,
2313        SubValue: 'static,
2314        NextValue: 'static,
2315    {
2316        let first = self.inner_keypath;
2317        let second = next;
2318
2319        let composed = OptionalKeyPath::new(move |inner: &InnerValue| {
2320            let sub = first.get(inner);
2321            second.get(sub)
2322        });
2323
2324        ArcParkingRwLockOptionalKeyPathChain {
2325            outer_keypath: self.outer_keypath,
2326            inner_keypath: composed,
2327        }
2328    }
2329}
2330
2331/// A composed optional keypath chain through Arc<parking_lot::RwLock<T>> - functional style
2332#[cfg(feature = "parking_lot")]
2333pub struct ArcParkingRwLockOptionalKeyPathChain<Root, InnerValue, SubValue, F, G>
2334where
2335    F: for<'r> Fn(&'r Root) -> &'r Arc<parking_lot::RwLock<InnerValue>>,
2336    G: for<'r> Fn(&'r InnerValue) -> Option<&'r SubValue>,
2337{
2338    outer_keypath: KeyPath<Root, Arc<parking_lot::RwLock<InnerValue>>, F>,
2339    inner_keypath: OptionalKeyPath<InnerValue, SubValue, G>,
2340}
2341
2342#[cfg(feature = "parking_lot")]
2343impl<Root, InnerValue, SubValue, F, G>
2344    ArcParkingRwLockOptionalKeyPathChain<Root, InnerValue, SubValue, F, G>
2345where
2346    F: for<'r> Fn(&'r Root) -> &'r Arc<parking_lot::RwLock<InnerValue>>,
2347    G: for<'r> Fn(&'r InnerValue) -> Option<&'r SubValue>,
2348{
2349    /// Apply the composed keypath chain to a container (read lock, if value exists)
2350    pub fn get<Callback>(self, container: &Root, callback: Callback) -> Option<()>
2351    where
2352        Callback: FnOnce(&SubValue) -> (),
2353    {
2354        let arc_rwlock_ref = self.outer_keypath.get(container);
2355        let guard = arc_rwlock_ref.read();
2356        self.inner_keypath.get(&*guard).map(|value| callback(value))
2357    }
2358
2359    /// Chain with another readable keypath through another level
2360    pub fn then<NextValue, H>(
2361        self,
2362        next: KeyPath<SubValue, NextValue, H>,
2363    ) -> ArcParkingRwLockOptionalKeyPathChain<
2364        Root,
2365        InnerValue,
2366        NextValue,
2367        F,
2368        impl for<'r> Fn(&'r InnerValue) -> Option<&'r NextValue> + 'static,
2369    >
2370    where
2371        H: for<'r> Fn(&'r SubValue) -> &'r NextValue,
2372        G: 'static,
2373        H: 'static,
2374        InnerValue: 'static,
2375        SubValue: 'static,
2376        NextValue: 'static,
2377    {
2378        let first = self.inner_keypath;
2379        let second = next;
2380
2381        let composed = OptionalKeyPath::new(move |inner: &InnerValue| {
2382            first.get(inner).map(|sub| second.get(sub))
2383        });
2384
2385        ArcParkingRwLockOptionalKeyPathChain {
2386            outer_keypath: self.outer_keypath,
2387            inner_keypath: composed,
2388        }
2389    }
2390
2391    /// Chain with an optional readable keypath through another level
2392    pub fn chain_optional<NextValue, H>(
2393        self,
2394        next: OptionalKeyPath<SubValue, NextValue, H>,
2395    ) -> ArcParkingRwLockOptionalKeyPathChain<
2396        Root,
2397        InnerValue,
2398        NextValue,
2399        F,
2400        impl for<'r> Fn(&'r InnerValue) -> Option<&'r NextValue> + 'static,
2401    >
2402    where
2403        H: for<'r> Fn(&'r SubValue) -> Option<&'r NextValue>,
2404        G: 'static,
2405        H: 'static,
2406        InnerValue: 'static,
2407        SubValue: 'static,
2408        NextValue: 'static,
2409    {
2410        let first = self.inner_keypath;
2411        let second = next;
2412
2413        let composed = OptionalKeyPath::new(move |inner: &InnerValue| {
2414            first.get(inner).and_then(|sub| second.get(sub))
2415        });
2416
2417        ArcParkingRwLockOptionalKeyPathChain {
2418            outer_keypath: self.outer_keypath,
2419            inner_keypath: composed,
2420        }
2421    }
2422}
2423
2424/// A composed writable keypath chain through Arc<parking_lot::RwLock<T>> - functional style
2425#[cfg(feature = "parking_lot")]
2426pub struct ArcParkingRwLockWritableKeyPathChain<Root, InnerValue, SubValue, F, G>
2427where
2428    F: for<'r> Fn(&'r Root) -> &'r Arc<parking_lot::RwLock<InnerValue>>,
2429    G: for<'r> Fn(&'r mut InnerValue) -> &'r mut SubValue,
2430{
2431    outer_keypath: KeyPath<Root, Arc<parking_lot::RwLock<InnerValue>>, F>,
2432    inner_keypath: WritableKeyPath<InnerValue, SubValue, G>,
2433}
2434
2435#[cfg(feature = "parking_lot")]
2436impl<Root, InnerValue, SubValue, F, G>
2437    ArcParkingRwLockWritableKeyPathChain<Root, InnerValue, SubValue, F, G>
2438where
2439    F: for<'r> Fn(&'r Root) -> &'r Arc<parking_lot::RwLock<InnerValue>>,
2440    G: for<'r> Fn(&'r mut InnerValue) -> &'r mut SubValue,
2441{
2442    /// Apply the composed keypath chain to a container with mutable access (write lock)
2443    pub fn get_mut<Callback, R>(self, container: &Root, callback: Callback) -> R
2444    where
2445        Callback: FnOnce(&mut SubValue) -> R,
2446    {
2447        let arc_rwlock_ref = self.outer_keypath.get(container);
2448        let mut guard = arc_rwlock_ref.write();
2449        let value_ref = self.inner_keypath.get_mut(&mut *guard);
2450        callback(value_ref)
2451    }
2452
2453    /// Monadic composition: chain with another writable keypath
2454    /// This allows composing deeper keypaths through the same Arc<parking_lot::RwLock<T>> structure
2455    pub fn then<NextValue, H>(
2456        self,
2457        next: WritableKeyPath<SubValue, NextValue, H>,
2458    ) -> ArcParkingRwLockWritableKeyPathChain<
2459        Root,
2460        InnerValue,
2461        NextValue,
2462        F,
2463        impl for<'r> Fn(&'r mut InnerValue) -> &'r mut NextValue + 'static,
2464    >
2465    where
2466        H: for<'r> Fn(&'r mut SubValue) -> &'r mut NextValue,
2467        G: 'static,
2468        H: 'static,
2469        InnerValue: 'static,
2470        SubValue: 'static,
2471        NextValue: 'static,
2472    {
2473        let first = self.inner_keypath;
2474        let second = next;
2475
2476        // Create a new composed writable keypath
2477        let composed = WritableKeyPath::new(move |inner: &mut InnerValue| {
2478            let sub = first.get_mut(inner);
2479            second.get_mut(sub)
2480        });
2481
2482        ArcParkingRwLockWritableKeyPathChain {
2483            outer_keypath: self.outer_keypath,
2484            inner_keypath: composed,
2485        }
2486    }
2487
2488    /// Monadic composition: chain with a writable optional keypath (for Option fields)
2489    /// This allows composing through Option types within the same Arc<parking_lot::RwLock<T>> structure
2490    pub fn chain_optional<NextValue, H>(
2491        self,
2492        next: WritableOptionalKeyPath<SubValue, NextValue, H>,
2493    ) -> ArcParkingRwLockWritableOptionalKeyPathChain<
2494        Root,
2495        InnerValue,
2496        NextValue,
2497        F,
2498        impl for<'r> Fn(&'r mut InnerValue) -> Option<&'r mut NextValue> + 'static,
2499    >
2500    where
2501        H: for<'r> Fn(&'r mut SubValue) -> Option<&'r mut NextValue>,
2502        G: 'static,
2503        H: 'static,
2504        InnerValue: 'static,
2505        SubValue: 'static,
2506        NextValue: 'static,
2507    {
2508        let first = self.inner_keypath;
2509        let second = next;
2510
2511        // Create a new composed writable optional keypath
2512        // first.get_mut returns &mut SubValue (not Option), second.get_mut returns Option<&mut NextValue>
2513        let composed = WritableOptionalKeyPath::new(move |inner: &mut InnerValue| {
2514            let sub = first.get_mut(inner);
2515            second.get_mut(sub)
2516        });
2517
2518        ArcParkingRwLockWritableOptionalKeyPathChain {
2519            outer_keypath: self.outer_keypath,
2520            inner_keypath: composed,
2521        }
2522    }
2523}
2524
2525/// A composed writable optional keypath chain through Arc<parking_lot::RwLock<T>> - functional style
2526#[cfg(feature = "parking_lot")]
2527pub struct ArcParkingRwLockWritableOptionalKeyPathChain<Root, InnerValue, SubValue, F, G>
2528where
2529    F: for<'r> Fn(&'r Root) -> &'r Arc<parking_lot::RwLock<InnerValue>>,
2530    G: for<'r> Fn(&'r mut InnerValue) -> Option<&'r mut SubValue>,
2531{
2532    outer_keypath: KeyPath<Root, Arc<parking_lot::RwLock<InnerValue>>, F>,
2533    inner_keypath: WritableOptionalKeyPath<InnerValue, SubValue, G>,
2534}
2535
2536#[cfg(feature = "parking_lot")]
2537impl<Root, InnerValue, SubValue, F, G>
2538    ArcParkingRwLockWritableOptionalKeyPathChain<Root, InnerValue, SubValue, F, G>
2539where
2540    F: for<'r> Fn(&'r Root) -> &'r Arc<parking_lot::RwLock<InnerValue>>,
2541    G: for<'r> Fn(&'r mut InnerValue) -> Option<&'r mut SubValue>,
2542{
2543    /// Apply the composed keypath chain to a container with mutable access (write lock, if value exists)
2544    pub fn get_mut<Callback, R>(self, container: &Root, callback: Callback) -> Option<R>
2545    where
2546        Callback: FnOnce(&mut SubValue) -> R,
2547    {
2548        let arc_rwlock_ref = self.outer_keypath.get(container);
2549        let mut guard = arc_rwlock_ref.write();
2550        self.inner_keypath
2551            .get_mut(&mut *guard)
2552            .map(|value_ref| callback(value_ref))
2553    }
2554
2555    /// Monadic composition: chain with another writable keypath
2556    /// This allows composing deeper keypaths through the same Arc<parking_lot::RwLock<T>> structure
2557    pub fn then<NextValue, H>(
2558        self,
2559        next: WritableKeyPath<SubValue, NextValue, H>,
2560    ) -> ArcParkingRwLockWritableOptionalKeyPathChain<
2561        Root,
2562        InnerValue,
2563        NextValue,
2564        F,
2565        impl for<'r> Fn(&'r mut InnerValue) -> Option<&'r mut NextValue> + 'static,
2566    >
2567    where
2568        H: for<'r> Fn(&'r mut SubValue) -> &'r mut NextValue,
2569        G: 'static,
2570        H: 'static,
2571        InnerValue: 'static,
2572        SubValue: 'static,
2573        NextValue: 'static,
2574    {
2575        let first_keypath = self.inner_keypath;
2576        let second_keypath = next;
2577
2578        // Create a new composed writable optional keypath
2579        // first_keypath.get_mut returns Option<&mut SubValue>, second_keypath.get_mut returns &mut NextValue
2580        let composed = WritableOptionalKeyPath::new(move |inner: &mut InnerValue| {
2581            first_keypath
2582                .get_mut(inner)
2583                .map(|sub| second_keypath.get_mut(sub))
2584        });
2585
2586        ArcParkingRwLockWritableOptionalKeyPathChain {
2587            outer_keypath: self.outer_keypath,
2588            inner_keypath: composed,
2589        }
2590    }
2591
2592    /// Monadic composition: chain with another writable optional keypath (for Option fields)
2593    /// This allows composing through Option types within the same Arc<parking_lot::RwLock<T>> structure
2594    pub fn chain_optional<NextValue, H>(
2595        self,
2596        next: WritableOptionalKeyPath<SubValue, NextValue, H>,
2597    ) -> ArcParkingRwLockWritableOptionalKeyPathChain<
2598        Root,
2599        InnerValue,
2600        NextValue,
2601        F,
2602        impl for<'r> Fn(&'r mut InnerValue) -> Option<&'r mut NextValue> + 'static,
2603    >
2604    where
2605        H: for<'r> Fn(&'r mut SubValue) -> Option<&'r mut NextValue>,
2606        G: 'static,
2607        H: 'static,
2608        InnerValue: 'static,
2609        SubValue: 'static,
2610        NextValue: 'static,
2611    {
2612        let first = self.inner_keypath;
2613        let second = next;
2614
2615        // Create a new composed writable optional keypath
2616        let composed = WritableOptionalKeyPath::new(move |inner: &mut InnerValue| {
2617            first.get_mut(inner).and_then(|sub| second.get_mut(sub))
2618        });
2619
2620        ArcParkingRwLockWritableOptionalKeyPathChain {
2621            outer_keypath: self.outer_keypath,
2622            inner_keypath: composed,
2623        }
2624    }
2625}
2626
2627// ========== OPTIONAL PARKING_LOT MUTEX KEYPATH CHAINS (from OptionalKeyPath) ==========
2628
2629/// A composed keypath chain from optional keypath through Arc<parking_lot::Mutex<T>> - functional style
2630#[cfg(feature = "parking_lot")]
2631pub struct OptionalArcParkingMutexKeyPathChain<Root, InnerValue, SubValue, F, G>
2632where
2633    F: for<'r> Fn(&'r Root) -> Option<&'r Arc<parking_lot::Mutex<InnerValue>>>,
2634    G: for<'r> Fn(&'r InnerValue) -> &'r SubValue,
2635{
2636    outer_keypath: OptionalKeyPath<Root, Arc<parking_lot::Mutex<InnerValue>>, F>,
2637    inner_keypath: KeyPath<InnerValue, SubValue, G>,
2638}
2639
2640#[cfg(feature = "parking_lot")]
2641impl<Root, InnerValue, SubValue, F, G>
2642    OptionalArcParkingMutexKeyPathChain<Root, InnerValue, SubValue, F, G>
2643where
2644    F: for<'r> Fn(&'r Root) -> Option<&'r Arc<parking_lot::Mutex<InnerValue>>>,
2645    G: for<'r> Fn(&'r InnerValue) -> &'r SubValue,
2646{
2647    /// Apply the composed keypath chain to a container
2648    pub fn get<Callback>(self, container: &Root, callback: Callback) -> Option<()>
2649    where
2650        Callback: FnOnce(&SubValue) -> (),
2651    {
2652        self.outer_keypath.get(container).map(|arc_mutex_ref| {
2653            let guard = arc_mutex_ref.lock();
2654            let value = self.inner_keypath.get(&*guard);
2655            callback(value)
2656        })
2657    }
2658
2659    /// Chain with another readable keypath through another level
2660    pub fn then<NextValue, H>(
2661        self,
2662        next: KeyPath<SubValue, NextValue, H>,
2663    ) -> OptionalArcParkingMutexKeyPathChain<
2664        Root,
2665        InnerValue,
2666        NextValue,
2667        F,
2668        impl for<'r> Fn(&'r InnerValue) -> &'r NextValue + 'static,
2669    >
2670    where
2671        H: for<'r> Fn(&'r SubValue) -> &'r NextValue,
2672        G: 'static,
2673        H: 'static,
2674        InnerValue: 'static,
2675        SubValue: 'static,
2676        NextValue: 'static,
2677    {
2678        let first = self.inner_keypath;
2679        let second = next;
2680
2681        let composed = KeyPath::new(move |inner: &InnerValue| {
2682            let sub = first.get(inner);
2683            second.get(sub)
2684        });
2685
2686        OptionalArcParkingMutexKeyPathChain {
2687            outer_keypath: self.outer_keypath,
2688            inner_keypath: composed,
2689        }
2690    }
2691
2692    /// Chain with an optional readable keypath through another level
2693    pub fn chain_optional<NextValue, H>(
2694        self,
2695        next: OptionalKeyPath<SubValue, NextValue, H>,
2696    ) -> OptionalArcParkingMutexOptionalKeyPathChain<
2697        Root,
2698        InnerValue,
2699        NextValue,
2700        F,
2701        impl for<'r> Fn(&'r InnerValue) -> Option<&'r NextValue> + 'static,
2702    >
2703    where
2704        H: for<'r> Fn(&'r SubValue) -> Option<&'r NextValue>,
2705        G: 'static,
2706        H: 'static,
2707        InnerValue: 'static,
2708        SubValue: 'static,
2709        NextValue: 'static,
2710    {
2711        let first = self.inner_keypath;
2712        let second = next;
2713
2714        let composed = OptionalKeyPath::new(move |inner: &InnerValue| {
2715            let sub = first.get(inner);
2716            second.get(sub)
2717        });
2718
2719        OptionalArcParkingMutexOptionalKeyPathChain {
2720            outer_keypath: self.outer_keypath,
2721            inner_keypath: composed,
2722        }
2723    }
2724}
2725
2726/// A composed optional keypath chain from optional keypath through Arc<parking_lot::Mutex<T>>
2727#[cfg(feature = "parking_lot")]
2728pub struct OptionalArcParkingMutexOptionalKeyPathChain<Root, InnerValue, SubValue, F, G>
2729where
2730    F: for<'r> Fn(&'r Root) -> Option<&'r Arc<parking_lot::Mutex<InnerValue>>>,
2731    G: for<'r> Fn(&'r InnerValue) -> Option<&'r SubValue>,
2732{
2733    outer_keypath: OptionalKeyPath<Root, Arc<parking_lot::Mutex<InnerValue>>, F>,
2734    inner_keypath: OptionalKeyPath<InnerValue, SubValue, G>,
2735}
2736
2737#[cfg(feature = "parking_lot")]
2738impl<Root, InnerValue, SubValue, F, G>
2739    OptionalArcParkingMutexOptionalKeyPathChain<Root, InnerValue, SubValue, F, G>
2740where
2741    F: for<'r> Fn(&'r Root) -> Option<&'r Arc<parking_lot::Mutex<InnerValue>>>,
2742    G: for<'r> Fn(&'r InnerValue) -> Option<&'r SubValue>,
2743{
2744    /// Apply the composed keypath chain to a container
2745    pub fn get<Callback>(self, container: &Root, callback: Callback) -> Option<()>
2746    where
2747        Callback: FnOnce(&SubValue) -> (),
2748    {
2749        self.outer_keypath.get(container).and_then(|arc_mutex_ref| {
2750            let guard = arc_mutex_ref.lock();
2751            self.inner_keypath.get(&*guard).map(|value| callback(value))
2752        })
2753    }
2754
2755    /// Chain with another readable keypath through another level
2756    pub fn then<NextValue, H>(
2757        self,
2758        next: KeyPath<SubValue, NextValue, H>,
2759    ) -> OptionalArcParkingMutexOptionalKeyPathChain<
2760        Root,
2761        InnerValue,
2762        NextValue,
2763        F,
2764        impl for<'r> Fn(&'r InnerValue) -> Option<&'r NextValue> + 'static,
2765    >
2766    where
2767        H: for<'r> Fn(&'r SubValue) -> &'r NextValue,
2768        G: 'static,
2769        H: 'static,
2770        InnerValue: 'static,
2771        SubValue: 'static,
2772        NextValue: 'static,
2773    {
2774        let first = self.inner_keypath;
2775        let second = next;
2776
2777        let composed = OptionalKeyPath::new(move |inner: &InnerValue| {
2778            first.get(inner).map(|sub| second.get(sub))
2779        });
2780
2781        OptionalArcParkingMutexOptionalKeyPathChain {
2782            outer_keypath: self.outer_keypath,
2783            inner_keypath: composed,
2784        }
2785    }
2786
2787    /// Chain with an optional readable keypath through another level
2788    pub fn chain_optional<NextValue, H>(
2789        self,
2790        next: OptionalKeyPath<SubValue, NextValue, H>,
2791    ) -> OptionalArcParkingMutexOptionalKeyPathChain<
2792        Root,
2793        InnerValue,
2794        NextValue,
2795        F,
2796        impl for<'r> Fn(&'r InnerValue) -> Option<&'r NextValue> + 'static,
2797    >
2798    where
2799        H: for<'r> Fn(&'r SubValue) -> Option<&'r NextValue>,
2800        G: 'static,
2801        H: 'static,
2802        InnerValue: 'static,
2803        SubValue: 'static,
2804        NextValue: 'static,
2805    {
2806        let first = self.inner_keypath;
2807        let second = next;
2808
2809        let composed = OptionalKeyPath::new(move |inner: &InnerValue| {
2810            first.get(inner).and_then(|sub| second.get(sub))
2811        });
2812
2813        OptionalArcParkingMutexOptionalKeyPathChain {
2814            outer_keypath: self.outer_keypath,
2815            inner_keypath: composed,
2816        }
2817    }
2818}
2819
2820/// A composed writable keypath chain from optional keypath through Arc<parking_lot::Mutex<T>>
2821#[cfg(feature = "parking_lot")]
2822pub struct OptionalArcParkingMutexWritableKeyPathChain<Root, InnerValue, SubValue, F, G>
2823where
2824    F: for<'r> Fn(&'r Root) -> Option<&'r Arc<parking_lot::Mutex<InnerValue>>>,
2825    G: for<'r> Fn(&'r mut InnerValue) -> &'r mut SubValue,
2826{
2827    outer_keypath: OptionalKeyPath<Root, Arc<parking_lot::Mutex<InnerValue>>, F>,
2828    inner_keypath: WritableKeyPath<InnerValue, SubValue, G>,
2829}
2830
2831#[cfg(feature = "parking_lot")]
2832impl<Root, InnerValue, SubValue, F, G>
2833    OptionalArcParkingMutexWritableKeyPathChain<Root, InnerValue, SubValue, F, G>
2834where
2835    F: for<'r> Fn(&'r Root) -> Option<&'r Arc<parking_lot::Mutex<InnerValue>>>,
2836    G: for<'r> Fn(&'r mut InnerValue) -> &'r mut SubValue,
2837{
2838    /// Apply the composed keypath chain to a container with mutable access
2839    pub fn get_mut<Callback, R>(self, container: &Root, callback: Callback) -> Option<R>
2840    where
2841        Callback: FnOnce(&mut SubValue) -> R,
2842    {
2843        self.outer_keypath.get(container).map(|arc_mutex_ref| {
2844            let mut guard = arc_mutex_ref.lock();
2845            let value_ref = self.inner_keypath.get_mut(&mut *guard);
2846            callback(value_ref)
2847        })
2848    }
2849
2850    /// Chain with another writable keypath through another level
2851    pub fn then<NextValue, H>(
2852        self,
2853        next: WritableKeyPath<SubValue, NextValue, H>,
2854    ) -> OptionalArcParkingMutexWritableKeyPathChain<
2855        Root,
2856        InnerValue,
2857        NextValue,
2858        F,
2859        impl for<'r> Fn(&'r mut InnerValue) -> &'r mut NextValue + 'static,
2860    >
2861    where
2862        H: for<'r> Fn(&'r mut SubValue) -> &'r mut NextValue,
2863        G: 'static,
2864        H: 'static,
2865        InnerValue: 'static,
2866        SubValue: 'static,
2867        NextValue: 'static,
2868    {
2869        let first = self.inner_keypath;
2870        let second = next;
2871
2872        let composed = WritableKeyPath::new(move |inner: &mut InnerValue| {
2873            let sub = first.get_mut(inner);
2874            second.get_mut(sub)
2875        });
2876
2877        OptionalArcParkingMutexWritableKeyPathChain {
2878            outer_keypath: self.outer_keypath,
2879            inner_keypath: composed,
2880        }
2881    }
2882
2883    /// Chain with an optional writable keypath through another level
2884    pub fn chain_optional<NextValue, H>(
2885        self,
2886        next: WritableOptionalKeyPath<SubValue, NextValue, H>,
2887    ) -> OptionalArcParkingMutexWritableOptionalKeyPathChain<
2888        Root,
2889        InnerValue,
2890        NextValue,
2891        F,
2892        impl for<'r> Fn(&'r mut InnerValue) -> Option<&'r mut NextValue> + 'static,
2893    >
2894    where
2895        H: for<'r> Fn(&'r mut SubValue) -> Option<&'r mut NextValue>,
2896        G: 'static,
2897        H: 'static,
2898        InnerValue: 'static,
2899        SubValue: 'static,
2900        NextValue: 'static,
2901    {
2902        let first = self.inner_keypath;
2903        let second = next;
2904
2905        let composed = WritableOptionalKeyPath::new(move |inner: &mut InnerValue| {
2906            let sub = first.get_mut(inner);
2907            second.get_mut(sub)
2908        });
2909
2910        OptionalArcParkingMutexWritableOptionalKeyPathChain {
2911            outer_keypath: self.outer_keypath,
2912            inner_keypath: composed,
2913        }
2914    }
2915}
2916
2917/// A composed writable optional keypath chain from optional keypath through Arc<parking_lot::Mutex<T>>
2918#[cfg(feature = "parking_lot")]
2919pub struct OptionalArcParkingMutexWritableOptionalKeyPathChain<Root, InnerValue, SubValue, F, G>
2920where
2921    F: for<'r> Fn(&'r Root) -> Option<&'r Arc<parking_lot::Mutex<InnerValue>>>,
2922    G: for<'r> Fn(&'r mut InnerValue) -> Option<&'r mut SubValue>,
2923{
2924    outer_keypath: OptionalKeyPath<Root, Arc<parking_lot::Mutex<InnerValue>>, F>,
2925    inner_keypath: WritableOptionalKeyPath<InnerValue, SubValue, G>,
2926}
2927
2928#[cfg(feature = "parking_lot")]
2929impl<Root, InnerValue, SubValue, F, G>
2930    OptionalArcParkingMutexWritableOptionalKeyPathChain<Root, InnerValue, SubValue, F, G>
2931where
2932    F: for<'r> Fn(&'r Root) -> Option<&'r Arc<parking_lot::Mutex<InnerValue>>>,
2933    G: for<'r> Fn(&'r mut InnerValue) -> Option<&'r mut SubValue>,
2934{
2935    /// Apply the composed keypath chain to a container with mutable access (if value exists)
2936    pub fn get_mut<Callback, R>(self, container: &Root, callback: Callback) -> Option<R>
2937    where
2938        Callback: FnOnce(&mut SubValue) -> R,
2939    {
2940        self.outer_keypath.get(container).and_then(|arc_mutex_ref| {
2941            let mut guard = arc_mutex_ref.lock();
2942            self.inner_keypath
2943                .get_mut(&mut *guard)
2944                .map(|value_ref| callback(value_ref))
2945        })
2946    }
2947
2948    /// Chain with another writable keypath through another level
2949    pub fn then<NextValue, H>(
2950        self,
2951        next: WritableKeyPath<SubValue, NextValue, H>,
2952    ) -> OptionalArcParkingMutexWritableOptionalKeyPathChain<
2953        Root,
2954        InnerValue,
2955        NextValue,
2956        F,
2957        impl for<'r> Fn(&'r mut InnerValue) -> Option<&'r mut NextValue> + 'static,
2958    >
2959    where
2960        H: for<'r> Fn(&'r mut SubValue) -> &'r mut NextValue,
2961        G: 'static,
2962        H: 'static,
2963        InnerValue: 'static,
2964        SubValue: 'static,
2965        NextValue: 'static,
2966    {
2967        let first = self.inner_keypath;
2968        let second = next;
2969
2970        let composed = WritableOptionalKeyPath::new(move |inner: &mut InnerValue| {
2971            first.get_mut(inner).map(|sub| second.get_mut(sub))
2972        });
2973
2974        OptionalArcParkingMutexWritableOptionalKeyPathChain {
2975            outer_keypath: self.outer_keypath,
2976            inner_keypath: composed,
2977        }
2978    }
2979
2980    /// Chain with an optional writable keypath through another level
2981    pub fn chain_optional<NextValue, H>(
2982        self,
2983        next: WritableOptionalKeyPath<SubValue, NextValue, H>,
2984    ) -> OptionalArcParkingMutexWritableOptionalKeyPathChain<
2985        Root,
2986        InnerValue,
2987        NextValue,
2988        F,
2989        impl for<'r> Fn(&'r mut InnerValue) -> Option<&'r mut NextValue> + 'static,
2990    >
2991    where
2992        H: for<'r> Fn(&'r mut SubValue) -> Option<&'r mut NextValue>,
2993        G: 'static,
2994        H: 'static,
2995        InnerValue: 'static,
2996        SubValue: 'static,
2997        NextValue: 'static,
2998    {
2999        let first = self.inner_keypath;
3000        let second = next;
3001
3002        let composed = WritableOptionalKeyPath::new(move |inner: &mut InnerValue| {
3003            first.get_mut(inner).and_then(|sub| second.get_mut(sub))
3004        });
3005
3006        OptionalArcParkingMutexWritableOptionalKeyPathChain {
3007            outer_keypath: self.outer_keypath,
3008            inner_keypath: composed,
3009        }
3010    }
3011}
3012
3013// ========== OPTIONAL PARKING_LOT RWLOCK KEYPATH CHAINS (from OptionalKeyPath) ==========
3014
3015/// A composed keypath chain from optional keypath through Arc<parking_lot::RwLock<T>> - functional style
3016#[cfg(feature = "parking_lot")]
3017pub struct OptionalArcParkingRwLockKeyPathChain<Root, InnerValue, SubValue, F, G>
3018where
3019    F: for<'r> Fn(&'r Root) -> Option<&'r Arc<parking_lot::RwLock<InnerValue>>>,
3020    G: for<'r> Fn(&'r InnerValue) -> &'r SubValue,
3021{
3022    outer_keypath: OptionalKeyPath<Root, Arc<parking_lot::RwLock<InnerValue>>, F>,
3023    inner_keypath: KeyPath<InnerValue, SubValue, G>,
3024}
3025
3026#[cfg(feature = "parking_lot")]
3027impl<Root, InnerValue, SubValue, F, G>
3028    OptionalArcParkingRwLockKeyPathChain<Root, InnerValue, SubValue, F, G>
3029where
3030    F: for<'r> Fn(&'r Root) -> Option<&'r Arc<parking_lot::RwLock<InnerValue>>>,
3031    G: for<'r> Fn(&'r InnerValue) -> &'r SubValue,
3032{
3033    /// Apply the composed keypath chain to a container (read lock)
3034    pub fn get<Callback>(self, container: &Root, callback: Callback) -> Option<()>
3035    where
3036        Callback: FnOnce(&SubValue) -> (),
3037    {
3038        self.outer_keypath.get(container).map(|arc_rwlock_ref| {
3039            let guard = arc_rwlock_ref.read();
3040            let value = self.inner_keypath.get(&*guard);
3041            callback(value)
3042        })
3043    }
3044
3045    /// Chain with another readable keypath through another level
3046    pub fn then<NextValue, H>(
3047        self,
3048        next: KeyPath<SubValue, NextValue, H>,
3049    ) -> OptionalArcParkingRwLockKeyPathChain<
3050        Root,
3051        InnerValue,
3052        NextValue,
3053        F,
3054        impl for<'r> Fn(&'r InnerValue) -> &'r NextValue + 'static,
3055    >
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        OptionalArcParkingRwLockKeyPathChain {
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    ) -> OptionalArcParkingRwLockOptionalKeyPathChain<
3083        Root,
3084        InnerValue,
3085        NextValue,
3086        F,
3087        impl for<'r> Fn(&'r InnerValue) -> Option<&'r NextValue> + 'static,
3088    >
3089    where
3090        H: for<'r> Fn(&'r SubValue) -> Option<&'r NextValue>,
3091        G: 'static,
3092        H: 'static,
3093        InnerValue: 'static,
3094        SubValue: 'static,
3095        NextValue: 'static,
3096    {
3097        let first = self.inner_keypath;
3098        let second = next;
3099
3100        let composed = OptionalKeyPath::new(move |inner: &InnerValue| {
3101            let sub = first.get(inner);
3102            second.get(sub)
3103        });
3104
3105        OptionalArcParkingRwLockOptionalKeyPathChain {
3106            outer_keypath: self.outer_keypath,
3107            inner_keypath: composed,
3108        }
3109    }
3110}
3111
3112/// A composed optional keypath chain from optional keypath through Arc<parking_lot::RwLock<T>>
3113#[cfg(feature = "parking_lot")]
3114pub struct OptionalArcParkingRwLockOptionalKeyPathChain<Root, InnerValue, SubValue, F, G>
3115where
3116    F: for<'r> Fn(&'r Root) -> Option<&'r Arc<parking_lot::RwLock<InnerValue>>>,
3117    G: for<'r> Fn(&'r InnerValue) -> Option<&'r SubValue>,
3118{
3119    outer_keypath: OptionalKeyPath<Root, Arc<parking_lot::RwLock<InnerValue>>, F>,
3120    inner_keypath: OptionalKeyPath<InnerValue, SubValue, G>,
3121}
3122
3123#[cfg(feature = "parking_lot")]
3124impl<Root, InnerValue, SubValue, F, G>
3125    OptionalArcParkingRwLockOptionalKeyPathChain<Root, InnerValue, SubValue, F, G>
3126where
3127    F: for<'r> Fn(&'r Root) -> Option<&'r Arc<parking_lot::RwLock<InnerValue>>>,
3128    G: for<'r> Fn(&'r InnerValue) -> Option<&'r SubValue>,
3129{
3130    /// Apply the composed keypath chain to a container (read lock)
3131    pub fn get<Callback>(self, container: &Root, callback: Callback) -> Option<()>
3132    where
3133        Callback: FnOnce(&SubValue) -> (),
3134    {
3135        self.outer_keypath
3136            .get(container)
3137            .and_then(|arc_rwlock_ref| {
3138                let guard = arc_rwlock_ref.read();
3139                self.inner_keypath.get(&*guard).map(|value| callback(value))
3140            })
3141    }
3142
3143    /// Chain with another readable keypath through another level
3144    pub fn then<NextValue, H>(
3145        self,
3146        next: KeyPath<SubValue, NextValue, H>,
3147    ) -> OptionalArcParkingRwLockOptionalKeyPathChain<
3148        Root,
3149        InnerValue,
3150        NextValue,
3151        F,
3152        impl for<'r> Fn(&'r InnerValue) -> Option<&'r NextValue> + 'static,
3153    >
3154    where
3155        H: for<'r> Fn(&'r SubValue) -> &'r NextValue,
3156        G: 'static,
3157        H: 'static,
3158        InnerValue: 'static,
3159        SubValue: 'static,
3160        NextValue: 'static,
3161    {
3162        let first = self.inner_keypath;
3163        let second = next;
3164
3165        let composed = OptionalKeyPath::new(move |inner: &InnerValue| {
3166            first.get(inner).map(|sub| second.get(sub))
3167        });
3168
3169        OptionalArcParkingRwLockOptionalKeyPathChain {
3170            outer_keypath: self.outer_keypath,
3171            inner_keypath: composed,
3172        }
3173    }
3174
3175    /// Chain with an optional readable keypath through another level
3176    pub fn chain_optional<NextValue, H>(
3177        self,
3178        next: OptionalKeyPath<SubValue, NextValue, H>,
3179    ) -> OptionalArcParkingRwLockOptionalKeyPathChain<
3180        Root,
3181        InnerValue,
3182        NextValue,
3183        F,
3184        impl for<'r> Fn(&'r InnerValue) -> Option<&'r NextValue> + 'static,
3185    >
3186    where
3187        H: for<'r> Fn(&'r SubValue) -> Option<&'r NextValue>,
3188        G: 'static,
3189        H: 'static,
3190        InnerValue: 'static,
3191        SubValue: 'static,
3192        NextValue: 'static,
3193    {
3194        let first = self.inner_keypath;
3195        let second = next;
3196
3197        let composed = OptionalKeyPath::new(move |inner: &InnerValue| {
3198            first.get(inner).and_then(|sub| second.get(sub))
3199        });
3200
3201        OptionalArcParkingRwLockOptionalKeyPathChain {
3202            outer_keypath: self.outer_keypath,
3203            inner_keypath: composed,
3204        }
3205    }
3206}
3207
3208/// A composed writable keypath chain from optional keypath through Arc<parking_lot::RwLock<T>>
3209#[cfg(feature = "parking_lot")]
3210pub struct OptionalArcParkingRwLockWritableKeyPathChain<Root, InnerValue, SubValue, F, G>
3211where
3212    F: for<'r> Fn(&'r Root) -> Option<&'r Arc<parking_lot::RwLock<InnerValue>>>,
3213    G: for<'r> Fn(&'r mut InnerValue) -> &'r mut SubValue,
3214{
3215    outer_keypath: OptionalKeyPath<Root, Arc<parking_lot::RwLock<InnerValue>>, F>,
3216    inner_keypath: WritableKeyPath<InnerValue, SubValue, G>,
3217}
3218
3219#[cfg(feature = "parking_lot")]
3220impl<Root, InnerValue, SubValue, F, G>
3221    OptionalArcParkingRwLockWritableKeyPathChain<Root, InnerValue, SubValue, F, G>
3222where
3223    F: for<'r> Fn(&'r Root) -> Option<&'r Arc<parking_lot::RwLock<InnerValue>>>,
3224    G: for<'r> Fn(&'r mut InnerValue) -> &'r mut SubValue,
3225{
3226    /// Apply the composed keypath chain to a container with mutable access (write lock)
3227    pub fn get_mut<Callback, R>(self, container: &Root, callback: Callback) -> Option<R>
3228    where
3229        Callback: FnOnce(&mut SubValue) -> R,
3230    {
3231        self.outer_keypath.get(container).map(|arc_rwlock_ref| {
3232            let mut guard = arc_rwlock_ref.write();
3233            let value_ref = self.inner_keypath.get_mut(&mut *guard);
3234            callback(value_ref)
3235        })
3236    }
3237
3238    /// Chain with another writable keypath through another level
3239    pub fn then<NextValue, H>(
3240        self,
3241        next: WritableKeyPath<SubValue, NextValue, H>,
3242    ) -> OptionalArcParkingRwLockWritableKeyPathChain<
3243        Root,
3244        InnerValue,
3245        NextValue,
3246        F,
3247        impl for<'r> Fn(&'r mut InnerValue) -> &'r mut NextValue + 'static,
3248    >
3249    where
3250        H: for<'r> Fn(&'r mut SubValue) -> &'r mut NextValue,
3251        G: 'static,
3252        H: 'static,
3253        InnerValue: 'static,
3254        SubValue: 'static,
3255        NextValue: 'static,
3256    {
3257        let first = self.inner_keypath;
3258        let second = next;
3259
3260        let composed = WritableKeyPath::new(move |inner: &mut InnerValue| {
3261            let sub = first.get_mut(inner);
3262            second.get_mut(sub)
3263        });
3264
3265        OptionalArcParkingRwLockWritableKeyPathChain {
3266            outer_keypath: self.outer_keypath,
3267            inner_keypath: composed,
3268        }
3269    }
3270
3271    /// Chain with an optional writable keypath through another level
3272    pub fn chain_optional<NextValue, H>(
3273        self,
3274        next: WritableOptionalKeyPath<SubValue, NextValue, H>,
3275    ) -> OptionalArcParkingRwLockWritableOptionalKeyPathChain<
3276        Root,
3277        InnerValue,
3278        NextValue,
3279        F,
3280        impl for<'r> Fn(&'r mut InnerValue) -> Option<&'r mut NextValue> + 'static,
3281    >
3282    where
3283        H: for<'r> Fn(&'r mut SubValue) -> Option<&'r mut NextValue>,
3284        G: 'static,
3285        H: 'static,
3286        InnerValue: 'static,
3287        SubValue: 'static,
3288        NextValue: 'static,
3289    {
3290        let first = self.inner_keypath;
3291        let second = next;
3292
3293        let composed = WritableOptionalKeyPath::new(move |inner: &mut InnerValue| {
3294            let sub = first.get_mut(inner);
3295            second.get_mut(sub)
3296        });
3297
3298        OptionalArcParkingRwLockWritableOptionalKeyPathChain {
3299            outer_keypath: self.outer_keypath,
3300            inner_keypath: composed,
3301        }
3302    }
3303}
3304
3305/// A composed writable optional keypath chain from optional keypath through Arc<parking_lot::RwLock<T>>
3306#[cfg(feature = "parking_lot")]
3307pub struct OptionalArcParkingRwLockWritableOptionalKeyPathChain<Root, InnerValue, SubValue, F, G>
3308where
3309    F: for<'r> Fn(&'r Root) -> Option<&'r Arc<parking_lot::RwLock<InnerValue>>>,
3310    G: for<'r> Fn(&'r mut InnerValue) -> Option<&'r mut SubValue>,
3311{
3312    outer_keypath: OptionalKeyPath<Root, Arc<parking_lot::RwLock<InnerValue>>, F>,
3313    inner_keypath: WritableOptionalKeyPath<InnerValue, SubValue, G>,
3314}
3315
3316#[cfg(feature = "parking_lot")]
3317impl<Root, InnerValue, SubValue, F, G>
3318    OptionalArcParkingRwLockWritableOptionalKeyPathChain<Root, InnerValue, SubValue, F, G>
3319where
3320    F: for<'r> Fn(&'r Root) -> Option<&'r Arc<parking_lot::RwLock<InnerValue>>>,
3321    G: for<'r> Fn(&'r mut InnerValue) -> Option<&'r mut SubValue>,
3322{
3323    /// Apply the composed keypath chain to a container with mutable access (write lock, if value exists)
3324    pub fn get_mut<Callback, R>(self, container: &Root, callback: Callback) -> Option<R>
3325    where
3326        Callback: FnOnce(&mut SubValue) -> R,
3327    {
3328        self.outer_keypath
3329            .get(container)
3330            .and_then(|arc_rwlock_ref| {
3331                let mut guard = arc_rwlock_ref.write();
3332                self.inner_keypath
3333                    .get_mut(&mut *guard)
3334                    .map(|value_ref| callback(value_ref))
3335            })
3336    }
3337
3338    /// Chain with another writable keypath through another level
3339    pub fn then<NextValue, H>(
3340        self,
3341        next: WritableKeyPath<SubValue, NextValue, H>,
3342    ) -> OptionalArcParkingRwLockWritableOptionalKeyPathChain<
3343        Root,
3344        InnerValue,
3345        NextValue,
3346        F,
3347        impl for<'r> Fn(&'r mut InnerValue) -> Option<&'r mut NextValue> + 'static,
3348    >
3349    where
3350        H: for<'r> Fn(&'r mut SubValue) -> &'r mut NextValue,
3351        G: 'static,
3352        H: 'static,
3353        InnerValue: 'static,
3354        SubValue: 'static,
3355        NextValue: 'static,
3356    {
3357        let first = self.inner_keypath;
3358        let second = next;
3359
3360        let composed = WritableOptionalKeyPath::new(move |inner: &mut InnerValue| {
3361            first.get_mut(inner).map(|sub| second.get_mut(sub))
3362        });
3363
3364        OptionalArcParkingRwLockWritableOptionalKeyPathChain {
3365            outer_keypath: self.outer_keypath,
3366            inner_keypath: composed,
3367        }
3368    }
3369
3370    /// Chain with an optional writable keypath through another level
3371    pub fn chain_optional<NextValue, H>(
3372        self,
3373        next: WritableOptionalKeyPath<SubValue, NextValue, H>,
3374    ) -> OptionalArcParkingRwLockWritableOptionalKeyPathChain<
3375        Root,
3376        InnerValue,
3377        NextValue,
3378        F,
3379        impl for<'r> Fn(&'r mut InnerValue) -> Option<&'r mut NextValue> + 'static,
3380    >
3381    where
3382        H: for<'r> Fn(&'r mut SubValue) -> Option<&'r mut NextValue>,
3383        G: 'static,
3384        H: 'static,
3385        InnerValue: 'static,
3386        SubValue: 'static,
3387        NextValue: 'static,
3388    {
3389        let first = self.inner_keypath;
3390        let second = next;
3391
3392        let composed = WritableOptionalKeyPath::new(move |inner: &mut InnerValue| {
3393            first.get_mut(inner).and_then(|sub| second.get_mut(sub))
3394        });
3395
3396        OptionalArcParkingRwLockWritableOptionalKeyPathChain {
3397            outer_keypath: self.outer_keypath,
3398            inner_keypath: composed,
3399        }
3400    }
3401}
3402
3403// ========== TOKIO MUTEX/RWLOCK CHAIN TYPES ==========
3404
3405#[cfg(feature = "tokio")]
3406use tokio::sync::{Mutex as TokioMutex, RwLock as TokioRwLock};
3407
3408/// A composed async keypath chain through Arc<tokio::sync::Mutex<T>> - functional style
3409#[cfg(feature = "tokio")]
3410pub struct ArcTokioMutexKeyPathChain<Root, MutexValue, InnerValue, SubValue, F, G>
3411where
3412    F: for<'r> Fn(&'r Root) -> &'r MutexValue,
3413    G: for<'r> Fn(&'r InnerValue) -> &'r SubValue,
3414{
3415    outer_keypath: KeyPath<Root, MutexValue, F>,
3416    inner_keypath: KeyPath<InnerValue, SubValue, G>,
3417}
3418
3419#[cfg(feature = "tokio")]
3420impl<Root, MutexValue, InnerValue, SubValue, F, G>
3421    ArcTokioMutexKeyPathChain<Root, MutexValue, InnerValue, SubValue, F, G>
3422where
3423    MutexValue: std::borrow::Borrow<Arc<TokioMutex<InnerValue>>>,
3424    F: for<'r> Fn(&'r Root) -> &'r MutexValue,
3425    G: for<'r> Fn(&'r InnerValue) -> &'r SubValue,
3426{
3427    /// Apply the composed keypath chain to a container (read, async)
3428    pub async fn get<Callback>(self, container: &Root, callback: Callback)
3429    where
3430        Callback: FnOnce(&SubValue) -> (),
3431    {
3432        let arc_mutex_ref = self.outer_keypath.get(container).borrow();
3433        let guard = arc_mutex_ref.lock().await;
3434        let value = self.inner_keypath.get(&*guard);
3435        callback(value);
3436    }
3437
3438    /// Chain with another readable keypath through another level
3439    pub fn then<NextValue, H>(
3440        self,
3441        next: KeyPath<SubValue, NextValue, H>,
3442    ) -> ArcTokioMutexKeyPathChain<
3443        Root,
3444        MutexValue,
3445        InnerValue,
3446        NextValue,
3447        F,
3448        impl for<'r> Fn(&'r InnerValue) -> &'r NextValue + 'static,
3449    >
3450    where
3451        H: for<'r> Fn(&'r SubValue) -> &'r NextValue,
3452        G: 'static,
3453        H: 'static,
3454        InnerValue: 'static,
3455        SubValue: 'static,
3456        NextValue: 'static,
3457    {
3458        let first = self.inner_keypath;
3459        let second = next;
3460
3461        let composed = KeyPath::new(move |inner: &InnerValue| {
3462            let sub = first.get(inner);
3463            second.get(sub)
3464        });
3465
3466        ArcTokioMutexKeyPathChain {
3467            outer_keypath: self.outer_keypath,
3468            inner_keypath: composed,
3469        }
3470    }
3471
3472    /// Chain with an optional readable keypath through another level
3473    pub fn chain_optional<NextValue, H>(
3474        self,
3475        next: OptionalKeyPath<SubValue, NextValue, H>,
3476    ) -> ArcTokioMutexOptionalKeyPathChain<
3477        Root,
3478        MutexValue,
3479        InnerValue,
3480        NextValue,
3481        F,
3482        impl for<'r> Fn(&'r InnerValue) -> Option<&'r NextValue> + 'static,
3483    >
3484    where
3485        H: for<'r> Fn(&'r SubValue) -> Option<&'r NextValue>,
3486        G: 'static,
3487        H: 'static,
3488        InnerValue: 'static,
3489        SubValue: 'static,
3490        NextValue: 'static,
3491    {
3492        let first = self.inner_keypath;
3493        let second = next;
3494
3495        let composed = OptionalKeyPath::new(move |inner: &InnerValue| {
3496            let sub = first.get(inner);
3497            second.get(sub)
3498        });
3499
3500        ArcTokioMutexOptionalKeyPathChain {
3501            outer_keypath: self.outer_keypath,
3502            inner_keypath: composed,
3503        }
3504    }
3505}
3506
3507/// A composed optional async keypath chain through Arc<tokio::sync::Mutex<T>> - functional style
3508#[cfg(feature = "tokio")]
3509pub struct ArcTokioMutexOptionalKeyPathChain<Root, MutexValue, InnerValue, SubValue, F, G>
3510where
3511    F: for<'r> Fn(&'r Root) -> &'r MutexValue,
3512    G: for<'r> Fn(&'r InnerValue) -> Option<&'r SubValue>,
3513{
3514    outer_keypath: KeyPath<Root, MutexValue, F>,
3515    inner_keypath: OptionalKeyPath<InnerValue, SubValue, G>,
3516}
3517
3518#[cfg(feature = "tokio")]
3519impl<Root, MutexValue, InnerValue, SubValue, F, G>
3520    ArcTokioMutexOptionalKeyPathChain<Root, MutexValue, InnerValue, SubValue, F, G>
3521where
3522    MutexValue: std::borrow::Borrow<Arc<TokioMutex<InnerValue>>>,
3523    F: for<'r> Fn(&'r Root) -> &'r MutexValue,
3524    G: for<'r> Fn(&'r InnerValue) -> Option<&'r SubValue>,
3525{
3526    /// Apply the composed keypath chain to a container (read, if value exists, async)
3527    pub async fn get<Callback>(self, container: &Root, callback: Callback) -> Option<()>
3528    where
3529        Callback: FnOnce(&SubValue) -> (),
3530    {
3531        let arc_mutex_ref = self.outer_keypath.get(container).borrow();
3532        let guard = arc_mutex_ref.lock().await;
3533        self.inner_keypath.get(&*guard).map(|value| callback(value))
3534    }
3535
3536    /// Chain with another readable keypath through another level
3537    pub fn then<NextValue, H>(
3538        self,
3539        next: KeyPath<SubValue, NextValue, H>,
3540    ) -> ArcTokioMutexOptionalKeyPathChain<
3541        Root,
3542        MutexValue,
3543        InnerValue,
3544        NextValue,
3545        F,
3546        impl for<'r> Fn(&'r InnerValue) -> Option<&'r NextValue> + 'static,
3547    >
3548    where
3549        H: for<'r> Fn(&'r SubValue) -> &'r NextValue,
3550        G: 'static,
3551        H: 'static,
3552        InnerValue: 'static,
3553        SubValue: 'static,
3554        NextValue: 'static,
3555    {
3556        let first = self.inner_keypath;
3557        let second = next;
3558
3559        let composed = OptionalKeyPath::new(move |inner: &InnerValue| {
3560            first.get(inner).map(|sub| second.get(sub))
3561        });
3562
3563        ArcTokioMutexOptionalKeyPathChain {
3564            outer_keypath: self.outer_keypath,
3565            inner_keypath: composed,
3566        }
3567    }
3568
3569    /// Chain with an optional readable keypath through another level
3570    pub fn chain_optional<NextValue, H>(
3571        self,
3572        next: OptionalKeyPath<SubValue, NextValue, H>,
3573    ) -> ArcTokioMutexOptionalKeyPathChain<
3574        Root,
3575        MutexValue,
3576        InnerValue,
3577        NextValue,
3578        F,
3579        impl for<'r> Fn(&'r InnerValue) -> Option<&'r NextValue> + 'static,
3580    >
3581    where
3582        H: for<'r> Fn(&'r SubValue) -> Option<&'r NextValue>,
3583        G: 'static,
3584        H: 'static,
3585        InnerValue: 'static,
3586        SubValue: 'static,
3587        NextValue: 'static,
3588    {
3589        let first = self.inner_keypath;
3590        let second = next;
3591
3592        let composed = OptionalKeyPath::new(move |inner: &InnerValue| {
3593            first.get(inner).and_then(|sub| second.get(sub))
3594        });
3595
3596        ArcTokioMutexOptionalKeyPathChain {
3597            outer_keypath: self.outer_keypath,
3598            inner_keypath: composed,
3599        }
3600    }
3601}
3602
3603/// A composed writable async keypath chain through Arc<tokio::sync::Mutex<T>> - functional style
3604#[cfg(feature = "tokio")]
3605pub struct ArcTokioMutexWritableKeyPathChain<Root, MutexValue, InnerValue, SubValue, F, G>
3606where
3607    F: for<'r> Fn(&'r Root) -> &'r MutexValue,
3608    G: for<'r> Fn(&'r mut InnerValue) -> &'r mut SubValue,
3609{
3610    outer_keypath: KeyPath<Root, MutexValue, F>,
3611    inner_keypath: WritableKeyPath<InnerValue, SubValue, G>,
3612}
3613
3614#[cfg(feature = "tokio")]
3615impl<Root, MutexValue, InnerValue, SubValue, F, G>
3616    ArcTokioMutexWritableKeyPathChain<Root, MutexValue, InnerValue, SubValue, F, G>
3617where
3618    MutexValue: std::borrow::Borrow<Arc<TokioMutex<InnerValue>>>,
3619    F: for<'r> Fn(&'r Root) -> &'r MutexValue,
3620    G: for<'r> Fn(&'r mut InnerValue) -> &'r mut SubValue,
3621{
3622    /// Apply the composed keypath chain to a container with mutable access (async)
3623    pub async fn get_mut<Callback, R>(self, container: &Root, callback: Callback) -> R
3624    where
3625        Callback: FnOnce(&mut SubValue) -> R,
3626    {
3627        let arc_mutex_ref = self.outer_keypath.get(container).borrow();
3628        let mut guard = arc_mutex_ref.lock().await;
3629        let value_ref = self.inner_keypath.get_mut(&mut *guard);
3630        callback(value_ref)
3631    }
3632
3633    /// Chain with another writable keypath through another level
3634    pub fn then<NextValue, H>(
3635        self,
3636        next: WritableKeyPath<SubValue, NextValue, H>,
3637    ) -> ArcTokioMutexWritableKeyPathChain<
3638        Root,
3639        MutexValue,
3640        InnerValue,
3641        NextValue,
3642        F,
3643        impl for<'r> Fn(&'r mut InnerValue) -> &'r mut NextValue + 'static,
3644    >
3645    where
3646        H: for<'r> Fn(&'r mut SubValue) -> &'r mut NextValue,
3647        G: 'static,
3648        H: 'static,
3649        InnerValue: 'static,
3650        SubValue: 'static,
3651        NextValue: 'static,
3652    {
3653        let first = self.inner_keypath;
3654        let second = next;
3655
3656        let composed = WritableKeyPath::new(move |inner: &mut InnerValue| {
3657            let sub = first.get_mut(inner);
3658            second.get_mut(sub)
3659        });
3660
3661        ArcTokioMutexWritableKeyPathChain {
3662            outer_keypath: self.outer_keypath,
3663            inner_keypath: composed,
3664        }
3665    }
3666
3667    /// Chain with an optional writable keypath through another level
3668    pub fn chain_optional<NextValue, H>(
3669        self,
3670        next: WritableOptionalKeyPath<SubValue, NextValue, H>,
3671    ) -> ArcTokioMutexWritableOptionalKeyPathChain<
3672        Root,
3673        MutexValue,
3674        InnerValue,
3675        NextValue,
3676        F,
3677        impl for<'r> Fn(&'r mut InnerValue) -> Option<&'r mut NextValue> + 'static,
3678    >
3679    where
3680        H: for<'r> Fn(&'r mut SubValue) -> Option<&'r mut NextValue>,
3681        G: 'static,
3682        H: 'static,
3683        InnerValue: 'static,
3684        SubValue: 'static,
3685        NextValue: 'static,
3686    {
3687        let first = self.inner_keypath;
3688        let second = next;
3689
3690        let composed = WritableOptionalKeyPath::new(move |inner: &mut InnerValue| {
3691            let sub = first.get_mut(inner);
3692            second.get_mut(sub)
3693        });
3694
3695        ArcTokioMutexWritableOptionalKeyPathChain {
3696            outer_keypath: self.outer_keypath,
3697            inner_keypath: composed,
3698        }
3699    }
3700}
3701
3702/// A composed writable optional async keypath chain through Arc<tokio::sync::Mutex<T>> - functional style
3703#[cfg(feature = "tokio")]
3704pub struct ArcTokioMutexWritableOptionalKeyPathChain<Root, MutexValue, InnerValue, SubValue, F, G>
3705where
3706    F: for<'r> Fn(&'r Root) -> &'r MutexValue,
3707    G: for<'r> Fn(&'r mut InnerValue) -> Option<&'r mut SubValue>,
3708{
3709    outer_keypath: KeyPath<Root, MutexValue, F>,
3710    inner_keypath: WritableOptionalKeyPath<InnerValue, SubValue, G>,
3711}
3712
3713#[cfg(feature = "tokio")]
3714impl<Root, MutexValue, InnerValue, SubValue, F, G>
3715    ArcTokioMutexWritableOptionalKeyPathChain<Root, MutexValue, InnerValue, SubValue, F, G>
3716where
3717    MutexValue: std::borrow::Borrow<Arc<TokioMutex<InnerValue>>>,
3718    F: for<'r> Fn(&'r Root) -> &'r MutexValue,
3719    G: for<'r> Fn(&'r mut InnerValue) -> Option<&'r mut SubValue>,
3720{
3721    /// Apply the composed keypath chain to a container with mutable access (if value exists, async)
3722    pub async fn get_mut<Callback, R>(self, container: &Root, callback: Callback) -> Option<R>
3723    where
3724        Callback: FnOnce(&mut SubValue) -> R,
3725    {
3726        let arc_mutex_ref = self.outer_keypath.get(container).borrow();
3727        let mut guard = arc_mutex_ref.lock().await;
3728        self.inner_keypath
3729            .get_mut(&mut *guard)
3730            .map(|value_ref| callback(value_ref))
3731    }
3732
3733    /// Chain with another writable keypath through another level
3734    pub fn then<NextValue, H>(
3735        self,
3736        next: WritableKeyPath<SubValue, NextValue, H>,
3737    ) -> ArcTokioMutexWritableOptionalKeyPathChain<
3738        Root,
3739        MutexValue,
3740        InnerValue,
3741        NextValue,
3742        F,
3743        impl for<'r> Fn(&'r mut InnerValue) -> Option<&'r mut NextValue> + 'static,
3744    >
3745    where
3746        H: for<'r> Fn(&'r mut SubValue) -> &'r mut 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 = WritableOptionalKeyPath::new(move |inner: &mut InnerValue| {
3757            first.get_mut(inner).map(|sub| second.get_mut(sub))
3758        });
3759
3760        ArcTokioMutexWritableOptionalKeyPathChain {
3761            outer_keypath: self.outer_keypath,
3762            inner_keypath: composed,
3763        }
3764    }
3765
3766    /// Chain with an optional writable keypath through another level
3767    pub fn chain_optional<NextValue, H>(
3768        self,
3769        next: WritableOptionalKeyPath<SubValue, NextValue, H>,
3770    ) -> ArcTokioMutexWritableOptionalKeyPathChain<
3771        Root,
3772        MutexValue,
3773        InnerValue,
3774        NextValue,
3775        F,
3776        impl for<'r> Fn(&'r mut InnerValue) -> Option<&'r mut NextValue> + 'static,
3777    >
3778    where
3779        H: for<'r> Fn(&'r mut SubValue) -> Option<&'r mut NextValue>,
3780        G: 'static,
3781        H: 'static,
3782        InnerValue: 'static,
3783        SubValue: 'static,
3784        NextValue: 'static,
3785    {
3786        let first = self.inner_keypath;
3787        let second = next;
3788
3789        let composed = WritableOptionalKeyPath::new(move |inner: &mut InnerValue| {
3790            first.get_mut(inner).and_then(|sub| second.get_mut(sub))
3791        });
3792
3793        ArcTokioMutexWritableOptionalKeyPathChain {
3794            outer_keypath: self.outer_keypath,
3795            inner_keypath: composed,
3796        }
3797    }
3798}
3799
3800/// A composed async keypath chain through Arc<tokio::sync::RwLock<T>> - functional style
3801#[cfg(feature = "tokio")]
3802pub struct ArcTokioRwLockKeyPathChain<Root, RwLockValue, InnerValue, SubValue, F, G>
3803where
3804    RwLockValue: std::borrow::Borrow<Arc<TokioRwLock<InnerValue>>>,
3805    F: for<'r> Fn(&'r Root) -> &'r RwLockValue,
3806    G: for<'r> Fn(&'r InnerValue) -> &'r SubValue,
3807{
3808    outer_keypath: KeyPath<Root, RwLockValue, F>,
3809    inner_keypath: KeyPath<InnerValue, SubValue, G>,
3810}
3811
3812#[cfg(feature = "tokio")]
3813impl<Root, RwLockValue, InnerValue, SubValue, F, G>
3814    ArcTokioRwLockKeyPathChain<Root, RwLockValue, InnerValue, SubValue, F, G>
3815where
3816    RwLockValue: std::borrow::Borrow<Arc<TokioRwLock<InnerValue>>>,
3817    F: for<'r> Fn(&'r Root) -> &'r RwLockValue,
3818    G: for<'r> Fn(&'r InnerValue) -> &'r SubValue,
3819{
3820    /// Apply the composed keypath chain to a container (read lock, async)
3821    pub async fn get<Callback>(self, container: &Root, callback: Callback)
3822    where
3823        Callback: FnOnce(&SubValue) -> (),
3824    {
3825        let arc_rwlock_ref = self.outer_keypath.get(container).borrow();
3826        let guard = arc_rwlock_ref.read().await;
3827        let value = self.inner_keypath.get(&*guard);
3828        callback(value);
3829    }
3830
3831    /// Chain with another readable keypath through another level
3832    pub fn then<NextValue, H>(
3833        self,
3834        next: KeyPath<SubValue, NextValue, H>,
3835    ) -> ArcTokioRwLockKeyPathChain<
3836        Root,
3837        RwLockValue,
3838        InnerValue,
3839        NextValue,
3840        F,
3841        impl for<'r> Fn(&'r InnerValue) -> &'r NextValue + 'static,
3842    >
3843    where
3844        H: for<'r> Fn(&'r SubValue) -> &'r NextValue,
3845        G: 'static,
3846        H: 'static,
3847        InnerValue: 'static,
3848        SubValue: 'static,
3849        NextValue: 'static,
3850    {
3851        let first = self.inner_keypath;
3852        let second = next;
3853
3854        let composed = KeyPath::new(move |inner: &InnerValue| {
3855            let sub = first.get(inner);
3856            second.get(sub)
3857        });
3858
3859        ArcTokioRwLockKeyPathChain {
3860            outer_keypath: self.outer_keypath,
3861            inner_keypath: composed,
3862        }
3863    }
3864
3865    /// Chain with an optional readable keypath through another level
3866    pub fn chain_optional<NextValue, H>(
3867        self,
3868        next: OptionalKeyPath<SubValue, NextValue, H>,
3869    ) -> ArcTokioRwLockOptionalKeyPathChain<
3870        Root,
3871        RwLockValue,
3872        InnerValue,
3873        NextValue,
3874        F,
3875        impl for<'r> Fn(&'r InnerValue) -> Option<&'r NextValue> + 'static,
3876    >
3877    where
3878        H: for<'r> Fn(&'r SubValue) -> Option<&'r NextValue>,
3879        G: 'static,
3880        H: 'static,
3881        InnerValue: 'static,
3882        SubValue: 'static,
3883        NextValue: 'static,
3884    {
3885        let first = self.inner_keypath;
3886        let second = next;
3887
3888        let composed = OptionalKeyPath::new(move |inner: &InnerValue| {
3889            let sub = first.get(inner);
3890            second.get(sub)
3891        });
3892
3893        ArcTokioRwLockOptionalKeyPathChain {
3894            outer_keypath: self.outer_keypath,
3895            inner_keypath: composed,
3896        }
3897    }
3898}
3899
3900/// A composed optional async keypath chain through Arc<tokio::sync::RwLock<T>> - functional style
3901#[cfg(feature = "tokio")]
3902pub struct ArcTokioRwLockOptionalKeyPathChain<Root, RwLockValue, InnerValue, SubValue, F, G>
3903where
3904    RwLockValue: std::borrow::Borrow<Arc<TokioRwLock<InnerValue>>>,
3905    F: for<'r> Fn(&'r Root) -> &'r RwLockValue,
3906    G: for<'r> Fn(&'r InnerValue) -> Option<&'r SubValue>,
3907{
3908    outer_keypath: KeyPath<Root, RwLockValue, F>,
3909    inner_keypath: OptionalKeyPath<InnerValue, SubValue, G>,
3910}
3911
3912#[cfg(feature = "tokio")]
3913impl<Root, RwLockValue, InnerValue, SubValue, F, G>
3914    ArcTokioRwLockOptionalKeyPathChain<Root, RwLockValue, InnerValue, SubValue, F, G>
3915where
3916    RwLockValue: std::borrow::Borrow<Arc<TokioRwLock<InnerValue>>>,
3917    F: for<'r> Fn(&'r Root) -> &'r RwLockValue,
3918    G: for<'r> Fn(&'r InnerValue) -> Option<&'r SubValue>,
3919{
3920    /// Apply the composed keypath chain to a container (read lock, if value exists, async)
3921    pub async fn get<Callback>(self, container: &Root, callback: Callback) -> Option<()>
3922    where
3923        Callback: FnOnce(&SubValue) -> (),
3924    {
3925        let arc_rwlock_ref = self.outer_keypath.get(container).borrow();
3926        let guard = arc_rwlock_ref.read().await;
3927        self.inner_keypath.get(&*guard).map(|value| callback(value))
3928    }
3929
3930    /// Chain with another readable keypath through another level
3931    pub fn then<NextValue, H>(
3932        self,
3933        next: KeyPath<SubValue, NextValue, H>,
3934    ) -> ArcTokioRwLockOptionalKeyPathChain<
3935        Root,
3936        RwLockValue,
3937        InnerValue,
3938        NextValue,
3939        F,
3940        impl for<'r> Fn(&'r InnerValue) -> Option<&'r NextValue> + 'static,
3941    >
3942    where
3943        H: for<'r> Fn(&'r SubValue) -> &'r NextValue,
3944        G: 'static,
3945        H: 'static,
3946        InnerValue: 'static,
3947        SubValue: 'static,
3948        NextValue: 'static,
3949    {
3950        let first = self.inner_keypath;
3951        let second = next;
3952
3953        let composed = OptionalKeyPath::new(move |inner: &InnerValue| {
3954            first.get(inner).map(|sub| second.get(sub))
3955        });
3956
3957        ArcTokioRwLockOptionalKeyPathChain {
3958            outer_keypath: self.outer_keypath,
3959            inner_keypath: composed,
3960        }
3961    }
3962
3963    /// Chain with an optional readable keypath through another level
3964    pub fn chain_optional<NextValue, H>(
3965        self,
3966        next: OptionalKeyPath<SubValue, NextValue, H>,
3967    ) -> ArcTokioRwLockOptionalKeyPathChain<
3968        Root,
3969        RwLockValue,
3970        InnerValue,
3971        NextValue,
3972        F,
3973        impl for<'r> Fn(&'r InnerValue) -> Option<&'r NextValue> + 'static,
3974    >
3975    where
3976        H: for<'r> Fn(&'r SubValue) -> Option<&'r NextValue>,
3977        G: 'static,
3978        H: 'static,
3979        InnerValue: 'static,
3980        SubValue: 'static,
3981        NextValue: 'static,
3982    {
3983        let first = self.inner_keypath;
3984        let second = next;
3985
3986        let composed = OptionalKeyPath::new(move |inner: &InnerValue| {
3987            first.get(inner).and_then(|sub| second.get(sub))
3988        });
3989
3990        ArcTokioRwLockOptionalKeyPathChain {
3991            outer_keypath: self.outer_keypath,
3992            inner_keypath: composed,
3993        }
3994    }
3995}
3996
3997/// A composed writable async keypath chain through Arc<tokio::sync::RwLock<T>> - functional style
3998#[cfg(feature = "tokio")]
3999pub struct ArcTokioRwLockWritableKeyPathChain<Root, RwLockValue, InnerValue, SubValue, F, G>
4000where
4001    RwLockValue: std::borrow::Borrow<Arc<TokioRwLock<InnerValue>>>,
4002    F: for<'r> Fn(&'r Root) -> &'r RwLockValue,
4003    G: for<'r> Fn(&'r mut InnerValue) -> &'r mut SubValue,
4004{
4005    outer_keypath: KeyPath<Root, RwLockValue, F>,
4006    inner_keypath: WritableKeyPath<InnerValue, SubValue, G>,
4007}
4008
4009#[cfg(feature = "tokio")]
4010impl<Root, RwLockValue, InnerValue, SubValue, F, G>
4011    ArcTokioRwLockWritableKeyPathChain<Root, RwLockValue, InnerValue, SubValue, F, G>
4012where
4013    RwLockValue: std::borrow::Borrow<Arc<TokioRwLock<InnerValue>>>,
4014    F: for<'r> Fn(&'r Root) -> &'r RwLockValue,
4015    G: for<'r> Fn(&'r mut InnerValue) -> &'r mut SubValue,
4016{
4017    /// Apply the composed keypath chain to a container with mutable access (write lock, async)
4018    pub async fn get_mut<Callback, R>(self, container: &Root, callback: Callback) -> R
4019    where
4020        Callback: FnOnce(&mut SubValue) -> R,
4021    {
4022        let arc_rwlock_ref = self.outer_keypath.get(container).borrow();
4023        let mut guard = arc_rwlock_ref.write().await;
4024        let value_ref = self.inner_keypath.get_mut(&mut *guard);
4025        callback(value_ref)
4026    }
4027
4028    /// Chain with another writable keypath through another level
4029    pub fn then<NextValue, H>(
4030        self,
4031        next: WritableKeyPath<SubValue, NextValue, H>,
4032    ) -> ArcTokioRwLockWritableKeyPathChain<
4033        Root,
4034        RwLockValue,
4035        InnerValue,
4036        NextValue,
4037        F,
4038        impl for<'r> Fn(&'r mut InnerValue) -> &'r mut NextValue + 'static,
4039    >
4040    where
4041        H: for<'r> Fn(&'r mut SubValue) -> &'r mut NextValue,
4042        G: 'static,
4043        H: 'static,
4044        InnerValue: 'static,
4045        SubValue: 'static,
4046        NextValue: 'static,
4047    {
4048        let first = self.inner_keypath;
4049        let second = next;
4050
4051        let composed = WritableKeyPath::new(move |inner: &mut InnerValue| {
4052            let sub = first.get_mut(inner);
4053            second.get_mut(sub)
4054        });
4055
4056        ArcTokioRwLockWritableKeyPathChain {
4057            outer_keypath: self.outer_keypath,
4058            inner_keypath: composed,
4059        }
4060    }
4061
4062    /// Chain with an optional writable keypath through another level
4063    pub fn chain_optional<NextValue, H>(
4064        self,
4065        next: WritableOptionalKeyPath<SubValue, NextValue, H>,
4066    ) -> ArcTokioRwLockWritableOptionalKeyPathChain<
4067        Root,
4068        RwLockValue,
4069        InnerValue,
4070        NextValue,
4071        F,
4072        impl for<'r> Fn(&'r mut InnerValue) -> Option<&'r mut NextValue> + 'static,
4073    >
4074    where
4075        H: for<'r> Fn(&'r mut SubValue) -> Option<&'r mut NextValue>,
4076        G: 'static,
4077        H: 'static,
4078        InnerValue: 'static,
4079        SubValue: 'static,
4080        NextValue: 'static,
4081    {
4082        let first = self.inner_keypath;
4083        let second = next;
4084
4085        let composed = WritableOptionalKeyPath::new(move |inner: &mut InnerValue| {
4086            let sub = first.get_mut(inner);
4087            second.get_mut(sub)
4088        });
4089
4090        ArcTokioRwLockWritableOptionalKeyPathChain {
4091            outer_keypath: self.outer_keypath,
4092            inner_keypath: composed,
4093        }
4094    }
4095}
4096
4097/// A composed writable optional async keypath chain through Arc<tokio::sync::RwLock<T>> - functional style
4098#[cfg(feature = "tokio")]
4099pub struct ArcTokioRwLockWritableOptionalKeyPathChain<Root, RwLockValue, InnerValue, SubValue, F, G>
4100where
4101    RwLockValue: std::borrow::Borrow<Arc<TokioRwLock<InnerValue>>>,
4102    F: for<'r> Fn(&'r Root) -> &'r RwLockValue,
4103    G: for<'r> Fn(&'r mut InnerValue) -> Option<&'r mut SubValue>,
4104{
4105    outer_keypath: KeyPath<Root, RwLockValue, F>,
4106    inner_keypath: WritableOptionalKeyPath<InnerValue, SubValue, G>,
4107}
4108
4109#[cfg(feature = "tokio")]
4110impl<Root, RwLockValue, InnerValue, SubValue, F, G>
4111    ArcTokioRwLockWritableOptionalKeyPathChain<Root, RwLockValue, InnerValue, SubValue, F, G>
4112where
4113    RwLockValue: std::borrow::Borrow<Arc<TokioRwLock<InnerValue>>>,
4114    F: for<'r> Fn(&'r Root) -> &'r RwLockValue,
4115    G: for<'r> Fn(&'r mut InnerValue) -> Option<&'r mut SubValue>,
4116{
4117    /// Apply the composed keypath chain to a container with mutable access (write lock, if value exists, async)
4118    pub async fn get_mut<Callback, R>(self, container: &Root, callback: Callback) -> Option<R>
4119    where
4120        Callback: FnOnce(&mut SubValue) -> R,
4121    {
4122        let arc_rwlock_ref = self.outer_keypath.get(container).borrow();
4123        let mut guard = arc_rwlock_ref.write().await;
4124        self.inner_keypath
4125            .get_mut(&mut *guard)
4126            .map(|value_ref| callback(value_ref))
4127    }
4128
4129    /// Chain with another writable keypath through another level
4130    pub fn then<NextValue, H>(
4131        self,
4132        next: WritableKeyPath<SubValue, NextValue, H>,
4133    ) -> ArcTokioRwLockWritableOptionalKeyPathChain<
4134        Root,
4135        RwLockValue,
4136        InnerValue,
4137        NextValue,
4138        F,
4139        impl for<'r> Fn(&'r mut InnerValue) -> Option<&'r mut NextValue> + 'static,
4140    >
4141    where
4142        H: for<'r> Fn(&'r mut SubValue) -> &'r mut NextValue,
4143        G: 'static,
4144        H: 'static,
4145        InnerValue: 'static,
4146        SubValue: 'static,
4147        NextValue: 'static,
4148    {
4149        let first = self.inner_keypath;
4150        let second = next;
4151
4152        let composed = WritableOptionalKeyPath::new(move |inner: &mut InnerValue| {
4153            first.get_mut(inner).map(|sub| second.get_mut(sub))
4154        });
4155
4156        ArcTokioRwLockWritableOptionalKeyPathChain {
4157            outer_keypath: self.outer_keypath,
4158            inner_keypath: composed,
4159        }
4160    }
4161
4162    /// Chain with an optional writable keypath through another level
4163    pub fn chain_optional<NextValue, H>(
4164        self,
4165        next: WritableOptionalKeyPath<SubValue, NextValue, H>,
4166    ) -> ArcTokioRwLockWritableOptionalKeyPathChain<
4167        Root,
4168        RwLockValue,
4169        InnerValue,
4170        NextValue,
4171        F,
4172        impl for<'r> Fn(&'r mut InnerValue) -> Option<&'r mut NextValue> + 'static,
4173    >
4174    where
4175        H: for<'r> Fn(&'r mut SubValue) -> Option<&'r mut NextValue>,
4176        G: 'static,
4177        H: 'static,
4178        InnerValue: 'static,
4179        SubValue: 'static,
4180        NextValue: 'static,
4181    {
4182        let first = self.inner_keypath;
4183        let second = next;
4184
4185        let composed = WritableOptionalKeyPath::new(move |inner: &mut InnerValue| {
4186            first.get_mut(inner).and_then(|sub| second.get_mut(sub))
4187        });
4188
4189        ArcTokioRwLockWritableOptionalKeyPathChain {
4190            outer_keypath: self.outer_keypath,
4191            inner_keypath: composed,
4192        }
4193    }
4194}
4195
4196// ========== OPTIONAL TOKIO MUTEX KEYPATH CHAINS (from OptionalKeyPath) ==========
4197
4198/// A composed async keypath chain from optional keypath through Arc<tokio::sync::Mutex<T>> - functional style
4199#[cfg(feature = "tokio")]
4200pub struct OptionalArcTokioMutexKeyPathChain<Root, MutexValue, InnerValue, SubValue, F, G>
4201where
4202    MutexValue: std::borrow::Borrow<Arc<TokioMutex<InnerValue>>>,
4203    F: for<'r> Fn(&'r Root) -> Option<&'r MutexValue>,
4204    G: for<'r> Fn(&'r InnerValue) -> &'r SubValue,
4205{
4206    outer_keypath: OptionalKeyPath<Root, MutexValue, F>,
4207    inner_keypath: KeyPath<InnerValue, SubValue, G>,
4208}
4209
4210#[cfg(feature = "tokio")]
4211impl<Root, MutexValue, InnerValue, SubValue, F, G>
4212    OptionalArcTokioMutexKeyPathChain<Root, MutexValue, InnerValue, SubValue, F, G>
4213where
4214    MutexValue: std::borrow::Borrow<Arc<TokioMutex<InnerValue>>>,
4215    F: for<'r> Fn(&'r Root) -> Option<&'r MutexValue>,
4216    G: for<'r> Fn(&'r InnerValue) -> &'r SubValue,
4217{
4218    /// Apply the composed keypath chain to a container (async)
4219    pub async fn get<Callback>(self, container: &Root, callback: Callback) -> Option<()>
4220    where
4221        Callback: FnOnce(&SubValue) -> (),
4222    {
4223        if let Some(arc_mutex_ref) = self.outer_keypath.get(container) {
4224            let arc_mutex_ref = arc_mutex_ref.borrow();
4225            let guard = arc_mutex_ref.lock().await;
4226            let value = self.inner_keypath.get(&*guard);
4227            callback(value);
4228            Some(())
4229        } else {
4230            None
4231        }
4232    }
4233
4234    /// Chain with another readable keypath through another level
4235    pub fn then<NextValue, H>(
4236        self,
4237        next: KeyPath<SubValue, NextValue, H>,
4238    ) -> OptionalArcTokioMutexKeyPathChain<
4239        Root,
4240        MutexValue,
4241        InnerValue,
4242        NextValue,
4243        F,
4244        impl for<'r> Fn(&'r InnerValue) -> &'r NextValue + 'static,
4245    >
4246    where
4247        H: for<'r> Fn(&'r SubValue) -> &'r NextValue,
4248        G: 'static,
4249        H: 'static,
4250        InnerValue: 'static,
4251        SubValue: 'static,
4252        NextValue: 'static,
4253    {
4254        let first = self.inner_keypath;
4255        let second = next;
4256
4257        let composed = KeyPath::new(move |inner: &InnerValue| {
4258            let sub = first.get(inner);
4259            second.get(sub)
4260        });
4261
4262        OptionalArcTokioMutexKeyPathChain {
4263            outer_keypath: self.outer_keypath,
4264            inner_keypath: composed,
4265        }
4266    }
4267
4268    /// Chain with an optional readable keypath through another level
4269    pub fn chain_optional<NextValue, H>(
4270        self,
4271        next: OptionalKeyPath<SubValue, NextValue, H>,
4272    ) -> OptionalArcTokioMutexOptionalKeyPathChain<
4273        Root,
4274        MutexValue,
4275        InnerValue,
4276        NextValue,
4277        F,
4278        impl for<'r> Fn(&'r InnerValue) -> Option<&'r NextValue> + 'static,
4279    >
4280    where
4281        H: for<'r> Fn(&'r SubValue) -> Option<&'r NextValue>,
4282        G: 'static,
4283        H: 'static,
4284        InnerValue: 'static,
4285        SubValue: 'static,
4286        NextValue: 'static,
4287    {
4288        let first = self.inner_keypath;
4289        let second = next;
4290
4291        let composed = OptionalKeyPath::new(move |inner: &InnerValue| {
4292            let sub = first.get(inner);
4293            second.get(sub)
4294        });
4295
4296        OptionalArcTokioMutexOptionalKeyPathChain {
4297            outer_keypath: self.outer_keypath,
4298            inner_keypath: composed,
4299        }
4300    }
4301}
4302
4303/// A composed optional async keypath chain from optional keypath through Arc<tokio::sync::Mutex<T>>
4304#[cfg(feature = "tokio")]
4305pub struct OptionalArcTokioMutexOptionalKeyPathChain<Root, MutexValue, InnerValue, SubValue, F, G>
4306where
4307    MutexValue: std::borrow::Borrow<Arc<TokioMutex<InnerValue>>>,
4308    F: for<'r> Fn(&'r Root) -> Option<&'r MutexValue>,
4309    G: for<'r> Fn(&'r InnerValue) -> Option<&'r SubValue>,
4310{
4311    outer_keypath: OptionalKeyPath<Root, MutexValue, F>,
4312    inner_keypath: OptionalKeyPath<InnerValue, SubValue, G>,
4313}
4314
4315#[cfg(feature = "tokio")]
4316impl<Root, MutexValue, InnerValue, SubValue, F, G>
4317    OptionalArcTokioMutexOptionalKeyPathChain<Root, MutexValue, InnerValue, SubValue, F, G>
4318where
4319    MutexValue: std::borrow::Borrow<Arc<TokioMutex<InnerValue>>>,
4320    F: for<'r> Fn(&'r Root) -> Option<&'r MutexValue>,
4321    G: for<'r> Fn(&'r InnerValue) -> Option<&'r SubValue>,
4322{
4323    /// Apply the composed keypath chain to a container (async)
4324    pub async fn get<Callback>(self, container: &Root, callback: Callback) -> Option<()>
4325    where
4326        Callback: FnOnce(&SubValue) -> (),
4327    {
4328        if let Some(arc_mutex_ref) = self.outer_keypath.get(container) {
4329            let arc_mutex_ref = arc_mutex_ref.borrow();
4330            let guard = arc_mutex_ref.lock().await;
4331            self.inner_keypath.get(&*guard).map(|value| callback(value))
4332        } else {
4333            None
4334        }
4335    }
4336
4337    /// Chain with another readable keypath through another level
4338    pub fn then<NextValue, H>(
4339        self,
4340        next: KeyPath<SubValue, NextValue, H>,
4341    ) -> OptionalArcTokioMutexOptionalKeyPathChain<
4342        Root,
4343        MutexValue,
4344        InnerValue,
4345        NextValue,
4346        F,
4347        impl for<'r> Fn(&'r InnerValue) -> Option<&'r NextValue> + 'static,
4348    >
4349    where
4350        H: for<'r> Fn(&'r SubValue) -> &'r NextValue,
4351        G: 'static,
4352        H: 'static,
4353        InnerValue: 'static,
4354        SubValue: 'static,
4355        NextValue: 'static,
4356    {
4357        let first = self.inner_keypath;
4358        let second = next;
4359
4360        let composed = OptionalKeyPath::new(move |inner: &InnerValue| {
4361            first.get(inner).map(|sub| second.get(sub))
4362        });
4363
4364        OptionalArcTokioMutexOptionalKeyPathChain {
4365            outer_keypath: self.outer_keypath,
4366            inner_keypath: composed,
4367        }
4368    }
4369
4370    /// Chain with an optional readable keypath through another level
4371    pub fn chain_optional<NextValue, H>(
4372        self,
4373        next: OptionalKeyPath<SubValue, NextValue, H>,
4374    ) -> OptionalArcTokioMutexOptionalKeyPathChain<
4375        Root,
4376        MutexValue,
4377        InnerValue,
4378        NextValue,
4379        F,
4380        impl for<'r> Fn(&'r InnerValue) -> Option<&'r NextValue> + 'static,
4381    >
4382    where
4383        H: for<'r> Fn(&'r SubValue) -> Option<&'r NextValue>,
4384        G: 'static,
4385        H: 'static,
4386        InnerValue: 'static,
4387        SubValue: 'static,
4388        NextValue: 'static,
4389    {
4390        let first = self.inner_keypath;
4391        let second = next;
4392
4393        let composed = OptionalKeyPath::new(move |inner: &InnerValue| {
4394            first.get(inner).and_then(|sub| second.get(sub))
4395        });
4396
4397        OptionalArcTokioMutexOptionalKeyPathChain {
4398            outer_keypath: self.outer_keypath,
4399            inner_keypath: composed,
4400        }
4401    }
4402}
4403
4404/// A composed writable async keypath chain from optional keypath through Arc<tokio::sync::Mutex<T>>
4405#[cfg(feature = "tokio")]
4406pub struct OptionalArcTokioMutexWritableKeyPathChain<Root, MutexValue, InnerValue, SubValue, F, G>
4407where
4408    MutexValue: std::borrow::Borrow<Arc<TokioMutex<InnerValue>>>,
4409    F: for<'r> Fn(&'r Root) -> Option<&'r MutexValue>,
4410    G: for<'r> Fn(&'r mut InnerValue) -> &'r mut SubValue,
4411{
4412    outer_keypath: OptionalKeyPath<Root, MutexValue, F>,
4413    inner_keypath: WritableKeyPath<InnerValue, SubValue, G>,
4414}
4415
4416#[cfg(feature = "tokio")]
4417impl<Root, MutexValue, InnerValue, SubValue, F, G>
4418    OptionalArcTokioMutexWritableKeyPathChain<Root, MutexValue, InnerValue, SubValue, F, G>
4419where
4420    MutexValue: std::borrow::Borrow<Arc<TokioMutex<InnerValue>>>,
4421    F: for<'r> Fn(&'r Root) -> Option<&'r MutexValue>,
4422    G: for<'r> Fn(&'r mut InnerValue) -> &'r mut SubValue,
4423{
4424    /// Apply the composed keypath chain to a container with mutable access (async)
4425    pub async fn get_mut<Callback, R>(self, container: &Root, callback: Callback) -> Option<R>
4426    where
4427        Callback: FnOnce(&mut SubValue) -> R,
4428    {
4429        if let Some(arc_mutex_ref) = self.outer_keypath.get(container) {
4430            let arc_mutex_ref = arc_mutex_ref.borrow();
4431            let mut guard = arc_mutex_ref.lock().await;
4432            let value_ref = self.inner_keypath.get_mut(&mut *guard);
4433            Some(callback(value_ref))
4434        } else {
4435            None
4436        }
4437    }
4438
4439    /// Chain with another writable keypath through another level
4440    pub fn then<NextValue, H>(
4441        self,
4442        next: WritableKeyPath<SubValue, NextValue, H>,
4443    ) -> OptionalArcTokioMutexWritableKeyPathChain<
4444        Root,
4445        MutexValue,
4446        InnerValue,
4447        NextValue,
4448        F,
4449        impl for<'r> Fn(&'r mut InnerValue) -> &'r mut NextValue + 'static,
4450    >
4451    where
4452        H: for<'r> Fn(&'r mut SubValue) -> &'r mut NextValue,
4453        G: 'static,
4454        H: 'static,
4455        InnerValue: 'static,
4456        SubValue: 'static,
4457        NextValue: 'static,
4458    {
4459        let first = self.inner_keypath;
4460        let second = next;
4461
4462        let composed = WritableKeyPath::new(move |inner: &mut InnerValue| {
4463            let sub = first.get_mut(inner);
4464            second.get_mut(sub)
4465        });
4466
4467        OptionalArcTokioMutexWritableKeyPathChain {
4468            outer_keypath: self.outer_keypath,
4469            inner_keypath: composed,
4470        }
4471    }
4472
4473    /// Chain with an optional writable keypath through another level
4474    pub fn chain_optional<NextValue, H>(
4475        self,
4476        next: WritableOptionalKeyPath<SubValue, NextValue, H>,
4477    ) -> OptionalArcTokioMutexWritableOptionalKeyPathChain<
4478        Root,
4479        MutexValue,
4480        InnerValue,
4481        NextValue,
4482        F,
4483        impl for<'r> Fn(&'r mut InnerValue) -> Option<&'r mut NextValue> + 'static,
4484    >
4485    where
4486        H: for<'r> Fn(&'r mut SubValue) -> Option<&'r mut NextValue>,
4487        G: 'static,
4488        H: 'static,
4489        InnerValue: 'static,
4490        SubValue: 'static,
4491        NextValue: 'static,
4492    {
4493        let first = self.inner_keypath;
4494        let second = next;
4495
4496        let composed = WritableOptionalKeyPath::new(move |inner: &mut InnerValue| {
4497            let sub = first.get_mut(inner);
4498            second.get_mut(sub)
4499        });
4500
4501        OptionalArcTokioMutexWritableOptionalKeyPathChain {
4502            outer_keypath: self.outer_keypath,
4503            inner_keypath: composed,
4504        }
4505    }
4506}
4507
4508/// A composed writable optional async keypath chain from optional keypath through Arc<tokio::sync::Mutex<T>>
4509#[cfg(feature = "tokio")]
4510pub struct OptionalArcTokioMutexWritableOptionalKeyPathChain<
4511    Root,
4512    MutexValue,
4513    InnerValue,
4514    SubValue,
4515    F,
4516    G,
4517> where
4518    MutexValue: std::borrow::Borrow<Arc<TokioMutex<InnerValue>>>,
4519    F: for<'r> Fn(&'r Root) -> Option<&'r MutexValue>,
4520    G: for<'r> Fn(&'r mut InnerValue) -> Option<&'r mut SubValue>,
4521{
4522    outer_keypath: OptionalKeyPath<Root, MutexValue, F>,
4523    inner_keypath: WritableOptionalKeyPath<InnerValue, SubValue, G>,
4524}
4525
4526#[cfg(feature = "tokio")]
4527impl<Root, MutexValue, InnerValue, SubValue, F, G>
4528    OptionalArcTokioMutexWritableOptionalKeyPathChain<Root, MutexValue, InnerValue, SubValue, F, G>
4529where
4530    MutexValue: std::borrow::Borrow<Arc<TokioMutex<InnerValue>>>,
4531    F: for<'r> Fn(&'r Root) -> Option<&'r MutexValue>,
4532    G: for<'r> Fn(&'r mut InnerValue) -> Option<&'r mut SubValue>,
4533{
4534    /// Apply the composed keypath chain to a container with mutable access (if value exists, async)
4535    pub async fn get_mut<Callback, R>(self, container: &Root, callback: Callback) -> Option<R>
4536    where
4537        Callback: FnOnce(&mut SubValue) -> R,
4538    {
4539        if let Some(arc_mutex_ref) = self.outer_keypath.get(container) {
4540            let arc_mutex_ref = arc_mutex_ref.borrow();
4541            let mut guard = arc_mutex_ref.lock().await;
4542            self.inner_keypath
4543                .get_mut(&mut *guard)
4544                .map(|value_ref| callback(value_ref))
4545        } else {
4546            None
4547        }
4548    }
4549
4550    /// Chain with another writable keypath through another level
4551    pub fn then<NextValue, H>(
4552        self,
4553        next: WritableKeyPath<SubValue, NextValue, H>,
4554    ) -> OptionalArcTokioMutexWritableOptionalKeyPathChain<
4555        Root,
4556        MutexValue,
4557        InnerValue,
4558        NextValue,
4559        F,
4560        impl for<'r> Fn(&'r mut InnerValue) -> Option<&'r mut NextValue> + 'static,
4561    >
4562    where
4563        H: for<'r> Fn(&'r mut SubValue) -> &'r mut NextValue,
4564        G: 'static,
4565        H: 'static,
4566        InnerValue: 'static,
4567        SubValue: 'static,
4568        NextValue: 'static,
4569    {
4570        let first = self.inner_keypath;
4571        let second = next;
4572
4573        let composed = WritableOptionalKeyPath::new(move |inner: &mut InnerValue| {
4574            first.get_mut(inner).map(|sub| second.get_mut(sub))
4575        });
4576
4577        OptionalArcTokioMutexWritableOptionalKeyPathChain {
4578            outer_keypath: self.outer_keypath,
4579            inner_keypath: composed,
4580        }
4581    }
4582
4583    /// Chain with an optional writable keypath through another level
4584    pub fn chain_optional<NextValue, H>(
4585        self,
4586        next: WritableOptionalKeyPath<SubValue, NextValue, H>,
4587    ) -> OptionalArcTokioMutexWritableOptionalKeyPathChain<
4588        Root,
4589        MutexValue,
4590        InnerValue,
4591        NextValue,
4592        F,
4593        impl for<'r> Fn(&'r mut InnerValue) -> Option<&'r mut NextValue> + 'static,
4594    >
4595    where
4596        H: for<'r> Fn(&'r mut SubValue) -> Option<&'r mut NextValue>,
4597        G: 'static,
4598        H: 'static,
4599        InnerValue: 'static,
4600        SubValue: 'static,
4601        NextValue: 'static,
4602    {
4603        let first = self.inner_keypath;
4604        let second = next;
4605
4606        let composed = WritableOptionalKeyPath::new(move |inner: &mut InnerValue| {
4607            first.get_mut(inner).and_then(|sub| second.get_mut(sub))
4608        });
4609
4610        OptionalArcTokioMutexWritableOptionalKeyPathChain {
4611            outer_keypath: self.outer_keypath,
4612            inner_keypath: composed,
4613        }
4614    }
4615}
4616
4617// ========== OPTIONAL TOKIO RWLOCK KEYPATH CHAINS (from OptionalKeyPath) ==========
4618
4619/// A composed async keypath chain from optional keypath through Arc<tokio::sync::RwLock<T>> - functional style
4620#[cfg(feature = "tokio")]
4621pub struct OptionalArcTokioRwLockKeyPathChain<Root, RwLockValue, InnerValue, SubValue, F, G>
4622where
4623    RwLockValue: std::borrow::Borrow<Arc<TokioRwLock<InnerValue>>>,
4624    F: for<'r> Fn(&'r Root) -> Option<&'r RwLockValue>,
4625    G: for<'r> Fn(&'r InnerValue) -> &'r SubValue,
4626{
4627    outer_keypath: OptionalKeyPath<Root, RwLockValue, F>,
4628    inner_keypath: KeyPath<InnerValue, SubValue, G>,
4629}
4630
4631#[cfg(feature = "tokio")]
4632impl<Root, RwLockValue, InnerValue, SubValue, F, G>
4633    OptionalArcTokioRwLockKeyPathChain<Root, RwLockValue, InnerValue, SubValue, F, G>
4634where
4635    RwLockValue: std::borrow::Borrow<Arc<TokioRwLock<InnerValue>>>,
4636    F: for<'r> Fn(&'r Root) -> Option<&'r RwLockValue>,
4637    G: for<'r> Fn(&'r InnerValue) -> &'r SubValue,
4638{
4639    /// Apply the composed keypath chain to a container (read lock, async)
4640    pub async fn get<Callback>(self, container: &Root, callback: Callback) -> Option<()>
4641    where
4642        Callback: FnOnce(&SubValue) -> (),
4643    {
4644        if let Some(arc_rwlock_ref) = self.outer_keypath.get(container) {
4645            let arc_rwlock_ref = arc_rwlock_ref.borrow();
4646            let guard = arc_rwlock_ref.read().await;
4647            let value = self.inner_keypath.get(&*guard);
4648            callback(value);
4649            Some(())
4650        } else {
4651            None
4652        }
4653    }
4654
4655    /// Chain with another readable keypath through another level
4656    pub fn then<NextValue, H>(
4657        self,
4658        next: KeyPath<SubValue, NextValue, H>,
4659    ) -> OptionalArcTokioRwLockKeyPathChain<
4660        Root,
4661        RwLockValue,
4662        InnerValue,
4663        NextValue,
4664        F,
4665        impl for<'r> Fn(&'r InnerValue) -> &'r NextValue + 'static,
4666    >
4667    where
4668        H: for<'r> Fn(&'r SubValue) -> &'r NextValue,
4669        G: 'static,
4670        H: 'static,
4671        InnerValue: 'static,
4672        SubValue: 'static,
4673        NextValue: 'static,
4674    {
4675        let first = self.inner_keypath;
4676        let second = next;
4677
4678        let composed = KeyPath::new(move |inner: &InnerValue| {
4679            let sub = first.get(inner);
4680            second.get(sub)
4681        });
4682
4683        OptionalArcTokioRwLockKeyPathChain {
4684            outer_keypath: self.outer_keypath,
4685            inner_keypath: composed,
4686        }
4687    }
4688
4689    /// Chain with an optional readable keypath through another level
4690    pub fn chain_optional<NextValue, H>(
4691        self,
4692        next: OptionalKeyPath<SubValue, NextValue, H>,
4693    ) -> OptionalArcTokioRwLockOptionalKeyPathChain<
4694        Root,
4695        RwLockValue,
4696        InnerValue,
4697        NextValue,
4698        F,
4699        impl for<'r> Fn(&'r InnerValue) -> Option<&'r NextValue> + 'static,
4700    >
4701    where
4702        H: for<'r> Fn(&'r SubValue) -> Option<&'r NextValue>,
4703        G: 'static,
4704        H: 'static,
4705        InnerValue: 'static,
4706        SubValue: 'static,
4707        NextValue: 'static,
4708    {
4709        let first = self.inner_keypath;
4710        let second = next;
4711
4712        let composed = OptionalKeyPath::new(move |inner: &InnerValue| {
4713            let sub = first.get(inner);
4714            second.get(sub)
4715        });
4716
4717        OptionalArcTokioRwLockOptionalKeyPathChain {
4718            outer_keypath: self.outer_keypath,
4719            inner_keypath: composed,
4720        }
4721    }
4722}
4723
4724/// A composed optional async keypath chain from optional keypath through Arc<tokio::sync::RwLock<T>>
4725#[cfg(feature = "tokio")]
4726pub struct OptionalArcTokioRwLockOptionalKeyPathChain<Root, RwLockValue, InnerValue, SubValue, F, G>
4727where
4728    RwLockValue: std::borrow::Borrow<Arc<TokioRwLock<InnerValue>>>,
4729    F: for<'r> Fn(&'r Root) -> Option<&'r RwLockValue>,
4730    G: for<'r> Fn(&'r InnerValue) -> Option<&'r SubValue>,
4731{
4732    outer_keypath: OptionalKeyPath<Root, RwLockValue, F>,
4733    inner_keypath: OptionalKeyPath<InnerValue, SubValue, G>,
4734}
4735
4736#[cfg(feature = "tokio")]
4737impl<Root, RwLockValue, InnerValue, SubValue, F, G>
4738    OptionalArcTokioRwLockOptionalKeyPathChain<Root, RwLockValue, InnerValue, SubValue, F, G>
4739where
4740    RwLockValue: std::borrow::Borrow<Arc<TokioRwLock<InnerValue>>>,
4741    F: for<'r> Fn(&'r Root) -> Option<&'r RwLockValue>,
4742    G: for<'r> Fn(&'r InnerValue) -> Option<&'r SubValue>,
4743{
4744    /// Apply the composed keypath chain to a container (read lock, async)
4745    pub async fn get<Callback>(self, container: &Root, callback: Callback) -> Option<()>
4746    where
4747        Callback: FnOnce(&SubValue) -> (),
4748    {
4749        if let Some(arc_rwlock_ref) = self.outer_keypath.get(container) {
4750            let arc_rwlock_ref = arc_rwlock_ref.borrow();
4751            let guard = arc_rwlock_ref.read().await;
4752            self.inner_keypath.get(&*guard).map(|value| callback(value))
4753        } else {
4754            None
4755        }
4756    }
4757
4758    /// Chain with another readable keypath through another level
4759    pub fn then<NextValue, H>(
4760        self,
4761        next: KeyPath<SubValue, NextValue, H>,
4762    ) -> OptionalArcTokioRwLockOptionalKeyPathChain<
4763        Root,
4764        RwLockValue,
4765        InnerValue,
4766        NextValue,
4767        F,
4768        impl for<'r> Fn(&'r InnerValue) -> Option<&'r NextValue> + 'static,
4769    >
4770    where
4771        H: for<'r> Fn(&'r SubValue) -> &'r NextValue,
4772        G: 'static,
4773        H: 'static,
4774        InnerValue: 'static,
4775        SubValue: 'static,
4776        NextValue: 'static,
4777    {
4778        let first = self.inner_keypath;
4779        let second = next;
4780
4781        let composed = OptionalKeyPath::new(move |inner: &InnerValue| {
4782            first.get(inner).map(|sub| second.get(sub))
4783        });
4784
4785        OptionalArcTokioRwLockOptionalKeyPathChain {
4786            outer_keypath: self.outer_keypath,
4787            inner_keypath: composed,
4788        }
4789    }
4790
4791    /// Chain with an optional readable keypath through another level
4792    pub fn chain_optional<NextValue, H>(
4793        self,
4794        next: OptionalKeyPath<SubValue, NextValue, H>,
4795    ) -> OptionalArcTokioRwLockOptionalKeyPathChain<
4796        Root,
4797        RwLockValue,
4798        InnerValue,
4799        NextValue,
4800        F,
4801        impl for<'r> Fn(&'r InnerValue) -> Option<&'r NextValue> + 'static,
4802    >
4803    where
4804        H: for<'r> Fn(&'r SubValue) -> Option<&'r NextValue>,
4805        G: 'static,
4806        H: 'static,
4807        InnerValue: 'static,
4808        SubValue: 'static,
4809        NextValue: 'static,
4810    {
4811        let first = self.inner_keypath;
4812        let second = next;
4813
4814        let composed = OptionalKeyPath::new(move |inner: &InnerValue| {
4815            first.get(inner).and_then(|sub| second.get(sub))
4816        });
4817
4818        OptionalArcTokioRwLockOptionalKeyPathChain {
4819            outer_keypath: self.outer_keypath,
4820            inner_keypath: composed,
4821        }
4822    }
4823}
4824
4825/// A composed writable async keypath chain from optional keypath through Arc<tokio::sync::RwLock<T>>
4826#[cfg(feature = "tokio")]
4827pub struct OptionalArcTokioRwLockWritableKeyPathChain<Root, RwLockValue, InnerValue, SubValue, F, G>
4828where
4829    RwLockValue: std::borrow::Borrow<Arc<TokioRwLock<InnerValue>>>,
4830    F: for<'r> Fn(&'r Root) -> Option<&'r RwLockValue>,
4831    G: for<'r> Fn(&'r mut InnerValue) -> &'r mut SubValue,
4832{
4833    outer_keypath: OptionalKeyPath<Root, RwLockValue, F>,
4834    inner_keypath: WritableKeyPath<InnerValue, SubValue, G>,
4835}
4836
4837#[cfg(feature = "tokio")]
4838impl<Root, RwLockValue, InnerValue, SubValue, F, G>
4839    OptionalArcTokioRwLockWritableKeyPathChain<Root, RwLockValue, InnerValue, SubValue, F, G>
4840where
4841    RwLockValue: std::borrow::Borrow<Arc<TokioRwLock<InnerValue>>>,
4842    F: for<'r> Fn(&'r Root) -> Option<&'r RwLockValue>,
4843    G: for<'r> Fn(&'r mut InnerValue) -> &'r mut SubValue,
4844{
4845    /// Apply the composed keypath chain to a container with mutable access (write lock, async)
4846    pub async fn get_mut<Callback, R>(self, container: &Root, callback: Callback) -> Option<R>
4847    where
4848        Callback: FnOnce(&mut SubValue) -> R,
4849    {
4850        if let Some(arc_rwlock_ref) = self.outer_keypath.get(container) {
4851            let arc_rwlock_ref = arc_rwlock_ref.borrow();
4852            let mut guard = arc_rwlock_ref.write().await;
4853            let value_ref = self.inner_keypath.get_mut(&mut *guard);
4854            Some(callback(value_ref))
4855        } else {
4856            None
4857        }
4858    }
4859
4860    /// Chain with another writable keypath through another level
4861    pub fn then<NextValue, H>(
4862        self,
4863        next: WritableKeyPath<SubValue, NextValue, H>,
4864    ) -> OptionalArcTokioRwLockWritableKeyPathChain<
4865        Root,
4866        RwLockValue,
4867        InnerValue,
4868        NextValue,
4869        F,
4870        impl for<'r> Fn(&'r mut InnerValue) -> &'r mut NextValue + 'static,
4871    >
4872    where
4873        H: for<'r> Fn(&'r mut SubValue) -> &'r mut NextValue,
4874        G: 'static,
4875        H: 'static,
4876        InnerValue: 'static,
4877        SubValue: 'static,
4878        NextValue: 'static,
4879    {
4880        let first = self.inner_keypath;
4881        let second = next;
4882
4883        let composed = WritableKeyPath::new(move |inner: &mut InnerValue| {
4884            let sub = first.get_mut(inner);
4885            second.get_mut(sub)
4886        });
4887
4888        OptionalArcTokioRwLockWritableKeyPathChain {
4889            outer_keypath: self.outer_keypath,
4890            inner_keypath: composed,
4891        }
4892    }
4893
4894    /// Chain with an optional writable keypath through another level
4895    pub fn chain_optional<NextValue, H>(
4896        self,
4897        next: WritableOptionalKeyPath<SubValue, NextValue, H>,
4898    ) -> OptionalArcTokioRwLockWritableOptionalKeyPathChain<
4899        Root,
4900        RwLockValue,
4901        InnerValue,
4902        NextValue,
4903        F,
4904        impl for<'r> Fn(&'r mut InnerValue) -> Option<&'r mut NextValue> + 'static,
4905    >
4906    where
4907        H: for<'r> Fn(&'r mut SubValue) -> Option<&'r mut NextValue>,
4908        G: 'static,
4909        H: 'static,
4910        InnerValue: 'static,
4911        SubValue: 'static,
4912        NextValue: 'static,
4913    {
4914        let first = self.inner_keypath;
4915        let second = next;
4916
4917        let composed = WritableOptionalKeyPath::new(move |inner: &mut InnerValue| {
4918            let sub = first.get_mut(inner);
4919            second.get_mut(sub)
4920        });
4921
4922        OptionalArcTokioRwLockWritableOptionalKeyPathChain {
4923            outer_keypath: self.outer_keypath,
4924            inner_keypath: composed,
4925        }
4926    }
4927}
4928
4929/// A composed writable optional async keypath chain from optional keypath through Arc<tokio::sync::RwLock<T>>
4930#[cfg(feature = "tokio")]
4931pub struct OptionalArcTokioRwLockWritableOptionalKeyPathChain<
4932    Root,
4933    RwLockValue,
4934    InnerValue,
4935    SubValue,
4936    F,
4937    G,
4938> where
4939    RwLockValue: std::borrow::Borrow<Arc<TokioRwLock<InnerValue>>>,
4940    F: for<'r> Fn(&'r Root) -> Option<&'r RwLockValue>,
4941    G: for<'r> Fn(&'r mut InnerValue) -> Option<&'r mut SubValue>,
4942{
4943    outer_keypath: OptionalKeyPath<Root, RwLockValue, F>,
4944    inner_keypath: WritableOptionalKeyPath<InnerValue, SubValue, G>,
4945}
4946
4947#[cfg(feature = "tokio")]
4948impl<Root, RwLockValue, InnerValue, SubValue, F, G>
4949    OptionalArcTokioRwLockWritableOptionalKeyPathChain<
4950        Root,
4951        RwLockValue,
4952        InnerValue,
4953        SubValue,
4954        F,
4955        G,
4956    >
4957where
4958    RwLockValue: std::borrow::Borrow<Arc<TokioRwLock<InnerValue>>>,
4959    F: for<'r> Fn(&'r Root) -> Option<&'r RwLockValue>,
4960    G: for<'r> Fn(&'r mut InnerValue) -> Option<&'r mut SubValue>,
4961{
4962    /// Apply the composed keypath chain to a container with mutable access (write lock, if value exists, async)
4963    pub async fn get_mut<Callback, R>(self, container: &Root, callback: Callback) -> Option<R>
4964    where
4965        Callback: FnOnce(&mut SubValue) -> R,
4966    {
4967        if let Some(arc_rwlock_ref) = self.outer_keypath.get(container) {
4968            let arc_rwlock_ref = arc_rwlock_ref.borrow();
4969            let mut guard = arc_rwlock_ref.write().await;
4970            self.inner_keypath
4971                .get_mut(&mut *guard)
4972                .map(|value_ref| callback(value_ref))
4973        } else {
4974            None
4975        }
4976    }
4977
4978    /// Chain with another writable keypath through another level
4979    pub fn then<NextValue, H>(
4980        self,
4981        next: WritableKeyPath<SubValue, NextValue, H>,
4982    ) -> OptionalArcTokioRwLockWritableOptionalKeyPathChain<
4983        Root,
4984        RwLockValue,
4985        InnerValue,
4986        NextValue,
4987        F,
4988        impl for<'r> Fn(&'r mut InnerValue) -> Option<&'r mut NextValue> + 'static,
4989    >
4990    where
4991        H: for<'r> Fn(&'r mut SubValue) -> &'r mut NextValue,
4992        G: 'static,
4993        H: 'static,
4994        InnerValue: 'static,
4995        SubValue: 'static,
4996        NextValue: 'static,
4997    {
4998        let first = self.inner_keypath;
4999        let second = next;
5000
5001        let composed = WritableOptionalKeyPath::new(move |inner: &mut InnerValue| {
5002            first.get_mut(inner).map(|sub| second.get_mut(sub))
5003        });
5004
5005        OptionalArcTokioRwLockWritableOptionalKeyPathChain {
5006            outer_keypath: self.outer_keypath,
5007            inner_keypath: composed,
5008        }
5009    }
5010
5011    /// Chain with an optional writable keypath through another level
5012    pub fn chain_optional<NextValue, H>(
5013        self,
5014        next: WritableOptionalKeyPath<SubValue, NextValue, H>,
5015    ) -> OptionalArcTokioRwLockWritableOptionalKeyPathChain<
5016        Root,
5017        RwLockValue,
5018        InnerValue,
5019        NextValue,
5020        F,
5021        impl for<'r> Fn(&'r mut InnerValue) -> Option<&'r mut NextValue> + 'static,
5022    >
5023    where
5024        H: for<'r> Fn(&'r mut SubValue) -> Option<&'r mut NextValue>,
5025        G: 'static,
5026        H: 'static,
5027        InnerValue: 'static,
5028        SubValue: 'static,
5029        NextValue: 'static,
5030    {
5031        let first = self.inner_keypath;
5032        let second = next;
5033
5034        let composed = WritableOptionalKeyPath::new(move |inner: &mut InnerValue| {
5035            first.get_mut(inner).and_then(|sub| second.get_mut(sub))
5036        });
5037
5038        OptionalArcTokioRwLockWritableOptionalKeyPathChain {
5039            outer_keypath: self.outer_keypath,
5040            inner_keypath: composed,
5041        }
5042    }
5043}
5044
5045#[cfg(feature = "tagged")]
5046use tagged_core::Tagged;
5047
5048// ========== HELPER MACROS FOR KEYPATH CREATION ==========
5049
5050/// Macro to create a `KeyPath` (readable, non-optional)
5051///
5052/// # Examples
5053///
5054/// ```rust
5055/// use rust_keypaths::keypath;
5056///
5057/// struct User { name: String, address: Address }
5058/// struct Address { street: String }
5059///
5060/// // Using a closure with type annotation
5061/// let kp = keypath!(|u: &User| &u.name);
5062///
5063/// // Nested field access
5064/// let kp = keypath!(|u: &User| &u.address.street);
5065///
5066/// // Or with automatic type inference
5067/// let kp = keypath!(|u| &u.name);
5068/// ```
5069#[macro_export]
5070macro_rules! keypath {
5071    // Accept a closure directly
5072    ($closure:expr) => {
5073        $crate::KeyPath::new($closure)
5074    };
5075}
5076
5077/// Macro to create an `OptionalKeyPath` (readable, optional)
5078///
5079/// # Examples
5080///
5081/// ```rust
5082/// use rust_keypaths::opt_keypath;
5083///
5084/// struct User { metadata: Option<String>, address: Option<Address> }
5085/// struct Address { street: String }
5086///
5087/// // Using a closure with type annotation
5088/// let kp = opt_keypath!(|u: &User| u.metadata.as_ref());
5089///
5090/// // Nested field access through Option
5091/// let kp = opt_keypath!(|u: &User| u.address.as_ref().map(|a| &a.street));
5092///
5093/// // Or with automatic type inference
5094/// let kp = opt_keypath!(|u| u.metadata.as_ref());
5095/// ```
5096#[macro_export]
5097macro_rules! opt_keypath {
5098    // Accept a closure directly
5099    ($closure:expr) => {
5100        $crate::OptionalKeyPath::new($closure)
5101    };
5102}
5103
5104/// Macro to create a `WritableKeyPath` (writable, non-optional)
5105///
5106/// # Examples
5107///
5108/// ```rust
5109/// use rust_keypaths::writable_keypath;
5110///
5111/// struct User { name: String, address: Address }
5112/// struct Address { street: String }
5113///
5114/// // Using a closure with type annotation
5115/// let kp = writable_keypath!(|u: &mut User| &mut u.name);
5116///
5117/// // Nested field access
5118/// let kp = writable_keypath!(|u: &mut User| &mut u.address.street);
5119///
5120/// // Or with automatic type inference
5121/// let kp = writable_keypath!(|u| &mut u.name);
5122/// ```
5123#[macro_export]
5124macro_rules! writable_keypath {
5125    // Accept a closure directly
5126    ($closure:expr) => {
5127        $crate::WritableKeyPath::new($closure)
5128    };
5129}
5130
5131/// Macro to create a `WritableOptionalKeyPath` (writable, optional)
5132///
5133/// # Examples
5134///
5135/// ```rust
5136/// use rust_keypaths::writable_opt_keypath;
5137///
5138/// struct User { metadata: Option<String>, address: Option<Address> }
5139/// struct Address { street: String }
5140///
5141/// // Using a closure with type annotation
5142/// let kp = writable_opt_keypath!(|u: &mut User| u.metadata.as_mut());
5143///
5144/// // Nested field access through Option
5145/// let kp = writable_opt_keypath!(|u: &mut User| u.address.as_mut().map(|a| &mut a.street));
5146///
5147/// // Or with automatic type inference
5148/// let kp = writable_opt_keypath!(|u| u.metadata.as_mut());
5149/// ```
5150#[macro_export]
5151macro_rules! writable_opt_keypath {
5152    // Accept a closure directly
5153    ($closure:expr) => {
5154        $crate::WritableOptionalKeyPath::new($closure)
5155    };
5156}
5157// ========== BASE KEYPATH TYPES ==========
5158
5159// Identity getters for keypath identity() constructors (fn pointers for concrete F type).
5160fn identity_ref<Root>(r: &Root) -> &Root {
5161    r
5162}
5163fn identity_opt_ref<Root>(r: &Root) -> Option<&Root> {
5164    Some(r)
5165}
5166fn identity_mut<Root>(r: &mut Root) -> &mut Root {
5167    r
5168}
5169fn identity_opt_mut<Root>(r: &mut Root) -> Option<&mut Root> {
5170    Some(r)
5171}
5172fn identity_value<E>(e: E) -> E {
5173    e
5174}
5175
5176// Base KeyPath
5177#[derive(Clone)]
5178pub struct KeyPath<Root, Value, F>
5179where
5180    F: for<'r> Fn(&'r Root) -> &'r Value,
5181{
5182    getter: F,
5183    _phantom: PhantomData<(Root, Value)>,
5184}
5185
5186impl<Root, Value, F> fmt::Display for KeyPath<Root, Value, F>
5187where
5188    F: for<'r> Fn(&'r Root) -> &'r Value,
5189{
5190    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
5191        let root_name = std::any::type_name::<Root>();
5192        let value_name = std::any::type_name::<Value>();
5193        // Simplify type names by removing module paths for cleaner output
5194        let root_short = root_name.split("::").last().unwrap_or(root_name);
5195        let value_short = value_name.split("::").last().unwrap_or(value_name);
5196        write!(f, "KeyPath<{} -> {}>", root_short, value_short)
5197    }
5198}
5199
5200impl<Root, Value, F> fmt::Debug for KeyPath<Root, Value, F>
5201where
5202    F: for<'r> Fn(&'r Root) -> &'r Value,
5203{
5204    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
5205        fmt::Display::fmt(self, f)
5206    }
5207}
5208
5209impl<Root> KeyPath<Root, Root, fn(&Root) -> &Root> {
5210    /// Identity keypath: projects `Root` to itself (`get(root) == root`).
5211    pub fn identity() -> Self {
5212        KeyPath {
5213            getter: identity_ref::<Root>,
5214            _phantom: PhantomData,
5215        }
5216    }
5217}
5218
5219impl<Root, Value, F> KeyPath<Root, Value, F>
5220where
5221    F: for<'r> Fn(&'r Root) -> &'r Value,
5222{
5223    pub fn new(getter: F) -> Self {
5224        Self {
5225            getter,
5226            _phantom: PhantomData,
5227        }
5228    }
5229
5230    pub fn get<'r>(&self, root: &'r Root) -> &'r Value {
5231        (self.getter)(root)
5232    }
5233
5234    /// Higher-order function: map the value reference through a function.
5235    /// Returns a new `KeyPath<Root, U, _>` that gets the value and applies `f` to the reference.
5236    ///
5237    /// # Example
5238    /// ```rust
5239    /// use rust_keypaths::KeyPath;
5240    /// let kp = KeyPath::new(|s: &String| s);
5241    /// let len_kp = kp.map(|s: &String| &s.len());
5242    /// let s = "hello".to_string();
5243    /// assert_eq!(*len_kp.get(&s), 5);
5244    /// ```
5245    pub fn map<U, G>(self, f: G) -> KeyPath<Root, U, impl for<'r> Fn(&'r Root) -> &'r U>
5246    where
5247        G: for<'r> Fn(&'r Value) -> &'r U,
5248        F: 'static,
5249        G: 'static,
5250        Root: 'static,
5251        Value: 'static,
5252    {
5253        let getter = self.getter;
5254        KeyPath {
5255            getter: move |root| f(getter(root)),
5256            _phantom: PhantomData,
5257        }
5258    }
5259
5260    /// Map through a function that returns `Option<&U>`, producing an `OptionalKeyPath`.
5261    /// Use when the projection may fail (e.g. `|v: &Vec<T>| v.first()`).
5262    ///
5263    /// # Example
5264    /// ```rust,ignore
5265    /// let first = struct::vec_field_r().map_optional(|x: &Vec<String>| x.first());
5266    /// let opt: Option<&String> = first.get(&value);
5267    /// ```
5268    pub fn map_optional<U, G>(
5269        self,
5270        f: G,
5271    ) -> OptionalKeyPath<Root, U, impl for<'r> Fn(&'r Root) -> Option<&'r U>>
5272    where
5273        G: for<'r> Fn(&'r Value) -> Option<&'r U>,
5274        F: 'static,
5275        G: 'static,
5276        Root: 'static,
5277        Value: 'static,
5278    {
5279        let getter = self.getter;
5280        OptionalKeyPath {
5281            getter: move |root| f(getter(root)),
5282            _phantom: PhantomData,
5283        }
5284    }
5285
5286    /// Chain this keypath with an inner keypath through Arc<Mutex<T>> - functional style
5287    /// Compose first, then apply container at get() time
5288    ///
5289    /// # Example
5290    /// ```rust
5291    /// let container = ContainerTest { mutex_data: Arc::new(Mutex::new(SomeStruct { data: "test".to_string() })) };
5292    ///
5293    /// // Functional style: compose first, apply container at get()
5294    /// ContainerTest::mutex_data_r()
5295    ///     .chain_arc_mutex_at_kp(SomeStruct::data_r())
5296    ///     .get(&container, |value| println!("Data: {}", value));
5297    /// ```
5298    pub fn chain_arc_mutex_at_kp<InnerValue, SubValue, G>(
5299        self,
5300        inner_keypath: KeyPath<InnerValue, SubValue, G>,
5301    ) -> ArcMutexKeyPathChain<Root, Value, InnerValue, SubValue, F, G>
5302    where
5303        G: for<'r> Fn(&'r InnerValue) -> &'r SubValue,
5304    {
5305        ArcMutexKeyPathChain {
5306            outer_keypath: self,
5307            inner_keypath,
5308        }
5309    }
5310
5311    /// Chain this keypath with an optional inner keypath through Arc<Mutex<T>> - functional style
5312    /// Compose first, then apply container at get() time
5313    ///
5314    /// # Example
5315    /// ```rust
5316    /// let container = ContainerTest { mutex_data: Arc::new(Mutex::new(SomeStruct { optional_field: Some("test".to_string()) })) };
5317    ///
5318    /// // Functional style: compose first, apply container at get()
5319    /// ContainerTest::mutex_data_r()
5320    ///     .chain_arc_mutex_optional_at_kp(SomeStruct::optional_field_fr())
5321    ///     .get(&container, |value| println!("Value: {}", value));
5322    /// ```
5323    pub fn chain_arc_mutex_optional_at_kp<InnerValue, SubValue, G>(
5324        self,
5325        inner_keypath: OptionalKeyPath<InnerValue, SubValue, G>,
5326    ) -> ArcMutexOptionalKeyPathChain<Root, Value, InnerValue, SubValue, F, G>
5327    where
5328        G: for<'r> Fn(&'r InnerValue) -> Option<&'r SubValue>,
5329    {
5330        ArcMutexOptionalKeyPathChain {
5331            outer_keypath: self,
5332            inner_keypath,
5333        }
5334    }
5335
5336    /// Chain this keypath with an inner keypath through Arc<RwLock<T>> - functional style
5337    /// Compose first, then apply container at get() time (uses read lock)
5338    ///
5339    /// # Example
5340    /// ```rust
5341    /// let container = ContainerTest { rwlock_data: Arc::new(RwLock::new(SomeStruct { data: "test".to_string() })) };
5342    ///
5343    /// // Functional style: compose first, apply container at get()
5344    /// ContainerTest::rwlock_data_r()
5345    ///     .chain_arc_rwlock_at_kp(SomeStruct::data_r())
5346    ///     .get(&container, |value| println!("Data: {}", value));
5347    /// ```
5348    pub fn chain_arc_rwlock_at_kp<InnerValue, SubValue, G>(
5349        self,
5350        inner_keypath: KeyPath<InnerValue, SubValue, G>,
5351    ) -> ArcRwLockKeyPathChain<Root, Value, InnerValue, SubValue, F, G>
5352    where
5353        G: for<'r> Fn(&'r InnerValue) -> &'r SubValue,
5354    {
5355        ArcRwLockKeyPathChain {
5356            outer_keypath: self,
5357            inner_keypath,
5358        }
5359    }
5360
5361    /// Chain this keypath with an optional inner keypath through Arc<RwLock<T>> - functional style
5362    /// Compose first, then apply container at get() time (uses read lock)
5363    ///
5364    /// # Example
5365    /// ```rust
5366    /// let container = ContainerTest { rwlock_data: Arc::new(RwLock::new(SomeStruct { optional_field: Some("test".to_string()) })) };
5367    ///
5368    /// // Functional style: compose first, apply container at get()
5369    /// ContainerTest::rwlock_data_r()
5370    ///     .chain_arc_rwlock_optional_at_kp(SomeStruct::optional_field_fr())
5371    ///     .get(&container, |value| println!("Value: {}", value));
5372    /// ```
5373    pub fn chain_arc_rwlock_optional_at_kp<InnerValue, SubValue, G>(
5374        self,
5375        inner_keypath: OptionalKeyPath<InnerValue, SubValue, G>,
5376    ) -> ArcRwLockOptionalKeyPathChain<Root, Value, InnerValue, SubValue, F, G>
5377    where
5378        G: for<'r> Fn(&'r InnerValue) -> Option<&'r SubValue>,
5379    {
5380        ArcRwLockOptionalKeyPathChain {
5381            outer_keypath: self,
5382            inner_keypath,
5383        }
5384    }
5385
5386    /// Chain this keypath with a writable inner keypath through Arc<Mutex<T>> - functional style
5387    /// Compose first, then apply container at get_mut() time
5388    ///
5389    /// # Example
5390    /// ```rust
5391    /// ContainerTest::mutex_data_r()
5392    ///     .chain_arc_mutex_writable_at_kp(SomeStruct::data_w())
5393    ///     .get_mut(&container, |value| *value = "new".to_string());
5394    /// ```
5395    pub fn chain_arc_mutex_writable_at_kp<InnerValue, SubValue, G>(
5396        self,
5397        inner_keypath: WritableKeyPath<InnerValue, SubValue, G>,
5398    ) -> ArcMutexWritableKeyPathChain<Root, Value, InnerValue, SubValue, F, G>
5399    where
5400        G: for<'r> Fn(&'r mut InnerValue) -> &'r mut SubValue,
5401    {
5402        ArcMutexWritableKeyPathChain {
5403            outer_keypath: self,
5404            inner_keypath,
5405        }
5406    }
5407
5408    /// Chain this keypath with a writable optional inner keypath through Arc<Mutex<T>> - functional style
5409    /// Compose first, then apply container at get_mut() time
5410    ///
5411    /// # Example
5412    /// ```rust
5413    /// ContainerTest::mutex_data_r()
5414    ///     .chain_arc_mutex_writable_optional_at_kp(SomeStruct::optional_field_fw())
5415    ///     .get_mut(&container, |value| *value = "new".to_string());
5416    /// ```
5417    pub fn chain_arc_mutex_writable_optional_at_kp<InnerValue, SubValue, G>(
5418        self,
5419        inner_keypath: WritableOptionalKeyPath<InnerValue, SubValue, G>,
5420    ) -> ArcMutexWritableOptionalKeyPathChain<Root, Value, InnerValue, SubValue, F, G>
5421    where
5422        G: for<'r> Fn(&'r mut InnerValue) -> Option<&'r mut SubValue>,
5423    {
5424        ArcMutexWritableOptionalKeyPathChain {
5425            outer_keypath: self,
5426            inner_keypath,
5427        }
5428    }
5429
5430    /// Chain this keypath with a writable inner keypath through Arc<RwLock<T>> - functional style
5431    /// Compose first, then apply container at get_mut() time (uses write lock)
5432    ///
5433    /// # Example
5434    /// ```rust
5435    /// ContainerTest::rwlock_data_r()
5436    ///     .chain_arc_rwlock_writable_at_kp(SomeStruct::data_w())
5437    ///     .get_mut(&container, |value| *value = "new".to_string());
5438    /// ```
5439    pub fn chain_arc_rwlock_writable_at_kp<InnerValue, SubValue, G>(
5440        self,
5441        inner_keypath: WritableKeyPath<InnerValue, SubValue, G>,
5442    ) -> ArcRwLockWritableKeyPathChain<Root, Value, InnerValue, SubValue, F, G>
5443    where
5444        G: for<'r> Fn(&'r mut InnerValue) -> &'r mut SubValue,
5445    {
5446        ArcRwLockWritableKeyPathChain {
5447            outer_keypath: self,
5448            inner_keypath,
5449        }
5450    }
5451
5452    /// Chain this keypath with a writable optional inner keypath through Arc<RwLock<T>> - functional style
5453    /// Compose first, then apply container at get_mut() time (uses write lock)
5454    ///
5455    /// # Example
5456    /// ```rust
5457    /// ContainerTest::rwlock_data_r()
5458    ///     .chain_arc_rwlock_writable_optional_at_kp(SomeStruct::optional_field_fw())
5459    ///     .get_mut(&container, |value| *value = "new".to_string());
5460    /// ```
5461    pub fn chain_arc_rwlock_writable_optional_at_kp<InnerValue, SubValue, G>(
5462        self,
5463        inner_keypath: WritableOptionalKeyPath<InnerValue, SubValue, G>,
5464    ) -> ArcRwLockWritableOptionalKeyPathChain<Root, Value, InnerValue, SubValue, F, G>
5465    where
5466        G: for<'r> Fn(&'r mut InnerValue) -> Option<&'r mut SubValue>,
5467    {
5468        ArcRwLockWritableOptionalKeyPathChain {
5469            outer_keypath: self,
5470            inner_keypath,
5471        }
5472    }
5473
5474    #[cfg(feature = "tokio")]
5475    /// Chain this keypath with an inner keypath through Arc<tokio::sync::Mutex<T>> - functional style (async)
5476    /// Compose first, then apply container at get() time
5477    pub fn chain_arc_tokio_mutex_at_kp<InnerValue, SubValue, G>(
5478        self,
5479        inner_keypath: KeyPath<InnerValue, SubValue, G>,
5480    ) -> ArcTokioMutexKeyPathChain<Root, Value, InnerValue, SubValue, F, G>
5481    where
5482        G: for<'r> Fn(&'r InnerValue) -> &'r SubValue,
5483    {
5484        ArcTokioMutexKeyPathChain {
5485            outer_keypath: self,
5486            inner_keypath,
5487        }
5488    }
5489
5490    #[cfg(feature = "tokio")]
5491    /// Chain this keypath with an optional inner keypath through Arc<tokio::sync::Mutex<T>> - functional style (async)
5492    pub fn chain_arc_tokio_mutex_optional_at_kp<InnerValue, SubValue, G>(
5493        self,
5494        inner_keypath: OptionalKeyPath<InnerValue, SubValue, G>,
5495    ) -> ArcTokioMutexOptionalKeyPathChain<Root, Value, InnerValue, SubValue, F, G>
5496    where
5497        Value: std::borrow::Borrow<Arc<tokio::sync::Mutex<InnerValue>>>,
5498        G: for<'r> Fn(&'r InnerValue) -> Option<&'r SubValue>,
5499    {
5500        ArcTokioMutexOptionalKeyPathChain {
5501            outer_keypath: self,
5502            inner_keypath,
5503        }
5504    }
5505
5506    #[cfg(feature = "tokio")]
5507    /// Chain this keypath with a writable inner keypath through Arc<tokio::sync::Mutex<T>> - functional style (async)
5508    pub fn chain_arc_tokio_mutex_writable_at_kp<InnerValue, SubValue, G>(
5509        self,
5510        inner_keypath: WritableKeyPath<InnerValue, SubValue, G>,
5511    ) -> ArcTokioMutexWritableKeyPathChain<Root, Value, InnerValue, SubValue, F, G>
5512    where
5513        Value: std::borrow::Borrow<Arc<tokio::sync::Mutex<InnerValue>>>,
5514        G: for<'r> Fn(&'r mut InnerValue) -> &'r mut SubValue,
5515    {
5516        ArcTokioMutexWritableKeyPathChain {
5517            outer_keypath: self,
5518            inner_keypath,
5519        }
5520    }
5521
5522    #[cfg(feature = "tokio")]
5523    /// Chain this keypath with a writable optional inner keypath through Arc<tokio::sync::Mutex<T>> - functional style (async)
5524    pub fn chain_arc_tokio_mutex_writable_optional_at_kp<InnerValue, SubValue, G>(
5525        self,
5526        inner_keypath: WritableOptionalKeyPath<InnerValue, SubValue, G>,
5527    ) -> ArcTokioMutexWritableOptionalKeyPathChain<Root, Value, InnerValue, SubValue, F, G>
5528    where
5529        Value: std::borrow::Borrow<Arc<tokio::sync::Mutex<InnerValue>>>,
5530        G: for<'r> Fn(&'r mut InnerValue) -> Option<&'r mut SubValue>,
5531    {
5532        ArcTokioMutexWritableOptionalKeyPathChain {
5533            outer_keypath: self,
5534            inner_keypath,
5535        }
5536    }
5537
5538    #[cfg(feature = "tokio")]
5539    /// Chain this keypath with an inner keypath through Arc<tokio::sync::RwLock<T>> - functional style (async, read lock)
5540    pub fn chain_arc_tokio_rwlock_at_kp<InnerValue, SubValue, G>(
5541        self,
5542        inner_keypath: KeyPath<InnerValue, SubValue, G>,
5543    ) -> ArcTokioRwLockKeyPathChain<Root, Value, InnerValue, SubValue, F, G>
5544    where
5545        Value: std::borrow::Borrow<Arc<tokio::sync::RwLock<InnerValue>>>,
5546        G: for<'r> Fn(&'r InnerValue) -> &'r SubValue,
5547    {
5548        ArcTokioRwLockKeyPathChain {
5549            outer_keypath: self,
5550            inner_keypath,
5551        }
5552    }
5553
5554    #[cfg(feature = "tokio")]
5555    /// Chain this keypath with an optional inner keypath through Arc<tokio::sync::RwLock<T>> - functional style (async, read lock)
5556    pub fn chain_arc_tokio_rwlock_optional_at_kp<InnerValue, SubValue, G>(
5557        self,
5558        inner_keypath: OptionalKeyPath<InnerValue, SubValue, G>,
5559    ) -> ArcTokioRwLockOptionalKeyPathChain<Root, Value, InnerValue, SubValue, F, G>
5560    where
5561        Value: std::borrow::Borrow<Arc<tokio::sync::RwLock<InnerValue>>>,
5562        G: for<'r> Fn(&'r InnerValue) -> Option<&'r SubValue>,
5563    {
5564        ArcTokioRwLockOptionalKeyPathChain {
5565            outer_keypath: self,
5566            inner_keypath,
5567        }
5568    }
5569
5570    #[cfg(feature = "tokio")]
5571    /// Chain this keypath with a writable inner keypath through Arc<tokio::sync::RwLock<T>> - functional style (async, write lock)
5572    pub fn chain_arc_tokio_rwlock_writable_at_kp<InnerValue, SubValue, G>(
5573        self,
5574        inner_keypath: WritableKeyPath<InnerValue, SubValue, G>,
5575    ) -> ArcTokioRwLockWritableKeyPathChain<Root, Value, InnerValue, SubValue, F, G>
5576    where
5577        Value: std::borrow::Borrow<Arc<tokio::sync::RwLock<InnerValue>>>,
5578        G: for<'r> Fn(&'r mut InnerValue) -> &'r mut SubValue,
5579    {
5580        ArcTokioRwLockWritableKeyPathChain {
5581            outer_keypath: self,
5582            inner_keypath,
5583        }
5584    }
5585
5586    #[cfg(feature = "tokio")]
5587    /// Chain this keypath with a writable optional inner keypath through Arc<tokio::sync::RwLock<T>> - functional style (async, write lock)
5588    pub fn chain_arc_tokio_rwlock_writable_optional_at_kp<InnerValue, SubValue, G>(
5589        self,
5590        inner_keypath: WritableOptionalKeyPath<InnerValue, SubValue, G>,
5591    ) -> ArcTokioRwLockWritableOptionalKeyPathChain<Root, Value, InnerValue, SubValue, F, G>
5592    where
5593        Value: std::borrow::Borrow<Arc<tokio::sync::RwLock<InnerValue>>>,
5594        G: for<'r> Fn(&'r mut InnerValue) -> Option<&'r mut SubValue>,
5595    {
5596        ArcTokioRwLockWritableOptionalKeyPathChain {
5597            outer_keypath: self,
5598            inner_keypath,
5599        }
5600    }
5601
5602    /// Monadic helper: shorthand for chain_arc_rwlock_writable_at_kp when Value is Arc<RwLock<T>>
5603    /// This allows chaining with .then().then().then() pattern for Arc<RwLock<T>> structures
5604    ///
5605    /// # Example
5606    /// ```rust,ignore
5607    /// ContainerTest::rwlock_data_r()
5608    ///     .then_rwlock(SomeStruct::data_w())
5609    ///     .then(OtherStruct::field_w())
5610    ///     .get_mut(&container, |value| *value = "new".to_string());
5611    /// ```
5612    pub fn then_rwlock<InnerValue, SubValue, G>(
5613        self,
5614        inner_keypath: WritableKeyPath<InnerValue, SubValue, G>,
5615    ) -> ArcRwLockWritableKeyPathChain<Root, Value, InnerValue, SubValue, F, G>
5616    where
5617        Value: std::borrow::Borrow<Arc<RwLock<InnerValue>>>,
5618        G: for<'r> Fn(&'r mut InnerValue) -> &'r mut SubValue,
5619    {
5620        self.chain_arc_rwlock_writable_at_kp(inner_keypath)
5621    }
5622
5623    // ========== LOCK KEYPATH CONVERSION METHODS ==========
5624    // These methods convert keypaths pointing to lock types into chain-ready keypaths
5625
5626    /// Convert this keypath to an Arc<RwLock> chain-ready keypath
5627    /// Returns self, but serves as a marker for intent and enables chaining
5628    ///
5629    /// # Example
5630    /// ```rust,ignore
5631    /// Container::rwlock_data_r()
5632    ///     .to_arc_rwlock_kp()
5633    ///     .chain_arc_rwlock_at_kp(InnerStruct::field_r());
5634    /// ```
5635    pub fn to_arc_rwlock_kp<InnerValue>(self) -> Self
5636    where
5637        Value: std::borrow::Borrow<Arc<RwLock<InnerValue>>>,
5638    {
5639        self
5640    }
5641
5642    /// Convert this keypath to an Arc<Mutex> chain-ready keypath
5643    /// Returns self, but serves as a marker for intent and enables chaining
5644    pub fn to_arc_mutex_kp<InnerValue>(self) -> Self
5645    where
5646        Value: std::borrow::Borrow<Arc<Mutex<InnerValue>>>,
5647    {
5648        self
5649    }
5650
5651    #[cfg(feature = "parking_lot")]
5652    /// Convert this keypath to an Arc<parking_lot::RwLock> chain-ready keypath
5653    /// Returns self, but serves as a marker for intent and enables chaining
5654    ///
5655    /// # Example
5656    /// ```rust,ignore
5657    /// Container::rwlock_data_r()
5658    ///     .to_arc_parking_rwlock_kp()
5659    ///     .chain_arc_parking_rwlock_at_kp(InnerStruct::field_r());
5660    /// ```
5661    pub fn to_arc_parking_rwlock_kp<InnerValue>(self) -> Self
5662    where
5663        Value: std::borrow::Borrow<Arc<parking_lot::RwLock<InnerValue>>>,
5664    {
5665        self
5666    }
5667
5668    #[cfg(feature = "parking_lot")]
5669    /// Convert this keypath to an Arc<parking_lot::Mutex> chain-ready keypath
5670    /// Returns self, but serves as a marker for intent and enables chaining
5671    pub fn to_arc_parking_mutex_kp<InnerValue>(self) -> Self
5672    where
5673        Value: std::borrow::Borrow<Arc<parking_lot::Mutex<InnerValue>>>,
5674    {
5675        self
5676    }
5677
5678    /// Convert this keypath to an Arc<RwLock> chain keypath
5679    /// Creates a chain with an identity inner keypath, ready for further chaining
5680    ///
5681    /// # Example
5682    /// ```rust,ignore
5683    /// Container::rwlock_data_r()
5684    ///     .to_arc_rwlock_chain()
5685    ///     .then(InnerStruct::field_r());
5686    /// ```
5687    /// Convert this keypath to an Arc<RwLock> chain keypath
5688    /// Creates a chain with an identity inner keypath, ready for further chaining
5689    /// Type inference automatically determines InnerValue from Value
5690    ///
5691    /// # Example
5692    /// ```rust,ignore
5693    /// Container::rwlock_data_r()
5694    ///     .to_arc_rwlock_chain()
5695    ///     .then(InnerStruct::field_r());
5696    /// ```
5697    pub fn to_arc_rwlock_chain<InnerValue>(
5698        self,
5699    ) -> ArcRwLockKeyPathChain<
5700        Root,
5701        Value,
5702        InnerValue,
5703        InnerValue,
5704        F,
5705        impl for<'r> Fn(&'r InnerValue) -> &'r InnerValue + 'static,
5706    >
5707    where
5708        Value: std::borrow::Borrow<Arc<RwLock<InnerValue>>>,
5709        F: 'static,
5710        InnerValue: 'static,
5711    {
5712        let identity = KeyPath::new(|inner: &InnerValue| inner);
5713        ArcRwLockKeyPathChain {
5714            outer_keypath: self,
5715            inner_keypath: identity,
5716        }
5717    }
5718
5719    /// Convert this keypath to an Arc<Mutex> chain keypath
5720    /// Creates a chain with an identity inner keypath, ready for further chaining
5721    /// Type inference automatically determines InnerValue from Value
5722    pub fn to_arc_mutex_chain<InnerValue>(
5723        self,
5724    ) -> ArcMutexKeyPathChain<
5725        Root,
5726        Value,
5727        InnerValue,
5728        InnerValue,
5729        F,
5730        impl for<'r> Fn(&'r InnerValue) -> &'r InnerValue + 'static,
5731    >
5732    where
5733        Value: std::borrow::Borrow<Arc<Mutex<InnerValue>>>,
5734        F: 'static,
5735        InnerValue: 'static,
5736    {
5737        let identity = KeyPath::new(|inner: &InnerValue| inner);
5738        ArcMutexKeyPathChain {
5739            outer_keypath: self,
5740            inner_keypath: identity,
5741        }
5742    }
5743
5744    // #[cfg(feature = "parking_lot")]
5745    // /// Convert this keypath to an Arc<parking_lot::RwLock> chain keypath
5746    // /// Creates a chain with an identity inner keypath, ready for further chaining
5747    // /// Type inference automatically determines InnerValue from Value
5748    // ///
5749    // /// # Example
5750    // /// ```rust,ignore
5751    // /// Container::rwlock_data_r()
5752    // ///     .to_arc_parking_rwlock_chain()
5753    // ///     .then(InnerStruct::field_r());
5754    // /// ```
5755    // 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>
5756    // where
5757    //     Value: std::borrow::Borrow<Arc<parking_lot::RwLock<InnerValue>>>,
5758    //     F: 'static + Clone,
5759    //     InnerValue: 'static,
5760    // {
5761    //     let identity = KeyPath::new(|inner: &InnerValue| inner);
5762    //     let getter = self.getter.clone();
5763    //     // Create a new keypath with the exact type needed, following the proc macro pattern
5764    //     // KeyPath::new(|s: &Root| &s.field).chain_arc_parking_rwlock_at_kp(inner_kp)
5765    //     let lock_kp: KeyPath<Root, Arc<parking_lot::RwLock<InnerValue>>, _> = KeyPath::new(move |root: &Root| {
5766    //         // Safe: Value is Arc<parking_lot::RwLock<InnerValue>> at call site, enforced by Borrow bound
5767    //         unsafe {
5768    //             std::mem::transmute::<&Value, &Arc<parking_lot::RwLock<InnerValue>>>(getter(root))
5769    //         }
5770    //     });
5771    //     lock_kp.chain_arc_parking_rwlock_at_kp(identity)
5772    // }
5773
5774    // #[cfg(feature = "parking_lot")]
5775    // /// Convert this keypath to an Arc<parking_lot::Mutex> chain keypath
5776    // /// Creates a chain with an identity inner keypath, ready for further chaining
5777    // /// Type inference automatically determines InnerValue from Value
5778    // 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>
5779    // where
5780    //     Value: std::borrow::Borrow<Arc<parking_lot::Mutex<InnerValue>>>,
5781    //     F: 'static + Clone,
5782    //     InnerValue: 'static,
5783    // {
5784    //     let identity = KeyPath::new(|inner: &InnerValue| inner);
5785    //     let getter = self.getter.clone();
5786    //     let lock_kp: KeyPath<Root, Arc<parking_lot::Mutex<InnerValue>>, _> = KeyPath::new(move |root: &Root| {
5787    //         unsafe {
5788    //             std::mem::transmute::<&Value, &Arc<parking_lot::Mutex<InnerValue>>>(getter(root))
5789    //         }
5790    //     });
5791    //     lock_kp.chain_arc_parking_mutex_at_kp(identity)
5792    // }
5793
5794    // Instance methods for unwrapping containers (automatically infers Target from Value::Target)
5795    // Box<T> -> T
5796    pub fn for_box<Target>(
5797        self,
5798    ) -> KeyPath<Root, Target, impl for<'r> Fn(&'r Root) -> &'r Target + 'static>
5799    where
5800        Value: std::ops::Deref<Target = Target>,
5801        F: 'static,
5802        Value: 'static,
5803    {
5804        let getter = self.getter;
5805
5806        KeyPath {
5807            getter: move |root: &Root| getter(root).deref(),
5808            _phantom: PhantomData,
5809        }
5810    }
5811
5812    // Arc<T> -> T
5813    pub fn for_arc<Target>(
5814        self,
5815    ) -> KeyPath<Root, Target, impl for<'r> Fn(&'r Root) -> &'r Target + 'static>
5816    where
5817        Value: std::ops::Deref<Target = Target>,
5818        F: 'static,
5819        Value: 'static,
5820    {
5821        let getter = self.getter;
5822
5823        KeyPath {
5824            getter: move |root: &Root| getter(root).deref(),
5825            _phantom: PhantomData,
5826        }
5827    }
5828
5829    // Rc<T> -> T
5830    pub fn for_rc<Target>(
5831        self,
5832    ) -> KeyPath<Root, Target, impl for<'r> Fn(&'r Root) -> &'r Target + 'static>
5833    where
5834        Value: std::ops::Deref<Target = Target>,
5835        F: 'static,
5836        Value: 'static,
5837    {
5838        let getter = self.getter;
5839
5840        KeyPath {
5841            getter: move |root: &Root| getter(root).deref(),
5842            _phantom: PhantomData,
5843        }
5844    }
5845
5846    // Overload: Adapt root type to Arc<Root> when Value is Sized (not a container)
5847    pub fn for_arc_root(
5848        self,
5849    ) -> OptionalKeyPath<
5850        Arc<Root>,
5851        Value,
5852        impl for<'r> Fn(&'r Arc<Root>) -> Option<&'r Value> + 'static,
5853    >
5854    where
5855        Value: Sized,
5856        F: 'static,
5857        Root: 'static,
5858        Value: 'static,
5859    {
5860        let getter = self.getter;
5861
5862        OptionalKeyPath {
5863            getter: move |arc: &Arc<Root>| Some(getter(arc.as_ref())),
5864            _phantom: PhantomData,
5865        }
5866    }
5867
5868    // Overload: Adapt root type to Box<Root> when Value is Sized (not a container)
5869    pub fn for_box_root(
5870        self,
5871    ) -> OptionalKeyPath<
5872        Box<Root>,
5873        Value,
5874        impl for<'r> Fn(&'r Box<Root>) -> Option<&'r Value> + 'static,
5875    >
5876    where
5877        Value: Sized,
5878        F: 'static,
5879        Root: 'static,
5880        Value: 'static,
5881    {
5882        let getter = self.getter;
5883
5884        OptionalKeyPath {
5885            getter: move |boxed: &Box<Root>| Some(getter(boxed.as_ref())),
5886            _phantom: PhantomData,
5887        }
5888    }
5889
5890    // Overload: Adapt root type to Rc<Root> when Value is Sized (not a container)
5891    pub fn for_rc_root(
5892        self,
5893    ) -> OptionalKeyPath<
5894        Rc<Root>,
5895        Value,
5896        impl for<'r> Fn(&'r Rc<Root>) -> Option<&'r Value> + 'static,
5897    >
5898    where
5899        Value: Sized,
5900        F: 'static,
5901        Root: 'static,
5902        Value: 'static,
5903    {
5904        let getter = self.getter;
5905
5906        OptionalKeyPath {
5907            getter: move |rc: &Rc<Root>| Some(getter(rc.as_ref())),
5908            _phantom: PhantomData,
5909        }
5910    }
5911
5912    /// Adapt this keypath to work with Result<Root, E> instead of Root
5913    /// This unwraps the Result and applies the keypath to the Ok value
5914    pub fn for_result<E>(
5915        self,
5916    ) -> OptionalKeyPath<
5917        Result<Root, E>,
5918        Value,
5919        impl for<'r> Fn(&'r Result<Root, E>) -> Option<&'r Value> + 'static,
5920    >
5921    where
5922        F: 'static,
5923        Root: 'static,
5924        Value: 'static,
5925        E: 'static,
5926    {
5927        let getter = self.getter;
5928
5929        OptionalKeyPath {
5930            getter: move |result: &Result<Root, E>| result.as_ref().ok().map(|root| getter(root)),
5931            _phantom: PhantomData,
5932        }
5933    }
5934
5935    /// Convert a KeyPath to OptionalKeyPath for chaining
5936    /// This allows non-optional keypaths to be chained with then()
5937    pub fn to_optional(
5938        self,
5939    ) -> OptionalKeyPath<Root, Value, impl for<'r> Fn(&'r Root) -> Option<&'r Value> + 'static>
5940    where
5941        F: 'static,
5942    {
5943        let getter = self.getter;
5944        OptionalKeyPath::new(move |root: &Root| Some(getter(root)))
5945    }
5946
5947    /// Execute a closure with a reference to the value inside an Option
5948    pub fn with_option<Callback, R>(&self, option: &Option<Root>, f: Callback) -> Option<R>
5949    where
5950        F: Clone,
5951        Callback: FnOnce(&Value) -> R,
5952    {
5953        option.as_ref().map(|root| {
5954            let value = self.get(root);
5955            f(value)
5956        })
5957    }
5958
5959    /// Execute a closure with a reference to the value inside a Result
5960    pub fn with_result<Callback, R, E>(&self, result: &Result<Root, E>, f: Callback) -> Option<R>
5961    where
5962        F: Clone,
5963        Callback: FnOnce(&Value) -> R,
5964    {
5965        result.as_ref().ok().map(|root| {
5966            let value = self.get(root);
5967            f(value)
5968        })
5969    }
5970
5971    /// Execute a closure with a reference to the value inside a Box
5972    pub fn with_box<Callback, R>(&self, boxed: &Box<Root>, f: Callback) -> R
5973    where
5974        F: Clone,
5975        Callback: FnOnce(&Value) -> R,
5976    {
5977        let value = self.get(boxed);
5978        f(value)
5979    }
5980
5981    /// Execute a closure with a reference to the value inside an Arc
5982    pub fn with_arc<Callback, R>(&self, arc: &Arc<Root>, f: Callback) -> R
5983    where
5984        F: Clone,
5985        Callback: FnOnce(&Value) -> R,
5986    {
5987        let value = self.get(arc);
5988        f(value)
5989    }
5990
5991    /// Execute a closure with a reference to the value inside an Rc
5992    pub fn with_rc<Callback, R>(&self, rc: &Rc<Root>, f: Callback) -> R
5993    where
5994        F: Clone,
5995        Callback: FnOnce(&Value) -> R,
5996    {
5997        let value = self.get(rc);
5998        f(value)
5999    }
6000
6001    /// Execute a closure with a reference to the value inside a RefCell
6002    pub fn with_refcell<Callback, R>(&self, refcell: &RefCell<Root>, f: Callback) -> Option<R>
6003    where
6004        F: Clone,
6005        Callback: FnOnce(&Value) -> R,
6006    {
6007        refcell.try_borrow().ok().map(|borrow| {
6008            let value = self.get(&*borrow);
6009            f(value)
6010        })
6011    }
6012
6013    /// Execute a closure with a reference to the value inside a Mutex
6014    pub fn with_mutex<Callback, R>(&self, mutex: &Mutex<Root>, f: Callback) -> Option<R>
6015    where
6016        F: Clone,
6017        Callback: FnOnce(&Value) -> R,
6018    {
6019        mutex.lock().ok().map(|guard| {
6020            let value = self.get(&*guard);
6021            f(value)
6022        })
6023    }
6024
6025    /// Execute a closure with a reference to the value inside an RwLock
6026    pub fn with_rwlock<Callback, R>(&self, rwlock: &RwLock<Root>, f: Callback) -> Option<R>
6027    where
6028        F: Clone,
6029        Callback: FnOnce(&Value) -> R,
6030    {
6031        rwlock.read().ok().map(|guard| {
6032            let value = self.get(&*guard);
6033            f(value)
6034        })
6035    }
6036
6037    /// Execute a closure with a reference to the value inside an Arc<RwLock<Root>>
6038    pub fn with_arc_rwlock<Callback, R>(
6039        &self,
6040        arc_rwlock: &Arc<RwLock<Root>>,
6041        f: Callback,
6042    ) -> Option<R>
6043    where
6044        F: Clone,
6045        Callback: FnOnce(&Value) -> R,
6046    {
6047        arc_rwlock.read().ok().map(|guard| {
6048            let value = self.get(&*guard);
6049            f(value)
6050        })
6051    }
6052
6053    /// Execute a closure with a reference to the value inside an Arc<Mutex<Root>>
6054    pub fn with_arc_mutex<Callback, R>(
6055        &self,
6056        arc_mutex: &Arc<Mutex<Root>>,
6057        f: Callback,
6058    ) -> Option<R>
6059    where
6060        F: Clone,
6061        Callback: FnOnce(&Value) -> R,
6062    {
6063        arc_mutex.lock().ok().map(|guard| {
6064            let value = self.get(&*guard);
6065            f(value)
6066        })
6067    }
6068
6069    #[cfg(feature = "tagged")]
6070    /// Adapt this keypath to work with Tagged<Root, Tag> instead of Root
6071    /// This unwraps the Tagged wrapper and applies the keypath to the inner value
6072    pub fn for_tagged<Tag>(
6073        self,
6074    ) -> KeyPath<
6075        Tagged<Root, Tag>,
6076        Value,
6077        impl for<'r> Fn(&'r Tagged<Root, Tag>) -> &'r Value + 'static,
6078    >
6079    where
6080        Tagged<Root, Tag>: std::ops::Deref<Target = Root>,
6081        F: 'static,
6082        Root: 'static,
6083        Value: 'static,
6084        Tag: 'static,
6085    {
6086        use std::ops::Deref;
6087        let getter = self.getter;
6088
6089        KeyPath {
6090            getter: move |tagged: &Tagged<Root, Tag>| getter(tagged.deref()),
6091            _phantom: PhantomData,
6092        }
6093    }
6094
6095    #[cfg(feature = "tagged")]
6096    /// Execute a closure with a reference to the value inside a Tagged
6097    /// This avoids cloning by working with references directly
6098    pub fn with_tagged<Tag, Callback, R>(&self, tagged: &Tagged<Root, Tag>, f: Callback) -> R
6099    where
6100        Tagged<Root, Tag>: std::ops::Deref<Target = Root>,
6101        Callback: FnOnce(&Value) -> R,
6102    {
6103        use std::ops::Deref;
6104        let value = self.get(tagged.deref());
6105        f(value)
6106    }
6107
6108    /// Adapt this keypath to work with Option<Root> instead of Root
6109    /// This converts the KeyPath to an OptionalKeyPath and unwraps the Option
6110    pub fn for_option(
6111        self,
6112    ) -> OptionalKeyPath<
6113        Option<Root>,
6114        Value,
6115        impl for<'r> Fn(&'r Option<Root>) -> Option<&'r Value> + 'static,
6116    >
6117    where
6118        F: 'static,
6119        Root: 'static,
6120        Value: 'static,
6121    {
6122        let getter = self.getter;
6123
6124        OptionalKeyPath {
6125            getter: move |opt: &Option<Root>| opt.as_ref().map(|root| getter(root)),
6126            _phantom: PhantomData,
6127        }
6128    }
6129
6130    /// Get an iterator over a Vec when Value is Vec<T>
6131    /// Returns Some(iterator) if the value is a Vec, None otherwise
6132    pub fn iter<'r, T>(&self, root: &'r Root) -> Option<std::slice::Iter<'r, T>>
6133    where
6134        Value: AsRef<[T]> + 'r,
6135    {
6136        let value_ref: &'r Value = self.get(root);
6137        Some(value_ref.as_ref().iter())
6138    }
6139
6140    /// Extract values from a slice of owned values
6141    /// Returns a Vec of references to the extracted values
6142    pub fn extract_from_slice<'r>(&self, slice: &'r [Root]) -> Vec<&'r Value> {
6143        slice.iter().map(|item| self.get(item)).collect()
6144    }
6145
6146    /// Extract values from a slice of references
6147    /// Returns a Vec of references to the extracted values
6148    pub fn extract_from_ref_slice<'r>(&self, slice: &'r [&Root]) -> Vec<&'r Value> {
6149        slice.iter().map(|item| self.get(item)).collect()
6150    }
6151
6152    /// Chain this keypath with another keypath
6153    /// Returns a KeyPath that chains both keypaths
6154    pub fn then<SubValue, G>(
6155        self,
6156        next: KeyPath<Value, SubValue, G>,
6157    ) -> KeyPath<Root, SubValue, impl for<'r> Fn(&'r Root) -> &'r SubValue>
6158    where
6159        G: for<'r> Fn(&'r Value) -> &'r SubValue,
6160        F: 'static,
6161        G: 'static,
6162        Value: 'static,
6163    {
6164        let first = self.getter;
6165        let second = next.getter;
6166
6167        KeyPath::new(move |root: &Root| {
6168            let value = first(root);
6169            second(value)
6170        })
6171    }
6172
6173    /// Chain this keypath with an optional keypath
6174    /// Returns an OptionalKeyPath that chains both keypaths
6175    pub fn chain_optional<SubValue, G>(
6176        self,
6177        next: OptionalKeyPath<Value, SubValue, G>,
6178    ) -> OptionalKeyPath<Root, SubValue, impl for<'r> Fn(&'r Root) -> Option<&'r SubValue>>
6179    where
6180        G: for<'r> Fn(&'r Value) -> Option<&'r SubValue>,
6181        F: 'static,
6182        G: 'static,
6183        Value: 'static,
6184    {
6185        let first = self.getter;
6186        let second = next.getter;
6187
6188        OptionalKeyPath::new(move |root: &Root| {
6189            let value = first(root);
6190            second(value)
6191        })
6192    }
6193}
6194
6195// Extension methods for KeyPath to support Arc<RwLock> and Arc<Mutex> directly
6196impl<Root, Value, F> KeyPath<Root, Value, F>
6197where
6198    F: for<'r> Fn(&'r Root) -> &'r Value,
6199{
6200    /// Execute a closure with a reference to the value inside an Arc<RwLock<Root>>
6201    /// This is a convenience method that works directly with Arc<RwLock<T>>
6202    pub fn with_arc_rwlock_direct<Callback, R>(
6203        &self,
6204        arc_rwlock: &Arc<RwLock<Root>>,
6205        f: Callback,
6206    ) -> Option<R>
6207    where
6208        Callback: FnOnce(&Value) -> R,
6209    {
6210        arc_rwlock.read().ok().map(|guard| {
6211            let value = self.get(&*guard);
6212            f(value)
6213        })
6214    }
6215
6216    /// Execute a closure with a reference to the value inside an Arc<Mutex<Root>>
6217    /// This is a convenience method that works directly with Arc<Mutex<T>>
6218    pub fn with_arc_mutex_direct<Callback, R>(
6219        &self,
6220        arc_mutex: &Arc<Mutex<Root>>,
6221        f: Callback,
6222    ) -> Option<R>
6223    where
6224        Callback: FnOnce(&Value) -> R,
6225    {
6226        arc_mutex.lock().ok().map(|guard| {
6227            let value = self.get(&*guard);
6228            f(value)
6229        })
6230    }
6231}
6232
6233// Utility function for slice access (kept as standalone function)
6234pub fn for_slice<T>() -> impl for<'r> Fn(&'r [T], usize) -> Option<&'r T> {
6235    |slice: &[T], index: usize| slice.get(index)
6236}
6237
6238// Container access utilities
6239pub mod containers {
6240    use super::{KeyPath, OptionalKeyPath, WritableKeyPath, WritableOptionalKeyPath};
6241    use std::collections::{
6242        BTreeMap, BTreeSet, BinaryHeap, HashMap, HashSet, LinkedList, VecDeque,
6243    };
6244    use std::ops::{Deref, DerefMut};
6245    use std::rc::{Rc, Weak as RcWeak};
6246    use std::sync::{Arc, Mutex, RwLock, Weak as StdWeak};
6247
6248    #[cfg(feature = "parking_lot")]
6249    use parking_lot::{Mutex as ParkingMutex, RwLock as ParkingRwLock};
6250
6251    #[cfg(feature = "tagged")]
6252    use tagged_core::Tagged;
6253
6254    /// Create a keypath for indexed access in Vec<T>
6255    pub fn for_vec_index<T>(
6256        index: usize,
6257    ) -> OptionalKeyPath<Vec<T>, T, impl for<'r> Fn(&'r Vec<T>) -> Option<&'r T>> {
6258        OptionalKeyPath::new(move |vec: &Vec<T>| vec.get(index))
6259    }
6260
6261    /// Create a keypath for indexed access in VecDeque<T>
6262    pub fn for_vecdeque_index<T>(
6263        index: usize,
6264    ) -> OptionalKeyPath<VecDeque<T>, T, impl for<'r> Fn(&'r VecDeque<T>) -> Option<&'r T>> {
6265        OptionalKeyPath::new(move |deque: &VecDeque<T>| deque.get(index))
6266    }
6267
6268    /// Create a keypath for indexed access in LinkedList<T>
6269    pub fn for_linkedlist_index<T>(
6270        index: usize,
6271    ) -> OptionalKeyPath<LinkedList<T>, T, impl for<'r> Fn(&'r LinkedList<T>) -> Option<&'r T>>
6272    {
6273        OptionalKeyPath::new(move |list: &LinkedList<T>| list.iter().nth(index))
6274    }
6275
6276    /// Create a keypath for key-based access in HashMap<K, V>
6277    pub fn for_hashmap_key<K, V>(
6278        key: K,
6279    ) -> OptionalKeyPath<HashMap<K, V>, V, impl for<'r> Fn(&'r HashMap<K, V>) -> Option<&'r V>>
6280    where
6281        K: std::hash::Hash + Eq + Clone + 'static,
6282        V: 'static,
6283    {
6284        OptionalKeyPath::new(move |map: &HashMap<K, V>| map.get(&key))
6285    }
6286
6287    /// Create a keypath for key-based access in BTreeMap<K, V>
6288    pub fn for_btreemap_key<K, V>(
6289        key: K,
6290    ) -> OptionalKeyPath<BTreeMap<K, V>, V, impl for<'r> Fn(&'r BTreeMap<K, V>) -> Option<&'r V>>
6291    where
6292        K: Ord + Clone + 'static,
6293        V: 'static,
6294    {
6295        OptionalKeyPath::new(move |map: &BTreeMap<K, V>| map.get(&key))
6296    }
6297
6298    /// Create a keypath for getting a value from HashSet<T> (returns Option<&T>)
6299    pub fn for_hashset_get<T>(
6300        value: T,
6301    ) -> OptionalKeyPath<HashSet<T>, T, impl for<'r> Fn(&'r HashSet<T>) -> Option<&'r T>>
6302    where
6303        T: std::hash::Hash + Eq + Clone + 'static,
6304    {
6305        OptionalKeyPath::new(move |set: &HashSet<T>| set.get(&value))
6306    }
6307
6308    /// Create a keypath for checking membership in BTreeSet<T>
6309    pub fn for_btreeset_get<T>(
6310        value: T,
6311    ) -> OptionalKeyPath<BTreeSet<T>, T, impl for<'r> Fn(&'r BTreeSet<T>) -> Option<&'r T>>
6312    where
6313        T: Ord + Clone + 'static,
6314    {
6315        OptionalKeyPath::new(move |set: &BTreeSet<T>| set.get(&value))
6316    }
6317
6318    /// Create a keypath for peeking at the top of BinaryHeap<T>
6319    pub fn for_binaryheap_peek<T>()
6320    -> OptionalKeyPath<BinaryHeap<T>, T, impl for<'r> Fn(&'r BinaryHeap<T>) -> Option<&'r T>>
6321    where
6322        T: Ord + 'static,
6323    {
6324        OptionalKeyPath::new(|heap: &BinaryHeap<T>| heap.peek())
6325    }
6326
6327    // ========== WRITABLE VERSIONS ==========
6328
6329    /// Create a writable keypath for indexed access in Vec<T>
6330    pub fn for_vec_index_mut<T>(
6331        index: usize,
6332    ) -> WritableOptionalKeyPath<Vec<T>, T, impl for<'r> Fn(&'r mut Vec<T>) -> Option<&'r mut T>>
6333    {
6334        WritableOptionalKeyPath::new(move |vec: &mut Vec<T>| vec.get_mut(index))
6335    }
6336
6337    /// Create a writable keypath for indexed access in VecDeque<T>
6338    pub fn for_vecdeque_index_mut<T>(
6339        index: usize,
6340    ) -> WritableOptionalKeyPath<
6341        VecDeque<T>,
6342        T,
6343        impl for<'r> Fn(&'r mut VecDeque<T>) -> Option<&'r mut T>,
6344    > {
6345        WritableOptionalKeyPath::new(move |deque: &mut VecDeque<T>| deque.get_mut(index))
6346    }
6347
6348    /// Create a writable keypath for indexed access in LinkedList<T>
6349    pub fn for_linkedlist_index_mut<T>(
6350        index: usize,
6351    ) -> WritableOptionalKeyPath<
6352        LinkedList<T>,
6353        T,
6354        impl for<'r> Fn(&'r mut LinkedList<T>) -> Option<&'r mut T>,
6355    > {
6356        WritableOptionalKeyPath::new(move |list: &mut LinkedList<T>| {
6357            // LinkedList doesn't have get_mut, so we need to iterate
6358            let mut iter = list.iter_mut();
6359            iter.nth(index)
6360        })
6361    }
6362
6363    /// Create a writable keypath for key-based access in HashMap<K, V>
6364    pub fn for_hashmap_key_mut<K, V>(
6365        key: K,
6366    ) -> WritableOptionalKeyPath<
6367        HashMap<K, V>,
6368        V,
6369        impl for<'r> Fn(&'r mut HashMap<K, V>) -> Option<&'r mut V>,
6370    >
6371    where
6372        K: std::hash::Hash + Eq + Clone + 'static,
6373        V: 'static,
6374    {
6375        WritableOptionalKeyPath::new(move |map: &mut HashMap<K, V>| map.get_mut(&key))
6376    }
6377
6378    /// Create a writable keypath for key-based access in BTreeMap<K, V>
6379    pub fn for_btreemap_key_mut<K, V>(
6380        key: K,
6381    ) -> WritableOptionalKeyPath<
6382        BTreeMap<K, V>,
6383        V,
6384        impl for<'r> Fn(&'r mut BTreeMap<K, V>) -> Option<&'r mut V>,
6385    >
6386    where
6387        K: Ord + Clone + 'static,
6388        V: 'static,
6389    {
6390        WritableOptionalKeyPath::new(move |map: &mut BTreeMap<K, V>| map.get_mut(&key))
6391    }
6392
6393    /// Create a writable keypath for getting a mutable value from HashSet<T>
6394    /// Note: HashSet doesn't support mutable access to elements, but we provide it for consistency
6395    pub fn for_hashset_get_mut<T>(
6396        value: T,
6397    ) -> WritableOptionalKeyPath<
6398        HashSet<T>,
6399        T,
6400        impl for<'r> Fn(&'r mut HashSet<T>) -> Option<&'r mut T>,
6401    >
6402    where
6403        T: std::hash::Hash + Eq + Clone + 'static,
6404    {
6405        WritableOptionalKeyPath::new(move |set: &mut HashSet<T>| {
6406            // HashSet doesn't have get_mut, so we need to check and return None
6407            // This is a limitation of HashSet's design
6408            if set.contains(&value) {
6409                // We can't return a mutable reference to the value in the set
6410                // This is a fundamental limitation of HashSet
6411                None
6412            } else {
6413                None
6414            }
6415        })
6416    }
6417
6418    /// Create a writable keypath for getting a mutable value from BTreeSet<T>
6419    /// Note: BTreeSet doesn't support mutable access to elements, but we provide it for consistency
6420    pub fn for_btreeset_get_mut<T>(
6421        value: T,
6422    ) -> WritableOptionalKeyPath<
6423        BTreeSet<T>,
6424        T,
6425        impl for<'r> Fn(&'r mut BTreeSet<T>) -> Option<&'r mut T>,
6426    >
6427    where
6428        T: Ord + Clone + 'static,
6429    {
6430        WritableOptionalKeyPath::new(move |set: &mut BTreeSet<T>| {
6431            // BTreeSet doesn't have get_mut, so we need to check and return None
6432            // This is a limitation of BTreeSet's design
6433            if set.contains(&value) {
6434                // We can't return a mutable reference to the value in the set
6435                // This is a fundamental limitation of BTreeSet
6436                None
6437            } else {
6438                None
6439            }
6440        })
6441    }
6442
6443    /// Create a writable keypath for peeking at the top of BinaryHeap<T>
6444    /// Note: BinaryHeap.peek_mut() returns PeekMut which is a guard type.
6445    /// Due to Rust's borrowing rules, we cannot return &mut T directly from PeekMut.
6446    /// This function returns None as BinaryHeap doesn't support direct mutable access
6447    /// through keypaths. Use heap.peek_mut() directly for mutable access.
6448    pub fn for_binaryheap_peek_mut<T>() -> WritableOptionalKeyPath<
6449        BinaryHeap<T>,
6450        T,
6451        impl for<'r> Fn(&'r mut BinaryHeap<T>) -> Option<&'r mut T>,
6452    >
6453    where
6454        T: Ord + 'static,
6455    {
6456        // BinaryHeap.peek_mut() returns PeekMut which is a guard type that owns the mutable reference.
6457        // We cannot return &mut T from it due to lifetime constraints.
6458        // This is a fundamental limitation - use heap.peek_mut() directly instead.
6459        WritableOptionalKeyPath::new(|_heap: &mut BinaryHeap<T>| None)
6460    }
6461
6462    // ========== SYNCHRONIZATION PRIMITIVES ==========
6463    // Note: Mutex and RwLock return guards that own the lock, not references.
6464    // We cannot create keypaths that return references from guards due to lifetime constraints.
6465    // These helper functions are provided for convenience, but direct lock()/read()/write() calls are recommended.
6466
6467    /// Helper function to lock a Mutex<T> and access its value
6468    /// Returns None if the mutex is poisoned
6469    /// Note: This returns a guard, not a reference, so it cannot be used in keypaths directly
6470    pub fn lock_mutex<T>(mutex: &Mutex<T>) -> Option<std::sync::MutexGuard<'_, T>> {
6471        mutex.lock().ok()
6472    }
6473
6474    /// Helper function to read-lock an RwLock<T> and access its value
6475    /// Returns None if the lock is poisoned
6476    /// Note: This returns a guard, not a reference, so it cannot be used in keypaths directly
6477    pub fn read_rwlock<T>(rwlock: &RwLock<T>) -> Option<std::sync::RwLockReadGuard<'_, T>> {
6478        rwlock.read().ok()
6479    }
6480
6481    /// Helper function to write-lock an RwLock<T> and access its value
6482    /// Returns None if the lock is poisoned
6483    /// Note: This returns a guard, not a reference, so it cannot be used in keypaths directly
6484    pub fn write_rwlock<T>(rwlock: &RwLock<T>) -> Option<std::sync::RwLockWriteGuard<'_, T>> {
6485        rwlock.write().ok()
6486    }
6487
6488    /// Helper function to lock an Arc<Mutex<T>> and access its value
6489    /// Returns None if the mutex is poisoned
6490    /// Note: This returns a guard, not a reference, so it cannot be used in keypaths directly
6491    pub fn lock_arc_mutex<T>(arc_mutex: &Arc<Mutex<T>>) -> Option<std::sync::MutexGuard<'_, T>> {
6492        arc_mutex.lock().ok()
6493    }
6494
6495    /// Helper function to read-lock an Arc<RwLock<T>> and access its value
6496    /// Returns None if the lock is poisoned
6497    /// Note: This returns a guard, not a reference, so it cannot be used in keypaths directly
6498    pub fn read_arc_rwlock<T>(
6499        arc_rwlock: &Arc<RwLock<T>>,
6500    ) -> Option<std::sync::RwLockReadGuard<'_, T>> {
6501        arc_rwlock.read().ok()
6502    }
6503
6504    /// Helper function to write-lock an Arc<RwLock<T>> and access its value
6505    /// Returns None if the lock is poisoned
6506    /// Note: This returns a guard, not a reference, so it cannot be used in keypaths directly
6507    pub fn write_arc_rwlock<T>(
6508        arc_rwlock: &Arc<RwLock<T>>,
6509    ) -> Option<std::sync::RwLockWriteGuard<'_, T>> {
6510        arc_rwlock.write().ok()
6511    }
6512
6513    /// Helper function to upgrade a Weak<T> to Arc<T>
6514    /// Returns None if the Arc has been dropped
6515    /// Note: This returns an owned Arc, not a reference, so it cannot be used in keypaths directly
6516    pub fn upgrade_weak<T>(weak: &StdWeak<T>) -> Option<Arc<T>> {
6517        weak.upgrade()
6518    }
6519
6520    /// Helper function to upgrade an Rc::Weak<T> to Rc<T>
6521    /// Returns None if the Rc has been dropped
6522    /// Note: This returns an owned Rc, not a reference, so it cannot be used in keypaths directly
6523    pub fn upgrade_rc_weak<T>(weak: &RcWeak<T>) -> Option<Rc<T>> {
6524        weak.upgrade()
6525    }
6526
6527    #[cfg(feature = "parking_lot")]
6528    /// Helper function to lock a parking_lot::Mutex<T> and access its value
6529    /// Note: This returns a guard, not a reference, so it cannot be used in keypaths directly
6530    pub fn lock_parking_mutex<T>(mutex: &ParkingMutex<T>) -> parking_lot::MutexGuard<'_, T> {
6531        mutex.lock()
6532    }
6533
6534    #[cfg(feature = "parking_lot")]
6535    /// Helper function to read-lock a parking_lot::RwLock<T> and access its value
6536    /// Note: This returns a guard, not a reference, so it cannot be used in keypaths directly
6537    pub fn read_parking_rwlock<T>(
6538        rwlock: &ParkingRwLock<T>,
6539    ) -> parking_lot::RwLockReadGuard<'_, T> {
6540        rwlock.read()
6541    }
6542
6543    #[cfg(feature = "parking_lot")]
6544    /// Helper function to write-lock a parking_lot::RwLock<T> and access its value
6545    /// Note: This returns a guard, not a reference, so it cannot be used in keypaths directly
6546    pub fn write_parking_rwlock<T>(
6547        rwlock: &ParkingRwLock<T>,
6548    ) -> parking_lot::RwLockWriteGuard<'_, T> {
6549        rwlock.write()
6550    }
6551
6552    #[cfg(feature = "tagged")]
6553    /// Create a keypath for accessing the inner value of Tagged<Tag, T>
6554    /// Tagged implements Deref, so we can access the inner value directly
6555    pub fn for_tagged<Tag, T>()
6556    -> KeyPath<Tagged<Tag, T>, T, impl for<'r> Fn(&'r Tagged<Tag, T>) -> &'r T>
6557    where
6558        Tagged<Tag, T>: std::ops::Deref<Target = T>,
6559        Tag: 'static,
6560        T: 'static,
6561    {
6562        KeyPath::new(|tagged: &Tagged<Tag, T>| tagged.deref())
6563    }
6564
6565    #[cfg(feature = "tagged")]
6566    /// Create a writable keypath for accessing the inner value of Tagged<Tag, T>
6567    /// Tagged implements DerefMut, so we can access the inner value directly
6568    pub fn for_tagged_mut<Tag, T>()
6569    -> WritableKeyPath<Tagged<Tag, T>, T, impl for<'r> Fn(&'r mut Tagged<Tag, T>) -> &'r mut T>
6570    where
6571        Tagged<Tag, T>: std::ops::DerefMut<Target = T>,
6572        Tag: 'static,
6573        T: 'static,
6574    {
6575        WritableKeyPath::new(|tagged: &mut Tagged<Tag, T>| tagged.deref_mut())
6576    }
6577}
6578
6579// ========== PARKING_LOT CHAIN METHODS FOR KEYPATH ==========
6580
6581#[cfg(feature = "parking_lot")]
6582impl<Root, InnerValue, F> KeyPath<Root, Arc<parking_lot::Mutex<InnerValue>>, F>
6583where
6584    F: for<'r> Fn(&'r Root) -> &'r Arc<parking_lot::Mutex<InnerValue>>,
6585{
6586    /// Chain this keypath with an inner keypath through Arc<parking_lot::Mutex<T>> - functional style
6587    pub fn chain_arc_parking_mutex_at_kp<SubValue, G>(
6588        self,
6589        inner_keypath: KeyPath<InnerValue, SubValue, G>,
6590    ) -> ArcParkingMutexKeyPathChain<Root, InnerValue, SubValue, F, G>
6591    where
6592        G: for<'r> Fn(&'r InnerValue) -> &'r SubValue,
6593    {
6594        ArcParkingMutexKeyPathChain {
6595            outer_keypath: self,
6596            inner_keypath,
6597        }
6598    }
6599
6600    /// Chain this keypath with an optional inner keypath through Arc<parking_lot::Mutex<T>>
6601    pub fn then_arc_parking_mutex_optional_at_kp<SubValue, G>(
6602        self,
6603        inner_keypath: OptionalKeyPath<InnerValue, SubValue, G>,
6604    ) -> ArcParkingMutexOptionalKeyPathChain<Root, InnerValue, SubValue, F, G>
6605    where
6606        G: for<'r> Fn(&'r InnerValue) -> Option<&'r SubValue>,
6607    {
6608        ArcParkingMutexOptionalKeyPathChain {
6609            outer_keypath: self,
6610            inner_keypath,
6611        }
6612    }
6613
6614    /// Chain this keypath with a writable inner keypath through Arc<parking_lot::Mutex<T>>
6615    pub fn chain_arc_parking_mutex_writable_at_kp<SubValue, G>(
6616        self,
6617        inner_keypath: WritableKeyPath<InnerValue, SubValue, G>,
6618    ) -> ArcParkingMutexWritableKeyPathChain<Root, InnerValue, SubValue, F, G>
6619    where
6620        G: for<'r> Fn(&'r mut InnerValue) -> &'r mut SubValue,
6621    {
6622        ArcParkingMutexWritableKeyPathChain {
6623            outer_keypath: self,
6624            inner_keypath,
6625        }
6626    }
6627
6628    /// Chain this keypath with a writable optional inner keypath through Arc<parking_lot::Mutex<T>>
6629    pub fn then_arc_parking_mutex_writable_optional_at_kp<SubValue, G>(
6630        self,
6631        inner_keypath: WritableOptionalKeyPath<InnerValue, SubValue, G>,
6632    ) -> ArcParkingMutexWritableOptionalKeyPathChain<Root, InnerValue, SubValue, F, G>
6633    where
6634        G: for<'r> Fn(&'r mut InnerValue) -> Option<&'r mut SubValue>,
6635    {
6636        ArcParkingMutexWritableOptionalKeyPathChain {
6637            outer_keypath: self,
6638            inner_keypath,
6639        }
6640    }
6641}
6642
6643#[cfg(feature = "parking_lot")]
6644impl<Root, InnerValue, F> KeyPath<Root, Arc<parking_lot::RwLock<InnerValue>>, F>
6645where
6646    F: for<'r> Fn(&'r Root) -> &'r Arc<parking_lot::RwLock<InnerValue>>,
6647{
6648    /// Chain this keypath with an inner keypath through Arc<parking_lot::RwLock<T>> - functional style
6649    pub fn chain_arc_parking_rwlock_at_kp<SubValue, G>(
6650        self,
6651        inner_keypath: KeyPath<InnerValue, SubValue, G>,
6652    ) -> ArcParkingRwLockKeyPathChain<Root, InnerValue, SubValue, F, G>
6653    where
6654        G: for<'r> Fn(&'r InnerValue) -> &'r SubValue,
6655    {
6656        ArcParkingRwLockKeyPathChain {
6657            outer_keypath: self,
6658            inner_keypath,
6659        }
6660    }
6661
6662    /// Chain this keypath with an optional inner keypath through Arc<parking_lot::RwLock<T>>
6663    pub fn then_arc_parking_rwlock_optional_at_kp<SubValue, G>(
6664        self,
6665        inner_keypath: OptionalKeyPath<InnerValue, SubValue, G>,
6666    ) -> ArcParkingRwLockOptionalKeyPathChain<Root, InnerValue, SubValue, F, G>
6667    where
6668        G: for<'r> Fn(&'r InnerValue) -> Option<&'r SubValue>,
6669    {
6670        ArcParkingRwLockOptionalKeyPathChain {
6671            outer_keypath: self,
6672            inner_keypath,
6673        }
6674    }
6675
6676    /// Chain this keypath with a writable inner keypath through Arc<parking_lot::RwLock<T>>
6677    pub fn chain_arc_parking_rwlock_writable_at_kp<SubValue, G>(
6678        self,
6679        inner_keypath: WritableKeyPath<InnerValue, SubValue, G>,
6680    ) -> ArcParkingRwLockWritableKeyPathChain<Root, InnerValue, SubValue, F, G>
6681    where
6682        G: for<'r> Fn(&'r mut InnerValue) -> &'r mut SubValue,
6683    {
6684        ArcParkingRwLockWritableKeyPathChain {
6685            outer_keypath: self,
6686            inner_keypath,
6687        }
6688    }
6689
6690    /// Chain this keypath with a writable optional inner keypath through Arc<parking_lot::RwLock<T>>
6691    pub fn then_arc_parking_rwlock_writable_optional_at_kp<SubValue, G>(
6692        self,
6693        inner_keypath: WritableOptionalKeyPath<InnerValue, SubValue, G>,
6694    ) -> ArcParkingRwLockWritableOptionalKeyPathChain<Root, InnerValue, SubValue, F, G>
6695    where
6696        G: for<'r> Fn(&'r mut InnerValue) -> Option<&'r mut SubValue>,
6697    {
6698        ArcParkingRwLockWritableOptionalKeyPathChain {
6699            outer_keypath: self,
6700            inner_keypath,
6701        }
6702    }
6703}
6704
6705// OptionalKeyPath for Option<T>
6706#[derive(Clone)]
6707pub struct OptionalKeyPath<Root, Value, F>
6708where
6709    F: for<'r> Fn(&'r Root) -> Option<&'r Value>,
6710{
6711    getter: F,
6712    _phantom: PhantomData<(Root, Value)>,
6713}
6714
6715impl<Root, Value, F> fmt::Display for OptionalKeyPath<Root, Value, F>
6716where
6717    F: for<'r> Fn(&'r Root) -> Option<&'r Value>,
6718{
6719    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
6720        let root_name = std::any::type_name::<Root>();
6721        let value_name = std::any::type_name::<Value>();
6722        // Simplify type names by removing module paths for cleaner output
6723        let root_short = root_name.split("::").last().unwrap_or(root_name);
6724        let value_short = value_name.split("::").last().unwrap_or(value_name);
6725        write!(
6726            f,
6727            "OptionalKeyPath<{} -> Option<{}>>",
6728            root_short, value_short
6729        )
6730    }
6731}
6732
6733impl<Root, Value, F> fmt::Debug for OptionalKeyPath<Root, Value, F>
6734where
6735    F: for<'r> Fn(&'r Root) -> Option<&'r Value>,
6736{
6737    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
6738        fmt::Display::fmt(self, f)
6739    }
6740}
6741
6742impl<Root> OptionalKeyPath<Root, Root, fn(&Root) -> Option<&Root>> {
6743    /// Identity optional keypath: projects `Root` to `Some(root)`.
6744    pub fn identity() -> Self {
6745        OptionalKeyPath {
6746            getter: identity_opt_ref::<Root>,
6747            _phantom: PhantomData,
6748        }
6749    }
6750}
6751
6752impl<Root, Value, F> OptionalKeyPath<Root, Value, F>
6753where
6754    F: for<'r> Fn(&'r Root) -> Option<&'r Value>,
6755{
6756    pub fn new(getter: F) -> Self {
6757        Self {
6758            getter,
6759            _phantom: PhantomData,
6760        }
6761    }
6762
6763    pub fn get<'r>(&self, root: &'r Root) -> Option<&'r Value> {
6764        (self.getter)(root)
6765    }
6766
6767    /// Higher-order function: map the optional value reference through a function.
6768    /// Returns a new `OptionalKeyPath<Root, U, _>` that gets the value and applies `f` to the reference when present.
6769    ///
6770    /// # Example
6771    /// ```rust
6772    /// use rust_keypaths::OptionalKeyPath;
6773    /// let kp = OptionalKeyPath::new(|o: &Option<String>| o.as_ref());
6774    /// let len_kp = kp.map(|s: &String| &s.len());
6775    /// let some_s = Some("hello".to_string());
6776    /// assert_eq!(*len_kp.get(&some_s).unwrap(), 5);
6777    /// assert!(len_kp.get(&None::<String>).is_none());
6778    /// ```
6779    pub fn map<U, G>(self, f: G) -> OptionalKeyPath<Root, U, impl for<'r> Fn(&'r Root) -> Option<&'r U>>
6780    where
6781        G: for<'r> Fn(&'r Value) -> &'r U,
6782        F: 'static,
6783        G: 'static,
6784        Root: 'static,
6785        Value: 'static,
6786    {
6787        let getter = self.getter;
6788        OptionalKeyPath {
6789            getter: move |root| getter(root).map(|v| f(v)),
6790            _phantom: PhantomData,
6791        }
6792    }
6793
6794    /// Map through a function that returns `Option<&U>`, keeping an `OptionalKeyPath`.
6795    /// Use when the inner projection may fail (e.g. `|v: &Vec<T>| v.first()`).
6796    pub fn map_optional<U, G>(
6797        self,
6798        f: G,
6799    ) -> OptionalKeyPath<Root, U, impl for<'r> Fn(&'r Root) -> Option<&'r U>>
6800    where
6801        G: for<'r> Fn(&'r Value) -> Option<&'r U>,
6802        F: 'static,
6803        G: 'static,
6804        Root: 'static,
6805        Value: 'static,
6806    {
6807        let getter = self.getter;
6808        OptionalKeyPath {
6809            getter: move |root| getter(root).and_then(|v| f(v)),
6810            _phantom: PhantomData,
6811        }
6812    }
6813
6814    /// Chain this optional keypath with an inner keypath through Arc<Mutex<T>> - functional style
6815    /// Compose first, then apply container at get() time
6816    ///
6817    /// # Example
6818    /// ```rust
6819    /// let container = ContainerTest { mutex_data: Some(Arc::new(Mutex::new(SomeStruct { data: "test".to_string() }))) };
6820    ///
6821    /// // Functional style: compose first, apply container at get()
6822    /// ContainerTest::mutex_data_fr()
6823    ///     .chain_arc_mutex_at_kp(SomeStruct::data_r())
6824    ///     .get(&container, |value| println!("Data: {}", value));
6825    /// ```
6826    pub fn chain_arc_mutex_at_kp<InnerValue, SubValue, G>(
6827        self,
6828        inner_keypath: KeyPath<InnerValue, SubValue, G>,
6829    ) -> OptionalArcMutexKeyPathChain<Root, Value, InnerValue, SubValue, F, G>
6830    where
6831        G: for<'r> Fn(&'r InnerValue) -> &'r SubValue,
6832    {
6833        OptionalArcMutexKeyPathChain {
6834            outer_keypath: self,
6835            inner_keypath,
6836        }
6837    }
6838
6839    /// Chain this optional keypath with an optional inner keypath through Arc<Mutex<T>> - functional style
6840    /// Compose first, then apply container at get() time
6841    ///
6842    /// # Example
6843    /// ```rust
6844    /// let container = ContainerTest { mutex_data: Some(Arc::new(Mutex::new(SomeStruct { optional_field: Some("test".to_string()) }))) };
6845    ///
6846    /// // Functional style: compose first, apply container at get()
6847    /// ContainerTest::mutex_data_fr()
6848    ///     .chain_arc_mutex_optional_at_kp(SomeStruct::optional_field_fr())
6849    ///     .get(&container, |value| println!("Value: {}", value));
6850    /// ```
6851    pub fn chain_arc_mutex_optional_at_kp<InnerValue, SubValue, G>(
6852        self,
6853        inner_keypath: OptionalKeyPath<InnerValue, SubValue, G>,
6854    ) -> OptionalArcMutexOptionalKeyPathChain<Root, Value, InnerValue, SubValue, F, G>
6855    where
6856        G: for<'r> Fn(&'r InnerValue) -> Option<&'r SubValue>,
6857    {
6858        OptionalArcMutexOptionalKeyPathChain {
6859            outer_keypath: self,
6860            inner_keypath,
6861        }
6862    }
6863
6864    /// Chain this optional keypath with an inner keypath through Arc<RwLock<T>> - functional style
6865    /// Compose first, then apply container at get() time (uses read lock)
6866    ///
6867    /// # Example
6868    /// ```rust
6869    /// let container = ContainerTest { rwlock_data: Some(Arc::new(RwLock::new(SomeStruct { data: "test".to_string() }))) };
6870    ///
6871    /// // Functional style: compose first, apply container at get()
6872    /// ContainerTest::rwlock_data_fr()
6873    ///     .chain_arc_rwlock_at_kp(SomeStruct::data_r())
6874    ///     .get(&container, |value| println!("Data: {}", value));
6875    /// ```
6876    pub fn chain_arc_rwlock_at_kp<InnerValue, SubValue, G>(
6877        self,
6878        inner_keypath: KeyPath<InnerValue, SubValue, G>,
6879    ) -> OptionalArcRwLockKeyPathChain<Root, Value, InnerValue, SubValue, F, G>
6880    where
6881        G: for<'r> Fn(&'r InnerValue) -> &'r SubValue,
6882    {
6883        OptionalArcRwLockKeyPathChain {
6884            outer_keypath: self,
6885            inner_keypath,
6886        }
6887    }
6888
6889    /// Chain this optional keypath with an optional inner keypath through Arc<RwLock<T>> - functional style
6890    /// Compose first, then apply container at get() time (uses read lock)
6891    ///
6892    /// # Example
6893    /// ```rust
6894    /// let container = ContainerTest { rwlock_data: Some(Arc::new(RwLock::new(SomeStruct { optional_field: Some("test".to_string()) }))) };
6895    ///
6896    /// // Functional style: compose first, apply container at get()
6897    /// ContainerTest::rwlock_data_fr()
6898    ///     .chain_arc_rwlock_optional_at_kp(SomeStruct::optional_field_fr())
6899    ///     .get(&container, |value| println!("Value: {}", value));
6900    /// ```
6901    pub fn chain_arc_rwlock_optional_at_kp<InnerValue, SubValue, G>(
6902        self,
6903        inner_keypath: OptionalKeyPath<InnerValue, SubValue, G>,
6904    ) -> OptionalArcRwLockOptionalKeyPathChain<Root, Value, InnerValue, SubValue, F, G>
6905    where
6906        G: for<'r> Fn(&'r InnerValue) -> Option<&'r SubValue>,
6907    {
6908        OptionalArcRwLockOptionalKeyPathChain {
6909            outer_keypath: self,
6910            inner_keypath,
6911        }
6912    }
6913
6914    /// Chain this optional keypath with a writable inner keypath through Arc<Mutex<T>> - functional style
6915    /// Compose first, then apply container at get_mut() time
6916    ///
6917    /// # Example
6918    /// ```rust
6919    /// let container = ContainerTest { mutex_data: Some(Arc::new(Mutex::new(SomeStruct { data: "test".to_string() }))) };
6920    ///
6921    /// // Functional style: compose first, apply container at get_mut()
6922    /// ContainerTest::mutex_data_fr()
6923    ///     .chain_arc_mutex_writable_at_kp(SomeStruct::data_w())
6924    ///     .get_mut(&container, |value| *value = "new".to_string());
6925    /// ```
6926    pub fn chain_arc_mutex_writable_at_kp<InnerValue, SubValue, G>(
6927        self,
6928        inner_keypath: WritableKeyPath<InnerValue, SubValue, G>,
6929    ) -> OptionalArcMutexWritableKeyPathChain<Root, Value, InnerValue, SubValue, F, G>
6930    where
6931        G: for<'r> Fn(&'r mut InnerValue) -> &'r mut SubValue,
6932    {
6933        OptionalArcMutexWritableKeyPathChain {
6934            outer_keypath: self,
6935            inner_keypath,
6936        }
6937    }
6938
6939    /// Chain this optional keypath with a writable optional inner keypath through Arc<Mutex<T>> - functional style
6940    /// Compose first, then apply container at get_mut() time
6941    ///
6942    /// # Example
6943    /// ```rust
6944    /// let container = ContainerTest { mutex_data: Some(Arc::new(Mutex::new(SomeStruct { optional_field: Some("test".to_string()) }))) };
6945    ///
6946    /// // Functional style: compose first, apply container at get_mut()
6947    /// ContainerTest::mutex_data_fr()
6948    ///     .chain_arc_mutex_writable_optional_at_kp(SomeStruct::optional_field_fw())
6949    ///     .get_mut(&container, |value| *value = "new".to_string());
6950    /// ```
6951    pub fn chain_arc_mutex_writable_optional_at_kp<InnerValue, SubValue, G>(
6952        self,
6953        inner_keypath: WritableOptionalKeyPath<InnerValue, SubValue, G>,
6954    ) -> OptionalArcMutexWritableOptionalKeyPathChain<Root, Value, InnerValue, SubValue, F, G>
6955    where
6956        G: for<'r> Fn(&'r mut InnerValue) -> Option<&'r mut SubValue>,
6957    {
6958        OptionalArcMutexWritableOptionalKeyPathChain {
6959            outer_keypath: self,
6960            inner_keypath,
6961        }
6962    }
6963
6964    /// Chain this optional keypath with a writable inner keypath through Arc<RwLock<T>> - functional style
6965    /// Compose first, then apply container at get_mut() time (uses write lock)
6966    ///
6967    /// # Example
6968    /// ```rust
6969    /// let container = ContainerTest { rwlock_data: Some(Arc::new(RwLock::new(SomeStruct { data: "test".to_string() }))) };
6970    ///
6971    /// // Functional style: compose first, apply container at get_mut()
6972    /// ContainerTest::rwlock_data_fr()
6973    ///     .chain_arc_rwlock_writable_at_kp(SomeStruct::data_w())
6974    ///     .get_mut(&container, |value| *value = "new".to_string());
6975    /// ```
6976    pub fn chain_arc_rwlock_writable_at_kp<InnerValue, SubValue, G>(
6977        self,
6978        inner_keypath: WritableKeyPath<InnerValue, SubValue, G>,
6979    ) -> OptionalArcRwLockWritableKeyPathChain<Root, Value, InnerValue, SubValue, F, G>
6980    where
6981        G: for<'r> Fn(&'r mut InnerValue) -> &'r mut SubValue,
6982    {
6983        OptionalArcRwLockWritableKeyPathChain {
6984            outer_keypath: self,
6985            inner_keypath,
6986        }
6987    }
6988
6989    /// Chain this optional keypath with a writable optional inner keypath through Arc<RwLock<T>> - functional style
6990    /// Compose first, then apply container at get_mut() time (uses write lock)
6991    ///
6992    /// # Example
6993    /// ```rust
6994    /// let container = ContainerTest { rwlock_data: Some(Arc::new(RwLock::new(SomeStruct { optional_field: Some("test".to_string()) }))) };
6995    ///
6996    /// // Functional style: compose first, apply container at get_mut()
6997    /// ContainerTest::rwlock_data_fr()
6998    ///     .chain_arc_rwlock_writable_optional_at_kp(SomeStruct::optional_field_fw())
6999    ///     .get_mut(&container, |value| *value = "new".to_string());
7000    /// ```
7001    pub fn chain_arc_rwlock_writable_optional_at_kp<InnerValue, SubValue, G>(
7002        self,
7003        inner_keypath: WritableOptionalKeyPath<InnerValue, SubValue, G>,
7004    ) -> OptionalArcRwLockWritableOptionalKeyPathChain<Root, Value, InnerValue, SubValue, F, G>
7005    where
7006        G: for<'r> Fn(&'r mut InnerValue) -> Option<&'r mut SubValue>,
7007    {
7008        OptionalArcRwLockWritableOptionalKeyPathChain {
7009            outer_keypath: self,
7010            inner_keypath,
7011        }
7012    }
7013
7014    #[cfg(feature = "tokio")]
7015    /// Chain this optional keypath with an inner keypath through Arc<tokio::sync::Mutex<T>> - functional style (async)
7016    pub fn chain_arc_tokio_mutex_at_kp<InnerValue, SubValue, G>(
7017        self,
7018        inner_keypath: KeyPath<InnerValue, SubValue, G>,
7019    ) -> OptionalArcTokioMutexKeyPathChain<Root, Value, InnerValue, SubValue, F, G>
7020    where
7021        Value: std::borrow::Borrow<Arc<tokio::sync::Mutex<InnerValue>>>,
7022        G: for<'r> Fn(&'r InnerValue) -> &'r SubValue,
7023    {
7024        OptionalArcTokioMutexKeyPathChain {
7025            outer_keypath: self,
7026            inner_keypath,
7027        }
7028    }
7029
7030    #[cfg(feature = "tokio")]
7031    /// Chain this optional keypath with an optional inner keypath through Arc<tokio::sync::Mutex<T>> - functional style (async)
7032    pub fn chain_arc_tokio_mutex_optional_at_kp<InnerValue, SubValue, G>(
7033        self,
7034        inner_keypath: OptionalKeyPath<InnerValue, SubValue, G>,
7035    ) -> OptionalArcTokioMutexOptionalKeyPathChain<Root, Value, InnerValue, SubValue, F, G>
7036    where
7037        Value: std::borrow::Borrow<Arc<tokio::sync::Mutex<InnerValue>>>,
7038        G: for<'r> Fn(&'r InnerValue) -> Option<&'r SubValue>,
7039    {
7040        OptionalArcTokioMutexOptionalKeyPathChain {
7041            outer_keypath: self,
7042            inner_keypath,
7043        }
7044    }
7045
7046    #[cfg(feature = "tokio")]
7047    /// Chain this optional keypath with a writable inner keypath through Arc<tokio::sync::Mutex<T>> - functional style (async)
7048    pub fn chain_arc_tokio_mutex_writable_at_kp<InnerValue, SubValue, G>(
7049        self,
7050        inner_keypath: WritableKeyPath<InnerValue, SubValue, G>,
7051    ) -> OptionalArcTokioMutexWritableKeyPathChain<Root, Value, InnerValue, SubValue, F, G>
7052    where
7053        Value: std::borrow::Borrow<Arc<tokio::sync::Mutex<InnerValue>>>,
7054        G: for<'r> Fn(&'r mut InnerValue) -> &'r mut SubValue,
7055    {
7056        OptionalArcTokioMutexWritableKeyPathChain {
7057            outer_keypath: self,
7058            inner_keypath,
7059        }
7060    }
7061
7062    #[cfg(feature = "tokio")]
7063    /// Chain this optional keypath with a writable optional inner keypath through Arc<tokio::sync::Mutex<T>> - functional style (async)
7064    pub fn chain_arc_tokio_mutex_writable_optional_at_kp<InnerValue, SubValue, G>(
7065        self,
7066        inner_keypath: WritableOptionalKeyPath<InnerValue, SubValue, G>,
7067    ) -> OptionalArcTokioMutexWritableOptionalKeyPathChain<Root, Value, InnerValue, SubValue, F, G>
7068    where
7069        Value: std::borrow::Borrow<Arc<tokio::sync::Mutex<InnerValue>>>,
7070        G: for<'r> Fn(&'r mut InnerValue) -> Option<&'r mut SubValue>,
7071    {
7072        OptionalArcTokioMutexWritableOptionalKeyPathChain {
7073            outer_keypath: self,
7074            inner_keypath,
7075        }
7076    }
7077
7078    #[cfg(feature = "tokio")]
7079    /// Chain this optional keypath with an inner keypath through Arc<tokio::sync::RwLock<T>> - functional style (async, read lock)
7080    pub fn chain_arc_tokio_rwlock_at_kp<InnerValue, SubValue, G>(
7081        self,
7082        inner_keypath: KeyPath<InnerValue, SubValue, G>,
7083    ) -> OptionalArcTokioRwLockKeyPathChain<Root, Value, InnerValue, SubValue, F, G>
7084    where
7085        Value: std::borrow::Borrow<Arc<tokio::sync::RwLock<InnerValue>>>,
7086        G: for<'r> Fn(&'r InnerValue) -> &'r SubValue,
7087    {
7088        OptionalArcTokioRwLockKeyPathChain {
7089            outer_keypath: self,
7090            inner_keypath,
7091        }
7092    }
7093
7094    #[cfg(feature = "tokio")]
7095    /// Chain this optional keypath with an optional inner keypath through Arc<tokio::sync::RwLock<T>> - functional style (async, read lock)
7096    pub fn chain_arc_tokio_rwlock_optional_at_kp<InnerValue, SubValue, G>(
7097        self,
7098        inner_keypath: OptionalKeyPath<InnerValue, SubValue, G>,
7099    ) -> OptionalArcTokioRwLockOptionalKeyPathChain<Root, Value, InnerValue, SubValue, F, G>
7100    where
7101        Value: std::borrow::Borrow<Arc<tokio::sync::RwLock<InnerValue>>>,
7102        G: for<'r> Fn(&'r InnerValue) -> Option<&'r SubValue>,
7103    {
7104        OptionalArcTokioRwLockOptionalKeyPathChain {
7105            outer_keypath: self,
7106            inner_keypath,
7107        }
7108    }
7109
7110    #[cfg(feature = "tokio")]
7111    /// Chain this optional keypath with a writable inner keypath through Arc<tokio::sync::RwLock<T>> - functional style (async, write lock)
7112    pub fn chain_arc_tokio_rwlock_writable_at_kp<InnerValue, SubValue, G>(
7113        self,
7114        inner_keypath: WritableKeyPath<InnerValue, SubValue, G>,
7115    ) -> OptionalArcTokioRwLockWritableKeyPathChain<Root, Value, InnerValue, SubValue, F, G>
7116    where
7117        Value: std::borrow::Borrow<Arc<tokio::sync::RwLock<InnerValue>>>,
7118        G: for<'r> Fn(&'r mut InnerValue) -> &'r mut SubValue,
7119    {
7120        OptionalArcTokioRwLockWritableKeyPathChain {
7121            outer_keypath: self,
7122            inner_keypath,
7123        }
7124    }
7125
7126    #[cfg(feature = "tokio")]
7127    /// Chain this optional keypath with a writable optional inner keypath through Arc<tokio::sync::RwLock<T>> - functional style (async, write lock)
7128    pub fn chain_arc_tokio_rwlock_writable_optional_at_kp<InnerValue, SubValue, G>(
7129        self,
7130        inner_keypath: WritableOptionalKeyPath<InnerValue, SubValue, G>,
7131    ) -> OptionalArcTokioRwLockWritableOptionalKeyPathChain<Root, Value, InnerValue, SubValue, F, G>
7132    where
7133        Value: std::borrow::Borrow<Arc<tokio::sync::RwLock<InnerValue>>>,
7134        G: for<'r> Fn(&'r mut InnerValue) -> Option<&'r mut SubValue>,
7135    {
7136        OptionalArcTokioRwLockWritableOptionalKeyPathChain {
7137            outer_keypath: self,
7138            inner_keypath,
7139        }
7140    }
7141
7142    // Swift-like operator for chaining OptionalKeyPath
7143    pub fn then<SubValue, G>(
7144        self,
7145        next: OptionalKeyPath<Value, SubValue, G>,
7146    ) -> OptionalKeyPath<Root, SubValue, impl for<'r> Fn(&'r Root) -> Option<&'r SubValue>>
7147    where
7148        G: for<'r> Fn(&'r Value) -> Option<&'r SubValue>,
7149        F: 'static,
7150        G: 'static,
7151        Value: 'static,
7152    {
7153        let first = self.getter;
7154        let second = next.getter;
7155
7156        OptionalKeyPath::new(move |root: &Root| first(root).and_then(|value| second(value)))
7157    }
7158
7159    // Instance methods for unwrapping containers from Option<Container<T>>
7160    // Option<Box<T>> -> Option<&T> (type automatically inferred from Value::Target)
7161    pub fn for_box<Target>(
7162        self,
7163    ) -> OptionalKeyPath<Root, Target, impl for<'r> Fn(&'r Root) -> Option<&'r Target> + 'static>
7164    where
7165        Value: std::ops::Deref<Target = Target>,
7166        F: 'static,
7167        Value: 'static,
7168    {
7169        let getter = self.getter;
7170
7171        OptionalKeyPath {
7172            getter: move |root: &Root| getter(root).map(|boxed| boxed.deref()),
7173            _phantom: PhantomData,
7174        }
7175    }
7176
7177    // Option<Arc<T>> -> Option<&T> (type automatically inferred from Value::Target)
7178    pub fn for_arc<Target>(
7179        self,
7180    ) -> OptionalKeyPath<Root, Target, impl for<'r> Fn(&'r Root) -> Option<&'r Target> + 'static>
7181    where
7182        Value: std::ops::Deref<Target = Target>,
7183        F: 'static,
7184        Value: 'static,
7185    {
7186        let getter = self.getter;
7187
7188        OptionalKeyPath {
7189            getter: move |root: &Root| getter(root).map(|arc| arc.deref()),
7190            _phantom: PhantomData,
7191        }
7192    }
7193
7194    // Option<Rc<T>> -> Option<&T> (type automatically inferred from Value::Target)
7195    pub fn for_rc<Target>(
7196        self,
7197    ) -> OptionalKeyPath<Root, Target, impl for<'r> Fn(&'r Root) -> Option<&'r Target> + 'static>
7198    where
7199        Value: std::ops::Deref<Target = Target>,
7200        F: 'static,
7201        Value: 'static,
7202    {
7203        let getter = self.getter;
7204
7205        OptionalKeyPath {
7206            getter: move |root: &Root| getter(root).map(|rc| rc.deref()),
7207            _phantom: PhantomData,
7208        }
7209    }
7210
7211    #[cfg(feature = "tagged")]
7212    /// Adapt this keypath to work with Tagged<Root, Tag> instead of Root
7213    /// This unwraps the Tagged wrapper and applies the keypath to the inner value
7214    pub fn for_tagged<Tag>(
7215        self,
7216    ) -> OptionalKeyPath<
7217        Tagged<Root, Tag>,
7218        Value,
7219        impl for<'r> Fn(&'r Tagged<Root, Tag>) -> Option<&'r Value> + 'static,
7220    >
7221    where
7222        Tagged<Root, Tag>: std::ops::Deref<Target = Root>,
7223        F: 'static,
7224        Root: 'static,
7225        Value: 'static,
7226        Tag: 'static,
7227    {
7228        use std::ops::Deref;
7229        let getter = self.getter;
7230
7231        OptionalKeyPath {
7232            getter: move |tagged: &Tagged<Root, Tag>| getter(tagged.deref()),
7233            _phantom: PhantomData,
7234        }
7235    }
7236
7237    #[cfg(feature = "tagged")]
7238    /// Execute a closure with a reference to the value inside a Tagged
7239    /// This avoids cloning by working with references directly
7240    pub fn with_tagged<Tag, Callback, R>(
7241        &self,
7242        tagged: &Tagged<Root, Tag>,
7243        f: Callback,
7244    ) -> Option<R>
7245    where
7246        Tagged<Root, Tag>: std::ops::Deref<Target = Root>,
7247        F: Clone,
7248        Callback: FnOnce(&Value) -> R,
7249    {
7250        use std::ops::Deref;
7251        self.get(tagged.deref()).map(|value| f(value))
7252    }
7253
7254    /// Adapt this keypath to work with Option<Root> instead of Root
7255    /// This unwraps the Option and applies the keypath to the inner value
7256    pub fn for_option(
7257        self,
7258    ) -> OptionalKeyPath<
7259        Option<Root>,
7260        Value,
7261        impl for<'r> Fn(&'r Option<Root>) -> Option<&'r Value> + 'static,
7262    >
7263    where
7264        F: 'static,
7265        Root: 'static,
7266        Value: 'static,
7267    {
7268        let getter = self.getter;
7269
7270        OptionalKeyPath {
7271            getter: move |opt: &Option<Root>| opt.as_ref().and_then(|root| getter(root)),
7272            _phantom: PhantomData,
7273        }
7274    }
7275
7276    /// Adapt this keypath to work with Result<Root, E> instead of Root
7277    /// This unwraps the Result and applies the keypath to the Ok value
7278    pub fn for_result<E>(
7279        self,
7280    ) -> OptionalKeyPath<
7281        Result<Root, E>,
7282        Value,
7283        impl for<'r> Fn(&'r Result<Root, E>) -> Option<&'r Value> + 'static,
7284    >
7285    where
7286        F: 'static,
7287        Root: 'static,
7288        Value: 'static,
7289        E: 'static,
7290    {
7291        let getter = self.getter;
7292
7293        OptionalKeyPath {
7294            getter: move |result: &Result<Root, E>| {
7295                result.as_ref().ok().and_then(|root| getter(root))
7296            },
7297            _phantom: PhantomData,
7298        }
7299    }
7300
7301    // ========== LOCK KEYPATH CONVERSION METHODS ==========
7302    // These methods convert keypaths pointing to lock types into chain-ready keypaths
7303
7304    /// Convert this optional keypath to an Arc<RwLock> chain-ready keypath
7305    /// Returns self, but serves as a marker for intent and enables chaining
7306    pub fn to_arc_rwlock_kp<InnerValue>(self) -> Self
7307    where
7308        Value: std::borrow::Borrow<Arc<RwLock<InnerValue>>>,
7309    {
7310        self
7311    }
7312
7313    /// Convert this optional keypath to an Arc<Mutex> chain-ready keypath
7314    /// Returns self, but serves as a marker for intent and enables chaining
7315    pub fn to_arc_mutex_kp<InnerValue>(self) -> Self
7316    where
7317        Value: std::borrow::Borrow<Arc<Mutex<InnerValue>>>,
7318    {
7319        self
7320    }
7321
7322    #[cfg(feature = "parking_lot")]
7323    /// Convert this optional keypath to an Arc<parking_lot::RwLock> chain-ready keypath
7324    /// Returns self, but serves as a marker for intent and enables chaining
7325    pub fn to_arc_parking_rwlock_kp<InnerValue>(self) -> Self
7326    where
7327        Value: std::borrow::Borrow<Arc<parking_lot::RwLock<InnerValue>>>,
7328    {
7329        self
7330    }
7331
7332    #[cfg(feature = "parking_lot")]
7333    /// Convert this optional keypath to an Arc<parking_lot::Mutex> chain-ready keypath
7334    /// Returns self, but serves as a marker for intent and enables chaining
7335    pub fn to_arc_parking_mutex_kp<InnerValue>(self) -> Self
7336    where
7337        Value: std::borrow::Borrow<Arc<parking_lot::Mutex<InnerValue>>>,
7338    {
7339        self
7340    }
7341
7342    /// Convert this optional keypath to an Arc<RwLock> chain keypath
7343    /// Creates a chain with an identity inner keypath, ready for further chaining
7344    /// Type inference automatically determines InnerValue from Value
7345    pub fn to_arc_rwlock_chain<InnerValue>(
7346        self,
7347    ) -> OptionalArcRwLockKeyPathChain<
7348        Root,
7349        Value,
7350        InnerValue,
7351        InnerValue,
7352        F,
7353        impl for<'r> Fn(&'r InnerValue) -> &'r InnerValue + 'static,
7354    >
7355    where
7356        Value: std::borrow::Borrow<Arc<RwLock<InnerValue>>>,
7357        F: 'static,
7358        InnerValue: 'static,
7359    {
7360        let identity = KeyPath::new(|inner: &InnerValue| inner);
7361        OptionalArcRwLockKeyPathChain {
7362            outer_keypath: self,
7363            inner_keypath: identity,
7364        }
7365    }
7366
7367    /// Convert this optional keypath to an Arc<Mutex> chain keypath
7368    /// Creates a chain with an identity inner keypath, ready for further chaining
7369    /// Type inference automatically determines InnerValue from Value
7370    pub fn to_arc_mutex_chain<InnerValue>(
7371        self,
7372    ) -> OptionalArcMutexKeyPathChain<
7373        Root,
7374        Value,
7375        InnerValue,
7376        InnerValue,
7377        F,
7378        impl for<'r> Fn(&'r InnerValue) -> &'r InnerValue + 'static,
7379    >
7380    where
7381        Value: std::borrow::Borrow<Arc<Mutex<InnerValue>>>,
7382        F: 'static,
7383        InnerValue: 'static,
7384    {
7385        let identity = KeyPath::new(|inner: &InnerValue| inner);
7386        OptionalArcMutexKeyPathChain {
7387            outer_keypath: self,
7388            inner_keypath: identity,
7389        }
7390    }
7391
7392    // #[cfg(feature = "parking_lot")]
7393    // /// Convert this optional keypath to an Arc<parking_lot::RwLock> chain keypath
7394    // /// Creates a chain with an identity inner keypath, ready for further chaining
7395    // /// Type inference automatically determines InnerValue from Value
7396    // 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>
7397    // where
7398    //     Value: std::borrow::Borrow<Arc<parking_lot::RwLock<InnerValue>>>,
7399    //     F: 'static + Clone,
7400    //     InnerValue: 'static,
7401    // {
7402    //     let identity = KeyPath::new(|inner: &InnerValue| inner);
7403    //     let getter = self.getter.clone();
7404    //     let lock_kp: OptionalKeyPath<Root, Arc<parking_lot::RwLock<InnerValue>>, _> = OptionalKeyPath::new(move |root: &Root| {
7405    //         getter(root).map(|v| {
7406    //             unsafe {
7407    //                 std::mem::transmute::<&Value, &Arc<parking_lot::RwLock<InnerValue>>>(v)
7408    //             }
7409    //         })
7410    //     });
7411    //     lock_kp.chain_arc_parking_rwlock_at_kp(identity)
7412    // }
7413
7414    // #[cfg(feature = "parking_lot")]
7415    // /// Convert this optional keypath to an Arc<parking_lot::Mutex> chain keypath
7416    // /// Creates a chain with an identity inner keypath, ready for further chaining
7417    // /// Type inference automatically determines InnerValue from Value
7418    // 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>
7419    // where
7420    //     Value: std::borrow::Borrow<Arc<parking_lot::Mutex<InnerValue>>>,
7421    //     F: 'static + Clone,
7422    //     InnerValue: 'static,
7423    // {
7424    //     let identity = KeyPath::new(|inner: &InnerValue| inner);
7425    //     let getter = self.getter.clone();
7426    //     let lock_kp: OptionalKeyPath<Root, Arc<parking_lot::Mutex<InnerValue>>, _> = OptionalKeyPath::new(move |root: &Root| {
7427    //         getter(root).map(|v| {
7428    //             unsafe {
7429    //                 std::mem::transmute::<&Value, &Arc<parking_lot::Mutex<InnerValue>>>(v)
7430    //             }
7431    //         })
7432    //     });
7433    //     lock_kp.chain_arc_parking_mutex_at_kp(identity)
7434    // }
7435
7436    // Overload: Adapt root type to Arc<Root> when Value is Sized (not a container)
7437    pub fn for_arc_root(
7438        self,
7439    ) -> OptionalKeyPath<
7440        Arc<Root>,
7441        Value,
7442        impl for<'r> Fn(&'r Arc<Root>) -> Option<&'r Value> + 'static,
7443    >
7444    where
7445        Value: Sized,
7446        F: 'static,
7447        Root: 'static,
7448        Value: 'static,
7449    {
7450        let getter = self.getter;
7451
7452        OptionalKeyPath {
7453            getter: move |arc: &Arc<Root>| getter(arc.as_ref()),
7454            _phantom: PhantomData,
7455        }
7456    }
7457
7458    // Overload: Adapt root type to Rc<Root> when Value is Sized (not a container)
7459    pub fn for_rc_root(
7460        self,
7461    ) -> OptionalKeyPath<
7462        Rc<Root>,
7463        Value,
7464        impl for<'r> Fn(&'r Rc<Root>) -> Option<&'r Value> + 'static,
7465    >
7466    where
7467        Value: Sized,
7468        F: 'static,
7469        Root: 'static,
7470        Value: 'static,
7471    {
7472        let getter = self.getter;
7473
7474        OptionalKeyPath {
7475            getter: move |rc: &Rc<Root>| getter(rc.as_ref()),
7476            _phantom: PhantomData,
7477        }
7478    }
7479
7480    /// Execute a closure with a reference to the value inside an Option
7481    pub fn with_option<Callback, R>(&self, option: &Option<Root>, f: Callback) -> Option<R>
7482    where
7483        F: Clone,
7484        Callback: FnOnce(&Value) -> R,
7485    {
7486        option
7487            .as_ref()
7488            .and_then(|root| self.get(root).map(|value| f(value)))
7489    }
7490
7491    /// Execute a closure with a reference to the value inside a Mutex
7492    pub fn with_mutex<Callback, R>(&self, mutex: &Mutex<Root>, f: Callback) -> Option<R>
7493    where
7494        F: Clone,
7495        Callback: FnOnce(&Value) -> R,
7496    {
7497        mutex
7498            .lock()
7499            .ok()
7500            .and_then(|guard| self.get(&*guard).map(|value| f(value)))
7501    }
7502
7503    /// Execute a closure with a reference to the value inside an RwLock
7504    pub fn with_rwlock<Callback, R>(&self, rwlock: &RwLock<Root>, f: Callback) -> Option<R>
7505    where
7506        F: Clone,
7507        Callback: FnOnce(&Value) -> R,
7508    {
7509        rwlock
7510            .read()
7511            .ok()
7512            .and_then(|guard| self.get(&*guard).map(|value| f(value)))
7513    }
7514
7515    /// Execute a closure with a reference to the value inside an Arc<RwLock<Root>>
7516    pub fn with_arc_rwlock<Callback, R>(
7517        &self,
7518        arc_rwlock: &Arc<RwLock<Root>>,
7519        f: Callback,
7520    ) -> Option<R>
7521    where
7522        F: Clone,
7523        Callback: FnOnce(&Value) -> R,
7524    {
7525        arc_rwlock
7526            .read()
7527            .ok()
7528            .and_then(|guard| self.get(&*guard).map(|value| f(value)))
7529    }
7530
7531    /// Execute a closure with a reference to the value inside an Arc<RwLock<Root>>
7532    /// This is a convenience method that works directly with Arc<RwLock<T>>
7533    /// Unlike with_arc_rwlock, this doesn't require F: Clone
7534    pub fn with_arc_rwlock_direct<Callback, R>(
7535        &self,
7536        arc_rwlock: &Arc<RwLock<Root>>,
7537        f: Callback,
7538    ) -> Option<R>
7539    where
7540        Callback: FnOnce(&Value) -> R,
7541    {
7542        arc_rwlock
7543            .read()
7544            .ok()
7545            .and_then(|guard| self.get(&*guard).map(|value| f(value)))
7546    }
7547
7548    /// Execute a closure with a reference to the value inside an Arc<Mutex<Root>>
7549    pub fn with_arc_mutex<Callback, R>(
7550        &self,
7551        arc_mutex: &Arc<Mutex<Root>>,
7552        f: Callback,
7553    ) -> Option<R>
7554    where
7555        F: Clone,
7556        Callback: FnOnce(&Value) -> R,
7557    {
7558        arc_mutex
7559            .lock()
7560            .ok()
7561            .and_then(|guard| self.get(&*guard).map(|value| f(value)))
7562    }
7563}
7564
7565// ========== PARKING_LOT CHAIN METHODS FOR OPTIONAL KEYPATH ==========
7566
7567#[cfg(feature = "parking_lot")]
7568impl<Root, InnerValue, F> OptionalKeyPath<Root, Arc<parking_lot::Mutex<InnerValue>>, F>
7569where
7570    F: for<'r> Fn(&'r Root) -> Option<&'r Arc<parking_lot::Mutex<InnerValue>>>,
7571{
7572    /// Chain this optional keypath with an inner keypath through Arc<parking_lot::Mutex<T>>
7573    pub fn chain_arc_parking_mutex_at_kp<SubValue, G>(
7574        self,
7575        inner_keypath: KeyPath<InnerValue, SubValue, G>,
7576    ) -> OptionalArcParkingMutexKeyPathChain<Root, InnerValue, SubValue, F, G>
7577    where
7578        G: for<'r> Fn(&'r InnerValue) -> &'r SubValue,
7579    {
7580        OptionalArcParkingMutexKeyPathChain {
7581            outer_keypath: self,
7582            inner_keypath,
7583        }
7584    }
7585
7586    /// Chain this optional keypath with an optional inner keypath through Arc<parking_lot::Mutex<T>>
7587    pub fn then_arc_parking_mutex_optional_at_kp<SubValue, G>(
7588        self,
7589        inner_keypath: OptionalKeyPath<InnerValue, SubValue, G>,
7590    ) -> OptionalArcParkingMutexOptionalKeyPathChain<Root, InnerValue, SubValue, F, G>
7591    where
7592        G: for<'r> Fn(&'r InnerValue) -> Option<&'r SubValue>,
7593    {
7594        OptionalArcParkingMutexOptionalKeyPathChain {
7595            outer_keypath: self,
7596            inner_keypath,
7597        }
7598    }
7599
7600    /// Chain this optional keypath with a writable inner keypath through Arc<parking_lot::Mutex<T>>
7601    pub fn chain_arc_parking_mutex_writable_at_kp<SubValue, G>(
7602        self,
7603        inner_keypath: WritableKeyPath<InnerValue, SubValue, G>,
7604    ) -> OptionalArcParkingMutexWritableKeyPathChain<Root, InnerValue, SubValue, F, G>
7605    where
7606        G: for<'r> Fn(&'r mut InnerValue) -> &'r mut SubValue,
7607    {
7608        OptionalArcParkingMutexWritableKeyPathChain {
7609            outer_keypath: self,
7610            inner_keypath,
7611        }
7612    }
7613
7614    /// Chain this optional keypath with a writable optional inner keypath through Arc<parking_lot::Mutex<T>>
7615    pub fn then_arc_parking_mutex_writable_optional_at_kp<SubValue, G>(
7616        self,
7617        inner_keypath: WritableOptionalKeyPath<InnerValue, SubValue, G>,
7618    ) -> OptionalArcParkingMutexWritableOptionalKeyPathChain<Root, InnerValue, SubValue, F, G>
7619    where
7620        G: for<'r> Fn(&'r mut InnerValue) -> Option<&'r mut SubValue>,
7621    {
7622        OptionalArcParkingMutexWritableOptionalKeyPathChain {
7623            outer_keypath: self,
7624            inner_keypath,
7625        }
7626    }
7627}
7628
7629#[cfg(feature = "parking_lot")]
7630impl<Root, InnerValue, F> OptionalKeyPath<Root, Arc<parking_lot::RwLock<InnerValue>>, F>
7631where
7632    F: for<'r> Fn(&'r Root) -> Option<&'r Arc<parking_lot::RwLock<InnerValue>>>,
7633{
7634    /// Chain this optional keypath with an inner keypath through Arc<parking_lot::RwLock<T>>
7635    pub fn chain_arc_parking_rwlock_at_kp<SubValue, G>(
7636        self,
7637        inner_keypath: KeyPath<InnerValue, SubValue, G>,
7638    ) -> OptionalArcParkingRwLockKeyPathChain<Root, InnerValue, SubValue, F, G>
7639    where
7640        G: for<'r> Fn(&'r InnerValue) -> &'r SubValue,
7641    {
7642        OptionalArcParkingRwLockKeyPathChain {
7643            outer_keypath: self,
7644            inner_keypath,
7645        }
7646    }
7647
7648    /// Chain this optional keypath with an optional inner keypath through Arc<parking_lot::RwLock<T>>
7649    pub fn then_arc_parking_rwlock_optional_at_kp<SubValue, G>(
7650        self,
7651        inner_keypath: OptionalKeyPath<InnerValue, SubValue, G>,
7652    ) -> OptionalArcParkingRwLockOptionalKeyPathChain<Root, InnerValue, SubValue, F, G>
7653    where
7654        G: for<'r> Fn(&'r InnerValue) -> Option<&'r SubValue>,
7655    {
7656        OptionalArcParkingRwLockOptionalKeyPathChain {
7657            outer_keypath: self,
7658            inner_keypath,
7659        }
7660    }
7661
7662    /// Chain this optional keypath with a writable inner keypath through Arc<parking_lot::RwLock<T>>
7663    pub fn chain_arc_parking_rwlock_writable_at_kp<SubValue, G>(
7664        self,
7665        inner_keypath: WritableKeyPath<InnerValue, SubValue, G>,
7666    ) -> OptionalArcParkingRwLockWritableKeyPathChain<Root, InnerValue, SubValue, F, G>
7667    where
7668        G: for<'r> Fn(&'r mut InnerValue) -> &'r mut SubValue,
7669    {
7670        OptionalArcParkingRwLockWritableKeyPathChain {
7671            outer_keypath: self,
7672            inner_keypath,
7673        }
7674    }
7675
7676    /// Chain this optional keypath with a writable optional inner keypath through Arc<parking_lot::RwLock<T>>
7677    pub fn then_arc_parking_rwlock_writable_optional_at_kp<SubValue, G>(
7678        self,
7679        inner_keypath: WritableOptionalKeyPath<InnerValue, SubValue, G>,
7680    ) -> OptionalArcParkingRwLockWritableOptionalKeyPathChain<Root, InnerValue, SubValue, F, G>
7681    where
7682        G: for<'r> Fn(&'r mut InnerValue) -> Option<&'r mut SubValue>,
7683    {
7684        OptionalArcParkingRwLockWritableOptionalKeyPathChain {
7685            outer_keypath: self,
7686            inner_keypath,
7687        }
7688    }
7689}
7690
7691// WritableKeyPath for mutable access
7692#[derive(Clone)]
7693pub struct WritableKeyPath<Root, Value, F>
7694where
7695    F: for<'r> Fn(&'r mut Root) -> &'r mut Value,
7696{
7697    getter: F,
7698    _phantom: PhantomData<(Root, Value)>,
7699}
7700
7701impl<Root, Value, F> fmt::Display for WritableKeyPath<Root, Value, F>
7702where
7703    F: for<'r> Fn(&'r mut Root) -> &'r mut Value,
7704{
7705    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
7706        let root_name = std::any::type_name::<Root>();
7707        let value_name = std::any::type_name::<Value>();
7708        // Simplify type names by removing module paths for cleaner output
7709        let root_short = root_name.split("::").last().unwrap_or(root_name);
7710        let value_short = value_name.split("::").last().unwrap_or(value_name);
7711        write!(f, "WritableKeyPath<{} -> {}>", root_short, value_short)
7712    }
7713}
7714
7715impl<Root, Value, F> fmt::Debug for WritableKeyPath<Root, Value, F>
7716where
7717    F: for<'r> Fn(&'r mut Root) -> &'r mut Value,
7718{
7719    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
7720        fmt::Display::fmt(self, f)
7721    }
7722}
7723
7724impl<Root> WritableKeyPath<Root, Root, fn(&mut Root) -> &mut Root> {
7725    /// Identity writable keypath: projects `&mut Root` to itself.
7726    pub fn identity() -> Self {
7727        WritableKeyPath {
7728            getter: identity_mut::<Root>,
7729            _phantom: PhantomData,
7730        }
7731    }
7732}
7733
7734impl<Root, Value, F> WritableKeyPath<Root, Value, F>
7735where
7736    F: for<'r> Fn(&'r mut Root) -> &'r mut Value,
7737{
7738    pub fn new(getter: F) -> Self {
7739        Self {
7740            getter,
7741            _phantom: PhantomData,
7742        }
7743    }
7744
7745    pub fn get_mut<'r>(&self, root: &'r mut Root) -> &'r mut Value {
7746        (self.getter)(root)
7747    }
7748
7749    /// Higher-order function: map the mutable value reference through a function.
7750    /// Returns a new `WritableKeyPath<Root, U, _>` that gets the value and applies `f` to the mutable reference.
7751    pub fn map<U, G>(self, f: G) -> WritableKeyPath<Root, U, impl for<'r> Fn(&'r mut Root) -> &'r mut U>
7752    where
7753        G: for<'r> Fn(&'r mut Value) -> &'r mut U,
7754        F: 'static,
7755        G: 'static,
7756        Root: 'static,
7757        Value: 'static,
7758    {
7759        let getter = self.getter;
7760        WritableKeyPath {
7761            getter: move |root| f(getter(root)),
7762            _phantom: PhantomData,
7763        }
7764    }
7765
7766    /// Map through a function that returns `Option<&mut U>`, producing a `WritableOptionalKeyPath`.
7767    /// Use when the projection may fail (e.g. `|v: &mut Vec<T>| v.first_mut()`).
7768    pub fn map_optional<U, G>(
7769        self,
7770        f: G,
7771    ) -> WritableOptionalKeyPath<Root, U, impl for<'r> Fn(&'r mut Root) -> Option<&'r mut U>>
7772    where
7773        G: for<'r> Fn(&'r mut Value) -> Option<&'r mut U>,
7774        F: 'static,
7775        G: 'static,
7776        Root: 'static,
7777        Value: 'static,
7778    {
7779        let getter = self.getter;
7780        WritableOptionalKeyPath {
7781            getter: move |root| f(getter(root)),
7782            _phantom: PhantomData,
7783        }
7784    }
7785
7786    /// Adapt this keypath to work with Result<Root, E> instead of Root
7787    /// This unwraps the Result and applies the keypath to the Ok value
7788    pub fn for_result<E>(
7789        self,
7790    ) -> WritableOptionalKeyPath<
7791        Result<Root, E>,
7792        Value,
7793        impl for<'r> Fn(&'r mut Result<Root, E>) -> Option<&'r mut Value> + 'static,
7794    >
7795    where
7796        F: 'static,
7797        Root: 'static,
7798        Value: 'static,
7799        E: 'static,
7800    {
7801        let getter = self.getter;
7802
7803        WritableOptionalKeyPath {
7804            getter: move |result: &mut Result<Root, E>| {
7805                result.as_mut().ok().map(|root| getter(root))
7806            },
7807            _phantom: PhantomData,
7808        }
7809    }
7810
7811    // Overload: Adapt root type to Box<Root> when Value is Sized (not a container)
7812    pub fn for_box_root(
7813        self,
7814    ) -> WritableKeyPath<
7815        Box<Root>,
7816        Value,
7817        impl for<'r> Fn(&'r mut Box<Root>) -> &'r mut Value + 'static,
7818    >
7819    where
7820        Value: Sized,
7821        F: 'static,
7822        Root: 'static,
7823        Value: 'static,
7824    {
7825        let getter = self.getter;
7826
7827        WritableKeyPath {
7828            getter: move |boxed: &mut Box<Root>| getter(boxed.as_mut()),
7829            _phantom: PhantomData,
7830        }
7831    }
7832
7833    /// Adapt this keypath to work with Option<Root> instead of Root
7834    /// This unwraps the Option and applies the keypath to the Some value
7835    pub fn for_option(
7836        self,
7837    ) -> WritableOptionalKeyPath<
7838        Option<Root>,
7839        Value,
7840        impl for<'r> Fn(&'r mut Option<Root>) -> Option<&'r mut Value> + 'static,
7841    >
7842    where
7843        F: 'static,
7844        Root: 'static,
7845        Value: 'static,
7846    {
7847        let getter = self.getter;
7848
7849        WritableOptionalKeyPath {
7850            getter: move |option: &mut Option<Root>| option.as_mut().map(|root| getter(root)),
7851            _phantom: PhantomData,
7852        }
7853    }
7854
7855    /// Convert a WritableKeyPath to WritableOptionalKeyPath for chaining
7856    /// This allows non-optional writable keypaths to be chained with then()
7857    pub fn to_optional(
7858        self,
7859    ) -> WritableOptionalKeyPath<
7860        Root,
7861        Value,
7862        impl for<'r> Fn(&'r mut Root) -> Option<&'r mut Value> + 'static,
7863    >
7864    where
7865        F: 'static,
7866    {
7867        let getter = self.getter;
7868        WritableOptionalKeyPath::new(move |root: &mut Root| Some(getter(root)))
7869    }
7870
7871    // Instance methods for unwrapping containers (automatically infers Target from Value::Target)
7872    // Box<T> -> T
7873    pub fn for_box<Target>(
7874        self,
7875    ) -> WritableKeyPath<Root, Target, impl for<'r> Fn(&'r mut Root) -> &'r mut Target + 'static>
7876    where
7877        Value: std::ops::DerefMut<Target = Target>,
7878        F: 'static,
7879        Value: 'static,
7880    {
7881        let getter = self.getter;
7882
7883        WritableKeyPath {
7884            getter: move |root: &mut Root| getter(root).deref_mut(),
7885            _phantom: PhantomData,
7886        }
7887    }
7888
7889    // Arc<T> -> T (Note: Arc doesn't support mutable access, but we provide it for consistency)
7890    // This will require interior mutability patterns
7891    pub fn for_arc<Target>(
7892        self,
7893    ) -> WritableKeyPath<Root, Target, impl for<'r> Fn(&'r mut Root) -> &'r mut Target + 'static>
7894    where
7895        Value: std::ops::DerefMut<Target = Target>,
7896        F: 'static,
7897        Value: 'static,
7898    {
7899        let getter = self.getter;
7900
7901        WritableKeyPath {
7902            getter: move |root: &mut Root| getter(root).deref_mut(),
7903            _phantom: PhantomData,
7904        }
7905    }
7906
7907    // Rc<T> -> T (Note: Rc doesn't support mutable access, but we provide it for consistency)
7908    // This will require interior mutability patterns
7909    pub fn for_rc<Target>(
7910        self,
7911    ) -> WritableKeyPath<Root, Target, impl for<'r> Fn(&'r mut Root) -> &'r mut Target + 'static>
7912    where
7913        Value: std::ops::DerefMut<Target = Target>,
7914        F: 'static,
7915        Value: 'static,
7916    {
7917        let getter = self.getter;
7918
7919        WritableKeyPath {
7920            getter: move |root: &mut Root| getter(root).deref_mut(),
7921            _phantom: PhantomData,
7922        }
7923    }
7924
7925    /// Execute a closure with a mutable reference to the value inside a Box
7926    pub fn with_box_mut<Callback, R>(&self, boxed: &mut Box<Root>, f: Callback) -> R
7927    where
7928        F: Clone,
7929        Callback: FnOnce(&mut Value) -> R,
7930    {
7931        let value = self.get_mut(boxed);
7932        f(value)
7933    }
7934
7935    /// Execute a closure with a mutable reference to the value inside a Result
7936    pub fn with_result_mut<Callback, R, E>(
7937        &self,
7938        result: &mut Result<Root, E>,
7939        f: Callback,
7940    ) -> Option<R>
7941    where
7942        F: Clone,
7943        Callback: FnOnce(&mut Value) -> R,
7944    {
7945        result.as_mut().ok().map(|root| {
7946            let value = self.get_mut(root);
7947            f(value)
7948        })
7949    }
7950
7951    /// Execute a closure with a mutable reference to the value inside an Option
7952    pub fn with_option_mut<Callback, R>(&self, option: &mut Option<Root>, f: Callback) -> Option<R>
7953    where
7954        F: Clone,
7955        Callback: FnOnce(&mut Value) -> R,
7956    {
7957        option.as_mut().map(|root| {
7958            let value = self.get_mut(root);
7959            f(value)
7960        })
7961    }
7962
7963    /// Execute a closure with a mutable reference to the value inside a RefCell
7964    pub fn with_refcell_mut<Callback, R>(&self, refcell: &RefCell<Root>, f: Callback) -> Option<R>
7965    where
7966        F: Clone,
7967        Callback: FnOnce(&mut Value) -> R,
7968    {
7969        refcell.try_borrow_mut().ok().map(|mut borrow| {
7970            let value = self.get_mut(&mut *borrow);
7971            f(value)
7972        })
7973    }
7974
7975    /// Execute a closure with a mutable reference to the value inside a Mutex
7976    pub fn with_mutex_mut<Callback, R>(&self, mutex: &mut Mutex<Root>, f: Callback) -> Option<R>
7977    where
7978        F: Clone,
7979        Callback: FnOnce(&mut Value) -> R,
7980    {
7981        mutex.get_mut().ok().map(|root| {
7982            let value = self.get_mut(root);
7983            f(value)
7984        })
7985    }
7986
7987    /// Execute a closure with a mutable reference to the value inside an RwLock
7988    pub fn with_rwlock_mut<Callback, R>(&self, rwlock: &mut RwLock<Root>, f: Callback) -> Option<R>
7989    where
7990        F: Clone,
7991        Callback: FnOnce(&mut Value) -> R,
7992    {
7993        rwlock.write().ok().map(|mut guard| {
7994            let value = self.get_mut(&mut *guard);
7995            f(value)
7996        })
7997    }
7998
7999    /// Get a mutable iterator over a Vec when Value is Vec<T>
8000    /// Returns Some(iterator) if the value is a Vec, None otherwise
8001    pub fn iter_mut<'r, T>(&self, root: &'r mut Root) -> Option<std::slice::IterMut<'r, T>>
8002    where
8003        Value: AsMut<[T]> + 'r,
8004    {
8005        let value_ref: &'r mut Value = self.get_mut(root);
8006        Some(value_ref.as_mut().iter_mut())
8007    }
8008
8009    /// Extract mutable values from a slice of owned mutable values
8010    /// Returns a Vec of mutable references to the extracted values
8011    pub fn extract_mut_from_slice<'r>(&self, slice: &'r mut [Root]) -> Vec<&'r mut Value> {
8012        slice.iter_mut().map(|item| self.get_mut(item)).collect()
8013    }
8014
8015    /// Extract mutable values from a slice of mutable references
8016    /// Returns a Vec of mutable references to the extracted values
8017    pub fn extract_mut_from_ref_slice<'r>(
8018        &self,
8019        slice: &'r mut [&'r mut Root],
8020    ) -> Vec<&'r mut Value> {
8021        slice.iter_mut().map(|item| self.get_mut(*item)).collect()
8022    }
8023
8024    /// Chain this keypath with another writable keypath
8025    /// Returns a WritableKeyPath that chains both keypaths
8026    pub fn then<SubValue, G>(
8027        self,
8028        next: WritableKeyPath<Value, SubValue, G>,
8029    ) -> WritableKeyPath<Root, SubValue, impl for<'r> Fn(&'r mut Root) -> &'r mut SubValue>
8030    where
8031        G: for<'r> Fn(&'r mut Value) -> &'r mut SubValue,
8032        F: 'static,
8033        G: 'static,
8034        Value: 'static,
8035    {
8036        let first = self.getter;
8037        let second = next.getter;
8038
8039        WritableKeyPath::new(move |root: &mut Root| {
8040            let value = first(root);
8041            second(value)
8042        })
8043    }
8044
8045    /// Chain this keypath with a writable optional keypath
8046    /// Returns a WritableOptionalKeyPath that chains both keypaths
8047    pub fn chain_optional<SubValue, G>(
8048        self,
8049        next: WritableOptionalKeyPath<Value, SubValue, G>,
8050    ) -> WritableOptionalKeyPath<
8051        Root,
8052        SubValue,
8053        impl for<'r> Fn(&'r mut Root) -> Option<&'r mut SubValue>,
8054    >
8055    where
8056        G: for<'r> Fn(&'r mut Value) -> Option<&'r mut SubValue>,
8057        F: 'static,
8058        G: 'static,
8059        Value: 'static,
8060    {
8061        let first = self.getter;
8062        let second = next.getter;
8063
8064        WritableOptionalKeyPath::new(move |root: &mut Root| {
8065            let value = first(root);
8066            second(value)
8067        })
8068    }
8069
8070    // ========== LOCK KEYPATH CONVERSION METHODS ==========
8071    // These methods convert keypaths pointing to lock types into chain-ready keypaths
8072
8073    /// Convert this writable keypath to an Arc<RwLock> chain-ready keypath
8074    /// Returns self, but serves as a marker for intent and enables chaining
8075    pub fn to_arc_rwlock_kp<InnerValue>(self) -> Self
8076    where
8077        Value: std::borrow::Borrow<Arc<RwLock<InnerValue>>>,
8078    {
8079        self
8080    }
8081
8082    /// Convert this writable keypath to an Arc<Mutex> chain-ready keypath
8083    /// Returns self, but serves as a marker for intent and enables chaining
8084    pub fn to_arc_mutex_kp<InnerValue>(self) -> Self
8085    where
8086        Value: std::borrow::Borrow<Arc<Mutex<InnerValue>>>,
8087    {
8088        self
8089    }
8090
8091    #[cfg(feature = "parking_lot")]
8092    /// Convert this writable keypath to an Arc<parking_lot::RwLock> chain-ready keypath
8093    /// Returns self, but serves as a marker for intent and enables chaining
8094    pub fn to_arc_parking_rwlock_kp<InnerValue>(self) -> Self
8095    where
8096        Value: std::borrow::Borrow<Arc<parking_lot::RwLock<InnerValue>>>,
8097    {
8098        self
8099    }
8100
8101    #[cfg(feature = "parking_lot")]
8102    /// Convert this writable keypath to an Arc<parking_lot::Mutex> chain-ready keypath
8103    /// Returns self, but serves as a marker for intent and enables chaining
8104    pub fn to_arc_parking_mutex_kp<InnerValue>(self) -> Self
8105    where
8106        Value: std::borrow::Borrow<Arc<parking_lot::Mutex<InnerValue>>>,
8107    {
8108        self
8109    }
8110}
8111
8112// WritableOptionalKeyPath for failable mutable access
8113#[derive(Clone)]
8114pub struct WritableOptionalKeyPath<Root, Value, F>
8115where
8116    F: for<'r> Fn(&'r mut Root) -> Option<&'r mut Value>,
8117{
8118    getter: F,
8119    _phantom: PhantomData<(Root, Value)>,
8120}
8121
8122impl<Root, Value, F> fmt::Display for WritableOptionalKeyPath<Root, Value, F>
8123where
8124    F: for<'r> Fn(&'r mut Root) -> Option<&'r mut Value>,
8125{
8126    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
8127        let root_name = std::any::type_name::<Root>();
8128        let value_name = std::any::type_name::<Value>();
8129        // Simplify type names by removing module paths for cleaner output
8130        let root_short = root_name.split("::").last().unwrap_or(root_name);
8131        let value_short = value_name.split("::").last().unwrap_or(value_name);
8132        write!(
8133            f,
8134            "WritableOptionalKeyPath<{} -> Option<{}>>",
8135            root_short, value_short
8136        )
8137    }
8138}
8139
8140impl<Root, Value, F> fmt::Debug for WritableOptionalKeyPath<Root, Value, F>
8141where
8142    F: for<'r> Fn(&'r mut Root) -> Option<&'r mut Value>,
8143{
8144    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
8145        // Show type information and indicate this is a chain that may fail
8146        let root_name = std::any::type_name::<Root>();
8147        let value_name = std::any::type_name::<Value>();
8148        let root_short = root_name.split("::").last().unwrap_or(root_name);
8149        let value_short = value_name.split("::").last().unwrap_or(value_name);
8150
8151        // Use alternate format for more detailed debugging
8152        if f.alternate() {
8153            writeln!(
8154                f,
8155                "WritableOptionalKeyPath<{} -> Option<{}>>",
8156                root_short, value_short
8157            )?;
8158            writeln!(
8159                f,
8160                "  âš  Chain may break if any intermediate step returns None"
8161            )?;
8162            writeln!(f, "  💡 Use trace_chain() to find where the chain breaks")
8163        } else {
8164            write!(
8165                f,
8166                "WritableOptionalKeyPath<{} -> Option<{}>>",
8167                root_short, value_short
8168            )
8169        }
8170    }
8171}
8172
8173impl<Root> WritableOptionalKeyPath<Root, Root, fn(&mut Root) -> Option<&mut Root>> {
8174    /// Identity writable optional keypath: projects `&mut Root` to `Some(root)`.
8175    pub fn identity() -> Self {
8176        WritableOptionalKeyPath {
8177            getter: identity_opt_mut::<Root>,
8178            _phantom: PhantomData,
8179        }
8180    }
8181}
8182
8183impl<Root, Value, F> WritableOptionalKeyPath<Root, Value, F>
8184where
8185    F: for<'r> Fn(&'r mut Root) -> Option<&'r mut Value>,
8186{
8187    pub fn new(getter: F) -> Self {
8188        Self {
8189            getter,
8190            _phantom: PhantomData,
8191        }
8192    }
8193
8194    pub fn get_mut<'r>(&self, root: &'r mut Root) -> Option<&'r mut Value> {
8195        (self.getter)(root)
8196    }
8197
8198    /// Higher-order function: map the optional mutable value reference through a function.
8199    /// Returns a new `WritableOptionalKeyPath<Root, U, _>` that gets the value and applies `f` when present.
8200    pub fn map<U, G>(
8201        self,
8202        f: G,
8203    ) -> WritableOptionalKeyPath<Root, U, impl for<'r> Fn(&'r mut Root) -> Option<&'r mut U>>
8204    where
8205        G: for<'r> Fn(&'r mut Value) -> &'r mut U,
8206        F: 'static,
8207        G: 'static,
8208        Root: 'static,
8209        Value: 'static,
8210    {
8211        let getter = self.getter;
8212        WritableOptionalKeyPath {
8213            getter: move |root| getter(root).map(|v| f(v)),
8214            _phantom: PhantomData,
8215        }
8216    }
8217
8218    /// Map through a function that returns `Option<&mut U>`, keeping a `WritableOptionalKeyPath`.
8219    /// Use when the inner projection may fail (e.g. `|v: &mut Vec<T>| v.first_mut()`).
8220    pub fn map_optional<U, G>(
8221        self,
8222        f: G,
8223    ) -> WritableOptionalKeyPath<Root, U, impl for<'r> Fn(&'r mut Root) -> Option<&'r mut U>>
8224    where
8225        G: for<'r> Fn(&'r mut Value) -> Option<&'r mut U>,
8226        F: 'static,
8227        G: 'static,
8228        Root: 'static,
8229        Value: 'static,
8230    {
8231        let getter = self.getter;
8232        WritableOptionalKeyPath {
8233            getter: move |root| getter(root).and_then(|v| f(v)),
8234            _phantom: PhantomData,
8235        }
8236    }
8237
8238    /// Trace the chain to find where it breaks
8239    /// Returns Ok(()) if the chain succeeds, or Err with diagnostic information
8240    ///
8241    /// # Example
8242    /// ```rust
8243    /// let path = SomeComplexStruct::scsf_fw()
8244    ///     .then(SomeOtherStruct::sosf_fw())
8245    ///     .then(SomeEnum::b_fw());
8246    ///
8247    /// match path.trace_chain(&mut instance) {
8248    ///     Ok(()) => println!("Chain succeeded"),
8249    ///     Err(msg) => println!("Chain broken: {}", msg),
8250    /// }
8251    /// ```
8252    pub fn trace_chain(&self, root: &mut Root) -> Result<(), String> {
8253        match self.get_mut(root) {
8254            Some(_) => Ok(()),
8255            None => {
8256                let root_name = std::any::type_name::<Root>();
8257                let value_name = std::any::type_name::<Value>();
8258                let root_short = root_name.split("::").last().unwrap_or(root_name);
8259                let value_short = value_name.split("::").last().unwrap_or(value_name);
8260                Err(format!(
8261                    "{} -> Option<{}> returned None (chain broken at this step)",
8262                    root_short, value_short
8263                ))
8264            }
8265        }
8266    }
8267
8268    /// Adapt this keypath to work with Option<Root> instead of Root
8269    /// This unwraps the Option and applies the keypath to the Some value
8270    pub fn for_option(
8271        self,
8272    ) -> WritableOptionalKeyPath<
8273        Option<Root>,
8274        Value,
8275        impl for<'r> Fn(&'r mut Option<Root>) -> Option<&'r mut Value> + 'static,
8276    >
8277    where
8278        F: 'static,
8279        Root: 'static,
8280        Value: 'static,
8281    {
8282        let getter = self.getter;
8283
8284        WritableOptionalKeyPath {
8285            getter: move |option: &mut Option<Root>| option.as_mut().and_then(|root| getter(root)),
8286            _phantom: PhantomData,
8287        }
8288    }
8289
8290    // Swift-like operator for chaining WritableOptionalKeyPath
8291    pub fn then<SubValue, G>(
8292        self,
8293        next: WritableOptionalKeyPath<Value, SubValue, G>,
8294    ) -> WritableOptionalKeyPath<
8295        Root,
8296        SubValue,
8297        impl for<'r> Fn(&'r mut Root) -> Option<&'r mut SubValue>,
8298    >
8299    where
8300        G: for<'r> Fn(&'r mut Value) -> Option<&'r mut SubValue>,
8301        F: 'static,
8302        G: 'static,
8303        Value: 'static,
8304    {
8305        let first = self.getter;
8306        let second = next.getter;
8307
8308        WritableOptionalKeyPath::new(move |root: &mut Root| {
8309            first(root).and_then(|value| second(value))
8310        })
8311    }
8312
8313    // Instance methods for unwrapping containers from Option<Container<T>>
8314    // Option<Box<T>> -> Option<&mut T> (type automatically inferred from Value::Target)
8315    pub fn for_box<Target>(
8316        self,
8317    ) -> WritableOptionalKeyPath<
8318        Root,
8319        Target,
8320        impl for<'r> Fn(&'r mut Root) -> Option<&'r mut Target> + 'static,
8321    >
8322    where
8323        Value: std::ops::DerefMut<Target = Target>,
8324        F: 'static,
8325        Value: 'static,
8326    {
8327        let getter = self.getter;
8328
8329        WritableOptionalKeyPath {
8330            getter: move |root: &mut Root| getter(root).map(|boxed| boxed.deref_mut()),
8331            _phantom: PhantomData,
8332        }
8333    }
8334
8335    // Option<Arc<T>> -> Option<&mut T> (type automatically inferred from Value::Target)
8336    pub fn for_arc<Target>(
8337        self,
8338    ) -> WritableOptionalKeyPath<
8339        Root,
8340        Target,
8341        impl for<'r> Fn(&'r mut Root) -> Option<&'r mut Target> + 'static,
8342    >
8343    where
8344        Value: std::ops::DerefMut<Target = Target>,
8345        F: 'static,
8346        Value: 'static,
8347    {
8348        let getter = self.getter;
8349
8350        WritableOptionalKeyPath {
8351            getter: move |root: &mut Root| getter(root).map(|arc| arc.deref_mut()),
8352            _phantom: PhantomData,
8353        }
8354    }
8355
8356    // Option<Rc<T>> -> Option<&mut T> (type automatically inferred from Value::Target)
8357    pub fn for_rc<Target>(
8358        self,
8359    ) -> WritableOptionalKeyPath<
8360        Root,
8361        Target,
8362        impl for<'r> Fn(&'r mut Root) -> Option<&'r mut Target> + 'static,
8363    >
8364    where
8365        Value: std::ops::DerefMut<Target = Target>,
8366        F: 'static,
8367        Value: 'static,
8368    {
8369        let getter = self.getter;
8370
8371        WritableOptionalKeyPath {
8372            getter: move |root: &mut Root| getter(root).map(|rc| rc.deref_mut()),
8373            _phantom: PhantomData,
8374        }
8375    }
8376
8377    /// Adapt this keypath to work with Result<Root, E> instead of Root
8378    /// This unwraps the Result and applies the keypath to the Ok value
8379    pub fn for_result<E>(
8380        self,
8381    ) -> WritableOptionalKeyPath<
8382        Result<Root, E>,
8383        Value,
8384        impl for<'r> Fn(&'r mut Result<Root, E>) -> Option<&'r mut Value> + 'static,
8385    >
8386    where
8387        F: 'static,
8388        Root: 'static,
8389        Value: 'static,
8390        E: 'static,
8391    {
8392        let getter = self.getter;
8393
8394        WritableOptionalKeyPath {
8395            getter: move |result: &mut Result<Root, E>| {
8396                result.as_mut().ok().and_then(|root| getter(root))
8397            },
8398            _phantom: PhantomData,
8399        }
8400    }
8401
8402    // Overload: Adapt root type to Box<Root> when Value is Sized (not a container)
8403    pub fn for_box_root(
8404        self,
8405    ) -> WritableOptionalKeyPath<
8406        Box<Root>,
8407        Value,
8408        impl for<'r> Fn(&'r mut Box<Root>) -> Option<&'r mut Value> + 'static,
8409    >
8410    where
8411        Value: Sized,
8412        F: 'static,
8413        Root: 'static,
8414        Value: 'static,
8415    {
8416        let getter = self.getter;
8417
8418        WritableOptionalKeyPath {
8419            getter: move |boxed: &mut Box<Root>| getter(boxed.as_mut()),
8420            _phantom: PhantomData,
8421        }
8422    }
8423
8424    // Overload: Adapt root type to Arc<Root> when Value is Sized (not a container)
8425    pub fn for_arc_root(
8426        self,
8427    ) -> WritableOptionalKeyPath<
8428        Arc<Root>,
8429        Value,
8430        impl for<'r> Fn(&'r mut Arc<Root>) -> Option<&'r mut Value> + 'static,
8431    >
8432    where
8433        Value: Sized,
8434        F: 'static,
8435        Root: 'static,
8436        Value: 'static,
8437    {
8438        let getter = self.getter;
8439
8440        WritableOptionalKeyPath {
8441            getter: move |arc: &mut Arc<Root>| {
8442                // Arc doesn't support mutable access without interior mutability
8443                // This will always return None, but we provide it for API consistency
8444                None
8445            },
8446            _phantom: PhantomData,
8447        }
8448    }
8449
8450    // Overload: Adapt root type to Rc<Root> when Value is Sized (not a container)
8451    pub fn for_rc_root(
8452        self,
8453    ) -> WritableOptionalKeyPath<
8454        Rc<Root>,
8455        Value,
8456        impl for<'r> Fn(&'r mut Rc<Root>) -> Option<&'r mut Value> + 'static,
8457    >
8458    where
8459        Value: Sized,
8460        F: 'static,
8461        Root: 'static,
8462        Value: 'static,
8463    {
8464        let getter = self.getter;
8465
8466        WritableOptionalKeyPath {
8467            getter: move |rc: &mut Rc<Root>| {
8468                // Rc doesn't support mutable access without interior mutability
8469                // This will always return None, but we provide it for API consistency
8470                None
8471            },
8472            _phantom: PhantomData,
8473        }
8474    }
8475
8476    // ========== LOCK KEYPATH CONVERSION METHODS ==========
8477    // These methods convert keypaths pointing to lock types into chain-ready keypaths
8478
8479    /// Convert this writable optional keypath to an Arc<RwLock> chain-ready keypath
8480    /// Returns self, but serves as a marker for intent and enables chaining
8481    pub fn to_arc_rwlock_kp<InnerValue>(self) -> Self
8482    where
8483        Value: std::borrow::Borrow<Arc<RwLock<InnerValue>>>,
8484    {
8485        self
8486    }
8487
8488    /// Convert this writable optional keypath to an Arc<Mutex> chain-ready keypath
8489    /// Returns self, but serves as a marker for intent and enables chaining
8490    pub fn to_arc_mutex_kp<InnerValue>(self) -> Self
8491    where
8492        Value: std::borrow::Borrow<Arc<Mutex<InnerValue>>>,
8493    {
8494        self
8495    }
8496
8497    #[cfg(feature = "parking_lot")]
8498    /// Convert this writable optional keypath to an Arc<parking_lot::RwLock> chain-ready keypath
8499    /// Returns self, but serves as a marker for intent and enables chaining
8500    pub fn to_arc_parking_rwlock_kp<InnerValue>(self) -> Self
8501    where
8502        Value: std::borrow::Borrow<Arc<parking_lot::RwLock<InnerValue>>>,
8503    {
8504        self
8505    }
8506
8507    #[cfg(feature = "parking_lot")]
8508    /// Convert this writable optional keypath to an Arc<parking_lot::Mutex> chain-ready keypath
8509    /// Returns self, but serves as a marker for intent and enables chaining
8510    pub fn to_arc_parking_mutex_kp<InnerValue>(self) -> Self
8511    where
8512        Value: std::borrow::Borrow<Arc<parking_lot::Mutex<InnerValue>>>,
8513    {
8514        self
8515    }
8516}
8517
8518// Static factory methods for WritableOptionalKeyPath
8519impl WritableOptionalKeyPath<(), (), fn(&mut ()) -> Option<&mut ()>> {
8520    // Static method for Option<T> -> Option<&mut T>
8521    // Note: This is a factory method. Use instance method `for_option()` to adapt existing keypaths.
8522    pub fn for_option_static<T>() -> WritableOptionalKeyPath<
8523        Option<T>,
8524        T,
8525        impl for<'r> Fn(&'r mut Option<T>) -> Option<&'r mut T>,
8526    > {
8527        WritableOptionalKeyPath::new(|opt: &mut Option<T>| opt.as_mut())
8528    }
8529
8530    /// Backword compatibility method for writable enum keypath
8531    // Create a writable enum keypath for enum variants
8532    /// This allows both reading and writing to enum variant fields
8533    ///
8534    /// # Arguments
8535    /// * `embedder` - Function to embed a value into the enum variant (for API consistency, not used)
8536    /// * `read_extractor` - Function to extract a read reference from the enum (for API consistency, not used)
8537    /// * `write_extractor` - Function to extract a mutable reference from the enum
8538    ///
8539    /// # Example
8540    /// ```rust
8541    /// enum Color { Other(RGBU8) }
8542    /// struct RGBU8(u8, u8, u8);
8543    ///
8544    /// let case_path = WritableOptionalKeyPath::writable_enum(
8545    ///     |v| Color::Other(v),
8546    ///     |p: &Color| match p { Color::Other(rgb) => Some(rgb), _ => None },
8547    ///     |p: &mut Color| match p { Color::Other(rgb) => Some(rgb), _ => None },
8548    /// );
8549    /// ```
8550    pub fn writable_enum<Enum, Variant, EmbedFn, ReadExtractFn, WriteExtractFn>(
8551        _embedder: EmbedFn,
8552        _read_extractor: ReadExtractFn,
8553        write_extractor: WriteExtractFn,
8554    ) -> WritableOptionalKeyPath<
8555        Enum,
8556        Variant,
8557        impl for<'r> Fn(&'r mut Enum) -> Option<&'r mut Variant> + 'static,
8558    >
8559    where
8560        EmbedFn: Fn(Variant) -> Enum + 'static,
8561        ReadExtractFn: for<'r> Fn(&'r Enum) -> Option<&'r Variant> + 'static,
8562        WriteExtractFn: for<'r> Fn(&'r mut Enum) -> Option<&'r mut Variant> + 'static,
8563    {
8564        WritableOptionalKeyPath::new(write_extractor)
8565    }
8566}
8567
8568// Enum-specific keypaths
8569/// EnumKeyPath - A keypath for enum variants that supports both extraction and embedding
8570/// Uses generic type parameters instead of dynamic dispatch for zero-cost abstraction
8571///
8572/// This struct serves dual purpose:
8573/// 1. As a concrete keypath instance: `EnumKeyPath<Enum, Variant, ExtractFn, EmbedFn>`
8574/// 2. As a namespace for static factory methods: `EnumKeyPath::readable_enum(...)`
8575pub struct EnumKeyPath<
8576    Enum = (),
8577    Variant = (),
8578    ExtractFn = fn(&()) -> Option<&()>,
8579    EmbedFn = fn(()) -> (),
8580> where
8581    ExtractFn: for<'r> Fn(&'r Enum) -> Option<&'r Variant> + 'static,
8582    EmbedFn: Fn(Variant) -> Enum + 'static,
8583{
8584    extractor: OptionalKeyPath<Enum, Variant, ExtractFn>,
8585    embedder: EmbedFn,
8586}
8587
8588impl<Enum, Variant, ExtractFn, EmbedFn> EnumKeyPath<Enum, Variant, ExtractFn, EmbedFn>
8589where
8590    ExtractFn: for<'r> Fn(&'r Enum) -> Option<&'r Variant> + 'static,
8591    EmbedFn: Fn(Variant) -> Enum + 'static,
8592{
8593    /// Create a new EnumKeyPath with extractor and embedder functions
8594    pub fn new(extractor: ExtractFn, embedder: EmbedFn) -> Self {
8595        Self {
8596            extractor: OptionalKeyPath::new(extractor),
8597            embedder,
8598        }
8599    }
8600
8601    /// Extract the value from an enum variant
8602    pub fn get<'r>(&self, enum_value: &'r Enum) -> Option<&'r Variant> {
8603        self.extractor.get(enum_value)
8604    }
8605
8606    /// Embed a value into the enum variant
8607    pub fn embed(&self, value: Variant) -> Enum {
8608        (self.embedder)(value)
8609    }
8610
8611    /// Get the underlying OptionalKeyPath for composition
8612    pub fn as_optional(&self) -> &OptionalKeyPath<Enum, Variant, ExtractFn> {
8613        &self.extractor
8614    }
8615
8616    /// Convert to OptionalKeyPath (loses embedding capability but gains composition)
8617    pub fn to_optional(self) -> OptionalKeyPath<Enum, Variant, ExtractFn> {
8618        self.extractor
8619    }
8620}
8621
8622// Static factory methods for EnumKeyPath
8623impl EnumKeyPath {
8624    /// Identity enum keypath: `Enum = Variant`, extract returns `Some(&e)`, embed returns the value unchanged.
8625    pub fn identity<E>() -> EnumKeyPath<E, E, fn(&E) -> Option<&E>, fn(E) -> E> {
8626        EnumKeyPath {
8627            extractor: OptionalKeyPath::new(identity_opt_ref::<E>),
8628            embedder: identity_value::<E>,
8629        }
8630    }
8631
8632    /// Create a readable enum keypath with both extraction and embedding
8633    /// Returns an EnumKeyPath that supports both get() and embed() operations
8634    pub fn readable_enum<Enum, Variant, ExtractFn, EmbedFn>(
8635        embedder: EmbedFn,
8636        extractor: ExtractFn,
8637    ) -> EnumKeyPath<Enum, Variant, ExtractFn, EmbedFn>
8638    where
8639        ExtractFn: for<'r> Fn(&'r Enum) -> Option<&'r Variant> + 'static,
8640        EmbedFn: Fn(Variant) -> Enum + 'static,
8641    {
8642        EnumKeyPath::new(extractor, embedder)
8643    }
8644
8645    /// Extract from a specific enum variant
8646    pub fn for_variant<Enum, Variant, ExtractFn>(
8647        extractor: ExtractFn,
8648    ) -> OptionalKeyPath<Enum, Variant, impl for<'r> Fn(&'r Enum) -> Option<&'r Variant>>
8649    where
8650        ExtractFn: Fn(&Enum) -> Option<&Variant>,
8651    {
8652        OptionalKeyPath::new(extractor)
8653    }
8654
8655    /// Match against multiple variants (returns a tagged union)
8656    pub fn for_match<Enum, Output, MatchFn>(
8657        matcher: MatchFn,
8658    ) -> KeyPath<Enum, Output, impl for<'r> Fn(&'r Enum) -> &'r Output>
8659    where
8660        MatchFn: Fn(&Enum) -> &Output,
8661    {
8662        KeyPath::new(matcher)
8663    }
8664
8665    /// Extract from Result<T, E> - Ok variant
8666    pub fn for_ok<T, E>()
8667    -> OptionalKeyPath<Result<T, E>, T, impl for<'r> Fn(&'r Result<T, E>) -> Option<&'r T>> {
8668        OptionalKeyPath::new(|result: &Result<T, E>| result.as_ref().ok())
8669    }
8670
8671    /// Extract from Result<T, E> - Err variant
8672    pub fn for_err<T, E>()
8673    -> OptionalKeyPath<Result<T, E>, E, impl for<'r> Fn(&'r Result<T, E>) -> Option<&'r E>> {
8674        OptionalKeyPath::new(|result: &Result<T, E>| result.as_ref().err())
8675    }
8676
8677    /// Extract from Option<T> - Some variant
8678    pub fn for_some<T>()
8679    -> OptionalKeyPath<Option<T>, T, impl for<'r> Fn(&'r Option<T>) -> Option<&'r T>> {
8680        OptionalKeyPath::new(|opt: &Option<T>| opt.as_ref())
8681    }
8682
8683    /// Extract from Option<T> - Some variant (alias for for_some for consistency)
8684    pub fn for_option<T>()
8685    -> OptionalKeyPath<Option<T>, T, impl for<'r> Fn(&'r Option<T>) -> Option<&'r T>> {
8686        OptionalKeyPath::new(|opt: &Option<T>| opt.as_ref())
8687    }
8688
8689    /// Unwrap Box<T> -> T
8690    pub fn for_box<T>() -> KeyPath<Box<T>, T, impl for<'r> Fn(&'r Box<T>) -> &'r T> {
8691        KeyPath::new(|b: &Box<T>| b.as_ref())
8692    }
8693
8694    /// Unwrap Arc<T> -> T
8695    pub fn for_arc<T>() -> KeyPath<Arc<T>, T, impl for<'r> Fn(&'r Arc<T>) -> &'r T> {
8696        KeyPath::new(|arc: &Arc<T>| arc.as_ref())
8697    }
8698
8699    /// Unwrap Rc<T> -> T
8700    pub fn for_rc<T>() -> KeyPath<std::rc::Rc<T>, T, impl for<'r> Fn(&'r std::rc::Rc<T>) -> &'r T> {
8701        KeyPath::new(|rc: &std::rc::Rc<T>| rc.as_ref())
8702    }
8703
8704    /// Unwrap Box<T> -> T (mutable)
8705    pub fn for_box_mut<T>()
8706    -> WritableKeyPath<Box<T>, T, impl for<'r> Fn(&'r mut Box<T>) -> &'r mut T> {
8707        WritableKeyPath::new(|b: &mut Box<T>| b.as_mut())
8708    }
8709
8710    // Note: Arc<T> and Rc<T> don't support direct mutable access without interior mutability
8711    // (e.g., Arc<Mutex<T>> or Rc<RefCell<T>>). These methods are not provided as they
8712    // would require unsafe code or interior mutability patterns.
8713}
8714
8715// Helper to create enum variant keypaths with type inference
8716pub fn variant_of<Enum, Variant, F>(extractor: F) -> OptionalKeyPath<Enum, Variant, F>
8717where
8718    F: for<'r> Fn(&'r Enum) -> Option<&'r Variant>,
8719{
8720    OptionalKeyPath::new(extractor)
8721}
8722
8723// ========== PARTIAL KEYPATHS (Hide Value Type) ==========
8724
8725/// PartialKeyPath - Hides the Value type but keeps Root visible
8726/// Useful for storing keypaths in collections without knowing the exact Value type
8727///
8728/// # Why PhantomData<Root>?
8729///
8730/// `PhantomData<Root>` is needed because:
8731/// 1. The `Root` type parameter is not actually stored in the struct (only used in the closure)
8732/// 2. Rust needs to know the generic type parameter for:
8733///    - Type checking at compile time
8734///    - Ensuring correct usage (e.g., `PartialKeyPath<User>` can only be used with `&User`)
8735///    - Preventing mixing different Root types
8736/// 3. Without `PhantomData`, Rust would complain that `Root` is unused
8737/// 4. `PhantomData` is zero-sized - it adds no runtime overhead
8738#[derive(Clone)]
8739pub struct PartialKeyPath<Root> {
8740    getter: Rc<dyn for<'r> Fn(&'r Root) -> &'r dyn Any>,
8741    value_type_id: TypeId,
8742    _phantom: PhantomData<Root>,
8743}
8744
8745impl<Root> PartialKeyPath<Root> {
8746    pub fn new<Value>(
8747        keypath: KeyPath<Root, Value, impl for<'r> Fn(&'r Root) -> &'r Value + 'static>,
8748    ) -> Self
8749    where
8750        Value: Any + 'static,
8751        Root: 'static,
8752    {
8753        let value_type_id = TypeId::of::<Value>();
8754        let getter = Rc::new(keypath.getter);
8755
8756        Self {
8757            getter: Rc::new(move |root: &Root| {
8758                let value: &Value = getter(root);
8759                value as &dyn Any
8760            }),
8761            value_type_id,
8762            _phantom: PhantomData,
8763        }
8764    }
8765
8766    /// Create a PartialKeyPath from a concrete KeyPath
8767    /// Alias for `new()` for consistency with `from()` pattern
8768    pub fn from<Value>(
8769        keypath: KeyPath<Root, Value, impl for<'r> Fn(&'r Root) -> &'r Value + 'static>,
8770    ) -> Self
8771    where
8772        Value: Any + 'static,
8773        Root: 'static,
8774    {
8775        Self::new(keypath)
8776    }
8777
8778    pub fn get<'r>(&self, root: &'r Root) -> &'r dyn Any {
8779        (self.getter)(root)
8780    }
8781
8782    /// Get the TypeId of the Value type
8783    pub fn value_type_id(&self) -> TypeId {
8784        self.value_type_id
8785    }
8786
8787    /// Try to downcast the result to a specific type
8788    pub fn get_as<'a, Value: Any>(&self, root: &'a Root) -> Option<&'a Value> {
8789        if self.value_type_id == TypeId::of::<Value>() {
8790            self.get(root).downcast_ref::<Value>()
8791        } else {
8792            None
8793        }
8794    }
8795
8796    /// Get a human-readable name for the value type
8797    /// Returns a string representation of the TypeId
8798    pub fn kind_name(&self) -> String {
8799        format!("{:?}", self.value_type_id)
8800    }
8801
8802    /// Adapt this keypath to work with Arc<Root> instead of Root
8803    pub fn for_arc(&self) -> PartialOptionalKeyPath<Arc<Root>>
8804    where
8805        Root: 'static,
8806    {
8807        let getter = self.getter.clone();
8808        let value_type_id = self.value_type_id;
8809
8810        PartialOptionalKeyPath {
8811            getter: Rc::new(move |arc: &Arc<Root>| Some(getter(arc.as_ref()))),
8812            value_type_id,
8813            _phantom: PhantomData,
8814        }
8815    }
8816
8817    /// Adapt this keypath to work with Box<Root> instead of Root
8818    pub fn for_box(&self) -> PartialOptionalKeyPath<Box<Root>>
8819    where
8820        Root: 'static,
8821    {
8822        let getter = self.getter.clone();
8823        let value_type_id = self.value_type_id;
8824
8825        PartialOptionalKeyPath {
8826            getter: Rc::new(move |boxed: &Box<Root>| Some(getter(boxed.as_ref()))),
8827            value_type_id,
8828            _phantom: PhantomData,
8829        }
8830    }
8831
8832    /// Adapt this keypath to work with Rc<Root> instead of Root
8833    pub fn for_rc(&self) -> PartialOptionalKeyPath<Rc<Root>>
8834    where
8835        Root: 'static,
8836    {
8837        let getter = self.getter.clone();
8838        let value_type_id = self.value_type_id;
8839
8840        PartialOptionalKeyPath {
8841            getter: Rc::new(move |rc: &Rc<Root>| Some(getter(rc.as_ref()))),
8842            value_type_id,
8843            _phantom: PhantomData,
8844        }
8845    }
8846
8847    /// Adapt this keypath to work with Option<Root> instead of Root
8848    pub fn for_option(&self) -> PartialOptionalKeyPath<Option<Root>>
8849    where
8850        Root: 'static,
8851    {
8852        let getter = self.getter.clone();
8853        let value_type_id = self.value_type_id;
8854
8855        PartialOptionalKeyPath {
8856            getter: Rc::new(move |opt: &Option<Root>| opt.as_ref().map(|root| getter(root))),
8857            value_type_id,
8858            _phantom: PhantomData,
8859        }
8860    }
8861
8862    /// Adapt this keypath to work with Result<Root, E> instead of Root
8863    pub fn for_result<E>(&self) -> PartialOptionalKeyPath<Result<Root, E>>
8864    where
8865        Root: 'static,
8866        E: 'static,
8867    {
8868        let getter = self.getter.clone();
8869        let value_type_id = self.value_type_id;
8870
8871        PartialOptionalKeyPath {
8872            getter: Rc::new(move |result: &Result<Root, E>| {
8873                result.as_ref().ok().map(|root| getter(root))
8874            }),
8875            value_type_id,
8876            _phantom: PhantomData,
8877        }
8878    }
8879
8880    /// Adapt this keypath to work with Arc<RwLock<Root>> instead of Root
8881    /// Note: This requires the Root to be cloned first, then use the keypath on the cloned value
8882    /// Example: `keypath.get_as::<Value>(&arc_rwlock.read().unwrap().clone())`
8883    pub fn for_arc_rwlock(&self) -> PartialOptionalKeyPath<Arc<RwLock<Root>>>
8884    where
8885        Root: Clone + 'static,
8886    {
8887        // We can't return a reference from a guard, so we return None
8888        // Users should clone the root first: arc_rwlock.read().unwrap().clone()
8889        PartialOptionalKeyPath {
8890            getter: Rc::new(move |_arc_rwlock: &Arc<RwLock<Root>>| {
8891                // Cannot return reference from temporary guard
8892                // User should clone the root first and use the keypath on the cloned value
8893                None
8894            }),
8895            value_type_id: self.value_type_id,
8896            _phantom: PhantomData,
8897        }
8898    }
8899
8900    /// Adapt this keypath to work with Arc<Mutex<Root>> instead of Root
8901    /// Note: This requires the Root to be cloned first, then use the keypath on the cloned value
8902    /// Example: `keypath.get_as::<Value>(&arc_mutex.lock().unwrap().clone())`
8903    pub fn for_arc_mutex(&self) -> PartialOptionalKeyPath<Arc<Mutex<Root>>>
8904    where
8905        Root: Clone + 'static,
8906    {
8907        // We can't return a reference from a guard, so we return None
8908        // Users should clone the root first: arc_mutex.lock().unwrap().clone()
8909        PartialOptionalKeyPath {
8910            getter: Rc::new(move |_arc_mutex: &Arc<Mutex<Root>>| {
8911                // Cannot return reference from temporary guard
8912                // User should clone the root first and use the keypath on the cloned value
8913                None
8914            }),
8915            value_type_id: self.value_type_id,
8916            _phantom: PhantomData,
8917        }
8918    }
8919}
8920
8921/// PartialOptionalKeyPath - Hides the Value type but keeps Root visible
8922/// Useful for storing optional keypaths in collections without knowing the exact Value type
8923///
8924/// # Why PhantomData<Root>?
8925///
8926/// See `PartialKeyPath` documentation for explanation of why `PhantomData` is needed.
8927#[derive(Clone)]
8928pub struct PartialOptionalKeyPath<Root> {
8929    getter: Rc<dyn for<'r> Fn(&'r Root) -> Option<&'r dyn Any>>,
8930    value_type_id: TypeId,
8931    _phantom: PhantomData<Root>,
8932}
8933
8934impl<Root> PartialOptionalKeyPath<Root> {
8935    pub fn new<Value>(
8936        keypath: OptionalKeyPath<
8937            Root,
8938            Value,
8939            impl for<'r> Fn(&'r Root) -> Option<&'r Value> + 'static,
8940        >,
8941    ) -> Self
8942    where
8943        Value: Any + 'static,
8944        Root: 'static,
8945    {
8946        let value_type_id = TypeId::of::<Value>();
8947        let getter = Rc::new(keypath.getter);
8948
8949        Self {
8950            getter: Rc::new(move |root: &Root| getter(root).map(|value: &Value| value as &dyn Any)),
8951            value_type_id,
8952            _phantom: PhantomData,
8953        }
8954    }
8955
8956    pub fn get<'r>(&self, root: &'r Root) -> Option<&'r dyn Any> {
8957        (self.getter)(root)
8958    }
8959
8960    /// Get the TypeId of the Value type
8961    pub fn value_type_id(&self) -> TypeId {
8962        self.value_type_id
8963    }
8964
8965    /// Try to downcast the result to a specific type
8966    pub fn get_as<'a, Value: Any>(&self, root: &'a Root) -> Option<Option<&'a Value>> {
8967        if self.value_type_id == TypeId::of::<Value>() {
8968            self.get(root).map(|any| any.downcast_ref::<Value>())
8969        } else {
8970            None
8971        }
8972    }
8973
8974    /// Chain with another PartialOptionalKeyPath
8975    /// Note: This requires the Value type of the first keypath to match the Root type of the second
8976    /// For type-erased chaining, consider using AnyKeyPath instead
8977    pub fn then<MidValue>(
8978        self,
8979        next: PartialOptionalKeyPath<MidValue>,
8980    ) -> PartialOptionalKeyPath<Root>
8981    where
8982        MidValue: Any + 'static,
8983        Root: 'static,
8984    {
8985        let first = self.getter;
8986        let second = next.getter;
8987        let value_type_id = next.value_type_id;
8988
8989        PartialOptionalKeyPath {
8990            getter: Rc::new(move |root: &Root| {
8991                first(root).and_then(|any| {
8992                    if let Some(mid_value) = any.downcast_ref::<MidValue>() {
8993                        second(mid_value)
8994                    } else {
8995                        None
8996                    }
8997                })
8998            }),
8999            value_type_id,
9000            _phantom: PhantomData,
9001        }
9002    }
9003}
9004
9005/// PartialWritableKeyPath - Hides the Value type but keeps Root visible (writable)
9006///
9007/// # Why PhantomData<Root>?
9008///
9009/// See `PartialKeyPath` documentation for explanation of why `PhantomData` is needed.
9010#[derive(Clone)]
9011pub struct PartialWritableKeyPath<Root> {
9012    getter: Rc<dyn for<'r> Fn(&'r mut Root) -> &'r mut dyn Any>,
9013    value_type_id: TypeId,
9014    _phantom: PhantomData<Root>,
9015}
9016
9017impl<Root> PartialWritableKeyPath<Root> {
9018    pub fn new<Value>(
9019        keypath: WritableKeyPath<
9020            Root,
9021            Value,
9022            impl for<'r> Fn(&'r mut Root) -> &'r mut Value + 'static,
9023        >,
9024    ) -> Self
9025    where
9026        Value: Any + 'static,
9027        Root: 'static,
9028    {
9029        let value_type_id = TypeId::of::<Value>();
9030        let getter = Rc::new(keypath.getter);
9031
9032        Self {
9033            getter: Rc::new(move |root: &mut Root| {
9034                let value: &mut Value = getter(root);
9035                value as &mut dyn Any
9036            }),
9037            value_type_id,
9038            _phantom: PhantomData,
9039        }
9040    }
9041
9042    /// Create a PartialWritableKeyPath from a concrete WritableKeyPath
9043    /// Alias for `new()` for consistency with `from()` pattern
9044    pub fn from<Value>(
9045        keypath: WritableKeyPath<
9046            Root,
9047            Value,
9048            impl for<'r> Fn(&'r mut Root) -> &'r mut Value + 'static,
9049        >,
9050    ) -> Self
9051    where
9052        Value: Any + 'static,
9053        Root: 'static,
9054    {
9055        Self::new(keypath)
9056    }
9057
9058    pub fn get_mut<'r>(&self, root: &'r mut Root) -> &'r mut dyn Any {
9059        (self.getter)(root)
9060    }
9061
9062    /// Get the TypeId of the Value type
9063    pub fn value_type_id(&self) -> TypeId {
9064        self.value_type_id
9065    }
9066
9067    /// Try to downcast the result to a specific type
9068    pub fn get_mut_as<'a, Value: Any>(&self, root: &'a mut Root) -> Option<&'a mut Value> {
9069        if self.value_type_id == TypeId::of::<Value>() {
9070            self.get_mut(root).downcast_mut::<Value>()
9071        } else {
9072            None
9073        }
9074    }
9075}
9076
9077/// PartialWritableOptionalKeyPath - Hides the Value type but keeps Root visible (writable optional)
9078///
9079/// # Why PhantomData<Root>?
9080///
9081/// See `PartialKeyPath` documentation for explanation of why `PhantomData` is needed.
9082#[derive(Clone)]
9083pub struct PartialWritableOptionalKeyPath<Root> {
9084    getter: Rc<dyn for<'r> Fn(&'r mut Root) -> Option<&'r mut dyn Any>>,
9085    value_type_id: TypeId,
9086    _phantom: PhantomData<Root>,
9087}
9088
9089impl<Root> PartialWritableOptionalKeyPath<Root> {
9090    pub fn new<Value>(
9091        keypath: WritableOptionalKeyPath<
9092            Root,
9093            Value,
9094            impl for<'r> Fn(&'r mut Root) -> Option<&'r mut Value> + 'static,
9095        >,
9096    ) -> Self
9097    where
9098        Value: Any + 'static,
9099        Root: 'static,
9100    {
9101        let value_type_id = TypeId::of::<Value>();
9102        let getter = Rc::new(keypath.getter);
9103
9104        Self {
9105            getter: Rc::new(move |root: &mut Root| {
9106                getter(root).map(|value: &mut Value| value as &mut dyn Any)
9107            }),
9108            value_type_id,
9109            _phantom: PhantomData,
9110        }
9111    }
9112
9113    pub fn get_mut<'r>(&self, root: &'r mut Root) -> Option<&'r mut dyn Any> {
9114        (self.getter)(root)
9115    }
9116
9117    /// Get the TypeId of the Value type
9118    pub fn value_type_id(&self) -> TypeId {
9119        self.value_type_id
9120    }
9121
9122    /// Try to downcast the result to a specific type
9123    pub fn get_mut_as<'a, Value: Any>(&self, root: &'a mut Root) -> Option<Option<&'a mut Value>> {
9124        if self.value_type_id == TypeId::of::<Value>() {
9125            self.get_mut(root).map(|any| any.downcast_mut::<Value>())
9126        } else {
9127            None
9128        }
9129    }
9130}
9131
9132// ========== ANY KEYPATHS (Hide Both Root and Value Types) ==========
9133
9134/// AnyKeyPath - Hides both Root and Value types
9135/// Equivalent to Swift's AnyKeyPath
9136/// Useful for storing keypaths in collections without knowing either type
9137///
9138/// # Why No PhantomData?
9139///
9140/// Unlike `PartialKeyPath`, `AnyKeyPath` doesn't need `PhantomData` because:
9141/// - Both `Root` and `Value` types are completely erased
9142/// - We store `TypeId` instead for runtime type checking
9143/// - The type information is encoded in the closure's behavior, not the struct
9144/// - There's no generic type parameter to track at compile time
9145#[derive(Clone)]
9146pub struct AnyKeyPath {
9147    getter: Rc<dyn for<'r> Fn(&'r dyn Any) -> Option<&'r dyn Any>>,
9148    root_type_id: TypeId,
9149    value_type_id: TypeId,
9150}
9151
9152impl AnyKeyPath {
9153    pub fn new<Root, Value>(
9154        keypath: OptionalKeyPath<
9155            Root,
9156            Value,
9157            impl for<'r> Fn(&'r Root) -> Option<&'r Value> + 'static,
9158        >,
9159    ) -> Self
9160    where
9161        Root: Any + 'static,
9162        Value: Any + 'static,
9163    {
9164        let root_type_id = TypeId::of::<Root>();
9165        let value_type_id = TypeId::of::<Value>();
9166        let getter = keypath.getter;
9167
9168        Self {
9169            getter: Rc::new(move |any: &dyn Any| {
9170                if let Some(root) = any.downcast_ref::<Root>() {
9171                    getter(root).map(|value: &Value| value as &dyn Any)
9172                } else {
9173                    None
9174                }
9175            }),
9176            root_type_id,
9177            value_type_id,
9178        }
9179    }
9180
9181    /// Create an AnyKeyPath from a concrete OptionalKeyPath
9182    /// Alias for `new()` for consistency with `from()` pattern
9183    pub fn from<Root, Value>(
9184        keypath: OptionalKeyPath<
9185            Root,
9186            Value,
9187            impl for<'r> Fn(&'r Root) -> Option<&'r Value> + 'static,
9188        >,
9189    ) -> Self
9190    where
9191        Root: Any + 'static,
9192        Value: Any + 'static,
9193    {
9194        Self::new(keypath)
9195    }
9196
9197    pub fn get<'r>(&self, root: &'r dyn Any) -> Option<&'r dyn Any> {
9198        (self.getter)(root)
9199    }
9200
9201    /// Get the TypeId of the Root type
9202    pub fn root_type_id(&self) -> TypeId {
9203        self.root_type_id
9204    }
9205
9206    /// Get the TypeId of the Value type
9207    pub fn value_type_id(&self) -> TypeId {
9208        self.value_type_id
9209    }
9210
9211    /// Try to get the value with type checking
9212    pub fn get_as<'a, Root: Any, Value: Any>(&self, root: &'a Root) -> Option<Option<&'a Value>> {
9213        if self.root_type_id == TypeId::of::<Root>() && self.value_type_id == TypeId::of::<Value>()
9214        {
9215            self.get(root as &dyn Any)
9216                .map(|any| any.downcast_ref::<Value>())
9217        } else {
9218            None
9219        }
9220    }
9221
9222    /// Get a human-readable name for the value type
9223    /// Returns a string representation of the TypeId
9224    pub fn kind_name(&self) -> String {
9225        format!("{:?}", self.value_type_id)
9226    }
9227
9228    /// Adapt this keypath to work with Arc<Root> instead of Root
9229    pub fn for_arc<Root>(&self) -> AnyKeyPath
9230    where
9231        Root: Any + 'static,
9232    {
9233        let root_type_id = self.root_type_id;
9234        let value_type_id = self.value_type_id;
9235        let getter = self.getter.clone();
9236
9237        AnyKeyPath {
9238            getter: Rc::new(move |any: &dyn Any| {
9239                if let Some(arc) = any.downcast_ref::<Arc<Root>>() {
9240                    getter(arc.as_ref() as &dyn Any)
9241                } else {
9242                    None
9243                }
9244            }),
9245            root_type_id: TypeId::of::<Arc<Root>>(),
9246            value_type_id,
9247        }
9248    }
9249
9250    /// Adapt this keypath to work with Box<Root> instead of Root
9251    pub fn for_box<Root>(&self) -> AnyKeyPath
9252    where
9253        Root: Any + 'static,
9254    {
9255        let root_type_id = self.root_type_id;
9256        let value_type_id = self.value_type_id;
9257        let getter = self.getter.clone();
9258
9259        AnyKeyPath {
9260            getter: Rc::new(move |any: &dyn Any| {
9261                if let Some(boxed) = any.downcast_ref::<Box<Root>>() {
9262                    getter(boxed.as_ref() as &dyn Any)
9263                } else {
9264                    None
9265                }
9266            }),
9267            root_type_id: TypeId::of::<Box<Root>>(),
9268            value_type_id,
9269        }
9270    }
9271
9272    /// Adapt this keypath to work with Rc<Root> instead of Root
9273    pub fn for_rc<Root>(&self) -> AnyKeyPath
9274    where
9275        Root: Any + 'static,
9276    {
9277        let root_type_id = self.root_type_id;
9278        let value_type_id = self.value_type_id;
9279        let getter = self.getter.clone();
9280
9281        AnyKeyPath {
9282            getter: Rc::new(move |any: &dyn Any| {
9283                if let Some(rc) = any.downcast_ref::<Rc<Root>>() {
9284                    getter(rc.as_ref() as &dyn Any)
9285                } else {
9286                    None
9287                }
9288            }),
9289            root_type_id: TypeId::of::<Rc<Root>>(),
9290            value_type_id,
9291        }
9292    }
9293
9294    /// Adapt this keypath to work with Option<Root> instead of Root
9295    pub fn for_option<Root>(&self) -> AnyKeyPath
9296    where
9297        Root: Any + 'static,
9298    {
9299        let root_type_id = self.root_type_id;
9300        let value_type_id = self.value_type_id;
9301        let getter = self.getter.clone();
9302
9303        AnyKeyPath {
9304            getter: Rc::new(move |any: &dyn Any| {
9305                if let Some(opt) = any.downcast_ref::<Option<Root>>() {
9306                    opt.as_ref().and_then(|root| getter(root as &dyn Any))
9307                } else {
9308                    None
9309                }
9310            }),
9311            root_type_id: TypeId::of::<Option<Root>>(),
9312            value_type_id,
9313        }
9314    }
9315
9316    /// Adapt this keypath to work with Result<Root, E> instead of Root
9317    pub fn for_result<Root, E>(&self) -> AnyKeyPath
9318    where
9319        Root: Any + 'static,
9320        E: Any + 'static,
9321    {
9322        let root_type_id = self.root_type_id;
9323        let value_type_id = self.value_type_id;
9324        let getter = self.getter.clone();
9325
9326        AnyKeyPath {
9327            getter: Rc::new(move |any: &dyn Any| {
9328                if let Some(result) = any.downcast_ref::<Result<Root, E>>() {
9329                    result
9330                        .as_ref()
9331                        .ok()
9332                        .and_then(|root| getter(root as &dyn Any))
9333                } else {
9334                    None
9335                }
9336            }),
9337            root_type_id: TypeId::of::<Result<Root, E>>(),
9338            value_type_id,
9339        }
9340    }
9341
9342    /// Adapt this keypath to work with Arc<RwLock<Root>> instead of Root
9343    /// Note: This requires the Root to be cloned first, then use the keypath on the cloned value
9344    pub fn for_arc_rwlock<Root>(&self) -> AnyKeyPath
9345    where
9346        Root: Any + Clone + 'static,
9347    {
9348        // We can't return a reference from a guard, so we return None
9349        // Users should clone the root first
9350        AnyKeyPath {
9351            getter: Rc::new(move |_any: &dyn Any| {
9352                // Cannot return reference from temporary guard
9353                // User should clone the root first and use the keypath on the cloned value
9354                None
9355            }),
9356            root_type_id: TypeId::of::<Arc<RwLock<Root>>>(),
9357            value_type_id: self.value_type_id,
9358        }
9359    }
9360
9361    /// Adapt this keypath to work with Arc<Mutex<Root>> instead of Root
9362    /// Note: This requires the Root to be cloned first, then use the keypath on the cloned value
9363    pub fn for_arc_mutex<Root>(&self) -> AnyKeyPath
9364    where
9365        Root: Any + Clone + 'static,
9366    {
9367        // We can't return a reference from a guard, so we return None
9368        // Users should clone the root first
9369        AnyKeyPath {
9370            getter: Rc::new(move |_any: &dyn Any| {
9371                // Cannot return reference from temporary guard
9372                // User should clone the root first and use the keypath on the cloned value
9373                None
9374            }),
9375            root_type_id: TypeId::of::<Arc<Mutex<Root>>>(),
9376            value_type_id: self.value_type_id,
9377        }
9378    }
9379}
9380
9381/// AnyWritableKeyPath - Hides both Root and Value types (writable)
9382#[derive(Clone)]
9383pub struct AnyWritableKeyPath {
9384    getter: Rc<dyn for<'r> Fn(&'r mut dyn Any) -> Option<&'r mut dyn Any>>,
9385    root_type_id: TypeId,
9386    value_type_id: TypeId,
9387}
9388
9389/// FailableCombinedKeyPath - A keypath that supports readable, writable, and owned access patterns
9390///
9391/// This keypath type combines the functionality of OptionalKeyPath, WritableOptionalKeyPath,
9392/// and adds owned access. It's useful when you need all three access patterns for the same field.
9393#[derive(Clone)]
9394pub struct FailableCombinedKeyPath<Root, Value, ReadFn, WriteFn, OwnedFn>
9395where
9396    ReadFn: for<'r> Fn(&'r Root) -> Option<&'r Value> + 'static,
9397    WriteFn: for<'r> Fn(&'r mut Root) -> Option<&'r mut Value> + 'static,
9398    OwnedFn: Fn(Root) -> Option<Value> + 'static,
9399{
9400    readable: ReadFn,
9401    writable: WriteFn,
9402    owned: OwnedFn,
9403    _phantom: PhantomData<(Root, Value)>,
9404}
9405
9406impl<Root, Value, ReadFn, WriteFn, OwnedFn>
9407    FailableCombinedKeyPath<Root, Value, ReadFn, WriteFn, OwnedFn>
9408where
9409    ReadFn: for<'r> Fn(&'r Root) -> Option<&'r Value> + 'static,
9410    WriteFn: for<'r> Fn(&'r mut Root) -> Option<&'r mut Value> + 'static,
9411    OwnedFn: Fn(Root) -> Option<Value> + 'static,
9412{
9413    /// Create a new FailableCombinedKeyPath with all three access patterns
9414    pub fn new(readable: ReadFn, writable: WriteFn, owned: OwnedFn) -> Self {
9415        Self {
9416            readable,
9417            writable,
9418            owned,
9419            _phantom: PhantomData,
9420        }
9421    }
9422
9423    /// Get an immutable reference to the value (readable access)
9424    pub fn get<'r>(&self, root: &'r Root) -> Option<&'r Value> {
9425        (self.readable)(root)
9426    }
9427
9428    /// Get a mutable reference to the value (writable access)
9429    pub fn get_mut<'r>(&self, root: &'r mut Root) -> Option<&'r mut Value> {
9430        (self.writable)(root)
9431    }
9432
9433    /// Get an owned value (owned access) - consumes the root
9434    pub fn get_failable_owned(&self, root: Root) -> Option<Value> {
9435        (self.owned)(root)
9436    }
9437
9438    /// Convert to OptionalKeyPath (loses writable and owned capabilities)
9439    pub fn to_optional(self) -> OptionalKeyPath<Root, Value, ReadFn> {
9440        OptionalKeyPath::new(self.readable)
9441    }
9442
9443    /// Convert to WritableOptionalKeyPath (loses owned capability)
9444    pub fn to_writable_optional(self) -> WritableOptionalKeyPath<Root, Value, WriteFn> {
9445        WritableOptionalKeyPath::new(self.writable)
9446    }
9447
9448    /// Compose this keypath with another FailableCombinedKeyPath
9449    /// Returns a new FailableCombinedKeyPath that chains both keypaths
9450    pub fn then<SubValue, SubReadFn, SubWriteFn, SubOwnedFn>(
9451        self,
9452        next: FailableCombinedKeyPath<Value, SubValue, SubReadFn, SubWriteFn, SubOwnedFn>,
9453    ) -> FailableCombinedKeyPath<
9454        Root,
9455        SubValue,
9456        impl for<'r> Fn(&'r Root) -> Option<&'r SubValue> + 'static,
9457        impl for<'r> Fn(&'r mut Root) -> Option<&'r mut SubValue> + 'static,
9458        impl Fn(Root) -> Option<SubValue> + 'static,
9459    >
9460    where
9461        SubReadFn: for<'r> Fn(&'r Value) -> Option<&'r SubValue> + 'static,
9462        SubWriteFn: for<'r> Fn(&'r mut Value) -> Option<&'r mut SubValue> + 'static,
9463        SubOwnedFn: Fn(Value) -> Option<SubValue> + 'static,
9464        ReadFn: 'static,
9465        WriteFn: 'static,
9466        OwnedFn: 'static,
9467        Value: 'static,
9468        Root: 'static,
9469        SubValue: 'static,
9470    {
9471        let first_read = self.readable;
9472        let first_write = self.writable;
9473        let first_owned = self.owned;
9474        let second_read = next.readable;
9475        let second_write = next.writable;
9476        let second_owned = next.owned;
9477
9478        FailableCombinedKeyPath::new(
9479            move |root: &Root| first_read(root).and_then(|value| second_read(value)),
9480            move |root: &mut Root| first_write(root).and_then(|value| second_write(value)),
9481            move |root: Root| first_owned(root).and_then(|value| second_owned(value)),
9482        )
9483    }
9484
9485    /// Compose with OptionalKeyPath (readable only)
9486    /// Returns a FailableCombinedKeyPath that uses the readable from OptionalKeyPath
9487    /// and creates dummy writable/owned closures that return None
9488    pub fn chain_optional<SubValue, SubReadFn>(
9489        self,
9490        next: OptionalKeyPath<Value, SubValue, SubReadFn>,
9491    ) -> FailableCombinedKeyPath<
9492        Root,
9493        SubValue,
9494        impl for<'r> Fn(&'r Root) -> Option<&'r SubValue> + 'static,
9495        impl for<'r> Fn(&'r mut Root) -> Option<&'r mut SubValue> + 'static,
9496        impl Fn(Root) -> Option<SubValue> + 'static,
9497    >
9498    where
9499        SubReadFn: for<'r> Fn(&'r Value) -> Option<&'r SubValue> + 'static,
9500        ReadFn: 'static,
9501        WriteFn: 'static,
9502        OwnedFn: 'static,
9503        Value: 'static,
9504        Root: 'static,
9505        SubValue: 'static,
9506    {
9507        let first_read = self.readable;
9508        let first_write = self.writable;
9509        let first_owned = self.owned;
9510        let second_read = next.getter;
9511
9512        FailableCombinedKeyPath::new(
9513            move |root: &Root| first_read(root).and_then(|value| second_read(value)),
9514            move |_root: &mut Root| {
9515                None // Writable not supported when composing with OptionalKeyPath
9516            },
9517            move |root: Root| {
9518                first_owned(root).and_then(|value| {
9519                    // Try to get owned value, but OptionalKeyPath doesn't support owned
9520                    None
9521                })
9522            },
9523        )
9524    }
9525}
9526
9527// Factory function for FailableCombinedKeyPath
9528impl
9529    FailableCombinedKeyPath<
9530        (),
9531        (),
9532        fn(&()) -> Option<&()>,
9533        fn(&mut ()) -> Option<&mut ()>,
9534        fn(()) -> Option<()>,
9535    >
9536{
9537    /// Create a FailableCombinedKeyPath with all three access patterns
9538    pub fn failable_combined<Root, Value, ReadFn, WriteFn, OwnedFn>(
9539        readable: ReadFn,
9540        writable: WriteFn,
9541        owned: OwnedFn,
9542    ) -> FailableCombinedKeyPath<Root, Value, ReadFn, WriteFn, OwnedFn>
9543    where
9544        ReadFn: for<'r> Fn(&'r Root) -> Option<&'r Value> + 'static,
9545        WriteFn: for<'r> Fn(&'r mut Root) -> Option<&'r mut Value> + 'static,
9546        OwnedFn: Fn(Root) -> Option<Value> + 'static,
9547    {
9548        FailableCombinedKeyPath::new(readable, writable, owned)
9549    }
9550}
9551
9552impl AnyWritableKeyPath {
9553    pub fn new<Root, Value>(
9554        keypath: WritableOptionalKeyPath<
9555            Root,
9556            Value,
9557            impl for<'r> Fn(&'r mut Root) -> Option<&'r mut Value> + 'static,
9558        >,
9559    ) -> Self
9560    where
9561        Root: Any + 'static,
9562        Value: Any + 'static,
9563    {
9564        let root_type_id = TypeId::of::<Root>();
9565        let value_type_id = TypeId::of::<Value>();
9566        let getter = keypath.getter;
9567
9568        Self {
9569            getter: Rc::new(move |any: &mut dyn Any| {
9570                if let Some(root) = any.downcast_mut::<Root>() {
9571                    getter(root).map(|value: &mut Value| value as &mut dyn Any)
9572                } else {
9573                    None
9574                }
9575            }),
9576            root_type_id,
9577            value_type_id,
9578        }
9579    }
9580
9581    pub fn get_mut<'r>(&self, root: &'r mut dyn Any) -> Option<&'r mut dyn Any> {
9582        (self.getter)(root)
9583    }
9584
9585    /// Get the TypeId of the Root type
9586    pub fn root_type_id(&self) -> TypeId {
9587        self.root_type_id
9588    }
9589
9590    /// Get the TypeId of the Value type
9591    pub fn value_type_id(&self) -> TypeId {
9592        self.value_type_id
9593    }
9594
9595    /// Try to get the value with type checking
9596    pub fn get_mut_as<'a, Root: Any, Value: Any>(
9597        &self,
9598        root: &'a mut Root,
9599    ) -> Option<Option<&'a mut Value>> {
9600        if self.root_type_id == TypeId::of::<Root>() && self.value_type_id == TypeId::of::<Value>()
9601        {
9602            self.get_mut(root as &mut dyn Any)
9603                .map(|any| any.downcast_mut::<Value>())
9604        } else {
9605            None
9606        }
9607    }
9608}
9609
9610// Conversion methods from concrete keypaths to partial/any keypaths
9611impl<Root, Value, F> KeyPath<Root, Value, F>
9612where
9613    F: for<'r> Fn(&'r Root) -> &'r Value + 'static,
9614    Root: 'static,
9615    Value: Any + 'static,
9616{
9617    /// Convert to PartialKeyPath (hides Value type)
9618    pub fn to_partial(self) -> PartialKeyPath<Root> {
9619        PartialKeyPath::new(self)
9620    }
9621
9622    /// Alias for `to_partial()` - converts to PartialKeyPath
9623    pub fn to(self) -> PartialKeyPath<Root> {
9624        self.to_partial()
9625    }
9626}
9627
9628impl<Root, Value, F> OptionalKeyPath<Root, Value, F>
9629where
9630    F: for<'r> Fn(&'r Root) -> Option<&'r Value> + 'static,
9631    Root: Any + 'static,
9632    Value: Any + 'static,
9633{
9634    /// Convert to PartialOptionalKeyPath (hides Value type)
9635    pub fn to_partial(self) -> PartialOptionalKeyPath<Root> {
9636        PartialOptionalKeyPath::new(self)
9637    }
9638
9639    /// Convert to AnyKeyPath (hides both Root and Value types)
9640    pub fn to_any(self) -> AnyKeyPath {
9641        AnyKeyPath::new(self)
9642    }
9643
9644    /// Convert to PartialOptionalKeyPath (alias for `to_partial()`)
9645    pub fn to(self) -> PartialOptionalKeyPath<Root> {
9646        self.to_partial()
9647    }
9648}
9649
9650impl<Root, Value, F> WritableKeyPath<Root, Value, F>
9651where
9652    F: for<'r> Fn(&'r mut Root) -> &'r mut Value + 'static,
9653    Root: 'static,
9654    Value: Any + 'static,
9655{
9656    /// Convert to PartialWritableKeyPath (hides Value type)
9657    pub fn to_partial(self) -> PartialWritableKeyPath<Root> {
9658        PartialWritableKeyPath::new(self)
9659    }
9660
9661    /// Alias for `to_partial()` - converts to PartialWritableKeyPath
9662    pub fn to(self) -> PartialWritableKeyPath<Root> {
9663        self.to_partial()
9664    }
9665}
9666
9667impl<Root, Value, F> WritableOptionalKeyPath<Root, Value, F>
9668where
9669    F: for<'r> Fn(&'r mut Root) -> Option<&'r mut Value> + 'static,
9670    Root: Any + 'static,
9671    Value: Any + 'static,
9672{
9673    /// Convert to PartialWritableOptionalKeyPath (hides Value type)
9674    pub fn to_partial(self) -> PartialWritableOptionalKeyPath<Root> {
9675        PartialWritableOptionalKeyPath::new(self)
9676    }
9677
9678    /// Convert to AnyWritableKeyPath (hides both Root and Value types)
9679    pub fn to_any(self) -> AnyWritableKeyPath {
9680        AnyWritableKeyPath::new(self)
9681    }
9682
9683    /// Convert to PartialWritableOptionalKeyPath (alias for `to_partial()`)
9684    pub fn to(self) -> PartialWritableOptionalKeyPath<Root> {
9685        self.to_partial()
9686    }
9687}
9688
9689// pub trait KPTrait<R, V>: {
9690//     fn getter(r: &R) -> Option<&V>;
9691//     fn setter(r: &mut R) -> Option< &mut V>;
9692// }
9693// pub trait KPGTrait<R, V> {
9694//     fn getter(r: &R) -> Option<&V>;
9695// }
9696
9697// pub trait KPSTrait<R, V> {
9698//         fn setter(r: &mut R) -> Option< &mut V>;
9699// }
9700
9701pub fn test<R, V, F>(x: R)
9702where
9703    F: Fn(&R) -> Option<&V>,
9704{
9705}
9706
9707type Getter<R, V> = for<'r> fn(&'r R) -> Option<&'r V>;
9708type Setter<R, V> = for<'r> fn(&'r mut R) -> Option<&'r mut V>;
9709// type LockGetter<R, V> = for<'r> fn(&'r R) -> Option<Arc<&'r V>>;
9710// type LockSetter<R, V> = for<'r> fn(&'r mut R) -> Option<Arc<&'r mut V>>;
9711
9712pub type Kp<R, V> = KpType<
9713    R,
9714    V,
9715    Getter<R, V>,
9716    Setter<R, V>,
9717    //  LockGetter<R, V>,
9718    //  LockSetter<R, V>
9719>;
9720
9721#[derive(Debug)]
9722pub struct KpType<
9723    R,
9724    V,
9725    G,
9726    S,
9727    // LG, SG
9728> where
9729    G: for<'r> Fn(&'r R) -> Option<&'r V>,
9730    S: for<'r> Fn(&'r mut R) -> Option<&'r mut V>,
9731    // LG:for<'r> Fn(&'r R) -> Option<Arc<&'r V>>,
9732    // SG:for<'r> Fn(&'r mut R) -> Option<Arc<&'r mut V>>,
9733{
9734    g: G,
9735    s: S,
9736    // lg: LG,
9737    // sg: SG,
9738    _p: PhantomData<(R, V)>,
9739}
9740
9741impl<
9742    R,
9743    V,
9744    G,
9745    S,
9746    // LG, SG
9747>
9748    KpType<
9749        R,
9750        V,
9751        G,
9752        S,
9753        // LG, SG
9754    >
9755where
9756    G: for<'r> Fn(&'r R) -> Option<&'r V>,
9757    S: for<'r> Fn(&'r mut R) -> Option<&'r mut V>,
9758{
9759    pub fn new(get: G, set: S) -> Self {
9760        Self {
9761            g: get,
9762            s: set,
9763            _p: PhantomData,
9764        }
9765    }
9766
9767    pub fn get<'a>(&self, r: &'a R) -> Option<&'a V> {
9768        (self.g)(r)
9769    }
9770
9771    pub fn get_mut<'a>(&self, r: &'a mut R) -> Option<&'a mut V> {
9772        (self.s)(r)
9773    }
9774
9775    pub fn then<SubValue, G2, S2>(
9776        self,
9777        next: KpType<V, SubValue, G2, S2>,
9778    ) -> KpType<
9779        R,
9780        SubValue,
9781        impl for<'r> Fn(&'r R) -> Option<&'r SubValue>,
9782        impl for<'r> Fn(&'r mut R) -> Option<&'r mut SubValue>,
9783    >
9784    where
9785        G2: for<'r> Fn(&'r V) -> Option<&'r SubValue>,
9786        S2: for<'r> Fn(&'r mut V) -> Option<&'r mut SubValue>,
9787        V: 'static,
9788    {
9789        KpType::new(
9790            move |root: &R| (self.g)(root).and_then(|value| (next.g)(value)),
9791            move |root: &mut R| (self.s)(root).and_then(|value| (next.s)(value)),
9792        )
9793    }
9794
9795    // /// Convert this keypath to an Arc<Mutex> chain-ready keypath
9796    // /// Returns self, but serves as a marker for intent and enables chaining
9797    // pub fn for_arc_mutex<InnerValue>(self) -> Self
9798    // where
9799    //     V: std::borrow::Borrow<Arc<Mutex<InnerValue>>>,
9800    // {
9801    //     self
9802    // }
9803
9804    // /// Convert this keypath to an Arc<RwLock> chain-ready keypath
9805    // /// Returns self, but serves as a marker for intent and enables chaining
9806    // pub fn for_arc_rwlock<InnerValue>(self) -> Self
9807    // where
9808    //     V: std::borrow::Borrow<Arc<RwLock<InnerValue>>>,
9809    // {
9810    //     self
9811    // }
9812}
9813
9814// Add identity as an associated function
9815impl<R> KpType<R, R, Getter<R, R>, Setter<R, R>> {
9816    /// Creates an identity keypath that returns the value itself
9817    pub fn identity() -> Self {
9818        Kp {
9819            g: |r: &R| Some(r),
9820            s: |r: &mut R| Some(r),
9821            _p: PhantomData,
9822        }
9823    }
9824}
9825
9826impl<R, V, G, S> KpType<R, V, G, S>
9827where
9828    G: for<'r> Fn(&'r R) -> Option<&'r V>,
9829    S: for<'r> Fn(&'r mut R) -> Option<&'r mut V>,
9830{
9831    // Converts Kp<R, V> to Kp<Arc<R>, V>
9832    pub fn for_arc(
9833        self,
9834    ) -> KpType<
9835        Arc<R>,
9836        V,
9837        impl for<'r> Fn(&'r Arc<R>) -> Option<&'r V>,
9838        impl for<'r> Fn(&'r mut Arc<R>) -> Option<&'r mut V>,
9839    > {
9840        KpType {
9841            g: move |root: &Arc<R>| {
9842                // Dereference the Arc to get &R, then apply the original getter
9843                (self.g)(&root)
9844            },
9845            s: move |root: &mut Arc<R>| {
9846                // For mutable access, we need to handle Arc's interior mutability carefully
9847                // This assumes R: Send + Sync for thread safety with Arc
9848                // Note: This will only work if the Arc has exactly one strong reference
9849                // Otherwise, we cannot get a mutable reference
9850
9851                // Try to get a mutable reference from Arc
9852                if let Some(r) = Arc::get_mut(root) {
9853                    (self.s)(r)
9854                } else {
9855                    None
9856                }
9857            },
9858            _p: PhantomData,
9859        }
9860    }
9861
9862    // Converts Kp<R, V> to Kp<Rc<R>, V>
9863    pub fn for_rc(
9864        self,
9865    ) -> KpType<
9866        Rc<R>,
9867        V,
9868        impl for<'r> Fn(&'r Rc<R>) -> Option<&'r V>,
9869        impl for<'r> Fn(&'r mut Rc<R>) -> Option<&'r mut V>,
9870    > {
9871        KpType {
9872            g: move |root: &Rc<R>| (self.g)(&root),
9873            s: move |root: &mut Rc<R>| {
9874                if let Some(r) = Rc::get_mut(root) {
9875                    (self.s)(r)
9876                } else {
9877                    None
9878                }
9879            },
9880            _p: PhantomData,
9881        }
9882    }
9883}
9884
9885struct TestKP {
9886    a: String,
9887    b: String,
9888    c: Arc<String>,
9889    d: Mutex<String>,
9890    e: Arc<Mutex<TestKP2>>,
9891    f: Option<TestKP2>,
9892}
9893
9894impl TestKP {
9895    fn new() -> Self {
9896        Self {
9897            a: String::from("a"),
9898            b: String::from("b"),
9899            c: Arc::new(String::from("c")),
9900            d: Mutex::new(String::from("d")),
9901            e: Arc::new(Mutex::new(TestKP2::new())),
9902            f: Some(TestKP2 {
9903                a: String::from("a3"),
9904                b: Arc::new(Mutex::new(TestKP3::new())),
9905            }),
9906        }
9907    }
9908
9909    // Helper to create an identity keypath for TestKP2
9910    fn identity() -> Kp<TestKP2, TestKP2> {
9911        Kp {
9912            g: |r: &TestKP2| Some(r),
9913            s: |r: &mut TestKP2| Some(r),
9914            _p: PhantomData,
9915        }
9916    }
9917}
9918
9919struct TestKP2 {
9920    a: String,
9921    b: Arc<Mutex<TestKP3>>,
9922}
9923
9924impl TestKP2 {
9925    fn new() -> Self {
9926        TestKP2 {
9927            a: String::from("a2"),
9928            b: Arc::new(Mutex::new(TestKP3::new())),
9929        }
9930    }
9931
9932    fn a() -> Kp<TestKP2, String> {
9933        Kp {
9934            g: |r: &TestKP2| Some(&r.a),
9935            s: |r: &mut TestKP2| Some(&mut r.a),
9936            _p: PhantomData,
9937        }
9938    }
9939
9940    fn b() -> Kp<TestKP2, Arc<Mutex<TestKP3>>> {
9941        Kp {
9942            g: |r: &TestKP2| Some(&r.b),
9943            s: |r: &mut TestKP2| Some(&mut r.b),
9944            _p: PhantomData,
9945        }
9946    }
9947
9948    // fn identity() -> Kp<Self, Self> {
9949    //     Kp::identity()
9950    // }
9951}
9952
9953#[derive(Debug)]
9954struct TestKP3 {
9955    a: String,
9956    b: Arc<Mutex<String>>,
9957}
9958
9959impl TestKP3 {
9960    fn new() -> Self {
9961        TestKP3 {
9962            a: String::from("a2"),
9963            b: Arc::new(Mutex::new(String::from("b2"))),
9964        }
9965    }
9966
9967    fn a() -> Kp<TestKP3, String> {
9968        Kp {
9969            g: |r: &TestKP3| Some(&r.a),
9970            s: |r: &mut TestKP3| Some(&mut r.a),
9971            _p: PhantomData,
9972        }
9973    }
9974
9975    fn b_lock() -> LKp<
9976        Kp<TestKP2, TestKP3>, // Root
9977        Kp<TestKP3, String>,  // MutexValue
9978        TestKP3,              // InnerValue
9979        String,               // SubValue
9980        fn(&TestKP3) -> Option<&String>,
9981        fn(&mut TestKP3) -> Option<&mut String>,
9982    > {
9983        todo!()
9984    }
9985
9986    // fn b() -> Kp<Arc<TestKP3>, Arc<Mutex<String>>> {
9987    //         let k = Kp {
9988    //             g: |r: &TestKP3| Some(&r.b),
9989    //             s: |r: &mut TestKP3| Some(&mut r.b),
9990    //             _p: PhantomData,
9991    //         };
9992    //         k.for_arc_mutex()
9993    //     }
9994
9995    // fn identity() -> Kp<Self, Self> {
9996    //     Kp::identity()
9997    // }
9998}
9999
10000impl TestKP3 {
10001    fn b() -> KpType<
10002        // Arc<TestKP3>,
10003        TestKP3,
10004        Arc<Mutex<String>>,
10005        // impl for<'r> Fn(&'r Arc<TestKP3>) -> Option<&'r Arc<Mutex<String>>>,
10006        impl for<'r> Fn(&'r TestKP3) -> Option<&'r Arc<Mutex<String>>>,
10007        impl for<'r> Fn(&'r mut TestKP3) -> Option<&'r mut Arc<Mutex<String>>>,
10008    > {
10009        Kp {
10010            g: |r: &TestKP3| Some(&r.b),
10011            s: |r: &mut TestKP3| Some(&mut r.b),
10012            _p: PhantomData,
10013        }
10014        // k.for_arc()
10015    }
10016}
10017
10018impl TestKP {
10019    fn a() -> Kp<TestKP, String> {
10020        Kp {
10021            g: |r: &TestKP| Some(&r.a),
10022            s: |r: &mut TestKP| Some(&mut r.a),
10023            _p: PhantomData,
10024        }
10025    }
10026
10027    fn b() -> Kp<TestKP, String> {
10028        Kp {
10029            g: |r: &TestKP| Some(&r.b),
10030            s: |r: &mut TestKP| Some(&mut r.b),
10031            _p: PhantomData,
10032        }
10033    }
10034
10035    fn c() -> Kp<TestKP, String> {
10036        Kp {
10037            g: |r: &TestKP| Some(r.c.as_ref()),
10038            s: |r: &mut TestKP| None,
10039            _p: PhantomData,
10040        }
10041    }
10042
10043    fn d() -> Kp<TestKP, Mutex<String>> {
10044        Kp {
10045            g: |r: &TestKP| Some(&r.d),
10046            s: |r: &mut TestKP| Some(&mut r.d),
10047            _p: PhantomData,
10048        }
10049    }
10050
10051    fn e() -> Kp<TestKP, Arc<Mutex<TestKP2>>> {
10052        Kp {
10053            g: |r: &TestKP| Some(&r.e),
10054            s: |r: &mut TestKP| Some(&mut r.e),
10055            _p: PhantomData,
10056        }
10057    }
10058
10059    fn f() -> Kp<TestKP, TestKP2> {
10060        Kp {
10061            g: |r: &TestKP| r.f.as_ref(),
10062            s: |r: &mut TestKP| r.f.as_mut(),
10063            _p: PhantomData,
10064        }
10065    }
10066}
10067
10068#[cfg(test)]
10069mod testsas {
10070    use super::*;
10071
10072    #[test]
10073    fn test_kp_for_struct() {
10074        let mut i = TestKP::new();
10075        let kp = TestKP::f().then(TestKP2::a());
10076        println!("initial value = {:?}", kp.get(&i));
10077        if let Some(x) = kp.get_mut(&mut i) {
10078            *x = "this is also working".to_string();
10079        }
10080        println!("updated value = {:?}", kp.get(&i));
10081        assert_eq!(kp.get(&i), Some(&"this is also working".to_string()));
10082    }
10083
10084    #[test]
10085    fn test_single_mutex_access() {
10086        let mut root = TestKP::new();
10087
10088        // Create LKp for TestKP.e -> TestKP2.a
10089        let lkp = LKp::new(TestKP::e(), TestKP2::a());
10090
10091        // Get value through mutex
10092        let value = lkp.get_cloned(&root);
10093        println!("Single mutex - initial value: {:?}", value);
10094        assert_eq!(value, Some("a2".to_string()));
10095
10096        // Mutate value through mutex
10097        lkp.get_mut(&mut root, |val| {
10098            *val = "modified a2".to_string();
10099        });
10100
10101        let new_value = lkp.get_cloned(&root);
10102        println!("Single mutex - updated value: {:?}", new_value);
10103        assert_eq!(new_value, Some("modified a2".to_string()));
10104    }
10105
10106    #[test]
10107    fn test_chained_mutex_access() {
10108        let mut root = TestKP::new();
10109
10110        // Create LKp for TestKP.e -> TestKP2
10111        let outer_lkp = LKp::new(TestKP::e(), Kp::identity());
10112
10113        // Chain to TestKP2.b (which is Arc<Mutex<String>>)
10114        let chained_lkp = outer_lkp.then(TestKP2::b());
10115        // Now we have: TestKP.e (Arc<Mutex<TestKP2>>) -> TestKP2 -> TestKP2.b (Arc<Mutex<String>>)
10116        // This gives us access to the Arc<Mutex<String>>
10117        let arc_mutex = chained_lkp.get_cloned(&root);
10118        println!("Chained mutex - Arc<Mutex>: {:?}", arc_mutex);
10119
10120        // To access the inner String, we need to lock it
10121        if let Some(am) = arc_mutex {
10122            if let Ok(guard) = am.lock() {
10123                println!("Chained mutex - inner value: {:?}", *guard);
10124                assert_eq!(*guard.a, "a2".to_string());
10125            }
10126        }
10127
10128        // Mutate the Arc<Mutex<String>> reference itself (swap it out)
10129        chained_lkp.get_mut(&mut root, |arc_mutex_ref| {
10130            *arc_mutex_ref = Arc::new(Mutex::new(TestKP3 {
10131                a: "replaced b2".to_string(),
10132                b: Arc::new(Mutex::new(String::new())),
10133            }));
10134        });
10135
10136        // Verify the change
10137        let new_arc_mutex = chained_lkp.get_cloned(&root);
10138        if let Some(am) = new_arc_mutex {
10139            if let Ok(guard) = am.lock() {
10140                println!("Chained mutex - replaced value: {:?}", *guard);
10141                assert_eq!(*guard.a, "replaced b2".to_string());
10142            }
10143        }
10144    }
10145
10146    #[test]
10147    fn test_double_nested_mutex() {
10148        let mut root = TestKP::new();
10149
10150        // First level: TestKP.e -> TestKP2
10151        let first_lkp: LKp<TestKP, Arc<Mutex<TestKP2>>, TestKP2, TestKP2, _, _> = LKp::new(
10152            TestKP::e(),
10153            Kp {
10154                g: |r: &TestKP2| Some(r),
10155                s: |r: &mut TestKP2| Some(r),
10156                _p: PhantomData,
10157            },
10158        );
10159
10160        // Second level: chain to TestKP2.b (Arc<Mutex<String>>)
10161        // This creates: TestKP -> Arc<Mutex<TestKP2>> -> TestKP2.b
10162        // let second_lkp = first_lkp.then(TestKP2::b()).get_mut(&mut root, |next| {
10163        //     let x = &next.lock().ok().unwrap();
10164        //     let result = TestKP3::b().get(x);
10165
10166        // });
10167
10168        // Now create another LKp to go through the second mutex
10169        // TestKP -> Arc<Mutex<TestKP2>> -> Arc<Mutex<String>> -> String
10170        let final_lkp = LKp::new(TestKP::e(), {
10171            let inner_kp = Kp {
10172                g: |r: &TestKP2| Some(&r.b),
10173                s: |r: &mut TestKP2| Some(&mut r.b),
10174                _p: PhantomData,
10175            };
10176            inner_kp
10177        });
10178
10179        // Access the deeply nested String value
10180        // let value = final_lkp.get_cloned(&root);
10181        // println!("Double nested mutex - value: {:?}", value);
10182
10183        // // The value should be cloned from the inner Arc<Mutex<String>>
10184        // if let Some(arc_string) = value {
10185        //     if let Ok(guard) = arc_string.lock() {
10186        //         assert_eq!(*guard, "b2".to_string());
10187        //     }
10188        // }
10189    }
10190
10191    #[test]
10192    fn test_lkp_then_chaining() {
10193        let mut root = TestKP::new();
10194
10195        // Start with TestKP.e -> TestKP2 (identity)
10196        let first_lkp = LKp::new(TestKP::e(), Kp::identity());
10197
10198        // Chain to TestKP2.a to get: TestKP.e -> TestKP2 -> TestKP2.a
10199        let chained = first_lkp.then(TestKP2::a());
10200
10201        // Access the deeply nested String value
10202        let value = chained.get_cloned(&root);
10203        println!("LKp chained - value: {:?}", value);
10204        assert_eq!(value, Some("a2".to_string()));
10205
10206        // Mutate it
10207        chained.get_mut(&mut root, |val| {
10208            *val = "chained modified".to_string();
10209        });
10210
10211        let new_value = chained.get_cloned(&root);
10212        assert_eq!(new_value, Some("chained modified".to_string()));
10213    }
10214
10215    #[test]
10216    fn test_simple_keypath_composition() {
10217        let mut root = TestKP::new();
10218
10219        // Option 1: Direct access without LKp (when you have a direct path)
10220        let direct_kp = TestKP::f().then(TestKP2::a());
10221        assert_eq!(direct_kp.get(&root), Some(&"a3".to_string()));
10222
10223        // Option 2: Through mutex using LKp
10224        let mutex_lkp = LKp::new(TestKP::e(), TestKP2::a());
10225        assert_eq!(mutex_lkp.get_cloned(&root), Some("a2".to_string()));
10226
10227        // Option 3: Chain LKp for deeper access
10228        let deep_lkp = LKp::new(TestKP::e(), Kp::identity()).then(TestKP2::a());
10229
10230        assert_eq!(deep_lkp.get_cloned(&root), Some("a2".to_string()));
10231    }
10232}
10233
10234// ========== SHR OPERATOR IMPLEMENTATIONS (>> operator) ==========
10235//
10236// The `>>` operator provides the same functionality as `then()` methods.
10237// It requires nightly Rust with the `nightly` feature enabled.
10238//
10239// Usage example (requires nightly):
10240// ```rust
10241// #![feature(impl_trait_in_assoc_type)]  // Must be in YOUR code
10242// use rust_keypaths::{keypath, KeyPath};
10243//
10244// struct User { address: Address }
10245// struct Address { street: String }
10246//
10247// let kp1 = keypath!(|u: &User| &u.address);
10248// let kp2 = keypath!(|a: &Address| &a.street);
10249// let chained = kp1 >> kp2; // Works with nightly feature
10250// ```
10251//
10252// On stable Rust, use `keypath1.then(keypath2)` instead.
10253//
10254// Supported combinations (same as `then()` methods):
10255// - `KeyPath >> KeyPath` → `KeyPath`
10256// - `KeyPath >> OptionalKeyPath` → `OptionalKeyPath`
10257// - `OptionalKeyPath >> OptionalKeyPath` → `OptionalKeyPath`
10258// - `WritableKeyPath >> WritableKeyPath` → `WritableKeyPath`
10259// - `WritableKeyPath >> WritableOptionalKeyPath` → `WritableOptionalKeyPath`
10260// - `WritableOptionalKeyPath >> WritableOptionalKeyPath` → `WritableOptionalKeyPath`
10261
10262// #[cfg(feature = "nightly")]
10263// mod shr_impls {
10264//     use super::*;
10265//
10266//     // Implement Shr for KeyPath >> KeyPath: returns KeyPath
10267//     impl<Root, Value, F, SubValue, G> Shr<KeyPath<Value, SubValue, G>> for KeyPath<Root, Value, F>
10268//     where
10269//         F: for<'r> Fn(&'r Root) -> &'r Value + 'static,
10270//         G: for<'r> Fn(&'r Value) -> &'r SubValue + 'static,
10271//         Value: 'static,
10272//     {
10273//         type Output = KeyPath<Root, SubValue, impl for<'r> Fn(&'r Root) -> &'r SubValue>;
10274//
10275//         fn shr(self, rhs: KeyPath<Value, SubValue, G>) -> Self::Output {
10276//             self.then(rhs)
10277//         }
10278//     }
10279//
10280//     // Implement Shr for KeyPath >> OptionalKeyPath: returns OptionalKeyPath
10281//     impl<Root, Value, F, SubValue, G> Shr<OptionalKeyPath<Value, SubValue, G>> for KeyPath<Root, Value, F>
10282//     where
10283//         F: for<'r> Fn(&'r Root) -> &'r Value + 'static,
10284//         G: for<'r> Fn(&'r Value) -> Option<&'r SubValue> + 'static,
10285//         Value: 'static,
10286//     {
10287//         type Output = OptionalKeyPath<Root, SubValue, impl for<'r> Fn(&'r Root) -> Option<&'r SubValue>>;
10288//
10289//         fn shr(self, rhs: OptionalKeyPath<Value, SubValue, G>) -> Self::Output {
10290//             self.chain_optional(rhs)
10291//         }
10292//     }
10293//
10294//     // Implement Shr for OptionalKeyPath >> OptionalKeyPath: returns OptionalKeyPath
10295//     impl<Root, Value, F, SubValue, G> Shr<OptionalKeyPath<Value, SubValue, G>> for OptionalKeyPath<Root, Value, F>
10296//     where
10297//         F: for<'r> Fn(&'r Root) -> Option<&'r Value> + 'static,
10298//         G: for<'r> Fn(&'r Value) -> Option<&'r SubValue> + 'static,
10299//         Value: 'static,
10300//     {
10301//         type Output = OptionalKeyPath<Root, SubValue, impl for<'r> Fn(&'r Root) -> Option<&'r SubValue>>;
10302//
10303//         fn shr(self, rhs: OptionalKeyPath<Value, SubValue, G>) -> Self::Output {
10304//             self.then(rhs)
10305//         }
10306//     }
10307//
10308//     // Implement Shr for WritableKeyPath >> WritableKeyPath: returns WritableKeyPath
10309//     impl<Root, Value, F, SubValue, G> Shr<WritableKeyPath<Value, SubValue, G>> for WritableKeyPath<Root, Value, F>
10310//     where
10311//         F: for<'r> Fn(&'r mut Root) -> &'r mut Value + 'static,
10312//         G: for<'r> Fn(&'r mut Value) -> &'r mut SubValue + 'static,
10313//         Value: 'static,
10314//     {
10315//         type Output = WritableKeyPath<Root, SubValue, impl for<'r> Fn(&'r mut Root) -> &'r mut SubValue>;
10316//
10317//         fn shr(self, rhs: WritableKeyPath<Value, SubValue, G>) -> Self::Output {
10318//             self.then(rhs)
10319//         }
10320//     }
10321//
10322//     // Implement Shr for WritableKeyPath >> WritableOptionalKeyPath: returns WritableOptionalKeyPath
10323//     impl<Root, Value, F, SubValue, G> Shr<WritableOptionalKeyPath<Value, SubValue, G>> for WritableKeyPath<Root, Value, F>
10324//     where
10325//         F: for<'r> Fn(&'r mut Root) -> &'r mut Value + 'static,
10326//         G: for<'r> Fn(&'r mut Value) -> Option<&'r mut SubValue> + 'static,
10327//         Value: 'static,
10328//     {
10329//         type Output = WritableOptionalKeyPath<Root, SubValue, impl for<'r> Fn(&'r mut Root) -> Option<&'r mut SubValue>>;
10330//
10331//         fn shr(self, rhs: WritableOptionalKeyPath<Value, SubValue, G>) -> Self::Output {
10332//             self.chain_optional(rhs)
10333//         }
10334//     }
10335//
10336//     // Implement Shr for WritableOptionalKeyPath >> WritableOptionalKeyPath: returns WritableOptionalKeyPath
10337//     impl<Root, Value, F, SubValue, G> Shr<WritableOptionalKeyPath<Value, SubValue, G>> for WritableOptionalKeyPath<Root, Value, F>
10338//     where
10339//         F: for<'r> Fn(&'r mut Root) -> Option<&'r mut Value> + 'static,
10340//         G: for<'r> Fn(&'r mut Value) -> Option<&'r mut SubValue> + 'static,
10341//         Value: 'static,
10342//     {
10343//         type Output = WritableOptionalKeyPath<Root, SubValue, impl for<'r> Fn(&'r mut Root) -> Option<&'r mut SubValue>>;
10344//
10345//         fn shr(self, rhs: WritableOptionalKeyPath<Value, SubValue, G>) -> Self::Output {
10346//             self.then(rhs)
10347//         }
10348//     }
10349// }
10350
10351#[cfg(test)]
10352mod tests {
10353    use super::*;
10354    use std::rc::Rc;
10355    use std::sync::atomic::{AtomicUsize, Ordering};
10356
10357    // Global counter to track memory allocations/deallocations
10358    static ALLOC_COUNT: AtomicUsize = AtomicUsize::new(0);
10359    static DEALLOC_COUNT: AtomicUsize = AtomicUsize::new(0);
10360
10361    // Type that panics on clone to detect unwanted cloning
10362    #[derive(Debug)]
10363    struct NoCloneType {
10364        id: usize,
10365        data: String,
10366    }
10367
10368    impl NoCloneType {
10369        fn new(data: String) -> Self {
10370            ALLOC_COUNT.fetch_add(1, Ordering::SeqCst);
10371            Self {
10372                id: ALLOC_COUNT.load(Ordering::SeqCst),
10373                data,
10374            }
10375        }
10376    }
10377
10378    impl Clone for NoCloneType {
10379        fn clone(&self) -> Self {
10380            eprintln!("[DEBUG] NoCloneType should not be cloned! ID: {}", self.id);
10381            unreachable!("NoCloneType should not be cloned! ID: {}", self.id);
10382        }
10383    }
10384
10385    impl Drop for NoCloneType {
10386        fn drop(&mut self) {
10387            DEALLOC_COUNT.fetch_add(1, Ordering::SeqCst);
10388        }
10389    }
10390
10391    // Helper functions for testing memory management
10392    fn reset_memory_counters() {
10393        ALLOC_COUNT.store(0, Ordering::SeqCst);
10394        DEALLOC_COUNT.store(0, Ordering::SeqCst);
10395    }
10396
10397    fn get_alloc_count() -> usize {
10398        ALLOC_COUNT.load(Ordering::SeqCst)
10399    }
10400
10401    fn get_dealloc_count() -> usize {
10402        DEALLOC_COUNT.load(Ordering::SeqCst)
10403    }
10404
10405    // Usage example
10406    #[derive(Debug)]
10407    struct User {
10408        name: String,
10409        metadata: Option<Box<UserMetadata>>,
10410        friends: Vec<Arc<User>>,
10411    }
10412
10413    #[derive(Debug)]
10414    struct UserMetadata {
10415        created_at: String,
10416    }
10417
10418    fn some_fn() {
10419        let akash = User {
10420            name: "Akash".to_string(),
10421            metadata: Some(Box::new(UserMetadata {
10422                created_at: "2024-01-01".to_string(),
10423            })),
10424            friends: vec![Arc::new(User {
10425                name: "Bob".to_string(),
10426                metadata: None,
10427                friends: vec![],
10428            })],
10429        };
10430
10431        // Create keypaths
10432        let name_kp = KeyPath::new(|u: &User| &u.name);
10433        let metadata_kp = OptionalKeyPath::new(|u: &User| u.metadata.as_ref());
10434        let friends_kp = KeyPath::new(|u: &User| &u.friends);
10435
10436        // Use them
10437        println!("Name: {}", name_kp.get(&akash));
10438
10439        if let Some(metadata) = metadata_kp.get(&akash) {
10440            println!("Has metadata: {:?}", metadata);
10441        }
10442
10443        // Access first friend's name
10444        if let Some(first_friend) = akash.friends.get(0) {
10445            println!("First friend: {}", name_kp.get(first_friend));
10446        }
10447
10448        // Access metadata through Box using for_box()
10449        let created_at_kp = KeyPath::new(|m: &UserMetadata| &m.created_at);
10450
10451        if let Some(metadata) = akash.metadata.as_ref() {
10452            // Use for_box() to unwrap Box<UserMetadata> to &UserMetadata
10453            let boxed_metadata: &Box<UserMetadata> = metadata;
10454            let unwrapped = boxed_metadata.as_ref();
10455            println!("Created at: {:?}", created_at_kp.get(unwrapped));
10456        }
10457    }
10458
10459    #[test]
10460    fn test_name() {
10461        some_fn();
10462    }
10463
10464    #[test]
10465    fn test_no_cloning_on_keypath_operations() {
10466        reset_memory_counters();
10467
10468        // Create a value that panics on clone
10469        let value = NoCloneType::new("test".to_string());
10470        let boxed = Box::new(value);
10471
10472        // Create keypath - should not clone
10473        let kp = KeyPath::new(|b: &Box<NoCloneType>| b.as_ref());
10474
10475        // Access value - should not clone
10476        let _ref = kp.get(&boxed);
10477
10478        // Clone the keypath itself (this is allowed)
10479        let _kp_clone = kp.clone();
10480
10481        // Access again - should not clone the value
10482        let _ref2 = _kp_clone.get(&boxed);
10483
10484        // Verify no panics occurred (if we got here, no cloning happened)
10485        assert_eq!(get_alloc_count(), 1);
10486    }
10487
10488    #[test]
10489    fn test_no_cloning_on_optional_keypath_operations() {
10490        reset_memory_counters();
10491
10492        let value = NoCloneType::new("test".to_string());
10493        let opt = Some(Box::new(value));
10494
10495        // Create optional keypath
10496        let okp = OptionalKeyPath::new(|o: &Option<Box<NoCloneType>>| o.as_ref());
10497
10498        // Access - should not clone
10499        let _ref = okp.get(&opt);
10500
10501        // Clone keypath (allowed)
10502        let _okp_clone = okp.clone();
10503
10504        // Chain operations - should not clone values
10505        let chained = okp.then(OptionalKeyPath::new(|b: &Box<NoCloneType>| {
10506            Some(b.as_ref())
10507        }));
10508        let _ref2 = chained.get(&opt);
10509
10510        assert_eq!(get_alloc_count(), 1);
10511    }
10512
10513    #[test]
10514    fn test_memory_release() {
10515        reset_memory_counters();
10516
10517        {
10518            let value = NoCloneType::new("test".to_string());
10519            let boxed = Box::new(value);
10520            let kp = KeyPath::new(|b: &Box<NoCloneType>| b.as_ref());
10521
10522            // Use the keypath
10523            let _ref = kp.get(&boxed);
10524
10525            // boxed goes out of scope here
10526        }
10527
10528        // After drop, memory should be released
10529        // Note: This is a best-effort check since drop timing can vary
10530        assert_eq!(get_alloc_count(), 1);
10531        // Deallocation happens when the value is dropped
10532        // We can't reliably test exact timing, but we verify the counter exists
10533    }
10534
10535    #[test]
10536    fn test_keypath_clone_does_not_clone_underlying_data() {
10537        reset_memory_counters();
10538
10539        let value = NoCloneType::new("data".to_string());
10540        let rc_value = Rc::new(value);
10541
10542        // Create keypath
10543        let kp = KeyPath::new(|r: &Rc<NoCloneType>| r.as_ref());
10544
10545        // Clone keypath multiple times
10546        let kp1 = kp.clone();
10547        let kp2 = kp.clone();
10548        let kp3 = kp1.clone();
10549
10550        // All should work without cloning the underlying data
10551        let _ref1 = kp.get(&rc_value);
10552        let _ref2 = kp1.get(&rc_value);
10553        let _ref3 = kp2.get(&rc_value);
10554        let _ref4 = kp3.get(&rc_value);
10555
10556        // Only one allocation should have happened
10557        assert_eq!(get_alloc_count(), 1);
10558    }
10559
10560    #[test]
10561    fn test_optional_keypath_chaining_no_clone() {
10562        reset_memory_counters();
10563
10564        let value = NoCloneType::new("value1".to_string());
10565
10566        struct Container {
10567            inner: Option<Box<NoCloneType>>,
10568        }
10569
10570        let container = Container {
10571            inner: Some(Box::new(value)),
10572        };
10573
10574        // Create chained keypath
10575        let kp1 = OptionalKeyPath::new(|c: &Container| c.inner.as_ref());
10576        let kp2 = OptionalKeyPath::new(|b: &Box<NoCloneType>| Some(b.as_ref()));
10577
10578        // Chain them - should not clone
10579        let chained = kp1.then(kp2);
10580
10581        // Use chained keypath
10582        let _result = chained.get(&container);
10583
10584        // Should only have one allocation
10585        assert_eq!(get_alloc_count(), 1);
10586    }
10587
10588    #[test]
10589    fn test_for_box_no_clone() {
10590        reset_memory_counters();
10591
10592        let value = NoCloneType::new("test".to_string());
10593        let boxed = Box::new(value);
10594        let opt_boxed = Some(boxed);
10595
10596        // Create keypath with for_box
10597        let kp = OptionalKeyPath::new(|o: &Option<Box<NoCloneType>>| o.as_ref());
10598        let unwrapped = kp.for_box();
10599
10600        // Access - should not clone
10601        let _ref = unwrapped.get(&opt_boxed);
10602
10603        assert_eq!(get_alloc_count(), 1);
10604    }
10605
10606    // ========== MACRO USAGE EXAMPLES ==========
10607
10608    #[derive(Debug, PartialEq)]
10609    struct TestUser {
10610        name: String,
10611        age: u32,
10612        metadata: Option<String>,
10613        address: Option<TestAddress>,
10614    }
10615
10616    #[derive(Debug, PartialEq)]
10617    struct TestAddress {
10618        street: String,
10619        city: String,
10620        country: Option<TestCountry>,
10621    }
10622
10623    #[derive(Debug, PartialEq)]
10624    struct TestCountry {
10625        name: String,
10626    }
10627
10628    #[test]
10629    fn test_keypath_macro() {
10630        let user = TestUser {
10631            name: "Akash".to_string(),
10632            age: 30,
10633            metadata: None,
10634            address: None,
10635        };
10636
10637        // Simple field access using closure
10638        let name_kp = keypath!(|u: &TestUser| &u.name);
10639        assert_eq!(name_kp.get(&user), "Akash");
10640
10641        // Nested field access
10642        let user_with_address = TestUser {
10643            name: "Bob".to_string(),
10644            age: 25,
10645            metadata: None,
10646            address: Some(TestAddress {
10647                street: "123 Main St".to_string(),
10648                city: "New York".to_string(),
10649                country: None,
10650            }),
10651        };
10652
10653        let street_kp = keypath!(|u: &TestUser| &u.address.as_ref().unwrap().street);
10654        assert_eq!(street_kp.get(&user_with_address), "123 Main St");
10655
10656        // Deeper nesting
10657        let user_with_country = TestUser {
10658            name: "Charlie".to_string(),
10659            age: 35,
10660            metadata: None,
10661            address: Some(TestAddress {
10662                street: "456 Oak Ave".to_string(),
10663                city: "London".to_string(),
10664                country: Some(TestCountry {
10665                    name: "UK".to_string(),
10666                }),
10667            }),
10668        };
10669
10670        let country_name_kp =
10671            keypath!(|u: &TestUser| &u.address.as_ref().unwrap().country.as_ref().unwrap().name);
10672        assert_eq!(country_name_kp.get(&user_with_country), "UK");
10673
10674        // Fallback: using closure
10675        let age_kp = keypath!(|u: &TestUser| &u.age);
10676        assert_eq!(age_kp.get(&user), &30);
10677    }
10678
10679    #[test]
10680    fn test_opt_keypath_macro() {
10681        let user = TestUser {
10682            name: "Akash".to_string(),
10683            age: 30,
10684            metadata: Some("admin".to_string()),
10685            address: None,
10686        };
10687
10688        // Simple Option field access using closure
10689        let metadata_kp = opt_keypath!(|u: &TestUser| u.metadata.as_ref());
10690        assert_eq!(metadata_kp.get(&user), Some(&"admin".to_string()));
10691
10692        // None case
10693        let user_no_metadata = TestUser {
10694            name: "Bob".to_string(),
10695            age: 25,
10696            metadata: None,
10697            address: None,
10698        };
10699        assert_eq!(metadata_kp.get(&user_no_metadata), None);
10700
10701        // Nested Option access
10702        let user_with_address = TestUser {
10703            name: "Charlie".to_string(),
10704            age: 35,
10705            metadata: None,
10706            address: Some(TestAddress {
10707                street: "789 Pine Rd".to_string(),
10708                city: "Paris".to_string(),
10709                country: None,
10710            }),
10711        };
10712
10713        let street_kp = opt_keypath!(|u: &TestUser| u.address.as_ref().map(|a| &a.street));
10714        assert_eq!(
10715            street_kp.get(&user_with_address),
10716            Some(&"789 Pine Rd".to_string())
10717        );
10718
10719        // Deeper nesting through Options
10720        let user_with_country = TestUser {
10721            name: "David".to_string(),
10722            age: 40,
10723            metadata: None,
10724            address: Some(TestAddress {
10725                street: "321 Elm St".to_string(),
10726                city: "Tokyo".to_string(),
10727                country: Some(TestCountry {
10728                    name: "Japan".to_string(),
10729                }),
10730            }),
10731        };
10732
10733        let country_name_kp = opt_keypath!(|u: &TestUser| u
10734            .address
10735            .as_ref()
10736            .and_then(|a| a.country.as_ref().map(|c| &c.name)));
10737        assert_eq!(
10738            country_name_kp.get(&user_with_country),
10739            Some(&"Japan".to_string())
10740        );
10741
10742        // Fallback: using closure
10743        let metadata_kp2 = opt_keypath!(|u: &TestUser| u.metadata.as_ref());
10744        assert_eq!(metadata_kp2.get(&user), Some(&"admin".to_string()));
10745    }
10746
10747    #[test]
10748    fn test_writable_keypath_macro() {
10749        let mut user = TestUser {
10750            name: "Akash".to_string(),
10751            age: 30,
10752            metadata: None,
10753            address: None,
10754        };
10755
10756        // Simple field mutation using closure
10757        let name_kp = writable_keypath!(|u: &mut TestUser| &mut u.name);
10758        *name_kp.get_mut(&mut user) = "Bob".to_string();
10759        assert_eq!(user.name, "Bob");
10760
10761        // Nested field mutation
10762        let mut user_with_address = TestUser {
10763            name: "Charlie".to_string(),
10764            age: 25,
10765            metadata: None,
10766            address: Some(TestAddress {
10767                street: "123 Main St".to_string(),
10768                city: "New York".to_string(),
10769                country: None,
10770            }),
10771        };
10772
10773        let street_kp =
10774            writable_keypath!(|u: &mut TestUser| &mut u.address.as_mut().unwrap().street);
10775        *street_kp.get_mut(&mut user_with_address) = "456 Oak Ave".to_string();
10776        assert_eq!(
10777            user_with_address.address.as_ref().unwrap().street,
10778            "456 Oak Ave"
10779        );
10780
10781        // Deeper nesting
10782        let mut user_with_country = TestUser {
10783            name: "David".to_string(),
10784            age: 35,
10785            metadata: None,
10786            address: Some(TestAddress {
10787                street: "789 Pine Rd".to_string(),
10788                city: "London".to_string(),
10789                country: Some(TestCountry {
10790                    name: "UK".to_string(),
10791                }),
10792            }),
10793        };
10794
10795        let country_name_kp = writable_keypath!(|u: &mut TestUser| &mut u
10796            .address
10797            .as_mut()
10798            .unwrap()
10799            .country
10800            .as_mut()
10801            .unwrap()
10802            .name);
10803        *country_name_kp.get_mut(&mut user_with_country) = "United Kingdom".to_string();
10804        assert_eq!(
10805            user_with_country
10806                .address
10807                .as_ref()
10808                .unwrap()
10809                .country
10810                .as_ref()
10811                .unwrap()
10812                .name,
10813            "United Kingdom"
10814        );
10815
10816        // Fallback: using closure
10817        let age_kp = writable_keypath!(|u: &mut TestUser| &mut u.age);
10818        *age_kp.get_mut(&mut user) = 31;
10819        assert_eq!(user.age, 31);
10820    }
10821
10822    #[test]
10823    fn test_writable_opt_keypath_macro() {
10824        let mut user = TestUser {
10825            name: "Akash".to_string(),
10826            age: 30,
10827            metadata: Some("user".to_string()),
10828            address: None,
10829        };
10830
10831        // Simple Option field mutation using closure
10832        let metadata_kp = writable_opt_keypath!(|u: &mut TestUser| u.metadata.as_mut());
10833        if let Some(metadata) = metadata_kp.get_mut(&mut user) {
10834            *metadata = "admin".to_string();
10835        }
10836        assert_eq!(user.metadata, Some("admin".to_string()));
10837
10838        // None case - should return None
10839        let mut user_no_metadata = TestUser {
10840            name: "Bob".to_string(),
10841            age: 25,
10842            metadata: None,
10843            address: None,
10844        };
10845        assert_eq!(metadata_kp.get_mut(&mut user_no_metadata), None);
10846
10847        // Nested Option access
10848        let mut user_with_address = TestUser {
10849            name: "Charlie".to_string(),
10850            age: 35,
10851            metadata: None,
10852            address: Some(TestAddress {
10853                street: "123 Main St".to_string(),
10854                city: "New York".to_string(),
10855                country: None,
10856            }),
10857        };
10858
10859        let street_kp =
10860            writable_opt_keypath!(|u: &mut TestUser| u.address.as_mut().map(|a| &mut a.street));
10861        if let Some(street) = street_kp.get_mut(&mut user_with_address) {
10862            *street = "456 Oak Ave".to_string();
10863        }
10864        assert_eq!(
10865            user_with_address.address.as_ref().unwrap().street,
10866            "456 Oak Ave"
10867        );
10868
10869        // Deeper nesting through Options
10870        let mut user_with_country = TestUser {
10871            name: "David".to_string(),
10872            age: 40,
10873            metadata: None,
10874            address: Some(TestAddress {
10875                street: "789 Pine Rd".to_string(),
10876                city: "Tokyo".to_string(),
10877                country: Some(TestCountry {
10878                    name: "Japan".to_string(),
10879                }),
10880            }),
10881        };
10882
10883        let country_name_kp = writable_opt_keypath!(|u: &mut TestUser| u
10884            .address
10885            .as_mut()
10886            .and_then(|a| a.country.as_mut().map(|c| &mut c.name)));
10887        if let Some(country_name) = country_name_kp.get_mut(&mut user_with_country) {
10888            *country_name = "Nippon".to_string();
10889        }
10890        assert_eq!(
10891            user_with_country
10892                .address
10893                .as_ref()
10894                .unwrap()
10895                .country
10896                .as_ref()
10897                .unwrap()
10898                .name,
10899            "Nippon"
10900        );
10901
10902        // Fallback: using closure
10903        let metadata_kp2 = writable_opt_keypath!(|u: &mut TestUser| u.metadata.as_mut());
10904        if let Some(metadata) = metadata_kp2.get_mut(&mut user) {
10905            *metadata = "super_admin".to_string();
10906        }
10907        assert_eq!(user.metadata, Some("super_admin".to_string()));
10908    }
10909
10910    // ========== map HOF tests ==========
10911
10912    #[test]
10913    fn test_keypath_map() {
10914        #[derive(Debug)]
10915        struct WithLen {
10916            name: String,
10917            len: usize,
10918        }
10919        let w = WithLen {
10920            name: "world".to_string(),
10921            len: 5,
10922        };
10923        let kp = KeyPath::new(|w: &WithLen| w);
10924        let len_kp = kp.map(|w: &WithLen| &w.len);
10925        assert_eq!(*len_kp.get(&w), 5);
10926
10927        let kp2 = KeyPath::new(|w: &WithLen| w);
10928        let name_kp = kp2.map(|w: &WithLen| &w.name);
10929        assert_eq!(name_kp.get(&w).as_str(), "world");
10930    }
10931
10932    #[test]
10933    fn test_optional_keypath_map() {
10934        #[derive(Debug)]
10935        struct WithLen {
10936            len: usize,
10937        }
10938        let kp = OptionalKeyPath::new(|o: &Option<WithLen>| o.as_ref());
10939        let len_kp = kp.map(|w: &WithLen| &w.len);
10940        assert_eq!(*len_kp.get(&Some(WithLen { len: 42 })).unwrap(), 42);
10941        assert!(len_kp.get(&None::<WithLen>).is_none());
10942
10943        #[derive(Debug)]
10944        struct WithName {
10945            name: String,
10946        }
10947        let kp2 = OptionalKeyPath::new(|o: &Option<WithName>| o.as_ref());
10948        let name_kp = kp2.map(|w: &WithName| &w.name);
10949        assert_eq!(
10950            name_kp.get(&Some(WithName { name: "foo".to_string() })),
10951            Some(&"foo".to_string())
10952        );
10953    }
10954
10955    #[test]
10956    fn test_writable_keypath_map() {
10957        #[derive(Debug)]
10958        struct Pair {
10959            x: u32,
10960            y: u32,
10961        }
10962        let kp = WritableKeyPath::new(|p: &mut Pair| p);
10963        let y_kp = kp.map(|p: &mut Pair| &mut p.y);
10964        let mut p = Pair { x: 1, y: 2 };
10965        *y_kp.get_mut(&mut p) = 42;
10966        assert_eq!(p.y, 42);
10967        assert_eq!(p.x, 1);
10968    }
10969
10970    #[test]
10971    fn test_writable_optional_keypath_map() {
10972        #[derive(Debug)]
10973        struct Item {
10974            value: i32,
10975        }
10976        let kp = WritableOptionalKeyPath::new(|o: &mut Option<Item>| o.as_mut());
10977        let value_kp = kp.map(|item: &mut Item| &mut item.value);
10978        let mut some_item = Some(Item { value: 10 });
10979        if let Some(v) = value_kp.get_mut(&mut some_item) {
10980            *v = 20;
10981        }
10982        assert_eq!(some_item.unwrap().value, 20);
10983
10984        let mut none_item: Option<Item> = None;
10985        assert!(value_kp.get_mut(&mut none_item).is_none());
10986    }
10987
10988    #[test]
10989    fn test_keypath_map_optional() {
10990        #[derive(Debug)]
10991        struct WithVec {
10992            vec_field: Vec<String>,
10993        }
10994        let vec_kp = KeyPath::new(|w: &WithVec| &w.vec_field);
10995        let first_kp = vec_kp.map_optional(|x: &Vec<String>| x.first());
10996        let value = WithVec {
10997            vec_field: vec!["a".into(), "b".into()],
10998        };
10999        assert_eq!(first_kp.get(&value), Some(&"a".to_string()));
11000        let empty = WithVec {
11001            vec_field: vec![],
11002        };
11003        assert!(first_kp.get(&empty).is_none());
11004    }
11005
11006    #[test]
11007    fn test_optional_keypath_map_optional() {
11008        #[derive(Debug)]
11009        struct WithVec {
11010            vec_field: Vec<String>,
11011        }
11012        let kp = OptionalKeyPath::new(|o: &Option<WithVec>| o.as_ref());
11013        let first_kp = kp.map_optional(|w: &WithVec| w.vec_field.first());
11014        assert_eq!(
11015            first_kp.get(&Some(WithVec {
11016                vec_field: vec!["x".into()]
11017            })),
11018            Some(&"x".to_string())
11019        );
11020        assert!(first_kp.get(&None::<WithVec>).is_none());
11021    }
11022
11023    #[test]
11024    fn test_keypath_identity() {
11025        let kp = KeyPath::<i32, i32, _>::identity();
11026        let x = 42;
11027        assert!(std::ptr::eq(kp.get(&x), &x));
11028        let s = "hello".to_string();
11029        let kp_s = KeyPath::<String, String, _>::identity();
11030        assert!(std::ptr::eq(kp_s.get(&s), &s));
11031    }
11032
11033    #[test]
11034    fn test_optional_keypath_identity() {
11035        let kp = OptionalKeyPath::<i32, i32, _>::identity();
11036        let x = 42;
11037        assert_eq!(kp.get(&x), Some(&x));
11038        assert!(std::ptr::eq(kp.get(&x).unwrap(), &x));
11039    }
11040
11041    #[test]
11042    fn test_writable_keypath_identity() {
11043        let kp = WritableKeyPath::<i32, i32, _>::identity();
11044        let mut x = 42;
11045        assert!(std::ptr::eq(kp.get_mut(&mut x), &mut x));
11046    }
11047
11048    #[test]
11049    fn test_writable_optional_keypath_identity() {
11050        let kp = WritableOptionalKeyPath::<i32, i32, _>::identity();
11051        let mut x = 42;
11052        assert_eq!(kp.get_mut(&mut x).map(|r| *r), Some(42));
11053        assert!(std::ptr::eq(kp.get_mut(&mut x).unwrap(), &mut x));
11054    }
11055
11056    #[test]
11057    fn test_enum_keypath_identity() {
11058        let kp = EnumKeyPath::identity::<i32>();
11059        let x = 42;
11060        assert_eq!(kp.get(&x), Some(&x));
11061        assert!(std::ptr::eq(kp.get(&x).unwrap(), &x));
11062        assert_eq!(kp.embed(100), 100);
11063    }
11064}
11065
11066// ========== WithContainer Trait ==========
11067
11068/// Trait for no-clone callback-based access to container types
11069/// Provides methods to execute closures with references to values inside containers
11070/// without requiring cloning of the values
11071pub trait WithContainer<Root, Value> {
11072    /// Execute a closure with a reference to the value inside an Arc
11073    fn with_arc<F, R>(&self, arc: &Arc<Root>, f: F) -> R
11074    where
11075        F: FnOnce(&Value) -> R;
11076
11077    /// Execute a closure with a reference to the value inside a Box
11078    fn with_box<F, R>(&self, boxed: &Box<Root>, f: F) -> R
11079    where
11080        F: FnOnce(&Value) -> R;
11081
11082    /// Execute a closure with a mutable reference to the value inside a Box
11083    fn with_box_mut<F, R>(&self, boxed: &mut Box<Root>, f: F) -> R
11084    where
11085        F: FnOnce(&mut Value) -> R;
11086
11087    /// Execute a closure with a reference to the value inside an Rc
11088    fn with_rc<F, R>(&self, rc: &Rc<Root>, f: F) -> R
11089    where
11090        F: FnOnce(&Value) -> R;
11091
11092    /// Execute a closure with a reference to the value inside a Result
11093    fn with_result<F, R, E>(&self, result: &Result<Root, E>, f: F) -> Option<R>
11094    where
11095        F: FnOnce(&Value) -> R;
11096
11097    /// Execute a closure with a mutable reference to the value inside a Result
11098    fn with_result_mut<F, R, E>(&self, result: &mut Result<Root, E>, f: F) -> Option<R>
11099    where
11100        F: FnOnce(&mut Value) -> R;
11101
11102    /// Execute a closure with a reference to the value inside an Option
11103    fn with_option<F, R>(&self, option: &Option<Root>, f: F) -> Option<R>
11104    where
11105        F: FnOnce(&Value) -> R;
11106
11107    /// Execute a closure with a mutable reference to the value inside an Option
11108    fn with_option_mut<F, R>(&self, option: &mut Option<Root>, f: F) -> Option<R>
11109    where
11110        F: FnOnce(&mut Value) -> R;
11111
11112    /// Execute a closure with a reference to the value inside a RefCell
11113    fn with_refcell<F, R>(&self, refcell: &RefCell<Root>, f: F) -> Option<R>
11114    where
11115        F: FnOnce(&Value) -> R;
11116
11117    /// Execute a closure with a mutable reference to the value inside a RefCell
11118    fn with_refcell_mut<F, R>(&self, refcell: &RefCell<Root>, f: F) -> Option<R>
11119    where
11120        F: FnOnce(&mut Value) -> R;
11121
11122    #[cfg(feature = "tagged")]
11123    /// Execute a closure with a reference to the value inside a Tagged
11124    fn with_tagged<F, R, Tag>(&self, tagged: &Tagged<Root, Tag>, f: F) -> R
11125    where
11126        Tagged<Root, Tag>: std::ops::Deref<Target = Root>,
11127        F: FnOnce(&Value) -> R;
11128
11129    /// Execute a closure with a reference to the value inside a Mutex
11130    fn with_mutex<F, R>(&self, mutex: &Mutex<Root>, f: F) -> Option<R>
11131    where
11132        F: FnOnce(&Value) -> R;
11133
11134    /// Execute a closure with a mutable reference to the value inside a Mutex
11135    fn with_mutex_mut<F, R>(&self, mutex: &mut Mutex<Root>, f: F) -> Option<R>
11136    where
11137        F: FnOnce(&mut Value) -> R;
11138
11139    /// Execute a closure with a reference to the value inside an RwLock
11140    fn with_rwlock<F, R>(&self, rwlock: &RwLock<Root>, f: F) -> Option<R>
11141    where
11142        F: FnOnce(&Value) -> R;
11143
11144    /// Execute a closure with a mutable reference to the value inside an RwLock
11145    fn with_rwlock_mut<F, R>(&self, rwlock: &mut RwLock<Root>, f: F) -> Option<R>
11146    where
11147        F: FnOnce(&mut Value) -> R;
11148
11149    /// Execute a closure with a reference to the value inside an Arc<RwLock<Root>>
11150    fn with_arc_rwlock<F, R>(&self, arc_rwlock: &Arc<RwLock<Root>>, f: F) -> Option<R>
11151    where
11152        F: FnOnce(&Value) -> R;
11153
11154    /// Execute a closure with a mutable reference to the value inside an Arc<RwLock<Root>>
11155    fn with_arc_rwlock_mut<F, R>(&self, arc_rwlock: &Arc<RwLock<Root>>, f: F) -> Option<R>
11156    where
11157        F: FnOnce(&mut Value) -> R;
11158}
11159
11160// Implement WithContainer for KeyPath
11161impl<Root, Value, F> WithContainer<Root, Value> for KeyPath<Root, Value, F>
11162where
11163    F: for<'r> Fn(&'r Root) -> &'r Value + Clone,
11164{
11165    fn with_arc<Callback, R>(&self, arc: &Arc<Root>, f: Callback) -> R
11166    where
11167        Callback: FnOnce(&Value) -> R,
11168    {
11169        self.with_arc(arc, f)
11170    }
11171
11172    fn with_box<Callback, R>(&self, boxed: &Box<Root>, f: Callback) -> R
11173    where
11174        Callback: FnOnce(&Value) -> R,
11175    {
11176        self.with_box(boxed, f)
11177    }
11178
11179    fn with_box_mut<Callback, R>(&self, _boxed: &mut Box<Root>, _f: Callback) -> R
11180    where
11181        Callback: FnOnce(&mut Value) -> R,
11182    {
11183        eprintln!("[DEBUG] KeyPath does not support mutable access - use WritableKeyPath instead");
11184        unreachable!("KeyPath does not support mutable access - use WritableKeyPath instead")
11185    }
11186
11187    fn with_rc<Callback, R>(&self, rc: &Rc<Root>, f: Callback) -> R
11188    where
11189        Callback: FnOnce(&Value) -> R,
11190    {
11191        self.with_rc(rc, f)
11192    }
11193
11194    fn with_result<Callback, R, E>(&self, result: &Result<Root, E>, f: Callback) -> Option<R>
11195    where
11196        Callback: FnOnce(&Value) -> R,
11197    {
11198        self.with_result(result, f)
11199    }
11200
11201    fn with_result_mut<Callback, R, E>(
11202        &self,
11203        _result: &mut Result<Root, E>,
11204        _f: Callback,
11205    ) -> Option<R>
11206    where
11207        Callback: FnOnce(&mut Value) -> R,
11208    {
11209        None
11210    }
11211
11212    fn with_option<Callback, R>(&self, option: &Option<Root>, f: Callback) -> Option<R>
11213    where
11214        Callback: FnOnce(&Value) -> R,
11215    {
11216        self.with_option(option, f)
11217    }
11218
11219    fn with_option_mut<Callback, R>(&self, _option: &mut Option<Root>, _f: Callback) -> Option<R>
11220    where
11221        Callback: FnOnce(&mut Value) -> R,
11222    {
11223        None
11224    }
11225
11226    fn with_refcell<Callback, R>(&self, refcell: &RefCell<Root>, f: Callback) -> Option<R>
11227    where
11228        Callback: FnOnce(&Value) -> R,
11229    {
11230        self.with_refcell(refcell, f)
11231    }
11232
11233    fn with_refcell_mut<Callback, R>(&self, _refcell: &RefCell<Root>, _f: Callback) -> Option<R>
11234    where
11235        Callback: FnOnce(&mut Value) -> R,
11236    {
11237        None
11238    }
11239
11240    #[cfg(feature = "tagged")]
11241    fn with_tagged<Callback, R, Tag>(&self, tagged: &Tagged<Root, Tag>, f: Callback) -> R
11242    where
11243        Tagged<Root, Tag>: std::ops::Deref<Target = Root>,
11244        Callback: FnOnce(&Value) -> R,
11245    {
11246        self.with_tagged(tagged, f)
11247    }
11248
11249    fn with_mutex<Callback, R>(&self, mutex: &Mutex<Root>, f: Callback) -> Option<R>
11250    where
11251        Callback: FnOnce(&Value) -> R,
11252    {
11253        self.with_mutex(mutex, f)
11254    }
11255
11256    fn with_mutex_mut<Callback, R>(&self, _mutex: &mut Mutex<Root>, _f: Callback) -> Option<R>
11257    where
11258        Callback: FnOnce(&mut Value) -> R,
11259    {
11260        None
11261    }
11262
11263    fn with_rwlock<Callback, R>(&self, rwlock: &RwLock<Root>, f: Callback) -> Option<R>
11264    where
11265        Callback: FnOnce(&Value) -> R,
11266    {
11267        self.with_rwlock(rwlock, f)
11268    }
11269
11270    fn with_rwlock_mut<Callback, R>(&self, _rwlock: &mut RwLock<Root>, _f: Callback) -> Option<R>
11271    where
11272        Callback: FnOnce(&mut Value) -> R,
11273    {
11274        None
11275    }
11276
11277    fn with_arc_rwlock<Callback, R>(&self, arc_rwlock: &Arc<RwLock<Root>>, f: Callback) -> Option<R>
11278    where
11279        Callback: FnOnce(&Value) -> R,
11280    {
11281        self.with_arc_rwlock(arc_rwlock, f)
11282    }
11283
11284    fn with_arc_rwlock_mut<Callback, R>(
11285        &self,
11286        _arc_rwlock: &Arc<RwLock<Root>>,
11287        _f: Callback,
11288    ) -> Option<R>
11289    where
11290        Callback: FnOnce(&mut Value) -> R,
11291    {
11292        None
11293    }
11294}
11295
11296// Implement WithContainer for OptionalKeyPath - read-only operations only
11297impl<Root, Value, F> WithContainer<Root, Value> for OptionalKeyPath<Root, Value, F>
11298where
11299    F: for<'r> Fn(&'r Root) -> Option<&'r Value> + Clone,
11300{
11301    fn with_arc<Callback, R>(&self, arc: &Arc<Root>, f: Callback) -> R
11302    where
11303        Callback: FnOnce(&Value) -> R,
11304    {
11305        self.with_arc(arc, f)
11306    }
11307
11308    fn with_box<Callback, R>(&self, boxed: &Box<Root>, f: Callback) -> R
11309    where
11310        Callback: FnOnce(&Value) -> R,
11311    {
11312        self.with_box(boxed, f)
11313    }
11314
11315    fn with_box_mut<Callback, R>(&self, _boxed: &mut Box<Root>, _f: Callback) -> R
11316    where
11317        Callback: FnOnce(&mut Value) -> R,
11318    {
11319        eprintln!(
11320            "[DEBUG] OptionalKeyPath does not support mutable access - use WritableOptionalKeyPath instead"
11321        );
11322        unreachable!(
11323            "OptionalKeyPath does not support mutable access - use WritableOptionalKeyPath instead"
11324        )
11325    }
11326
11327    fn with_rc<Callback, R>(&self, rc: &Rc<Root>, f: Callback) -> R
11328    where
11329        Callback: FnOnce(&Value) -> R,
11330    {
11331        self.with_rc(rc, f)
11332    }
11333
11334    fn with_result<Callback, R, E>(&self, result: &Result<Root, E>, f: Callback) -> Option<R>
11335    where
11336        Callback: FnOnce(&Value) -> R,
11337    {
11338        self.with_result(result, f)
11339    }
11340
11341    fn with_result_mut<Callback, R, E>(
11342        &self,
11343        _result: &mut Result<Root, E>,
11344        _f: Callback,
11345    ) -> Option<R>
11346    where
11347        Callback: FnOnce(&mut Value) -> R,
11348    {
11349        None // OptionalKeyPath doesn't support mutable access
11350    }
11351
11352    fn with_option<Callback, R>(&self, option: &Option<Root>, f: Callback) -> Option<R>
11353    where
11354        Callback: FnOnce(&Value) -> R,
11355    {
11356        self.with_option(option, f)
11357    }
11358
11359    fn with_option_mut<Callback, R>(&self, _option: &mut Option<Root>, _f: Callback) -> Option<R>
11360    where
11361        Callback: FnOnce(&mut Value) -> R,
11362    {
11363        None // OptionalKeyPath doesn't support mutable access
11364    }
11365
11366    fn with_refcell<Callback, R>(&self, refcell: &RefCell<Root>, f: Callback) -> Option<R>
11367    where
11368        Callback: FnOnce(&Value) -> R,
11369    {
11370        self.with_refcell(refcell, f)
11371    }
11372
11373    fn with_refcell_mut<Callback, R>(&self, _refcell: &RefCell<Root>, _f: Callback) -> Option<R>
11374    where
11375        Callback: FnOnce(&mut Value) -> R,
11376    {
11377        None // OptionalKeyPath doesn't support mutable access
11378    }
11379
11380    #[cfg(feature = "tagged")]
11381    fn with_tagged<Callback, R, Tag>(&self, tagged: &Tagged<Root, Tag>, f: Callback) -> R
11382    where
11383        Tagged<Root, Tag>: std::ops::Deref<Target = Root>,
11384        Callback: FnOnce(&Value) -> R,
11385    {
11386        use std::ops::Deref;
11387        self.get(tagged.deref())
11388            .map(|value| f(value))
11389            .expect("OptionalKeyPath::with_tagged: Tagged should always contain a value that matches the keypath")
11390    }
11391
11392    fn with_mutex<Callback, R>(&self, mutex: &Mutex<Root>, f: Callback) -> Option<R>
11393    where
11394        Callback: FnOnce(&Value) -> R,
11395    {
11396        self.with_mutex(mutex, f)
11397    }
11398
11399    fn with_mutex_mut<Callback, R>(&self, _mutex: &mut Mutex<Root>, _f: Callback) -> Option<R>
11400    where
11401        Callback: FnOnce(&mut Value) -> R,
11402    {
11403        None // OptionalKeyPath doesn't support mutable access
11404    }
11405
11406    fn with_rwlock<Callback, R>(&self, rwlock: &RwLock<Root>, f: Callback) -> Option<R>
11407    where
11408        Callback: FnOnce(&Value) -> R,
11409    {
11410        self.with_rwlock(rwlock, f)
11411    }
11412
11413    fn with_rwlock_mut<Callback, R>(&self, _rwlock: &mut RwLock<Root>, _f: Callback) -> Option<R>
11414    where
11415        Callback: FnOnce(&mut Value) -> R,
11416    {
11417        None // OptionalKeyPath doesn't support mutable access
11418    }
11419
11420    fn with_arc_rwlock<Callback, R>(&self, arc_rwlock: &Arc<RwLock<Root>>, f: Callback) -> Option<R>
11421    where
11422        Callback: FnOnce(&Value) -> R,
11423    {
11424        self.with_arc_rwlock(arc_rwlock, f)
11425    }
11426
11427    fn with_arc_rwlock_mut<Callback, R>(
11428        &self,
11429        _arc_rwlock: &Arc<RwLock<Root>>,
11430        _f: Callback,
11431    ) -> Option<R>
11432    where
11433        Callback: FnOnce(&mut Value) -> R,
11434    {
11435        None // OptionalKeyPath doesn't support mutable access - use WritableOptionalKeyPath instead
11436    }
11437}
11438
11439// Implement WithContainer for WritableKeyPath - supports all mutable operations
11440impl<Root, Value, F> WithContainer<Root, Value> for WritableKeyPath<Root, Value, F>
11441where
11442    F: for<'r> Fn(&'r mut Root) -> &'r mut Value,
11443{
11444    fn with_arc<Callback, R>(&self, _arc: &Arc<Root>, _f: Callback) -> R
11445    where
11446        Callback: FnOnce(&Value) -> R,
11447    {
11448        // Arc doesn't support mutable access without interior mutability
11449        // This method requires &mut Arc<Root> which we don't have
11450        eprintln!(
11451            "[DEBUG] WritableKeyPath::with_arc requires &mut Arc<Root> or interior mutability"
11452        );
11453        unreachable!("WritableKeyPath::with_arc requires &mut Arc<Root> or interior mutability")
11454    }
11455
11456    fn with_box<Callback, R>(&self, boxed: &Box<Root>, f: Callback) -> R
11457    where
11458        Callback: FnOnce(&Value) -> R,
11459    {
11460        // Box doesn't support getting mutable reference from immutable reference
11461        // This is a limitation - we'd need &mut Box<Root> for mutable access
11462        eprintln!(
11463            "[DEBUG] WritableKeyPath::with_box requires &mut Box<Root> - use with_box_mut instead"
11464        );
11465        unreachable!("WritableKeyPath::with_box requires &mut Box<Root> - use with_box_mut instead")
11466    }
11467
11468    fn with_box_mut<Callback, R>(&self, boxed: &mut Box<Root>, f: Callback) -> R
11469    where
11470        Callback: FnOnce(&mut Value) -> R,
11471    {
11472        let value = self.get_mut(boxed.as_mut());
11473        f(value)
11474    }
11475
11476    fn with_rc<Callback, R>(&self, _rc: &Rc<Root>, _f: Callback) -> R
11477    where
11478        Callback: FnOnce(&Value) -> R,
11479    {
11480        // Rc doesn't support mutable access without interior mutability
11481        // This method requires &mut Rc<Root> which we don't have
11482        eprintln!("[DEBUG] WritableKeyPath::with_rc requires &mut Rc<Root> or interior mutability");
11483        unreachable!("WritableKeyPath::with_rc requires &mut Rc<Root> or interior mutability")
11484    }
11485
11486    fn with_result<Callback, R, E>(&self, _result: &Result<Root, E>, _f: Callback) -> Option<R>
11487    where
11488        Callback: FnOnce(&Value) -> R,
11489    {
11490        // WritableKeyPath requires &mut Root, but we only have &Result<Root, E>
11491        // This is a limitation - use with_result_mut for mutable access
11492        None
11493    }
11494
11495    fn with_result_mut<Callback, R, E>(
11496        &self,
11497        result: &mut Result<Root, E>,
11498        f: Callback,
11499    ) -> Option<R>
11500    where
11501        Callback: FnOnce(&mut Value) -> R,
11502    {
11503        result.as_mut().ok().map(|root| {
11504            let value = self.get_mut(root);
11505            f(value)
11506        })
11507    }
11508
11509    fn with_option<Callback, R>(&self, _option: &Option<Root>, _f: Callback) -> Option<R>
11510    where
11511        Callback: FnOnce(&Value) -> R,
11512    {
11513        // WritableKeyPath requires &mut Root, but we only have &Option<Root>
11514        // This is a limitation - use with_option_mut for mutable access
11515        None
11516    }
11517
11518    fn with_option_mut<Callback, R>(&self, option: &mut Option<Root>, f: Callback) -> Option<R>
11519    where
11520        Callback: FnOnce(&mut Value) -> R,
11521    {
11522        option.as_mut().map(|root| {
11523            let value = self.get_mut(root);
11524            f(value)
11525        })
11526    }
11527
11528    fn with_refcell<Callback, R>(&self, refcell: &RefCell<Root>, f: Callback) -> Option<R>
11529    where
11530        Callback: FnOnce(&Value) -> R,
11531    {
11532        // RefCell doesn't allow getting mutable reference from immutable borrow
11533        // This is a limitation - we'd need try_borrow_mut for mutable access
11534        None
11535    }
11536
11537    fn with_refcell_mut<Callback, R>(&self, refcell: &RefCell<Root>, f: Callback) -> Option<R>
11538    where
11539        Callback: FnOnce(&mut Value) -> R,
11540    {
11541        refcell.try_borrow_mut().ok().map(|mut borrow| {
11542            let value = self.get_mut(&mut *borrow);
11543            f(value)
11544        })
11545    }
11546
11547    #[cfg(feature = "tagged")]
11548    fn with_tagged<Callback, R, Tag>(&self, _tagged: &Tagged<Root, Tag>, _f: Callback) -> R
11549    where
11550        Tagged<Root, Tag>: std::ops::Deref<Target = Root>,
11551        Callback: FnOnce(&Value) -> R,
11552    {
11553        // WritableKeyPath requires &mut Root, but we only have &Tagged<Root, Tag>
11554        // This is a limitation - Tagged doesn't support mutable access without interior mutability
11555        eprintln!(
11556            "[DEBUG] WritableKeyPath::with_tagged requires &mut Tagged<Root, Tag> or interior mutability"
11557        );
11558        unreachable!(
11559            "WritableKeyPath::with_tagged requires &mut Tagged<Root, Tag> or interior mutability"
11560        )
11561    }
11562
11563    fn with_mutex<Callback, R>(&self, mutex: &Mutex<Root>, f: Callback) -> Option<R>
11564    where
11565        Callback: FnOnce(&Value) -> R,
11566    {
11567        mutex.lock().ok().map(|mut guard| {
11568            let value = self.get_mut(&mut *guard);
11569            f(value)
11570        })
11571    }
11572
11573    fn with_mutex_mut<Callback, R>(&self, mutex: &mut Mutex<Root>, f: Callback) -> Option<R>
11574    where
11575        Callback: FnOnce(&mut Value) -> R,
11576    {
11577        // Mutex::get_mut returns Result<&mut Root, PoisonError>
11578        mutex.get_mut().ok().map(|root| {
11579            let value = self.get_mut(root);
11580            f(value)
11581        })
11582    }
11583
11584    fn with_rwlock<Callback, R>(&self, rwlock: &RwLock<Root>, f: Callback) -> Option<R>
11585    where
11586        Callback: FnOnce(&Value) -> R,
11587    {
11588        // RwLock read guard doesn't allow mutable access
11589        // This is a limitation - we'd need write() for mutable access
11590        None
11591    }
11592
11593    fn with_rwlock_mut<Callback, R>(&self, rwlock: &mut RwLock<Root>, f: Callback) -> Option<R>
11594    where
11595        Callback: FnOnce(&mut Value) -> R,
11596    {
11597        // RwLock::get_mut returns Result<&mut Root, PoisonError>
11598        rwlock.get_mut().ok().map(|root| {
11599            let value = self.get_mut(root);
11600            f(value)
11601        })
11602    }
11603
11604    fn with_arc_rwlock<Callback, R>(&self, arc_rwlock: &Arc<RwLock<Root>>, f: Callback) -> Option<R>
11605    where
11606        Callback: FnOnce(&Value) -> R,
11607    {
11608        // Arc<RwLock> read guard doesn't allow mutable access
11609        // This is a limitation - we'd need write() for mutable access
11610        None
11611    }
11612
11613    fn with_arc_rwlock_mut<Callback, R>(
11614        &self,
11615        arc_rwlock: &Arc<RwLock<Root>>,
11616        f: Callback,
11617    ) -> Option<R>
11618    where
11619        Callback: FnOnce(&mut Value) -> R,
11620    {
11621        arc_rwlock.write().ok().map(|mut guard| {
11622            let value = self.get_mut(&mut *guard);
11623            f(value)
11624        })
11625    }
11626}
11627
11628// Implement WithContainer for WritableOptionalKeyPath - supports all mutable operations
11629impl<Root, Value, F> WithContainer<Root, Value> for WritableOptionalKeyPath<Root, Value, F>
11630where
11631    F: for<'r> Fn(&'r mut Root) -> Option<&'r mut Value>,
11632{
11633    fn with_arc<Callback, R>(&self, _arc: &Arc<Root>, _f: Callback) -> R
11634    where
11635        Callback: FnOnce(&Value) -> R,
11636    {
11637        // Arc doesn't support mutable access without interior mutability
11638        // This method requires &mut Arc<Root> which we don't have
11639        eprintln!(
11640            "[DEBUG] WritableOptionalKeyPath::with_arc requires &mut Arc<Root> or interior mutability"
11641        );
11642        unreachable!(
11643            "WritableOptionalKeyPath::with_arc requires &mut Arc<Root> or interior mutability"
11644        )
11645    }
11646
11647    fn with_box<Callback, R>(&self, _boxed: &Box<Root>, _f: Callback) -> R
11648    where
11649        Callback: FnOnce(&Value) -> R,
11650    {
11651        // WritableOptionalKeyPath requires &mut Root, but we only have &Box<Root>
11652        // This is a limitation - use with_box_mut for mutable access
11653        eprintln!(
11654            "[DEBUG] WritableOptionalKeyPath::with_box requires &mut Box<Root> - use with_box_mut instead"
11655        );
11656        unreachable!(
11657            "WritableOptionalKeyPath::with_box requires &mut Box<Root> - use with_box_mut instead"
11658        )
11659    }
11660
11661    fn with_box_mut<Callback, R>(&self, boxed: &mut Box<Root>, f: Callback) -> R
11662    where
11663        Callback: FnOnce(&mut Value) -> R,
11664    {
11665        if let Some(value) = self.get_mut(boxed.as_mut()) {
11666            f(value)
11667        } else {
11668            eprintln!("[DEBUG] WritableOptionalKeyPath failed to get value from Box");
11669            unreachable!("WritableOptionalKeyPath failed to get value from Box")
11670        }
11671    }
11672
11673    fn with_rc<Callback, R>(&self, _rc: &Rc<Root>, _f: Callback) -> R
11674    where
11675        Callback: FnOnce(&Value) -> R,
11676    {
11677        // Rc doesn't support mutable access without interior mutability
11678        // This method requires &mut Rc<Root> which we don't have
11679        eprintln!(
11680            "[DEBUG] WritableOptionalKeyPath::with_rc requires &mut Rc<Root> or interior mutability"
11681        );
11682        unreachable!(
11683            "WritableOptionalKeyPath::with_rc requires &mut Rc<Root> or interior mutability"
11684        )
11685    }
11686
11687    fn with_result<Callback, R, E>(&self, _result: &Result<Root, E>, _f: Callback) -> Option<R>
11688    where
11689        Callback: FnOnce(&Value) -> R,
11690    {
11691        // WritableOptionalKeyPath requires &mut Root, but we only have &Result<Root, E>
11692        // This is a limitation - use with_result_mut for mutable access
11693        None
11694    }
11695
11696    fn with_result_mut<Callback, R, E>(
11697        &self,
11698        result: &mut Result<Root, E>,
11699        f: Callback,
11700    ) -> Option<R>
11701    where
11702        Callback: FnOnce(&mut Value) -> R,
11703    {
11704        result
11705            .as_mut()
11706            .ok()
11707            .and_then(|root| self.get_mut(root).map(|value| f(value)))
11708    }
11709
11710    fn with_option<Callback, R>(&self, _option: &Option<Root>, _f: Callback) -> Option<R>
11711    where
11712        Callback: FnOnce(&Value) -> R,
11713    {
11714        // WritableOptionalKeyPath requires &mut Root, but we only have &Option<Root>
11715        // This is a limitation - use with_option_mut for mutable access
11716        None
11717    }
11718
11719    fn with_option_mut<Callback, R>(&self, option: &mut Option<Root>, f: Callback) -> Option<R>
11720    where
11721        Callback: FnOnce(&mut Value) -> R,
11722    {
11723        option
11724            .as_mut()
11725            .and_then(|root| self.get_mut(root).map(|value| f(value)))
11726    }
11727
11728    fn with_refcell<Callback, R>(&self, _refcell: &RefCell<Root>, _f: Callback) -> Option<R>
11729    where
11730        Callback: FnOnce(&Value) -> R,
11731    {
11732        // RefCell doesn't allow getting mutable reference from immutable borrow
11733        // This is a limitation - we'd need try_borrow_mut for mutable access
11734        None
11735    }
11736
11737    fn with_refcell_mut<Callback, R>(&self, refcell: &RefCell<Root>, f: Callback) -> Option<R>
11738    where
11739        Callback: FnOnce(&mut Value) -> R,
11740    {
11741        refcell
11742            .try_borrow_mut()
11743            .ok()
11744            .and_then(|mut borrow| self.get_mut(&mut *borrow).map(|value| f(value)))
11745    }
11746
11747    #[cfg(feature = "tagged")]
11748    fn with_tagged<Callback, R, Tag>(&self, _tagged: &Tagged<Root, Tag>, _f: Callback) -> R
11749    where
11750        Tagged<Root, Tag>: std::ops::Deref<Target = Root>,
11751        Callback: FnOnce(&Value) -> R,
11752    {
11753        // WritableOptionalKeyPath requires &mut Root, but we only have &Tagged<Root, Tag>
11754        // This is a limitation - Tagged doesn't support mutable access without interior mutability
11755        eprintln!(
11756            "[DEBUG] WritableOptionalKeyPath::with_tagged requires &mut Tagged<Root, Tag> or interior mutability"
11757        );
11758        unreachable!(
11759            "WritableOptionalKeyPath::with_tagged requires &mut Tagged<Root, Tag> or interior mutability"
11760        )
11761    }
11762
11763    fn with_mutex<Callback, R>(&self, mutex: &Mutex<Root>, f: Callback) -> Option<R>
11764    where
11765        Callback: FnOnce(&Value) -> R,
11766    {
11767        mutex
11768            .lock()
11769            .ok()
11770            .and_then(|mut guard| self.get_mut(&mut *guard).map(|value| f(value)))
11771    }
11772
11773    fn with_mutex_mut<Callback, R>(&self, mutex: &mut Mutex<Root>, f: Callback) -> Option<R>
11774    where
11775        Callback: FnOnce(&mut Value) -> R,
11776    {
11777        // Mutex::get_mut returns Result<&mut Root, PoisonError>
11778        mutex
11779            .get_mut()
11780            .ok()
11781            .and_then(|root| self.get_mut(root).map(|value| f(value)))
11782    }
11783
11784    fn with_rwlock<Callback, R>(&self, _rwlock: &RwLock<Root>, _f: Callback) -> Option<R>
11785    where
11786        Callback: FnOnce(&Value) -> R,
11787    {
11788        // RwLock read guard doesn't allow mutable access
11789        // This is a limitation - we'd need write() for mutable access
11790        None
11791    }
11792
11793    fn with_rwlock_mut<Callback, R>(&self, rwlock: &mut RwLock<Root>, f: Callback) -> Option<R>
11794    where
11795        Callback: FnOnce(&mut Value) -> R,
11796    {
11797        // RwLock::get_mut returns Result<&mut Root, PoisonError>
11798        rwlock
11799            .get_mut()
11800            .ok()
11801            .and_then(|root| self.get_mut(root).map(|value| f(value)))
11802    }
11803
11804    fn with_arc_rwlock<Callback, R>(
11805        &self,
11806        _arc_rwlock: &Arc<RwLock<Root>>,
11807        _f: Callback,
11808    ) -> Option<R>
11809    where
11810        Callback: FnOnce(&Value) -> R,
11811    {
11812        // Arc<RwLock> read guard doesn't allow mutable access
11813        // This is a limitation - we'd need write() for mutable access
11814        None
11815    }
11816
11817    fn with_arc_rwlock_mut<Callback, R>(
11818        &self,
11819        arc_rwlock: &Arc<RwLock<Root>>,
11820        f: Callback,
11821    ) -> Option<R>
11822    where
11823        Callback: FnOnce(&mut Value) -> R,
11824    {
11825        arc_rwlock
11826            .write()
11827            .ok()
11828            .and_then(|mut guard| self.get_mut(&mut *guard).map(|value| f(value)))
11829    }
11830}