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    /// Type-erase the getter into a `Box<dyn Fn>`, so the keypath can be stored without the concrete closure type.
5235    pub fn boxed(
5236        self,
5237    ) -> KeyPath<Root, Value, Box<dyn for<'r> Fn(&'r Root) -> &'r Value + 'static>>
5238    where
5239        F: 'static,
5240        Root: 'static,
5241        Value: 'static,
5242    {
5243        KeyPath {
5244            getter: Box::new(self.getter),
5245            _phantom: PhantomData,
5246        }
5247    }
5248
5249    /// Higher-order function: map the value reference through a function.
5250    /// Returns a new `KeyPath<Root, U, _>` that gets the value and applies `f` to the reference.
5251    ///
5252    /// # Example
5253    /// ```rust
5254    /// use rust_keypaths::KeyPath;
5255    /// let kp = KeyPath::new(|s: &String| s);
5256    /// let len_kp = kp.map(|s: &String| &s.len());
5257    /// let s = "hello".to_string();
5258    /// assert_eq!(*len_kp.get(&s), 5);
5259    /// ```
5260    pub fn map<U, G>(self, f: G) -> KeyPath<Root, U, impl for<'r> Fn(&'r Root) -> &'r U>
5261    where
5262        G: for<'r> Fn(&'r Value) -> &'r U,
5263        F: 'static,
5264        G: 'static,
5265        Root: 'static,
5266        Value: 'static,
5267    {
5268        let getter = self.getter;
5269        KeyPath {
5270            getter: move |root| f(getter(root)),
5271            _phantom: PhantomData,
5272        }
5273    }
5274
5275    /// Map through a function that returns `Option<&U>`, producing an `OptionalKeyPath`.
5276    /// Use when the projection may fail (e.g. `|v: &Vec<T>| v.first()`).
5277    ///
5278    /// # Example
5279    /// ```rust,ignore
5280    /// let first = struct::vec_field_r().map_optional(|x: &Vec<String>| x.first());
5281    /// let opt: Option<&String> = first.get(&value);
5282    /// ```
5283    pub fn map_optional<U, G>(
5284        self,
5285        f: G,
5286    ) -> OptionalKeyPath<Root, U, impl for<'r> Fn(&'r Root) -> Option<&'r U>>
5287    where
5288        G: for<'r> Fn(&'r Value) -> Option<&'r U>,
5289        F: 'static,
5290        G: 'static,
5291        Root: 'static,
5292        Value: 'static,
5293    {
5294        let getter = self.getter;
5295        OptionalKeyPath {
5296            getter: move |root| f(getter(root)),
5297            _phantom: PhantomData,
5298        }
5299    }
5300
5301    /// Chain this keypath with an inner keypath through Arc<Mutex<T>> - functional style
5302    /// Compose first, then apply container at get() time
5303    ///
5304    /// # Example
5305    /// ```rust
5306    /// let container = ContainerTest { mutex_data: Arc::new(Mutex::new(SomeStruct { data: "test".to_string() })) };
5307    ///
5308    /// // Functional style: compose first, apply container at get()
5309    /// ContainerTest::mutex_data_r()
5310    ///     .chain_arc_mutex_at_kp(SomeStruct::data_r())
5311    ///     .get(&container, |value| println!("Data: {}", value));
5312    /// ```
5313    pub fn chain_arc_mutex_at_kp<InnerValue, SubValue, G>(
5314        self,
5315        inner_keypath: KeyPath<InnerValue, SubValue, G>,
5316    ) -> ArcMutexKeyPathChain<Root, Value, InnerValue, SubValue, F, G>
5317    where
5318        G: for<'r> Fn(&'r InnerValue) -> &'r SubValue,
5319    {
5320        ArcMutexKeyPathChain {
5321            outer_keypath: self,
5322            inner_keypath,
5323        }
5324    }
5325
5326    /// Chain this keypath with an optional inner keypath through Arc<Mutex<T>> - functional style
5327    /// Compose first, then apply container at get() time
5328    ///
5329    /// # Example
5330    /// ```rust
5331    /// let container = ContainerTest { mutex_data: Arc::new(Mutex::new(SomeStruct { optional_field: Some("test".to_string()) })) };
5332    ///
5333    /// // Functional style: compose first, apply container at get()
5334    /// ContainerTest::mutex_data_r()
5335    ///     .chain_arc_mutex_optional_at_kp(SomeStruct::optional_field_fr())
5336    ///     .get(&container, |value| println!("Value: {}", value));
5337    /// ```
5338    pub fn chain_arc_mutex_optional_at_kp<InnerValue, SubValue, G>(
5339        self,
5340        inner_keypath: OptionalKeyPath<InnerValue, SubValue, G>,
5341    ) -> ArcMutexOptionalKeyPathChain<Root, Value, InnerValue, SubValue, F, G>
5342    where
5343        G: for<'r> Fn(&'r InnerValue) -> Option<&'r SubValue>,
5344    {
5345        ArcMutexOptionalKeyPathChain {
5346            outer_keypath: self,
5347            inner_keypath,
5348        }
5349    }
5350
5351    /// Chain this keypath with an inner keypath through Arc<RwLock<T>> - functional style
5352    /// Compose first, then apply container at get() time (uses read lock)
5353    ///
5354    /// # Example
5355    /// ```rust
5356    /// let container = ContainerTest { rwlock_data: Arc::new(RwLock::new(SomeStruct { data: "test".to_string() })) };
5357    ///
5358    /// // Functional style: compose first, apply container at get()
5359    /// ContainerTest::rwlock_data_r()
5360    ///     .chain_arc_rwlock_at_kp(SomeStruct::data_r())
5361    ///     .get(&container, |value| println!("Data: {}", value));
5362    /// ```
5363    pub fn chain_arc_rwlock_at_kp<InnerValue, SubValue, G>(
5364        self,
5365        inner_keypath: KeyPath<InnerValue, SubValue, G>,
5366    ) -> ArcRwLockKeyPathChain<Root, Value, InnerValue, SubValue, F, G>
5367    where
5368        G: for<'r> Fn(&'r InnerValue) -> &'r SubValue,
5369    {
5370        ArcRwLockKeyPathChain {
5371            outer_keypath: self,
5372            inner_keypath,
5373        }
5374    }
5375
5376    /// Chain this keypath with an optional inner keypath through Arc<RwLock<T>> - functional style
5377    /// Compose first, then apply container at get() time (uses read lock)
5378    ///
5379    /// # Example
5380    /// ```rust
5381    /// let container = ContainerTest { rwlock_data: Arc::new(RwLock::new(SomeStruct { optional_field: Some("test".to_string()) })) };
5382    ///
5383    /// // Functional style: compose first, apply container at get()
5384    /// ContainerTest::rwlock_data_r()
5385    ///     .chain_arc_rwlock_optional_at_kp(SomeStruct::optional_field_fr())
5386    ///     .get(&container, |value| println!("Value: {}", value));
5387    /// ```
5388    pub fn chain_arc_rwlock_optional_at_kp<InnerValue, SubValue, G>(
5389        self,
5390        inner_keypath: OptionalKeyPath<InnerValue, SubValue, G>,
5391    ) -> ArcRwLockOptionalKeyPathChain<Root, Value, InnerValue, SubValue, F, G>
5392    where
5393        G: for<'r> Fn(&'r InnerValue) -> Option<&'r SubValue>,
5394    {
5395        ArcRwLockOptionalKeyPathChain {
5396            outer_keypath: self,
5397            inner_keypath,
5398        }
5399    }
5400
5401    /// Chain this keypath with a writable inner keypath through Arc<Mutex<T>> - functional style
5402    /// Compose first, then apply container at get_mut() time
5403    ///
5404    /// # Example
5405    /// ```rust
5406    /// ContainerTest::mutex_data_r()
5407    ///     .chain_arc_mutex_writable_at_kp(SomeStruct::data_w())
5408    ///     .get_mut(&container, |value| *value = "new".to_string());
5409    /// ```
5410    pub fn chain_arc_mutex_writable_at_kp<InnerValue, SubValue, G>(
5411        self,
5412        inner_keypath: WritableKeyPath<InnerValue, SubValue, G>,
5413    ) -> ArcMutexWritableKeyPathChain<Root, Value, InnerValue, SubValue, F, G>
5414    where
5415        G: for<'r> Fn(&'r mut InnerValue) -> &'r mut SubValue,
5416    {
5417        ArcMutexWritableKeyPathChain {
5418            outer_keypath: self,
5419            inner_keypath,
5420        }
5421    }
5422
5423    /// Chain this keypath with a writable optional inner keypath through Arc<Mutex<T>> - functional style
5424    /// Compose first, then apply container at get_mut() time
5425    ///
5426    /// # Example
5427    /// ```rust
5428    /// ContainerTest::mutex_data_r()
5429    ///     .chain_arc_mutex_writable_optional_at_kp(SomeStruct::optional_field_fw())
5430    ///     .get_mut(&container, |value| *value = "new".to_string());
5431    /// ```
5432    pub fn chain_arc_mutex_writable_optional_at_kp<InnerValue, SubValue, G>(
5433        self,
5434        inner_keypath: WritableOptionalKeyPath<InnerValue, SubValue, G>,
5435    ) -> ArcMutexWritableOptionalKeyPathChain<Root, Value, InnerValue, SubValue, F, G>
5436    where
5437        G: for<'r> Fn(&'r mut InnerValue) -> Option<&'r mut SubValue>,
5438    {
5439        ArcMutexWritableOptionalKeyPathChain {
5440            outer_keypath: self,
5441            inner_keypath,
5442        }
5443    }
5444
5445    /// Chain this keypath with a writable inner keypath through Arc<RwLock<T>> - functional style
5446    /// Compose first, then apply container at get_mut() time (uses write lock)
5447    ///
5448    /// # Example
5449    /// ```rust
5450    /// ContainerTest::rwlock_data_r()
5451    ///     .chain_arc_rwlock_writable_at_kp(SomeStruct::data_w())
5452    ///     .get_mut(&container, |value| *value = "new".to_string());
5453    /// ```
5454    pub fn chain_arc_rwlock_writable_at_kp<InnerValue, SubValue, G>(
5455        self,
5456        inner_keypath: WritableKeyPath<InnerValue, SubValue, G>,
5457    ) -> ArcRwLockWritableKeyPathChain<Root, Value, InnerValue, SubValue, F, G>
5458    where
5459        G: for<'r> Fn(&'r mut InnerValue) -> &'r mut SubValue,
5460    {
5461        ArcRwLockWritableKeyPathChain {
5462            outer_keypath: self,
5463            inner_keypath,
5464        }
5465    }
5466
5467    /// Chain this keypath with a writable optional inner keypath through Arc<RwLock<T>> - functional style
5468    /// Compose first, then apply container at get_mut() time (uses write lock)
5469    ///
5470    /// # Example
5471    /// ```rust
5472    /// ContainerTest::rwlock_data_r()
5473    ///     .chain_arc_rwlock_writable_optional_at_kp(SomeStruct::optional_field_fw())
5474    ///     .get_mut(&container, |value| *value = "new".to_string());
5475    /// ```
5476    pub fn chain_arc_rwlock_writable_optional_at_kp<InnerValue, SubValue, G>(
5477        self,
5478        inner_keypath: WritableOptionalKeyPath<InnerValue, SubValue, G>,
5479    ) -> ArcRwLockWritableOptionalKeyPathChain<Root, Value, InnerValue, SubValue, F, G>
5480    where
5481        G: for<'r> Fn(&'r mut InnerValue) -> Option<&'r mut SubValue>,
5482    {
5483        ArcRwLockWritableOptionalKeyPathChain {
5484            outer_keypath: self,
5485            inner_keypath,
5486        }
5487    }
5488
5489    #[cfg(feature = "tokio")]
5490    /// Chain this keypath with an inner keypath through Arc<tokio::sync::Mutex<T>> - functional style (async)
5491    /// Compose first, then apply container at get() time
5492    pub fn chain_arc_tokio_mutex_at_kp<InnerValue, SubValue, G>(
5493        self,
5494        inner_keypath: KeyPath<InnerValue, SubValue, G>,
5495    ) -> ArcTokioMutexKeyPathChain<Root, Value, InnerValue, SubValue, F, G>
5496    where
5497        G: for<'r> Fn(&'r InnerValue) -> &'r SubValue,
5498    {
5499        ArcTokioMutexKeyPathChain {
5500            outer_keypath: self,
5501            inner_keypath,
5502        }
5503    }
5504
5505    #[cfg(feature = "tokio")]
5506    /// Chain this keypath with an optional inner keypath through Arc<tokio::sync::Mutex<T>> - functional style (async)
5507    pub fn chain_arc_tokio_mutex_optional_at_kp<InnerValue, SubValue, G>(
5508        self,
5509        inner_keypath: OptionalKeyPath<InnerValue, SubValue, G>,
5510    ) -> ArcTokioMutexOptionalKeyPathChain<Root, Value, InnerValue, SubValue, F, G>
5511    where
5512        Value: std::borrow::Borrow<Arc<tokio::sync::Mutex<InnerValue>>>,
5513        G: for<'r> Fn(&'r InnerValue) -> Option<&'r SubValue>,
5514    {
5515        ArcTokioMutexOptionalKeyPathChain {
5516            outer_keypath: self,
5517            inner_keypath,
5518        }
5519    }
5520
5521    #[cfg(feature = "tokio")]
5522    /// Chain this keypath with a writable inner keypath through Arc<tokio::sync::Mutex<T>> - functional style (async)
5523    pub fn chain_arc_tokio_mutex_writable_at_kp<InnerValue, SubValue, G>(
5524        self,
5525        inner_keypath: WritableKeyPath<InnerValue, SubValue, G>,
5526    ) -> ArcTokioMutexWritableKeyPathChain<Root, Value, InnerValue, SubValue, F, G>
5527    where
5528        Value: std::borrow::Borrow<Arc<tokio::sync::Mutex<InnerValue>>>,
5529        G: for<'r> Fn(&'r mut InnerValue) -> &'r mut SubValue,
5530    {
5531        ArcTokioMutexWritableKeyPathChain {
5532            outer_keypath: self,
5533            inner_keypath,
5534        }
5535    }
5536
5537    #[cfg(feature = "tokio")]
5538    /// Chain this keypath with a writable optional inner keypath through Arc<tokio::sync::Mutex<T>> - functional style (async)
5539    pub fn chain_arc_tokio_mutex_writable_optional_at_kp<InnerValue, SubValue, G>(
5540        self,
5541        inner_keypath: WritableOptionalKeyPath<InnerValue, SubValue, G>,
5542    ) -> ArcTokioMutexWritableOptionalKeyPathChain<Root, Value, InnerValue, SubValue, F, G>
5543    where
5544        Value: std::borrow::Borrow<Arc<tokio::sync::Mutex<InnerValue>>>,
5545        G: for<'r> Fn(&'r mut InnerValue) -> Option<&'r mut SubValue>,
5546    {
5547        ArcTokioMutexWritableOptionalKeyPathChain {
5548            outer_keypath: self,
5549            inner_keypath,
5550        }
5551    }
5552
5553    #[cfg(feature = "tokio")]
5554    /// Chain this keypath with an inner keypath through Arc<tokio::sync::RwLock<T>> - functional style (async, read lock)
5555    pub fn chain_arc_tokio_rwlock_at_kp<InnerValue, SubValue, G>(
5556        self,
5557        inner_keypath: KeyPath<InnerValue, SubValue, G>,
5558    ) -> ArcTokioRwLockKeyPathChain<Root, Value, InnerValue, SubValue, F, G>
5559    where
5560        Value: std::borrow::Borrow<Arc<tokio::sync::RwLock<InnerValue>>>,
5561        G: for<'r> Fn(&'r InnerValue) -> &'r SubValue,
5562    {
5563        ArcTokioRwLockKeyPathChain {
5564            outer_keypath: self,
5565            inner_keypath,
5566        }
5567    }
5568
5569    #[cfg(feature = "tokio")]
5570    /// Chain this keypath with an optional inner keypath through Arc<tokio::sync::RwLock<T>> - functional style (async, read lock)
5571    pub fn chain_arc_tokio_rwlock_optional_at_kp<InnerValue, SubValue, G>(
5572        self,
5573        inner_keypath: OptionalKeyPath<InnerValue, SubValue, G>,
5574    ) -> ArcTokioRwLockOptionalKeyPathChain<Root, Value, InnerValue, SubValue, F, G>
5575    where
5576        Value: std::borrow::Borrow<Arc<tokio::sync::RwLock<InnerValue>>>,
5577        G: for<'r> Fn(&'r InnerValue) -> Option<&'r SubValue>,
5578    {
5579        ArcTokioRwLockOptionalKeyPathChain {
5580            outer_keypath: self,
5581            inner_keypath,
5582        }
5583    }
5584
5585    #[cfg(feature = "tokio")]
5586    /// Chain this keypath with a writable inner keypath through Arc<tokio::sync::RwLock<T>> - functional style (async, write lock)
5587    pub fn chain_arc_tokio_rwlock_writable_at_kp<InnerValue, SubValue, G>(
5588        self,
5589        inner_keypath: WritableKeyPath<InnerValue, SubValue, G>,
5590    ) -> ArcTokioRwLockWritableKeyPathChain<Root, Value, InnerValue, SubValue, F, G>
5591    where
5592        Value: std::borrow::Borrow<Arc<tokio::sync::RwLock<InnerValue>>>,
5593        G: for<'r> Fn(&'r mut InnerValue) -> &'r mut SubValue,
5594    {
5595        ArcTokioRwLockWritableKeyPathChain {
5596            outer_keypath: self,
5597            inner_keypath,
5598        }
5599    }
5600
5601    #[cfg(feature = "tokio")]
5602    /// Chain this keypath with a writable optional inner keypath through Arc<tokio::sync::RwLock<T>> - functional style (async, write lock)
5603    pub fn chain_arc_tokio_rwlock_writable_optional_at_kp<InnerValue, SubValue, G>(
5604        self,
5605        inner_keypath: WritableOptionalKeyPath<InnerValue, SubValue, G>,
5606    ) -> ArcTokioRwLockWritableOptionalKeyPathChain<Root, Value, InnerValue, SubValue, F, G>
5607    where
5608        Value: std::borrow::Borrow<Arc<tokio::sync::RwLock<InnerValue>>>,
5609        G: for<'r> Fn(&'r mut InnerValue) -> Option<&'r mut SubValue>,
5610    {
5611        ArcTokioRwLockWritableOptionalKeyPathChain {
5612            outer_keypath: self,
5613            inner_keypath,
5614        }
5615    }
5616
5617    /// Monadic helper: shorthand for chain_arc_rwlock_writable_at_kp when Value is Arc<RwLock<T>>
5618    /// This allows chaining with .then().then().then() pattern for Arc<RwLock<T>> structures
5619    ///
5620    /// # Example
5621    /// ```rust,ignore
5622    /// ContainerTest::rwlock_data_r()
5623    ///     .then_rwlock(SomeStruct::data_w())
5624    ///     .then(OtherStruct::field_w())
5625    ///     .get_mut(&container, |value| *value = "new".to_string());
5626    /// ```
5627    pub fn then_rwlock<InnerValue, SubValue, G>(
5628        self,
5629        inner_keypath: WritableKeyPath<InnerValue, SubValue, G>,
5630    ) -> ArcRwLockWritableKeyPathChain<Root, Value, InnerValue, SubValue, F, G>
5631    where
5632        Value: std::borrow::Borrow<Arc<RwLock<InnerValue>>>,
5633        G: for<'r> Fn(&'r mut InnerValue) -> &'r mut SubValue,
5634    {
5635        self.chain_arc_rwlock_writable_at_kp(inner_keypath)
5636    }
5637
5638    // ========== LOCK KEYPATH CONVERSION METHODS ==========
5639    // These methods convert keypaths pointing to lock types into chain-ready keypaths
5640
5641    /// Convert this keypath to an Arc<RwLock> chain-ready keypath
5642    /// Returns self, but serves as a marker for intent and enables chaining
5643    ///
5644    /// # Example
5645    /// ```rust,ignore
5646    /// Container::rwlock_data_r()
5647    ///     .to_arc_rwlock_kp()
5648    ///     .chain_arc_rwlock_at_kp(InnerStruct::field_r());
5649    /// ```
5650    pub fn to_arc_rwlock_kp<InnerValue>(self) -> Self
5651    where
5652        Value: std::borrow::Borrow<Arc<RwLock<InnerValue>>>,
5653    {
5654        self
5655    }
5656
5657    /// Convert this keypath to an Arc<Mutex> chain-ready keypath
5658    /// Returns self, but serves as a marker for intent and enables chaining
5659    pub fn to_arc_mutex_kp<InnerValue>(self) -> Self
5660    where
5661        Value: std::borrow::Borrow<Arc<Mutex<InnerValue>>>,
5662    {
5663        self
5664    }
5665
5666    #[cfg(feature = "parking_lot")]
5667    /// Convert this keypath to an Arc<parking_lot::RwLock> chain-ready keypath
5668    /// Returns self, but serves as a marker for intent and enables chaining
5669    ///
5670    /// # Example
5671    /// ```rust,ignore
5672    /// Container::rwlock_data_r()
5673    ///     .to_arc_parking_rwlock_kp()
5674    ///     .chain_arc_parking_rwlock_at_kp(InnerStruct::field_r());
5675    /// ```
5676    pub fn to_arc_parking_rwlock_kp<InnerValue>(self) -> Self
5677    where
5678        Value: std::borrow::Borrow<Arc<parking_lot::RwLock<InnerValue>>>,
5679    {
5680        self
5681    }
5682
5683    #[cfg(feature = "parking_lot")]
5684    /// Convert this keypath to an Arc<parking_lot::Mutex> chain-ready keypath
5685    /// Returns self, but serves as a marker for intent and enables chaining
5686    pub fn to_arc_parking_mutex_kp<InnerValue>(self) -> Self
5687    where
5688        Value: std::borrow::Borrow<Arc<parking_lot::Mutex<InnerValue>>>,
5689    {
5690        self
5691    }
5692
5693    /// Convert this keypath to an Arc<RwLock> chain keypath
5694    /// Creates a chain with an identity inner keypath, ready for further chaining
5695    ///
5696    /// # Example
5697    /// ```rust,ignore
5698    /// Container::rwlock_data_r()
5699    ///     .to_arc_rwlock_chain()
5700    ///     .then(InnerStruct::field_r());
5701    /// ```
5702    /// Convert this keypath to an Arc<RwLock> chain keypath
5703    /// Creates a chain with an identity inner keypath, ready for further chaining
5704    /// Type inference automatically determines InnerValue from Value
5705    ///
5706    /// # Example
5707    /// ```rust,ignore
5708    /// Container::rwlock_data_r()
5709    ///     .to_arc_rwlock_chain()
5710    ///     .then(InnerStruct::field_r());
5711    /// ```
5712    pub fn to_arc_rwlock_chain<InnerValue>(
5713        self,
5714    ) -> ArcRwLockKeyPathChain<
5715        Root,
5716        Value,
5717        InnerValue,
5718        InnerValue,
5719        F,
5720        impl for<'r> Fn(&'r InnerValue) -> &'r InnerValue + 'static,
5721    >
5722    where
5723        Value: std::borrow::Borrow<Arc<RwLock<InnerValue>>>,
5724        F: 'static,
5725        InnerValue: 'static,
5726    {
5727        let identity = KeyPath::new(|inner: &InnerValue| inner);
5728        ArcRwLockKeyPathChain {
5729            outer_keypath: self,
5730            inner_keypath: identity,
5731        }
5732    }
5733
5734    /// Convert this keypath to an Arc<Mutex> chain keypath
5735    /// Creates a chain with an identity inner keypath, ready for further chaining
5736    /// Type inference automatically determines InnerValue from Value
5737    pub fn to_arc_mutex_chain<InnerValue>(
5738        self,
5739    ) -> ArcMutexKeyPathChain<
5740        Root,
5741        Value,
5742        InnerValue,
5743        InnerValue,
5744        F,
5745        impl for<'r> Fn(&'r InnerValue) -> &'r InnerValue + 'static,
5746    >
5747    where
5748        Value: std::borrow::Borrow<Arc<Mutex<InnerValue>>>,
5749        F: 'static,
5750        InnerValue: 'static,
5751    {
5752        let identity = KeyPath::new(|inner: &InnerValue| inner);
5753        ArcMutexKeyPathChain {
5754            outer_keypath: self,
5755            inner_keypath: identity,
5756        }
5757    }
5758
5759    // #[cfg(feature = "parking_lot")]
5760    // /// Convert this keypath to an Arc<parking_lot::RwLock> chain keypath
5761    // /// Creates a chain with an identity inner keypath, ready for further chaining
5762    // /// Type inference automatically determines InnerValue from Value
5763    // ///
5764    // /// # Example
5765    // /// ```rust,ignore
5766    // /// Container::rwlock_data_r()
5767    // ///     .to_arc_parking_rwlock_chain()
5768    // ///     .then(InnerStruct::field_r());
5769    // /// ```
5770    // 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>
5771    // where
5772    //     Value: std::borrow::Borrow<Arc<parking_lot::RwLock<InnerValue>>>,
5773    //     F: 'static + Clone,
5774    //     InnerValue: 'static,
5775    // {
5776    //     let identity = KeyPath::new(|inner: &InnerValue| inner);
5777    //     let getter = self.getter.clone();
5778    //     // Create a new keypath with the exact type needed, following the proc macro pattern
5779    //     // KeyPath::new(|s: &Root| &s.field).chain_arc_parking_rwlock_at_kp(inner_kp)
5780    //     let lock_kp: KeyPath<Root, Arc<parking_lot::RwLock<InnerValue>>, _> = KeyPath::new(move |root: &Root| {
5781    //         // Safe: Value is Arc<parking_lot::RwLock<InnerValue>> at call site, enforced by Borrow bound
5782    //         unsafe {
5783    //             std::mem::transmute::<&Value, &Arc<parking_lot::RwLock<InnerValue>>>(getter(root))
5784    //         }
5785    //     });
5786    //     lock_kp.chain_arc_parking_rwlock_at_kp(identity)
5787    // }
5788
5789    // #[cfg(feature = "parking_lot")]
5790    // /// Convert this keypath to an Arc<parking_lot::Mutex> chain keypath
5791    // /// Creates a chain with an identity inner keypath, ready for further chaining
5792    // /// Type inference automatically determines InnerValue from Value
5793    // 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>
5794    // where
5795    //     Value: std::borrow::Borrow<Arc<parking_lot::Mutex<InnerValue>>>,
5796    //     F: 'static + Clone,
5797    //     InnerValue: 'static,
5798    // {
5799    //     let identity = KeyPath::new(|inner: &InnerValue| inner);
5800    //     let getter = self.getter.clone();
5801    //     let lock_kp: KeyPath<Root, Arc<parking_lot::Mutex<InnerValue>>, _> = KeyPath::new(move |root: &Root| {
5802    //         unsafe {
5803    //             std::mem::transmute::<&Value, &Arc<parking_lot::Mutex<InnerValue>>>(getter(root))
5804    //         }
5805    //     });
5806    //     lock_kp.chain_arc_parking_mutex_at_kp(identity)
5807    // }
5808
5809    // Instance methods for unwrapping containers (automatically infers Target from Value::Target)
5810    // Box<T> -> T
5811    pub fn for_box<Target>(
5812        self,
5813    ) -> KeyPath<Root, Target, impl for<'r> Fn(&'r Root) -> &'r Target + 'static>
5814    where
5815        Value: std::ops::Deref<Target = Target>,
5816        F: 'static,
5817        Value: 'static,
5818    {
5819        let getter = self.getter;
5820
5821        KeyPath {
5822            getter: move |root: &Root| getter(root).deref(),
5823            _phantom: PhantomData,
5824        }
5825    }
5826
5827    // Arc<T> -> T
5828    pub fn for_arc<Target>(
5829        self,
5830    ) -> KeyPath<Root, Target, impl for<'r> Fn(&'r Root) -> &'r Target + 'static>
5831    where
5832        Value: std::ops::Deref<Target = Target>,
5833        F: 'static,
5834        Value: 'static,
5835    {
5836        let getter = self.getter;
5837
5838        KeyPath {
5839            getter: move |root: &Root| getter(root).deref(),
5840            _phantom: PhantomData,
5841        }
5842    }
5843
5844    // Rc<T> -> T
5845    pub fn for_rc<Target>(
5846        self,
5847    ) -> KeyPath<Root, Target, impl for<'r> Fn(&'r Root) -> &'r Target + 'static>
5848    where
5849        Value: std::ops::Deref<Target = Target>,
5850        F: 'static,
5851        Value: 'static,
5852    {
5853        let getter = self.getter;
5854
5855        KeyPath {
5856            getter: move |root: &Root| getter(root).deref(),
5857            _phantom: PhantomData,
5858        }
5859    }
5860
5861    // Overload: Adapt root type to Arc<Root> when Value is Sized (not a container)
5862    pub fn for_arc_root(
5863        self,
5864    ) -> OptionalKeyPath<
5865        Arc<Root>,
5866        Value,
5867        impl for<'r> Fn(&'r Arc<Root>) -> Option<&'r Value> + 'static,
5868    >
5869    where
5870        Value: Sized,
5871        F: 'static,
5872        Root: 'static,
5873        Value: 'static,
5874    {
5875        let getter = self.getter;
5876
5877        OptionalKeyPath {
5878            getter: move |arc: &Arc<Root>| Some(getter(arc.as_ref())),
5879            _phantom: PhantomData,
5880        }
5881    }
5882
5883    // Overload: Adapt root type to Box<Root> when Value is Sized (not a container)
5884    pub fn for_box_root(
5885        self,
5886    ) -> OptionalKeyPath<
5887        Box<Root>,
5888        Value,
5889        impl for<'r> Fn(&'r Box<Root>) -> Option<&'r Value> + 'static,
5890    >
5891    where
5892        Value: Sized,
5893        F: 'static,
5894        Root: 'static,
5895        Value: 'static,
5896    {
5897        let getter = self.getter;
5898
5899        OptionalKeyPath {
5900            getter: move |boxed: &Box<Root>| Some(getter(boxed.as_ref())),
5901            _phantom: PhantomData,
5902        }
5903    }
5904
5905    // Overload: Adapt root type to Rc<Root> when Value is Sized (not a container)
5906    pub fn for_rc_root(
5907        self,
5908    ) -> OptionalKeyPath<
5909        Rc<Root>,
5910        Value,
5911        impl for<'r> Fn(&'r Rc<Root>) -> Option<&'r Value> + 'static,
5912    >
5913    where
5914        Value: Sized,
5915        F: 'static,
5916        Root: 'static,
5917        Value: 'static,
5918    {
5919        let getter = self.getter;
5920
5921        OptionalKeyPath {
5922            getter: move |rc: &Rc<Root>| Some(getter(rc.as_ref())),
5923            _phantom: PhantomData,
5924        }
5925    }
5926
5927    /// Adapt this keypath to work with Result<Root, E> instead of Root
5928    /// This unwraps the Result and applies the keypath to the Ok value
5929    pub fn for_result<E>(
5930        self,
5931    ) -> OptionalKeyPath<
5932        Result<Root, E>,
5933        Value,
5934        impl for<'r> Fn(&'r Result<Root, E>) -> Option<&'r Value> + 'static,
5935    >
5936    where
5937        F: 'static,
5938        Root: 'static,
5939        Value: 'static,
5940        E: 'static,
5941    {
5942        let getter = self.getter;
5943
5944        OptionalKeyPath {
5945            getter: move |result: &Result<Root, E>| result.as_ref().ok().map(|root| getter(root)),
5946            _phantom: PhantomData,
5947        }
5948    }
5949
5950    /// Convert a KeyPath to OptionalKeyPath for chaining
5951    /// This allows non-optional keypaths to be chained with then()
5952    pub fn to_optional(
5953        self,
5954    ) -> OptionalKeyPath<Root, Value, impl for<'r> Fn(&'r Root) -> Option<&'r Value> + 'static>
5955    where
5956        F: 'static,
5957    {
5958        let getter = self.getter;
5959        OptionalKeyPath::new(move |root: &Root| Some(getter(root)))
5960    }
5961
5962    /// Execute a closure with a reference to the value inside an Option
5963    pub fn with_option<Callback, R>(&self, option: &Option<Root>, f: Callback) -> Option<R>
5964    where
5965        F: Clone,
5966        Callback: FnOnce(&Value) -> R,
5967    {
5968        option.as_ref().map(|root| {
5969            let value = self.get(root);
5970            f(value)
5971        })
5972    }
5973
5974    /// Execute a closure with a reference to the value inside a Result
5975    pub fn with_result<Callback, R, E>(&self, result: &Result<Root, E>, f: Callback) -> Option<R>
5976    where
5977        F: Clone,
5978        Callback: FnOnce(&Value) -> R,
5979    {
5980        result.as_ref().ok().map(|root| {
5981            let value = self.get(root);
5982            f(value)
5983        })
5984    }
5985
5986    /// Execute a closure with a reference to the value inside a Box
5987    pub fn with_box<Callback, R>(&self, boxed: &Box<Root>, f: Callback) -> R
5988    where
5989        F: Clone,
5990        Callback: FnOnce(&Value) -> R,
5991    {
5992        let value = self.get(boxed);
5993        f(value)
5994    }
5995
5996    /// Execute a closure with a reference to the value inside an Arc
5997    pub fn with_arc<Callback, R>(&self, arc: &Arc<Root>, f: Callback) -> R
5998    where
5999        F: Clone,
6000        Callback: FnOnce(&Value) -> R,
6001    {
6002        let value = self.get(arc);
6003        f(value)
6004    }
6005
6006    /// Execute a closure with a reference to the value inside an Rc
6007    pub fn with_rc<Callback, R>(&self, rc: &Rc<Root>, f: Callback) -> R
6008    where
6009        F: Clone,
6010        Callback: FnOnce(&Value) -> R,
6011    {
6012        let value = self.get(rc);
6013        f(value)
6014    }
6015
6016    /// Execute a closure with a reference to the value inside a RefCell
6017    pub fn with_refcell<Callback, R>(&self, refcell: &RefCell<Root>, f: Callback) -> Option<R>
6018    where
6019        F: Clone,
6020        Callback: FnOnce(&Value) -> R,
6021    {
6022        refcell.try_borrow().ok().map(|borrow| {
6023            let value = self.get(&*borrow);
6024            f(value)
6025        })
6026    }
6027
6028    /// Execute a closure with a reference to the value inside a Mutex
6029    pub fn with_mutex<Callback, R>(&self, mutex: &Mutex<Root>, f: Callback) -> Option<R>
6030    where
6031        F: Clone,
6032        Callback: FnOnce(&Value) -> R,
6033    {
6034        mutex.lock().ok().map(|guard| {
6035            let value = self.get(&*guard);
6036            f(value)
6037        })
6038    }
6039
6040    /// Execute a closure with a reference to the value inside an RwLock
6041    pub fn with_rwlock<Callback, R>(&self, rwlock: &RwLock<Root>, f: Callback) -> Option<R>
6042    where
6043        F: Clone,
6044        Callback: FnOnce(&Value) -> R,
6045    {
6046        rwlock.read().ok().map(|guard| {
6047            let value = self.get(&*guard);
6048            f(value)
6049        })
6050    }
6051
6052    /// Execute a closure with a reference to the value inside an Arc<RwLock<Root>>
6053    pub fn with_arc_rwlock<Callback, R>(
6054        &self,
6055        arc_rwlock: &Arc<RwLock<Root>>,
6056        f: Callback,
6057    ) -> Option<R>
6058    where
6059        F: Clone,
6060        Callback: FnOnce(&Value) -> R,
6061    {
6062        arc_rwlock.read().ok().map(|guard| {
6063            let value = self.get(&*guard);
6064            f(value)
6065        })
6066    }
6067
6068    /// Execute a closure with a reference to the value inside an Arc<Mutex<Root>>
6069    pub fn with_arc_mutex<Callback, R>(
6070        &self,
6071        arc_mutex: &Arc<Mutex<Root>>,
6072        f: Callback,
6073    ) -> Option<R>
6074    where
6075        F: Clone,
6076        Callback: FnOnce(&Value) -> R,
6077    {
6078        arc_mutex.lock().ok().map(|guard| {
6079            let value = self.get(&*guard);
6080            f(value)
6081        })
6082    }
6083
6084    #[cfg(feature = "tagged")]
6085    /// Adapt this keypath to work with Tagged<Root, Tag> instead of Root
6086    /// This unwraps the Tagged wrapper and applies the keypath to the inner value
6087    pub fn for_tagged<Tag>(
6088        self,
6089    ) -> KeyPath<
6090        Tagged<Root, Tag>,
6091        Value,
6092        impl for<'r> Fn(&'r Tagged<Root, Tag>) -> &'r Value + 'static,
6093    >
6094    where
6095        Tagged<Root, Tag>: std::ops::Deref<Target = Root>,
6096        F: 'static,
6097        Root: 'static,
6098        Value: 'static,
6099        Tag: 'static,
6100    {
6101        use std::ops::Deref;
6102        let getter = self.getter;
6103
6104        KeyPath {
6105            getter: move |tagged: &Tagged<Root, Tag>| getter(tagged.deref()),
6106            _phantom: PhantomData,
6107        }
6108    }
6109
6110    #[cfg(feature = "tagged")]
6111    /// Execute a closure with a reference to the value inside a Tagged
6112    /// This avoids cloning by working with references directly
6113    pub fn with_tagged<Tag, Callback, R>(&self, tagged: &Tagged<Root, Tag>, f: Callback) -> R
6114    where
6115        Tagged<Root, Tag>: std::ops::Deref<Target = Root>,
6116        Callback: FnOnce(&Value) -> R,
6117    {
6118        use std::ops::Deref;
6119        let value = self.get(tagged.deref());
6120        f(value)
6121    }
6122
6123    /// Adapt this keypath to work with Option<Root> instead of Root
6124    /// This converts the KeyPath to an OptionalKeyPath and unwraps the Option
6125    pub fn for_option(
6126        self,
6127    ) -> OptionalKeyPath<
6128        Option<Root>,
6129        Value,
6130        impl for<'r> Fn(&'r Option<Root>) -> Option<&'r Value> + 'static,
6131    >
6132    where
6133        F: 'static,
6134        Root: 'static,
6135        Value: 'static,
6136    {
6137        let getter = self.getter;
6138
6139        OptionalKeyPath {
6140            getter: move |opt: &Option<Root>| opt.as_ref().map(|root| getter(root)),
6141            _phantom: PhantomData,
6142        }
6143    }
6144
6145    /// Get an iterator over a Vec when Value is Vec<T>
6146    /// Returns Some(iterator) if the value is a Vec, None otherwise
6147    pub fn iter<'r, T>(&self, root: &'r Root) -> Option<std::slice::Iter<'r, T>>
6148    where
6149        Value: AsRef<[T]> + 'r,
6150    {
6151        let value_ref: &'r Value = self.get(root);
6152        Some(value_ref.as_ref().iter())
6153    }
6154
6155    /// Extract values from a slice of owned values
6156    /// Returns a Vec of references to the extracted values
6157    pub fn extract_from_slice<'r>(&self, slice: &'r [Root]) -> Vec<&'r Value> {
6158        slice.iter().map(|item| self.get(item)).collect()
6159    }
6160
6161    /// Extract values from a slice of references
6162    /// Returns a Vec of references to the extracted values
6163    pub fn extract_from_ref_slice<'r>(&self, slice: &'r [&Root]) -> Vec<&'r Value> {
6164        slice.iter().map(|item| self.get(item)).collect()
6165    }
6166
6167    /// Chain this keypath with another keypath
6168    /// Returns a KeyPath that chains both keypaths
6169    pub fn then<SubValue, G>(
6170        self,
6171        next: KeyPath<Value, SubValue, G>,
6172    ) -> KeyPath<Root, SubValue, impl for<'r> Fn(&'r Root) -> &'r SubValue>
6173    where
6174        G: for<'r> Fn(&'r Value) -> &'r SubValue,
6175        F: 'static,
6176        G: 'static,
6177        Value: 'static,
6178    {
6179        let first = self.getter;
6180        let second = next.getter;
6181
6182        KeyPath::new(move |root: &Root| {
6183            let value = first(root);
6184            second(value)
6185        })
6186    }
6187
6188    /// Chain this keypath with an optional keypath
6189    /// Returns an OptionalKeyPath that chains both keypaths
6190    pub fn chain_optional<SubValue, G>(
6191        self,
6192        next: OptionalKeyPath<Value, SubValue, G>,
6193    ) -> OptionalKeyPath<Root, SubValue, impl for<'r> Fn(&'r Root) -> Option<&'r SubValue>>
6194    where
6195        G: for<'r> Fn(&'r Value) -> Option<&'r SubValue>,
6196        F: 'static,
6197        G: 'static,
6198        Value: 'static,
6199    {
6200        let first = self.getter;
6201        let second = next.getter;
6202
6203        OptionalKeyPath::new(move |root: &Root| {
6204            let value = first(root);
6205            second(value)
6206        })
6207    }
6208}
6209
6210// Extension methods for KeyPath to support Arc<RwLock> and Arc<Mutex> directly
6211impl<Root, Value, F> KeyPath<Root, Value, F>
6212where
6213    F: for<'r> Fn(&'r Root) -> &'r Value,
6214{
6215    /// Execute a closure with a reference to the value inside an Arc<RwLock<Root>>
6216    /// This is a convenience method that works directly with Arc<RwLock<T>>
6217    pub fn with_arc_rwlock_direct<Callback, R>(
6218        &self,
6219        arc_rwlock: &Arc<RwLock<Root>>,
6220        f: Callback,
6221    ) -> Option<R>
6222    where
6223        Callback: FnOnce(&Value) -> R,
6224    {
6225        arc_rwlock.read().ok().map(|guard| {
6226            let value = self.get(&*guard);
6227            f(value)
6228        })
6229    }
6230
6231    /// Execute a closure with a reference to the value inside an Arc<Mutex<Root>>
6232    /// This is a convenience method that works directly with Arc<Mutex<T>>
6233    pub fn with_arc_mutex_direct<Callback, R>(
6234        &self,
6235        arc_mutex: &Arc<Mutex<Root>>,
6236        f: Callback,
6237    ) -> Option<R>
6238    where
6239        Callback: FnOnce(&Value) -> R,
6240    {
6241        arc_mutex.lock().ok().map(|guard| {
6242            let value = self.get(&*guard);
6243            f(value)
6244        })
6245    }
6246}
6247
6248// Utility function for slice access (kept as standalone function)
6249pub fn for_slice<T>() -> impl for<'r> Fn(&'r [T], usize) -> Option<&'r T> {
6250    |slice: &[T], index: usize| slice.get(index)
6251}
6252
6253// Container access utilities
6254pub mod containers {
6255    use super::{KeyPath, OptionalKeyPath, WritableKeyPath, WritableOptionalKeyPath};
6256    use std::collections::{
6257        BTreeMap, BTreeSet, BinaryHeap, HashMap, HashSet, LinkedList, VecDeque,
6258    };
6259    use std::ops::{Deref, DerefMut};
6260    use std::rc::{Rc, Weak as RcWeak};
6261    use std::sync::{Arc, Mutex, RwLock, Weak as StdWeak};
6262
6263    #[cfg(feature = "parking_lot")]
6264    use parking_lot::{Mutex as ParkingMutex, RwLock as ParkingRwLock};
6265
6266    #[cfg(feature = "tagged")]
6267    use tagged_core::Tagged;
6268
6269    /// Create a keypath for indexed access in Vec<T>
6270    pub fn for_vec_index<T>(
6271        index: usize,
6272    ) -> OptionalKeyPath<Vec<T>, T, impl for<'r> Fn(&'r Vec<T>) -> Option<&'r T>> {
6273        OptionalKeyPath::new(move |vec: &Vec<T>| vec.get(index))
6274    }
6275
6276    /// Create a keypath for indexed access in VecDeque<T>
6277    pub fn for_vecdeque_index<T>(
6278        index: usize,
6279    ) -> OptionalKeyPath<VecDeque<T>, T, impl for<'r> Fn(&'r VecDeque<T>) -> Option<&'r T>> {
6280        OptionalKeyPath::new(move |deque: &VecDeque<T>| deque.get(index))
6281    }
6282
6283    /// Create a keypath for indexed access in LinkedList<T>
6284    pub fn for_linkedlist_index<T>(
6285        index: usize,
6286    ) -> OptionalKeyPath<LinkedList<T>, T, impl for<'r> Fn(&'r LinkedList<T>) -> Option<&'r T>>
6287    {
6288        OptionalKeyPath::new(move |list: &LinkedList<T>| list.iter().nth(index))
6289    }
6290
6291    /// Create a keypath for key-based access in HashMap<K, V>
6292    pub fn for_hashmap_key<K, V>(
6293        key: K,
6294    ) -> OptionalKeyPath<HashMap<K, V>, V, impl for<'r> Fn(&'r HashMap<K, V>) -> Option<&'r V>>
6295    where
6296        K: std::hash::Hash + Eq + Clone + 'static,
6297        V: 'static,
6298    {
6299        OptionalKeyPath::new(move |map: &HashMap<K, V>| map.get(&key))
6300    }
6301
6302    /// Create a keypath for key-based access in BTreeMap<K, V>
6303    pub fn for_btreemap_key<K, V>(
6304        key: K,
6305    ) -> OptionalKeyPath<BTreeMap<K, V>, V, impl for<'r> Fn(&'r BTreeMap<K, V>) -> Option<&'r V>>
6306    where
6307        K: Ord + Clone + 'static,
6308        V: 'static,
6309    {
6310        OptionalKeyPath::new(move |map: &BTreeMap<K, V>| map.get(&key))
6311    }
6312
6313    /// Create a keypath for getting a value from HashSet<T> (returns Option<&T>)
6314    pub fn for_hashset_get<T>(
6315        value: T,
6316    ) -> OptionalKeyPath<HashSet<T>, T, impl for<'r> Fn(&'r HashSet<T>) -> Option<&'r T>>
6317    where
6318        T: std::hash::Hash + Eq + Clone + 'static,
6319    {
6320        OptionalKeyPath::new(move |set: &HashSet<T>| set.get(&value))
6321    }
6322
6323    /// Create a keypath for checking membership in BTreeSet<T>
6324    pub fn for_btreeset_get<T>(
6325        value: T,
6326    ) -> OptionalKeyPath<BTreeSet<T>, T, impl for<'r> Fn(&'r BTreeSet<T>) -> Option<&'r T>>
6327    where
6328        T: Ord + Clone + 'static,
6329    {
6330        OptionalKeyPath::new(move |set: &BTreeSet<T>| set.get(&value))
6331    }
6332
6333    /// Create a keypath for peeking at the top of BinaryHeap<T>
6334    pub fn for_binaryheap_peek<T>()
6335    -> OptionalKeyPath<BinaryHeap<T>, T, impl for<'r> Fn(&'r BinaryHeap<T>) -> Option<&'r T>>
6336    where
6337        T: Ord + 'static,
6338    {
6339        OptionalKeyPath::new(|heap: &BinaryHeap<T>| heap.peek())
6340    }
6341
6342    // ========== WRITABLE VERSIONS ==========
6343
6344    /// Create a writable keypath for indexed access in Vec<T>
6345    pub fn for_vec_index_mut<T>(
6346        index: usize,
6347    ) -> WritableOptionalKeyPath<Vec<T>, T, impl for<'r> Fn(&'r mut Vec<T>) -> Option<&'r mut T>>
6348    {
6349        WritableOptionalKeyPath::new(move |vec: &mut Vec<T>| vec.get_mut(index))
6350    }
6351
6352    /// Create a writable keypath for indexed access in VecDeque<T>
6353    pub fn for_vecdeque_index_mut<T>(
6354        index: usize,
6355    ) -> WritableOptionalKeyPath<
6356        VecDeque<T>,
6357        T,
6358        impl for<'r> Fn(&'r mut VecDeque<T>) -> Option<&'r mut T>,
6359    > {
6360        WritableOptionalKeyPath::new(move |deque: &mut VecDeque<T>| deque.get_mut(index))
6361    }
6362
6363    /// Create a writable keypath for indexed access in LinkedList<T>
6364    pub fn for_linkedlist_index_mut<T>(
6365        index: usize,
6366    ) -> WritableOptionalKeyPath<
6367        LinkedList<T>,
6368        T,
6369        impl for<'r> Fn(&'r mut LinkedList<T>) -> Option<&'r mut T>,
6370    > {
6371        WritableOptionalKeyPath::new(move |list: &mut LinkedList<T>| {
6372            // LinkedList doesn't have get_mut, so we need to iterate
6373            let mut iter = list.iter_mut();
6374            iter.nth(index)
6375        })
6376    }
6377
6378    /// Create a writable keypath for key-based access in HashMap<K, V>
6379    pub fn for_hashmap_key_mut<K, V>(
6380        key: K,
6381    ) -> WritableOptionalKeyPath<
6382        HashMap<K, V>,
6383        V,
6384        impl for<'r> Fn(&'r mut HashMap<K, V>) -> Option<&'r mut V>,
6385    >
6386    where
6387        K: std::hash::Hash + Eq + Clone + 'static,
6388        V: 'static,
6389    {
6390        WritableOptionalKeyPath::new(move |map: &mut HashMap<K, V>| map.get_mut(&key))
6391    }
6392
6393    /// Create a writable keypath for key-based access in BTreeMap<K, V>
6394    pub fn for_btreemap_key_mut<K, V>(
6395        key: K,
6396    ) -> WritableOptionalKeyPath<
6397        BTreeMap<K, V>,
6398        V,
6399        impl for<'r> Fn(&'r mut BTreeMap<K, V>) -> Option<&'r mut V>,
6400    >
6401    where
6402        K: Ord + Clone + 'static,
6403        V: 'static,
6404    {
6405        WritableOptionalKeyPath::new(move |map: &mut BTreeMap<K, V>| map.get_mut(&key))
6406    }
6407
6408    /// Create a writable keypath for getting a mutable value from HashSet<T>
6409    /// Note: HashSet doesn't support mutable access to elements, but we provide it for consistency
6410    pub fn for_hashset_get_mut<T>(
6411        value: T,
6412    ) -> WritableOptionalKeyPath<
6413        HashSet<T>,
6414        T,
6415        impl for<'r> Fn(&'r mut HashSet<T>) -> Option<&'r mut T>,
6416    >
6417    where
6418        T: std::hash::Hash + Eq + Clone + 'static,
6419    {
6420        WritableOptionalKeyPath::new(move |set: &mut HashSet<T>| {
6421            // HashSet doesn't have get_mut, so we need to check and return None
6422            // This is a limitation of HashSet's design
6423            if set.contains(&value) {
6424                // We can't return a mutable reference to the value in the set
6425                // This is a fundamental limitation of HashSet
6426                None
6427            } else {
6428                None
6429            }
6430        })
6431    }
6432
6433    /// Create a writable keypath for getting a mutable value from BTreeSet<T>
6434    /// Note: BTreeSet doesn't support mutable access to elements, but we provide it for consistency
6435    pub fn for_btreeset_get_mut<T>(
6436        value: T,
6437    ) -> WritableOptionalKeyPath<
6438        BTreeSet<T>,
6439        T,
6440        impl for<'r> Fn(&'r mut BTreeSet<T>) -> Option<&'r mut T>,
6441    >
6442    where
6443        T: Ord + Clone + 'static,
6444    {
6445        WritableOptionalKeyPath::new(move |set: &mut BTreeSet<T>| {
6446            // BTreeSet doesn't have get_mut, so we need to check and return None
6447            // This is a limitation of BTreeSet's design
6448            if set.contains(&value) {
6449                // We can't return a mutable reference to the value in the set
6450                // This is a fundamental limitation of BTreeSet
6451                None
6452            } else {
6453                None
6454            }
6455        })
6456    }
6457
6458    /// Create a writable keypath for peeking at the top of BinaryHeap<T>
6459    /// Note: BinaryHeap.peek_mut() returns PeekMut which is a guard type.
6460    /// Due to Rust's borrowing rules, we cannot return &mut T directly from PeekMut.
6461    /// This function returns None as BinaryHeap doesn't support direct mutable access
6462    /// through keypaths. Use heap.peek_mut() directly for mutable access.
6463    pub fn for_binaryheap_peek_mut<T>() -> WritableOptionalKeyPath<
6464        BinaryHeap<T>,
6465        T,
6466        impl for<'r> Fn(&'r mut BinaryHeap<T>) -> Option<&'r mut T>,
6467    >
6468    where
6469        T: Ord + 'static,
6470    {
6471        // BinaryHeap.peek_mut() returns PeekMut which is a guard type that owns the mutable reference.
6472        // We cannot return &mut T from it due to lifetime constraints.
6473        // This is a fundamental limitation - use heap.peek_mut() directly instead.
6474        WritableOptionalKeyPath::new(|_heap: &mut BinaryHeap<T>| None)
6475    }
6476
6477    // ========== SYNCHRONIZATION PRIMITIVES ==========
6478    // Note: Mutex and RwLock return guards that own the lock, not references.
6479    // We cannot create keypaths that return references from guards due to lifetime constraints.
6480    // These helper functions are provided for convenience, but direct lock()/read()/write() calls are recommended.
6481
6482    /// Helper function to lock a Mutex<T> and access its value
6483    /// Returns None if the mutex is poisoned
6484    /// Note: This returns a guard, not a reference, so it cannot be used in keypaths directly
6485    pub fn lock_mutex<T>(mutex: &Mutex<T>) -> Option<std::sync::MutexGuard<'_, T>> {
6486        mutex.lock().ok()
6487    }
6488
6489    /// Helper function to read-lock an RwLock<T> and access its value
6490    /// Returns None if the lock is poisoned
6491    /// Note: This returns a guard, not a reference, so it cannot be used in keypaths directly
6492    pub fn read_rwlock<T>(rwlock: &RwLock<T>) -> Option<std::sync::RwLockReadGuard<'_, T>> {
6493        rwlock.read().ok()
6494    }
6495
6496    /// Helper function to write-lock an RwLock<T> and access its value
6497    /// Returns None if the lock is poisoned
6498    /// Note: This returns a guard, not a reference, so it cannot be used in keypaths directly
6499    pub fn write_rwlock<T>(rwlock: &RwLock<T>) -> Option<std::sync::RwLockWriteGuard<'_, T>> {
6500        rwlock.write().ok()
6501    }
6502
6503    /// Helper function to lock an Arc<Mutex<T>> and access its value
6504    /// Returns None if the mutex is poisoned
6505    /// Note: This returns a guard, not a reference, so it cannot be used in keypaths directly
6506    pub fn lock_arc_mutex<T>(arc_mutex: &Arc<Mutex<T>>) -> Option<std::sync::MutexGuard<'_, T>> {
6507        arc_mutex.lock().ok()
6508    }
6509
6510    /// Helper function to read-lock an Arc<RwLock<T>> and access its value
6511    /// Returns None if the lock is poisoned
6512    /// Note: This returns a guard, not a reference, so it cannot be used in keypaths directly
6513    pub fn read_arc_rwlock<T>(
6514        arc_rwlock: &Arc<RwLock<T>>,
6515    ) -> Option<std::sync::RwLockReadGuard<'_, T>> {
6516        arc_rwlock.read().ok()
6517    }
6518
6519    /// Helper function to write-lock an Arc<RwLock<T>> and access its value
6520    /// Returns None if the lock is poisoned
6521    /// Note: This returns a guard, not a reference, so it cannot be used in keypaths directly
6522    pub fn write_arc_rwlock<T>(
6523        arc_rwlock: &Arc<RwLock<T>>,
6524    ) -> Option<std::sync::RwLockWriteGuard<'_, T>> {
6525        arc_rwlock.write().ok()
6526    }
6527
6528    /// Helper function to upgrade a Weak<T> to Arc<T>
6529    /// Returns None if the Arc has been dropped
6530    /// Note: This returns an owned Arc, not a reference, so it cannot be used in keypaths directly
6531    pub fn upgrade_weak<T>(weak: &StdWeak<T>) -> Option<Arc<T>> {
6532        weak.upgrade()
6533    }
6534
6535    /// Helper function to upgrade an Rc::Weak<T> to Rc<T>
6536    /// Returns None if the Rc has been dropped
6537    /// Note: This returns an owned Rc, not a reference, so it cannot be used in keypaths directly
6538    pub fn upgrade_rc_weak<T>(weak: &RcWeak<T>) -> Option<Rc<T>> {
6539        weak.upgrade()
6540    }
6541
6542    #[cfg(feature = "parking_lot")]
6543    /// Helper function to lock a parking_lot::Mutex<T> and access its value
6544    /// Note: This returns a guard, not a reference, so it cannot be used in keypaths directly
6545    pub fn lock_parking_mutex<T>(mutex: &ParkingMutex<T>) -> parking_lot::MutexGuard<'_, T> {
6546        mutex.lock()
6547    }
6548
6549    #[cfg(feature = "parking_lot")]
6550    /// Helper function to read-lock a parking_lot::RwLock<T> and access its value
6551    /// Note: This returns a guard, not a reference, so it cannot be used in keypaths directly
6552    pub fn read_parking_rwlock<T>(
6553        rwlock: &ParkingRwLock<T>,
6554    ) -> parking_lot::RwLockReadGuard<'_, T> {
6555        rwlock.read()
6556    }
6557
6558    #[cfg(feature = "parking_lot")]
6559    /// Helper function to write-lock a parking_lot::RwLock<T> and access its value
6560    /// Note: This returns a guard, not a reference, so it cannot be used in keypaths directly
6561    pub fn write_parking_rwlock<T>(
6562        rwlock: &ParkingRwLock<T>,
6563    ) -> parking_lot::RwLockWriteGuard<'_, T> {
6564        rwlock.write()
6565    }
6566
6567    #[cfg(feature = "tagged")]
6568    /// Create a keypath for accessing the inner value of Tagged<Tag, T>
6569    /// Tagged implements Deref, so we can access the inner value directly
6570    pub fn for_tagged<Tag, T>()
6571    -> KeyPath<Tagged<Tag, T>, T, impl for<'r> Fn(&'r Tagged<Tag, T>) -> &'r T>
6572    where
6573        Tagged<Tag, T>: std::ops::Deref<Target = T>,
6574        Tag: 'static,
6575        T: 'static,
6576    {
6577        KeyPath::new(|tagged: &Tagged<Tag, T>| tagged.deref())
6578    }
6579
6580    #[cfg(feature = "tagged")]
6581    /// Create a writable keypath for accessing the inner value of Tagged<Tag, T>
6582    /// Tagged implements DerefMut, so we can access the inner value directly
6583    pub fn for_tagged_mut<Tag, T>()
6584    -> WritableKeyPath<Tagged<Tag, T>, T, impl for<'r> Fn(&'r mut Tagged<Tag, T>) -> &'r mut T>
6585    where
6586        Tagged<Tag, T>: std::ops::DerefMut<Target = T>,
6587        Tag: 'static,
6588        T: 'static,
6589    {
6590        WritableKeyPath::new(|tagged: &mut Tagged<Tag, T>| tagged.deref_mut())
6591    }
6592}
6593
6594// ========== PARKING_LOT CHAIN METHODS FOR KEYPATH ==========
6595
6596#[cfg(feature = "parking_lot")]
6597impl<Root, InnerValue, F> KeyPath<Root, Arc<parking_lot::Mutex<InnerValue>>, F>
6598where
6599    F: for<'r> Fn(&'r Root) -> &'r Arc<parking_lot::Mutex<InnerValue>>,
6600{
6601    /// Chain this keypath with an inner keypath through Arc<parking_lot::Mutex<T>> - functional style
6602    pub fn chain_arc_parking_mutex_at_kp<SubValue, G>(
6603        self,
6604        inner_keypath: KeyPath<InnerValue, SubValue, G>,
6605    ) -> ArcParkingMutexKeyPathChain<Root, InnerValue, SubValue, F, G>
6606    where
6607        G: for<'r> Fn(&'r InnerValue) -> &'r SubValue,
6608    {
6609        ArcParkingMutexKeyPathChain {
6610            outer_keypath: self,
6611            inner_keypath,
6612        }
6613    }
6614
6615    /// Chain this keypath with an optional inner keypath through Arc<parking_lot::Mutex<T>>
6616    pub fn then_arc_parking_mutex_optional_at_kp<SubValue, G>(
6617        self,
6618        inner_keypath: OptionalKeyPath<InnerValue, SubValue, G>,
6619    ) -> ArcParkingMutexOptionalKeyPathChain<Root, InnerValue, SubValue, F, G>
6620    where
6621        G: for<'r> Fn(&'r InnerValue) -> Option<&'r SubValue>,
6622    {
6623        ArcParkingMutexOptionalKeyPathChain {
6624            outer_keypath: self,
6625            inner_keypath,
6626        }
6627    }
6628
6629    /// Chain this keypath with a writable inner keypath through Arc<parking_lot::Mutex<T>>
6630    pub fn chain_arc_parking_mutex_writable_at_kp<SubValue, G>(
6631        self,
6632        inner_keypath: WritableKeyPath<InnerValue, SubValue, G>,
6633    ) -> ArcParkingMutexWritableKeyPathChain<Root, InnerValue, SubValue, F, G>
6634    where
6635        G: for<'r> Fn(&'r mut InnerValue) -> &'r mut SubValue,
6636    {
6637        ArcParkingMutexWritableKeyPathChain {
6638            outer_keypath: self,
6639            inner_keypath,
6640        }
6641    }
6642
6643    /// Chain this keypath with a writable optional inner keypath through Arc<parking_lot::Mutex<T>>
6644    pub fn then_arc_parking_mutex_writable_optional_at_kp<SubValue, G>(
6645        self,
6646        inner_keypath: WritableOptionalKeyPath<InnerValue, SubValue, G>,
6647    ) -> ArcParkingMutexWritableOptionalKeyPathChain<Root, InnerValue, SubValue, F, G>
6648    where
6649        G: for<'r> Fn(&'r mut InnerValue) -> Option<&'r mut SubValue>,
6650    {
6651        ArcParkingMutexWritableOptionalKeyPathChain {
6652            outer_keypath: self,
6653            inner_keypath,
6654        }
6655    }
6656}
6657
6658#[cfg(feature = "parking_lot")]
6659impl<Root, InnerValue, F> KeyPath<Root, Arc<parking_lot::RwLock<InnerValue>>, F>
6660where
6661    F: for<'r> Fn(&'r Root) -> &'r Arc<parking_lot::RwLock<InnerValue>>,
6662{
6663    /// Chain this keypath with an inner keypath through Arc<parking_lot::RwLock<T>> - functional style
6664    pub fn chain_arc_parking_rwlock_at_kp<SubValue, G>(
6665        self,
6666        inner_keypath: KeyPath<InnerValue, SubValue, G>,
6667    ) -> ArcParkingRwLockKeyPathChain<Root, InnerValue, SubValue, F, G>
6668    where
6669        G: for<'r> Fn(&'r InnerValue) -> &'r SubValue,
6670    {
6671        ArcParkingRwLockKeyPathChain {
6672            outer_keypath: self,
6673            inner_keypath,
6674        }
6675    }
6676
6677    /// Chain this keypath with an optional inner keypath through Arc<parking_lot::RwLock<T>>
6678    pub fn then_arc_parking_rwlock_optional_at_kp<SubValue, G>(
6679        self,
6680        inner_keypath: OptionalKeyPath<InnerValue, SubValue, G>,
6681    ) -> ArcParkingRwLockOptionalKeyPathChain<Root, InnerValue, SubValue, F, G>
6682    where
6683        G: for<'r> Fn(&'r InnerValue) -> Option<&'r SubValue>,
6684    {
6685        ArcParkingRwLockOptionalKeyPathChain {
6686            outer_keypath: self,
6687            inner_keypath,
6688        }
6689    }
6690
6691    /// Chain this keypath with a writable inner keypath through Arc<parking_lot::RwLock<T>>
6692    pub fn chain_arc_parking_rwlock_writable_at_kp<SubValue, G>(
6693        self,
6694        inner_keypath: WritableKeyPath<InnerValue, SubValue, G>,
6695    ) -> ArcParkingRwLockWritableKeyPathChain<Root, InnerValue, SubValue, F, G>
6696    where
6697        G: for<'r> Fn(&'r mut InnerValue) -> &'r mut SubValue,
6698    {
6699        ArcParkingRwLockWritableKeyPathChain {
6700            outer_keypath: self,
6701            inner_keypath,
6702        }
6703    }
6704
6705    /// Chain this keypath with a writable optional inner keypath through Arc<parking_lot::RwLock<T>>
6706    pub fn then_arc_parking_rwlock_writable_optional_at_kp<SubValue, G>(
6707        self,
6708        inner_keypath: WritableOptionalKeyPath<InnerValue, SubValue, G>,
6709    ) -> ArcParkingRwLockWritableOptionalKeyPathChain<Root, InnerValue, SubValue, F, G>
6710    where
6711        G: for<'r> Fn(&'r mut InnerValue) -> Option<&'r mut SubValue>,
6712    {
6713        ArcParkingRwLockWritableOptionalKeyPathChain {
6714            outer_keypath: self,
6715            inner_keypath,
6716        }
6717    }
6718}
6719
6720// OptionalKeyPath for Option<T>
6721#[derive(Clone)]
6722pub struct OptionalKeyPath<Root, Value, F>
6723where
6724    F: for<'r> Fn(&'r Root) -> Option<&'r Value>,
6725{
6726    getter: F,
6727    _phantom: PhantomData<(Root, Value)>,
6728}
6729
6730impl<Root, Value, F> fmt::Display for OptionalKeyPath<Root, Value, F>
6731where
6732    F: for<'r> Fn(&'r Root) -> Option<&'r Value>,
6733{
6734    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
6735        let root_name = std::any::type_name::<Root>();
6736        let value_name = std::any::type_name::<Value>();
6737        // Simplify type names by removing module paths for cleaner output
6738        let root_short = root_name.split("::").last().unwrap_or(root_name);
6739        let value_short = value_name.split("::").last().unwrap_or(value_name);
6740        write!(
6741            f,
6742            "OptionalKeyPath<{} -> Option<{}>>",
6743            root_short, value_short
6744        )
6745    }
6746}
6747
6748impl<Root, Value, F> fmt::Debug for OptionalKeyPath<Root, Value, F>
6749where
6750    F: for<'r> Fn(&'r Root) -> Option<&'r Value>,
6751{
6752    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
6753        fmt::Display::fmt(self, f)
6754    }
6755}
6756
6757impl<Root> OptionalKeyPath<Root, Root, fn(&Root) -> Option<&Root>> {
6758    /// Identity optional keypath: projects `Root` to `Some(root)`.
6759    pub fn identity() -> Self {
6760        OptionalKeyPath {
6761            getter: identity_opt_ref::<Root>,
6762            _phantom: PhantomData,
6763        }
6764    }
6765}
6766
6767impl<Root, Value, F> OptionalKeyPath<Root, Value, F>
6768where
6769    F: for<'r> Fn(&'r Root) -> Option<&'r Value>,
6770{
6771    pub fn new(getter: F) -> Self {
6772        Self {
6773            getter,
6774            _phantom: PhantomData,
6775        }
6776    }
6777
6778    pub fn get<'r>(&self, root: &'r Root) -> Option<&'r Value> {
6779        (self.getter)(root)
6780    }
6781
6782    /// Type-erase the getter into a `Box<dyn Fn>`, so the keypath can be stored without the concrete closure type.
6783    pub fn boxed(
6784        self,
6785    ) -> OptionalKeyPath<Root, Value, Box<dyn for<'r> Fn(&'r Root) -> Option<&'r Value> + 'static>>
6786    where
6787        F: 'static,
6788        Root: 'static,
6789        Value: 'static,
6790    {
6791        OptionalKeyPath {
6792            getter: Box::new(self.getter),
6793            _phantom: PhantomData,
6794        }
6795    }
6796
6797    /// Higher-order function: map the optional value reference through a function.
6798    /// Returns a new `OptionalKeyPath<Root, U, _>` that gets the value and applies `f` to the reference when present.
6799    ///
6800    /// # Example
6801    /// ```rust
6802    /// use rust_keypaths::OptionalKeyPath;
6803    /// let kp = OptionalKeyPath::new(|o: &Option<String>| o.as_ref());
6804    /// let len_kp = kp.map(|s: &String| &s.len());
6805    /// let some_s = Some("hello".to_string());
6806    /// assert_eq!(*len_kp.get(&some_s).unwrap(), 5);
6807    /// assert!(len_kp.get(&None::<String>).is_none());
6808    /// ```
6809    pub fn map<U, G>(self, f: G) -> OptionalKeyPath<Root, U, impl for<'r> Fn(&'r Root) -> Option<&'r U>>
6810    where
6811        G: for<'r> Fn(&'r Value) -> &'r U,
6812        F: 'static,
6813        G: 'static,
6814        Root: 'static,
6815        Value: 'static,
6816    {
6817        let getter = self.getter;
6818        OptionalKeyPath {
6819            getter: move |root| getter(root).map(|v| f(v)),
6820            _phantom: PhantomData,
6821        }
6822    }
6823
6824    /// Map through a function that returns `Option<&U>`, keeping an `OptionalKeyPath`.
6825    /// Use when the inner projection may fail (e.g. `|v: &Vec<T>| v.first()`).
6826    pub fn map_optional<U, G>(
6827        self,
6828        f: G,
6829    ) -> OptionalKeyPath<Root, U, impl for<'r> Fn(&'r Root) -> Option<&'r U>>
6830    where
6831        G: for<'r> Fn(&'r Value) -> Option<&'r U>,
6832        F: 'static,
6833        G: 'static,
6834        Root: 'static,
6835        Value: 'static,
6836    {
6837        let getter = self.getter;
6838        OptionalKeyPath {
6839            getter: move |root| getter(root).and_then(|v| f(v)),
6840            _phantom: PhantomData,
6841        }
6842    }
6843
6844    /// Chain this optional keypath with an inner keypath through Arc<Mutex<T>> - functional style
6845    /// Compose first, then apply container at get() time
6846    ///
6847    /// # Example
6848    /// ```rust
6849    /// let container = ContainerTest { mutex_data: Some(Arc::new(Mutex::new(SomeStruct { data: "test".to_string() }))) };
6850    ///
6851    /// // Functional style: compose first, apply container at get()
6852    /// ContainerTest::mutex_data_fr()
6853    ///     .chain_arc_mutex_at_kp(SomeStruct::data_r())
6854    ///     .get(&container, |value| println!("Data: {}", value));
6855    /// ```
6856    pub fn chain_arc_mutex_at_kp<InnerValue, SubValue, G>(
6857        self,
6858        inner_keypath: KeyPath<InnerValue, SubValue, G>,
6859    ) -> OptionalArcMutexKeyPathChain<Root, Value, InnerValue, SubValue, F, G>
6860    where
6861        G: for<'r> Fn(&'r InnerValue) -> &'r SubValue,
6862    {
6863        OptionalArcMutexKeyPathChain {
6864            outer_keypath: self,
6865            inner_keypath,
6866        }
6867    }
6868
6869    /// Chain this optional keypath with an optional inner keypath through Arc<Mutex<T>> - functional style
6870    /// Compose first, then apply container at get() time
6871    ///
6872    /// # Example
6873    /// ```rust
6874    /// let container = ContainerTest { mutex_data: Some(Arc::new(Mutex::new(SomeStruct { optional_field: Some("test".to_string()) }))) };
6875    ///
6876    /// // Functional style: compose first, apply container at get()
6877    /// ContainerTest::mutex_data_fr()
6878    ///     .chain_arc_mutex_optional_at_kp(SomeStruct::optional_field_fr())
6879    ///     .get(&container, |value| println!("Value: {}", value));
6880    /// ```
6881    pub fn chain_arc_mutex_optional_at_kp<InnerValue, SubValue, G>(
6882        self,
6883        inner_keypath: OptionalKeyPath<InnerValue, SubValue, G>,
6884    ) -> OptionalArcMutexOptionalKeyPathChain<Root, Value, InnerValue, SubValue, F, G>
6885    where
6886        G: for<'r> Fn(&'r InnerValue) -> Option<&'r SubValue>,
6887    {
6888        OptionalArcMutexOptionalKeyPathChain {
6889            outer_keypath: self,
6890            inner_keypath,
6891        }
6892    }
6893
6894    /// Chain this optional keypath with an inner keypath through Arc<RwLock<T>> - functional style
6895    /// Compose first, then apply container at get() time (uses read lock)
6896    ///
6897    /// # Example
6898    /// ```rust
6899    /// let container = ContainerTest { rwlock_data: Some(Arc::new(RwLock::new(SomeStruct { data: "test".to_string() }))) };
6900    ///
6901    /// // Functional style: compose first, apply container at get()
6902    /// ContainerTest::rwlock_data_fr()
6903    ///     .chain_arc_rwlock_at_kp(SomeStruct::data_r())
6904    ///     .get(&container, |value| println!("Data: {}", value));
6905    /// ```
6906    pub fn chain_arc_rwlock_at_kp<InnerValue, SubValue, G>(
6907        self,
6908        inner_keypath: KeyPath<InnerValue, SubValue, G>,
6909    ) -> OptionalArcRwLockKeyPathChain<Root, Value, InnerValue, SubValue, F, G>
6910    where
6911        G: for<'r> Fn(&'r InnerValue) -> &'r SubValue,
6912    {
6913        OptionalArcRwLockKeyPathChain {
6914            outer_keypath: self,
6915            inner_keypath,
6916        }
6917    }
6918
6919    /// Chain this optional keypath with an optional inner keypath through Arc<RwLock<T>> - functional style
6920    /// Compose first, then apply container at get() time (uses read lock)
6921    ///
6922    /// # Example
6923    /// ```rust
6924    /// let container = ContainerTest { rwlock_data: Some(Arc::new(RwLock::new(SomeStruct { optional_field: Some("test".to_string()) }))) };
6925    ///
6926    /// // Functional style: compose first, apply container at get()
6927    /// ContainerTest::rwlock_data_fr()
6928    ///     .chain_arc_rwlock_optional_at_kp(SomeStruct::optional_field_fr())
6929    ///     .get(&container, |value| println!("Value: {}", value));
6930    /// ```
6931    pub fn chain_arc_rwlock_optional_at_kp<InnerValue, SubValue, G>(
6932        self,
6933        inner_keypath: OptionalKeyPath<InnerValue, SubValue, G>,
6934    ) -> OptionalArcRwLockOptionalKeyPathChain<Root, Value, InnerValue, SubValue, F, G>
6935    where
6936        G: for<'r> Fn(&'r InnerValue) -> Option<&'r SubValue>,
6937    {
6938        OptionalArcRwLockOptionalKeyPathChain {
6939            outer_keypath: self,
6940            inner_keypath,
6941        }
6942    }
6943
6944    /// Chain this optional keypath with a writable inner keypath through Arc<Mutex<T>> - functional style
6945    /// Compose first, then apply container at get_mut() time
6946    ///
6947    /// # Example
6948    /// ```rust
6949    /// let container = ContainerTest { mutex_data: Some(Arc::new(Mutex::new(SomeStruct { data: "test".to_string() }))) };
6950    ///
6951    /// // Functional style: compose first, apply container at get_mut()
6952    /// ContainerTest::mutex_data_fr()
6953    ///     .chain_arc_mutex_writable_at_kp(SomeStruct::data_w())
6954    ///     .get_mut(&container, |value| *value = "new".to_string());
6955    /// ```
6956    pub fn chain_arc_mutex_writable_at_kp<InnerValue, SubValue, G>(
6957        self,
6958        inner_keypath: WritableKeyPath<InnerValue, SubValue, G>,
6959    ) -> OptionalArcMutexWritableKeyPathChain<Root, Value, InnerValue, SubValue, F, G>
6960    where
6961        G: for<'r> Fn(&'r mut InnerValue) -> &'r mut SubValue,
6962    {
6963        OptionalArcMutexWritableKeyPathChain {
6964            outer_keypath: self,
6965            inner_keypath,
6966        }
6967    }
6968
6969    /// Chain this optional keypath with a writable optional inner keypath through Arc<Mutex<T>> - functional style
6970    /// Compose first, then apply container at get_mut() time
6971    ///
6972    /// # Example
6973    /// ```rust
6974    /// let container = ContainerTest { mutex_data: Some(Arc::new(Mutex::new(SomeStruct { optional_field: Some("test".to_string()) }))) };
6975    ///
6976    /// // Functional style: compose first, apply container at get_mut()
6977    /// ContainerTest::mutex_data_fr()
6978    ///     .chain_arc_mutex_writable_optional_at_kp(SomeStruct::optional_field_fw())
6979    ///     .get_mut(&container, |value| *value = "new".to_string());
6980    /// ```
6981    pub fn chain_arc_mutex_writable_optional_at_kp<InnerValue, SubValue, G>(
6982        self,
6983        inner_keypath: WritableOptionalKeyPath<InnerValue, SubValue, G>,
6984    ) -> OptionalArcMutexWritableOptionalKeyPathChain<Root, Value, InnerValue, SubValue, F, G>
6985    where
6986        G: for<'r> Fn(&'r mut InnerValue) -> Option<&'r mut SubValue>,
6987    {
6988        OptionalArcMutexWritableOptionalKeyPathChain {
6989            outer_keypath: self,
6990            inner_keypath,
6991        }
6992    }
6993
6994    /// Chain this optional keypath with a writable inner keypath through Arc<RwLock<T>> - functional style
6995    /// Compose first, then apply container at get_mut() time (uses write lock)
6996    ///
6997    /// # Example
6998    /// ```rust
6999    /// let container = ContainerTest { rwlock_data: Some(Arc::new(RwLock::new(SomeStruct { data: "test".to_string() }))) };
7000    ///
7001    /// // Functional style: compose first, apply container at get_mut()
7002    /// ContainerTest::rwlock_data_fr()
7003    ///     .chain_arc_rwlock_writable_at_kp(SomeStruct::data_w())
7004    ///     .get_mut(&container, |value| *value = "new".to_string());
7005    /// ```
7006    pub fn chain_arc_rwlock_writable_at_kp<InnerValue, SubValue, G>(
7007        self,
7008        inner_keypath: WritableKeyPath<InnerValue, SubValue, G>,
7009    ) -> OptionalArcRwLockWritableKeyPathChain<Root, Value, InnerValue, SubValue, F, G>
7010    where
7011        G: for<'r> Fn(&'r mut InnerValue) -> &'r mut SubValue,
7012    {
7013        OptionalArcRwLockWritableKeyPathChain {
7014            outer_keypath: self,
7015            inner_keypath,
7016        }
7017    }
7018
7019    /// Chain this optional keypath with a writable optional inner keypath through Arc<RwLock<T>> - functional style
7020    /// Compose first, then apply container at get_mut() time (uses write lock)
7021    ///
7022    /// # Example
7023    /// ```rust
7024    /// let container = ContainerTest { rwlock_data: Some(Arc::new(RwLock::new(SomeStruct { optional_field: Some("test".to_string()) }))) };
7025    ///
7026    /// // Functional style: compose first, apply container at get_mut()
7027    /// ContainerTest::rwlock_data_fr()
7028    ///     .chain_arc_rwlock_writable_optional_at_kp(SomeStruct::optional_field_fw())
7029    ///     .get_mut(&container, |value| *value = "new".to_string());
7030    /// ```
7031    pub fn chain_arc_rwlock_writable_optional_at_kp<InnerValue, SubValue, G>(
7032        self,
7033        inner_keypath: WritableOptionalKeyPath<InnerValue, SubValue, G>,
7034    ) -> OptionalArcRwLockWritableOptionalKeyPathChain<Root, Value, InnerValue, SubValue, F, G>
7035    where
7036        G: for<'r> Fn(&'r mut InnerValue) -> Option<&'r mut SubValue>,
7037    {
7038        OptionalArcRwLockWritableOptionalKeyPathChain {
7039            outer_keypath: self,
7040            inner_keypath,
7041        }
7042    }
7043
7044    #[cfg(feature = "tokio")]
7045    /// Chain this optional keypath with an inner keypath through Arc<tokio::sync::Mutex<T>> - functional style (async)
7046    pub fn chain_arc_tokio_mutex_at_kp<InnerValue, SubValue, G>(
7047        self,
7048        inner_keypath: KeyPath<InnerValue, SubValue, G>,
7049    ) -> OptionalArcTokioMutexKeyPathChain<Root, Value, InnerValue, SubValue, F, G>
7050    where
7051        Value: std::borrow::Borrow<Arc<tokio::sync::Mutex<InnerValue>>>,
7052        G: for<'r> Fn(&'r InnerValue) -> &'r SubValue,
7053    {
7054        OptionalArcTokioMutexKeyPathChain {
7055            outer_keypath: self,
7056            inner_keypath,
7057        }
7058    }
7059
7060    #[cfg(feature = "tokio")]
7061    /// Chain this optional keypath with an optional inner keypath through Arc<tokio::sync::Mutex<T>> - functional style (async)
7062    pub fn chain_arc_tokio_mutex_optional_at_kp<InnerValue, SubValue, G>(
7063        self,
7064        inner_keypath: OptionalKeyPath<InnerValue, SubValue, G>,
7065    ) -> OptionalArcTokioMutexOptionalKeyPathChain<Root, Value, InnerValue, SubValue, F, G>
7066    where
7067        Value: std::borrow::Borrow<Arc<tokio::sync::Mutex<InnerValue>>>,
7068        G: for<'r> Fn(&'r InnerValue) -> Option<&'r SubValue>,
7069    {
7070        OptionalArcTokioMutexOptionalKeyPathChain {
7071            outer_keypath: self,
7072            inner_keypath,
7073        }
7074    }
7075
7076    #[cfg(feature = "tokio")]
7077    /// Chain this optional keypath with a writable inner keypath through Arc<tokio::sync::Mutex<T>> - functional style (async)
7078    pub fn chain_arc_tokio_mutex_writable_at_kp<InnerValue, SubValue, G>(
7079        self,
7080        inner_keypath: WritableKeyPath<InnerValue, SubValue, G>,
7081    ) -> OptionalArcTokioMutexWritableKeyPathChain<Root, Value, InnerValue, SubValue, F, G>
7082    where
7083        Value: std::borrow::Borrow<Arc<tokio::sync::Mutex<InnerValue>>>,
7084        G: for<'r> Fn(&'r mut InnerValue) -> &'r mut SubValue,
7085    {
7086        OptionalArcTokioMutexWritableKeyPathChain {
7087            outer_keypath: self,
7088            inner_keypath,
7089        }
7090    }
7091
7092    #[cfg(feature = "tokio")]
7093    /// Chain this optional keypath with a writable optional inner keypath through Arc<tokio::sync::Mutex<T>> - functional style (async)
7094    pub fn chain_arc_tokio_mutex_writable_optional_at_kp<InnerValue, SubValue, G>(
7095        self,
7096        inner_keypath: WritableOptionalKeyPath<InnerValue, SubValue, G>,
7097    ) -> OptionalArcTokioMutexWritableOptionalKeyPathChain<Root, Value, InnerValue, SubValue, F, G>
7098    where
7099        Value: std::borrow::Borrow<Arc<tokio::sync::Mutex<InnerValue>>>,
7100        G: for<'r> Fn(&'r mut InnerValue) -> Option<&'r mut SubValue>,
7101    {
7102        OptionalArcTokioMutexWritableOptionalKeyPathChain {
7103            outer_keypath: self,
7104            inner_keypath,
7105        }
7106    }
7107
7108    #[cfg(feature = "tokio")]
7109    /// Chain this optional keypath with an inner keypath through Arc<tokio::sync::RwLock<T>> - functional style (async, read lock)
7110    pub fn chain_arc_tokio_rwlock_at_kp<InnerValue, SubValue, G>(
7111        self,
7112        inner_keypath: KeyPath<InnerValue, SubValue, G>,
7113    ) -> OptionalArcTokioRwLockKeyPathChain<Root, Value, InnerValue, SubValue, F, G>
7114    where
7115        Value: std::borrow::Borrow<Arc<tokio::sync::RwLock<InnerValue>>>,
7116        G: for<'r> Fn(&'r InnerValue) -> &'r SubValue,
7117    {
7118        OptionalArcTokioRwLockKeyPathChain {
7119            outer_keypath: self,
7120            inner_keypath,
7121        }
7122    }
7123
7124    #[cfg(feature = "tokio")]
7125    /// Chain this optional keypath with an optional inner keypath through Arc<tokio::sync::RwLock<T>> - functional style (async, read lock)
7126    pub fn chain_arc_tokio_rwlock_optional_at_kp<InnerValue, SubValue, G>(
7127        self,
7128        inner_keypath: OptionalKeyPath<InnerValue, SubValue, G>,
7129    ) -> OptionalArcTokioRwLockOptionalKeyPathChain<Root, Value, InnerValue, SubValue, F, G>
7130    where
7131        Value: std::borrow::Borrow<Arc<tokio::sync::RwLock<InnerValue>>>,
7132        G: for<'r> Fn(&'r InnerValue) -> Option<&'r SubValue>,
7133    {
7134        OptionalArcTokioRwLockOptionalKeyPathChain {
7135            outer_keypath: self,
7136            inner_keypath,
7137        }
7138    }
7139
7140    #[cfg(feature = "tokio")]
7141    /// Chain this optional keypath with a writable inner keypath through Arc<tokio::sync::RwLock<T>> - functional style (async, write lock)
7142    pub fn chain_arc_tokio_rwlock_writable_at_kp<InnerValue, SubValue, G>(
7143        self,
7144        inner_keypath: WritableKeyPath<InnerValue, SubValue, G>,
7145    ) -> OptionalArcTokioRwLockWritableKeyPathChain<Root, Value, InnerValue, SubValue, F, G>
7146    where
7147        Value: std::borrow::Borrow<Arc<tokio::sync::RwLock<InnerValue>>>,
7148        G: for<'r> Fn(&'r mut InnerValue) -> &'r mut SubValue,
7149    {
7150        OptionalArcTokioRwLockWritableKeyPathChain {
7151            outer_keypath: self,
7152            inner_keypath,
7153        }
7154    }
7155
7156    #[cfg(feature = "tokio")]
7157    /// Chain this optional keypath with a writable optional inner keypath through Arc<tokio::sync::RwLock<T>> - functional style (async, write lock)
7158    pub fn chain_arc_tokio_rwlock_writable_optional_at_kp<InnerValue, SubValue, G>(
7159        self,
7160        inner_keypath: WritableOptionalKeyPath<InnerValue, SubValue, G>,
7161    ) -> OptionalArcTokioRwLockWritableOptionalKeyPathChain<Root, Value, InnerValue, SubValue, F, G>
7162    where
7163        Value: std::borrow::Borrow<Arc<tokio::sync::RwLock<InnerValue>>>,
7164        G: for<'r> Fn(&'r mut InnerValue) -> Option<&'r mut SubValue>,
7165    {
7166        OptionalArcTokioRwLockWritableOptionalKeyPathChain {
7167            outer_keypath: self,
7168            inner_keypath,
7169        }
7170    }
7171
7172    // Swift-like operator for chaining OptionalKeyPath
7173    pub fn then<SubValue, G>(
7174        self,
7175        next: OptionalKeyPath<Value, SubValue, G>,
7176    ) -> OptionalKeyPath<Root, SubValue, impl for<'r> Fn(&'r Root) -> Option<&'r SubValue>>
7177    where
7178        G: for<'r> Fn(&'r Value) -> Option<&'r SubValue>,
7179        F: 'static,
7180        G: 'static,
7181        Value: 'static,
7182    {
7183        let first = self.getter;
7184        let second = next.getter;
7185
7186        OptionalKeyPath::new(move |root: &Root| first(root).and_then(|value| second(value)))
7187    }
7188
7189    // Instance methods for unwrapping containers from Option<Container<T>>
7190    // Option<Box<T>> -> Option<&T> (type automatically inferred from Value::Target)
7191    pub fn for_box<Target>(
7192        self,
7193    ) -> OptionalKeyPath<Root, Target, impl for<'r> Fn(&'r Root) -> Option<&'r Target> + 'static>
7194    where
7195        Value: std::ops::Deref<Target = Target>,
7196        F: 'static,
7197        Value: 'static,
7198    {
7199        let getter = self.getter;
7200
7201        OptionalKeyPath {
7202            getter: move |root: &Root| getter(root).map(|boxed| boxed.deref()),
7203            _phantom: PhantomData,
7204        }
7205    }
7206
7207    // Option<Arc<T>> -> Option<&T> (type automatically inferred from Value::Target)
7208    pub fn for_arc<Target>(
7209        self,
7210    ) -> OptionalKeyPath<Root, Target, impl for<'r> Fn(&'r Root) -> Option<&'r Target> + 'static>
7211    where
7212        Value: std::ops::Deref<Target = Target>,
7213        F: 'static,
7214        Value: 'static,
7215    {
7216        let getter = self.getter;
7217
7218        OptionalKeyPath {
7219            getter: move |root: &Root| getter(root).map(|arc| arc.deref()),
7220            _phantom: PhantomData,
7221        }
7222    }
7223
7224    // Option<Rc<T>> -> Option<&T> (type automatically inferred from Value::Target)
7225    pub fn for_rc<Target>(
7226        self,
7227    ) -> OptionalKeyPath<Root, Target, impl for<'r> Fn(&'r Root) -> Option<&'r Target> + 'static>
7228    where
7229        Value: std::ops::Deref<Target = Target>,
7230        F: 'static,
7231        Value: 'static,
7232    {
7233        let getter = self.getter;
7234
7235        OptionalKeyPath {
7236            getter: move |root: &Root| getter(root).map(|rc| rc.deref()),
7237            _phantom: PhantomData,
7238        }
7239    }
7240
7241    #[cfg(feature = "tagged")]
7242    /// Adapt this keypath to work with Tagged<Root, Tag> instead of Root
7243    /// This unwraps the Tagged wrapper and applies the keypath to the inner value
7244    pub fn for_tagged<Tag>(
7245        self,
7246    ) -> OptionalKeyPath<
7247        Tagged<Root, Tag>,
7248        Value,
7249        impl for<'r> Fn(&'r Tagged<Root, Tag>) -> Option<&'r Value> + 'static,
7250    >
7251    where
7252        Tagged<Root, Tag>: std::ops::Deref<Target = Root>,
7253        F: 'static,
7254        Root: 'static,
7255        Value: 'static,
7256        Tag: 'static,
7257    {
7258        use std::ops::Deref;
7259        let getter = self.getter;
7260
7261        OptionalKeyPath {
7262            getter: move |tagged: &Tagged<Root, Tag>| getter(tagged.deref()),
7263            _phantom: PhantomData,
7264        }
7265    }
7266
7267    #[cfg(feature = "tagged")]
7268    /// Execute a closure with a reference to the value inside a Tagged
7269    /// This avoids cloning by working with references directly
7270    pub fn with_tagged<Tag, Callback, R>(
7271        &self,
7272        tagged: &Tagged<Root, Tag>,
7273        f: Callback,
7274    ) -> Option<R>
7275    where
7276        Tagged<Root, Tag>: std::ops::Deref<Target = Root>,
7277        F: Clone,
7278        Callback: FnOnce(&Value) -> R,
7279    {
7280        use std::ops::Deref;
7281        self.get(tagged.deref()).map(|value| f(value))
7282    }
7283
7284    /// Adapt this keypath to work with Option<Root> instead of Root
7285    /// This unwraps the Option and applies the keypath to the inner value
7286    pub fn for_option(
7287        self,
7288    ) -> OptionalKeyPath<
7289        Option<Root>,
7290        Value,
7291        impl for<'r> Fn(&'r Option<Root>) -> Option<&'r Value> + 'static,
7292    >
7293    where
7294        F: 'static,
7295        Root: 'static,
7296        Value: 'static,
7297    {
7298        let getter = self.getter;
7299
7300        OptionalKeyPath {
7301            getter: move |opt: &Option<Root>| opt.as_ref().and_then(|root| getter(root)),
7302            _phantom: PhantomData,
7303        }
7304    }
7305
7306    /// Adapt this keypath to work with Result<Root, E> instead of Root
7307    /// This unwraps the Result and applies the keypath to the Ok value
7308    pub fn for_result<E>(
7309        self,
7310    ) -> OptionalKeyPath<
7311        Result<Root, E>,
7312        Value,
7313        impl for<'r> Fn(&'r Result<Root, E>) -> Option<&'r Value> + 'static,
7314    >
7315    where
7316        F: 'static,
7317        Root: 'static,
7318        Value: 'static,
7319        E: 'static,
7320    {
7321        let getter = self.getter;
7322
7323        OptionalKeyPath {
7324            getter: move |result: &Result<Root, E>| {
7325                result.as_ref().ok().and_then(|root| getter(root))
7326            },
7327            _phantom: PhantomData,
7328        }
7329    }
7330
7331    // ========== LOCK KEYPATH CONVERSION METHODS ==========
7332    // These methods convert keypaths pointing to lock types into chain-ready keypaths
7333
7334    /// Convert this optional keypath to an Arc<RwLock> chain-ready keypath
7335    /// Returns self, but serves as a marker for intent and enables chaining
7336    pub fn to_arc_rwlock_kp<InnerValue>(self) -> Self
7337    where
7338        Value: std::borrow::Borrow<Arc<RwLock<InnerValue>>>,
7339    {
7340        self
7341    }
7342
7343    /// Convert this optional keypath to an Arc<Mutex> chain-ready keypath
7344    /// Returns self, but serves as a marker for intent and enables chaining
7345    pub fn to_arc_mutex_kp<InnerValue>(self) -> Self
7346    where
7347        Value: std::borrow::Borrow<Arc<Mutex<InnerValue>>>,
7348    {
7349        self
7350    }
7351
7352    #[cfg(feature = "parking_lot")]
7353    /// Convert this optional keypath to an Arc<parking_lot::RwLock> chain-ready keypath
7354    /// Returns self, but serves as a marker for intent and enables chaining
7355    pub fn to_arc_parking_rwlock_kp<InnerValue>(self) -> Self
7356    where
7357        Value: std::borrow::Borrow<Arc<parking_lot::RwLock<InnerValue>>>,
7358    {
7359        self
7360    }
7361
7362    #[cfg(feature = "parking_lot")]
7363    /// Convert this optional keypath to an Arc<parking_lot::Mutex> chain-ready keypath
7364    /// Returns self, but serves as a marker for intent and enables chaining
7365    pub fn to_arc_parking_mutex_kp<InnerValue>(self) -> Self
7366    where
7367        Value: std::borrow::Borrow<Arc<parking_lot::Mutex<InnerValue>>>,
7368    {
7369        self
7370    }
7371
7372    /// Convert this optional keypath to an Arc<RwLock> chain keypath
7373    /// Creates a chain with an identity inner keypath, ready for further chaining
7374    /// Type inference automatically determines InnerValue from Value
7375    pub fn to_arc_rwlock_chain<InnerValue>(
7376        self,
7377    ) -> OptionalArcRwLockKeyPathChain<
7378        Root,
7379        Value,
7380        InnerValue,
7381        InnerValue,
7382        F,
7383        impl for<'r> Fn(&'r InnerValue) -> &'r InnerValue + 'static,
7384    >
7385    where
7386        Value: std::borrow::Borrow<Arc<RwLock<InnerValue>>>,
7387        F: 'static,
7388        InnerValue: 'static,
7389    {
7390        let identity = KeyPath::new(|inner: &InnerValue| inner);
7391        OptionalArcRwLockKeyPathChain {
7392            outer_keypath: self,
7393            inner_keypath: identity,
7394        }
7395    }
7396
7397    /// Convert this optional keypath to an Arc<Mutex> chain keypath
7398    /// Creates a chain with an identity inner keypath, ready for further chaining
7399    /// Type inference automatically determines InnerValue from Value
7400    pub fn to_arc_mutex_chain<InnerValue>(
7401        self,
7402    ) -> OptionalArcMutexKeyPathChain<
7403        Root,
7404        Value,
7405        InnerValue,
7406        InnerValue,
7407        F,
7408        impl for<'r> Fn(&'r InnerValue) -> &'r InnerValue + 'static,
7409    >
7410    where
7411        Value: std::borrow::Borrow<Arc<Mutex<InnerValue>>>,
7412        F: 'static,
7413        InnerValue: 'static,
7414    {
7415        let identity = KeyPath::new(|inner: &InnerValue| inner);
7416        OptionalArcMutexKeyPathChain {
7417            outer_keypath: self,
7418            inner_keypath: identity,
7419        }
7420    }
7421
7422    // #[cfg(feature = "parking_lot")]
7423    // /// Convert this optional keypath to an Arc<parking_lot::RwLock> chain keypath
7424    // /// Creates a chain with an identity inner keypath, ready for further chaining
7425    // /// Type inference automatically determines InnerValue from Value
7426    // 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>
7427    // where
7428    //     Value: std::borrow::Borrow<Arc<parking_lot::RwLock<InnerValue>>>,
7429    //     F: 'static + Clone,
7430    //     InnerValue: 'static,
7431    // {
7432    //     let identity = KeyPath::new(|inner: &InnerValue| inner);
7433    //     let getter = self.getter.clone();
7434    //     let lock_kp: OptionalKeyPath<Root, Arc<parking_lot::RwLock<InnerValue>>, _> = OptionalKeyPath::new(move |root: &Root| {
7435    //         getter(root).map(|v| {
7436    //             unsafe {
7437    //                 std::mem::transmute::<&Value, &Arc<parking_lot::RwLock<InnerValue>>>(v)
7438    //             }
7439    //         })
7440    //     });
7441    //     lock_kp.chain_arc_parking_rwlock_at_kp(identity)
7442    // }
7443
7444    // #[cfg(feature = "parking_lot")]
7445    // /// Convert this optional keypath to an Arc<parking_lot::Mutex> chain keypath
7446    // /// Creates a chain with an identity inner keypath, ready for further chaining
7447    // /// Type inference automatically determines InnerValue from Value
7448    // 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>
7449    // where
7450    //     Value: std::borrow::Borrow<Arc<parking_lot::Mutex<InnerValue>>>,
7451    //     F: 'static + Clone,
7452    //     InnerValue: 'static,
7453    // {
7454    //     let identity = KeyPath::new(|inner: &InnerValue| inner);
7455    //     let getter = self.getter.clone();
7456    //     let lock_kp: OptionalKeyPath<Root, Arc<parking_lot::Mutex<InnerValue>>, _> = OptionalKeyPath::new(move |root: &Root| {
7457    //         getter(root).map(|v| {
7458    //             unsafe {
7459    //                 std::mem::transmute::<&Value, &Arc<parking_lot::Mutex<InnerValue>>>(v)
7460    //             }
7461    //         })
7462    //     });
7463    //     lock_kp.chain_arc_parking_mutex_at_kp(identity)
7464    // }
7465
7466    // Overload: Adapt root type to Arc<Root> when Value is Sized (not a container)
7467    pub fn for_arc_root(
7468        self,
7469    ) -> OptionalKeyPath<
7470        Arc<Root>,
7471        Value,
7472        impl for<'r> Fn(&'r Arc<Root>) -> Option<&'r Value> + 'static,
7473    >
7474    where
7475        Value: Sized,
7476        F: 'static,
7477        Root: 'static,
7478        Value: 'static,
7479    {
7480        let getter = self.getter;
7481
7482        OptionalKeyPath {
7483            getter: move |arc: &Arc<Root>| getter(arc.as_ref()),
7484            _phantom: PhantomData,
7485        }
7486    }
7487
7488    // Overload: Adapt root type to Rc<Root> when Value is Sized (not a container)
7489    pub fn for_rc_root(
7490        self,
7491    ) -> OptionalKeyPath<
7492        Rc<Root>,
7493        Value,
7494        impl for<'r> Fn(&'r Rc<Root>) -> Option<&'r Value> + 'static,
7495    >
7496    where
7497        Value: Sized,
7498        F: 'static,
7499        Root: 'static,
7500        Value: 'static,
7501    {
7502        let getter = self.getter;
7503
7504        OptionalKeyPath {
7505            getter: move |rc: &Rc<Root>| getter(rc.as_ref()),
7506            _phantom: PhantomData,
7507        }
7508    }
7509
7510    /// Execute a closure with a reference to the value inside an Option
7511    pub fn with_option<Callback, R>(&self, option: &Option<Root>, f: Callback) -> Option<R>
7512    where
7513        F: Clone,
7514        Callback: FnOnce(&Value) -> R,
7515    {
7516        option
7517            .as_ref()
7518            .and_then(|root| self.get(root).map(|value| f(value)))
7519    }
7520
7521    /// Execute a closure with a reference to the value inside a Mutex
7522    pub fn with_mutex<Callback, R>(&self, mutex: &Mutex<Root>, f: Callback) -> Option<R>
7523    where
7524        F: Clone,
7525        Callback: FnOnce(&Value) -> R,
7526    {
7527        mutex
7528            .lock()
7529            .ok()
7530            .and_then(|guard| self.get(&*guard).map(|value| f(value)))
7531    }
7532
7533    /// Execute a closure with a reference to the value inside an RwLock
7534    pub fn with_rwlock<Callback, R>(&self, rwlock: &RwLock<Root>, f: Callback) -> Option<R>
7535    where
7536        F: Clone,
7537        Callback: FnOnce(&Value) -> R,
7538    {
7539        rwlock
7540            .read()
7541            .ok()
7542            .and_then(|guard| self.get(&*guard).map(|value| f(value)))
7543    }
7544
7545    /// Execute a closure with a reference to the value inside an Arc<RwLock<Root>>
7546    pub fn with_arc_rwlock<Callback, R>(
7547        &self,
7548        arc_rwlock: &Arc<RwLock<Root>>,
7549        f: Callback,
7550    ) -> Option<R>
7551    where
7552        F: Clone,
7553        Callback: FnOnce(&Value) -> R,
7554    {
7555        arc_rwlock
7556            .read()
7557            .ok()
7558            .and_then(|guard| self.get(&*guard).map(|value| f(value)))
7559    }
7560
7561    /// Execute a closure with a reference to the value inside an Arc<RwLock<Root>>
7562    /// This is a convenience method that works directly with Arc<RwLock<T>>
7563    /// Unlike with_arc_rwlock, this doesn't require F: Clone
7564    pub fn with_arc_rwlock_direct<Callback, R>(
7565        &self,
7566        arc_rwlock: &Arc<RwLock<Root>>,
7567        f: Callback,
7568    ) -> Option<R>
7569    where
7570        Callback: FnOnce(&Value) -> R,
7571    {
7572        arc_rwlock
7573            .read()
7574            .ok()
7575            .and_then(|guard| self.get(&*guard).map(|value| f(value)))
7576    }
7577
7578    /// Execute a closure with a reference to the value inside an Arc<Mutex<Root>>
7579    pub fn with_arc_mutex<Callback, R>(
7580        &self,
7581        arc_mutex: &Arc<Mutex<Root>>,
7582        f: Callback,
7583    ) -> Option<R>
7584    where
7585        F: Clone,
7586        Callback: FnOnce(&Value) -> R,
7587    {
7588        arc_mutex
7589            .lock()
7590            .ok()
7591            .and_then(|guard| self.get(&*guard).map(|value| f(value)))
7592    }
7593}
7594
7595// ========== PARKING_LOT CHAIN METHODS FOR OPTIONAL KEYPATH ==========
7596
7597#[cfg(feature = "parking_lot")]
7598impl<Root, InnerValue, F> OptionalKeyPath<Root, Arc<parking_lot::Mutex<InnerValue>>, F>
7599where
7600    F: for<'r> Fn(&'r Root) -> Option<&'r Arc<parking_lot::Mutex<InnerValue>>>,
7601{
7602    /// Chain this optional keypath with an inner keypath through Arc<parking_lot::Mutex<T>>
7603    pub fn chain_arc_parking_mutex_at_kp<SubValue, G>(
7604        self,
7605        inner_keypath: KeyPath<InnerValue, SubValue, G>,
7606    ) -> OptionalArcParkingMutexKeyPathChain<Root, InnerValue, SubValue, F, G>
7607    where
7608        G: for<'r> Fn(&'r InnerValue) -> &'r SubValue,
7609    {
7610        OptionalArcParkingMutexKeyPathChain {
7611            outer_keypath: self,
7612            inner_keypath,
7613        }
7614    }
7615
7616    /// Chain this optional keypath with an optional inner keypath through Arc<parking_lot::Mutex<T>>
7617    pub fn then_arc_parking_mutex_optional_at_kp<SubValue, G>(
7618        self,
7619        inner_keypath: OptionalKeyPath<InnerValue, SubValue, G>,
7620    ) -> OptionalArcParkingMutexOptionalKeyPathChain<Root, InnerValue, SubValue, F, G>
7621    where
7622        G: for<'r> Fn(&'r InnerValue) -> Option<&'r SubValue>,
7623    {
7624        OptionalArcParkingMutexOptionalKeyPathChain {
7625            outer_keypath: self,
7626            inner_keypath,
7627        }
7628    }
7629
7630    /// Chain this optional keypath with a writable inner keypath through Arc<parking_lot::Mutex<T>>
7631    pub fn chain_arc_parking_mutex_writable_at_kp<SubValue, G>(
7632        self,
7633        inner_keypath: WritableKeyPath<InnerValue, SubValue, G>,
7634    ) -> OptionalArcParkingMutexWritableKeyPathChain<Root, InnerValue, SubValue, F, G>
7635    where
7636        G: for<'r> Fn(&'r mut InnerValue) -> &'r mut SubValue,
7637    {
7638        OptionalArcParkingMutexWritableKeyPathChain {
7639            outer_keypath: self,
7640            inner_keypath,
7641        }
7642    }
7643
7644    /// Chain this optional keypath with a writable optional inner keypath through Arc<parking_lot::Mutex<T>>
7645    pub fn then_arc_parking_mutex_writable_optional_at_kp<SubValue, G>(
7646        self,
7647        inner_keypath: WritableOptionalKeyPath<InnerValue, SubValue, G>,
7648    ) -> OptionalArcParkingMutexWritableOptionalKeyPathChain<Root, InnerValue, SubValue, F, G>
7649    where
7650        G: for<'r> Fn(&'r mut InnerValue) -> Option<&'r mut SubValue>,
7651    {
7652        OptionalArcParkingMutexWritableOptionalKeyPathChain {
7653            outer_keypath: self,
7654            inner_keypath,
7655        }
7656    }
7657}
7658
7659#[cfg(feature = "parking_lot")]
7660impl<Root, InnerValue, F> OptionalKeyPath<Root, Arc<parking_lot::RwLock<InnerValue>>, F>
7661where
7662    F: for<'r> Fn(&'r Root) -> Option<&'r Arc<parking_lot::RwLock<InnerValue>>>,
7663{
7664    /// Chain this optional keypath with an inner keypath through Arc<parking_lot::RwLock<T>>
7665    pub fn chain_arc_parking_rwlock_at_kp<SubValue, G>(
7666        self,
7667        inner_keypath: KeyPath<InnerValue, SubValue, G>,
7668    ) -> OptionalArcParkingRwLockKeyPathChain<Root, InnerValue, SubValue, F, G>
7669    where
7670        G: for<'r> Fn(&'r InnerValue) -> &'r SubValue,
7671    {
7672        OptionalArcParkingRwLockKeyPathChain {
7673            outer_keypath: self,
7674            inner_keypath,
7675        }
7676    }
7677
7678    /// Chain this optional keypath with an optional inner keypath through Arc<parking_lot::RwLock<T>>
7679    pub fn then_arc_parking_rwlock_optional_at_kp<SubValue, G>(
7680        self,
7681        inner_keypath: OptionalKeyPath<InnerValue, SubValue, G>,
7682    ) -> OptionalArcParkingRwLockOptionalKeyPathChain<Root, InnerValue, SubValue, F, G>
7683    where
7684        G: for<'r> Fn(&'r InnerValue) -> Option<&'r SubValue>,
7685    {
7686        OptionalArcParkingRwLockOptionalKeyPathChain {
7687            outer_keypath: self,
7688            inner_keypath,
7689        }
7690    }
7691
7692    /// Chain this optional keypath with a writable inner keypath through Arc<parking_lot::RwLock<T>>
7693    pub fn chain_arc_parking_rwlock_writable_at_kp<SubValue, G>(
7694        self,
7695        inner_keypath: WritableKeyPath<InnerValue, SubValue, G>,
7696    ) -> OptionalArcParkingRwLockWritableKeyPathChain<Root, InnerValue, SubValue, F, G>
7697    where
7698        G: for<'r> Fn(&'r mut InnerValue) -> &'r mut SubValue,
7699    {
7700        OptionalArcParkingRwLockWritableKeyPathChain {
7701            outer_keypath: self,
7702            inner_keypath,
7703        }
7704    }
7705
7706    /// Chain this optional keypath with a writable optional inner keypath through Arc<parking_lot::RwLock<T>>
7707    pub fn then_arc_parking_rwlock_writable_optional_at_kp<SubValue, G>(
7708        self,
7709        inner_keypath: WritableOptionalKeyPath<InnerValue, SubValue, G>,
7710    ) -> OptionalArcParkingRwLockWritableOptionalKeyPathChain<Root, InnerValue, SubValue, F, G>
7711    where
7712        G: for<'r> Fn(&'r mut InnerValue) -> Option<&'r mut SubValue>,
7713    {
7714        OptionalArcParkingRwLockWritableOptionalKeyPathChain {
7715            outer_keypath: self,
7716            inner_keypath,
7717        }
7718    }
7719}
7720
7721// WritableKeyPath for mutable access
7722#[derive(Clone)]
7723pub struct WritableKeyPath<Root, Value, F>
7724where
7725    F: for<'r> Fn(&'r mut Root) -> &'r mut Value,
7726{
7727    getter: F,
7728    _phantom: PhantomData<(Root, Value)>,
7729}
7730
7731impl<Root, Value, F> fmt::Display for WritableKeyPath<Root, Value, F>
7732where
7733    F: for<'r> Fn(&'r mut Root) -> &'r mut Value,
7734{
7735    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
7736        let root_name = std::any::type_name::<Root>();
7737        let value_name = std::any::type_name::<Value>();
7738        // Simplify type names by removing module paths for cleaner output
7739        let root_short = root_name.split("::").last().unwrap_or(root_name);
7740        let value_short = value_name.split("::").last().unwrap_or(value_name);
7741        write!(f, "WritableKeyPath<{} -> {}>", root_short, value_short)
7742    }
7743}
7744
7745impl<Root, Value, F> fmt::Debug for WritableKeyPath<Root, Value, F>
7746where
7747    F: for<'r> Fn(&'r mut Root) -> &'r mut Value,
7748{
7749    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
7750        fmt::Display::fmt(self, f)
7751    }
7752}
7753
7754impl<Root> WritableKeyPath<Root, Root, fn(&mut Root) -> &mut Root> {
7755    /// Identity writable keypath: projects `&mut Root` to itself.
7756    pub fn identity() -> Self {
7757        WritableKeyPath {
7758            getter: identity_mut::<Root>,
7759            _phantom: PhantomData,
7760        }
7761    }
7762}
7763
7764impl<Root, Value, F> WritableKeyPath<Root, Value, F>
7765where
7766    F: for<'r> Fn(&'r mut Root) -> &'r mut Value,
7767{
7768    pub fn new(getter: F) -> Self {
7769        Self {
7770            getter,
7771            _phantom: PhantomData,
7772        }
7773    }
7774
7775    pub fn get_mut<'r>(&self, root: &'r mut Root) -> &'r mut Value {
7776        (self.getter)(root)
7777    }
7778
7779    /// Type-erase the getter into a `Box<dyn Fn>`, so the keypath can be stored without the concrete closure type.
7780    pub fn boxed(
7781        self,
7782    ) -> WritableKeyPath<
7783        Root,
7784        Value,
7785        Box<dyn for<'r> Fn(&'r mut Root) -> &'r mut Value + 'static>,
7786    >
7787    where
7788        F: 'static,
7789        Root: 'static,
7790        Value: 'static,
7791    {
7792        WritableKeyPath {
7793            getter: Box::new(self.getter),
7794            _phantom: PhantomData,
7795        }
7796    }
7797
7798    /// Higher-order function: map the mutable value reference through a function.
7799    /// Returns a new `WritableKeyPath<Root, U, _>` that gets the value and applies `f` to the mutable reference.
7800    pub fn map<U, G>(self, f: G) -> WritableKeyPath<Root, U, impl for<'r> Fn(&'r mut Root) -> &'r mut U>
7801    where
7802        G: for<'r> Fn(&'r mut Value) -> &'r mut U,
7803        F: 'static,
7804        G: 'static,
7805        Root: 'static,
7806        Value: 'static,
7807    {
7808        let getter = self.getter;
7809        WritableKeyPath {
7810            getter: move |root| f(getter(root)),
7811            _phantom: PhantomData,
7812        }
7813    }
7814
7815    /// Map through a function that returns `Option<&mut U>`, producing a `WritableOptionalKeyPath`.
7816    /// Use when the projection may fail (e.g. `|v: &mut Vec<T>| v.first_mut()`).
7817    pub fn map_optional<U, G>(
7818        self,
7819        f: G,
7820    ) -> WritableOptionalKeyPath<Root, U, impl for<'r> Fn(&'r mut Root) -> Option<&'r mut U>>
7821    where
7822        G: for<'r> Fn(&'r mut Value) -> Option<&'r mut U>,
7823        F: 'static,
7824        G: 'static,
7825        Root: 'static,
7826        Value: 'static,
7827    {
7828        let getter = self.getter;
7829        WritableOptionalKeyPath {
7830            getter: move |root| f(getter(root)),
7831            _phantom: PhantomData,
7832        }
7833    }
7834
7835    /// Adapt this keypath to work with Result<Root, E> instead of Root
7836    /// This unwraps the Result and applies the keypath to the Ok value
7837    pub fn for_result<E>(
7838        self,
7839    ) -> WritableOptionalKeyPath<
7840        Result<Root, E>,
7841        Value,
7842        impl for<'r> Fn(&'r mut Result<Root, E>) -> Option<&'r mut Value> + 'static,
7843    >
7844    where
7845        F: 'static,
7846        Root: 'static,
7847        Value: 'static,
7848        E: 'static,
7849    {
7850        let getter = self.getter;
7851
7852        WritableOptionalKeyPath {
7853            getter: move |result: &mut Result<Root, E>| {
7854                result.as_mut().ok().map(|root| getter(root))
7855            },
7856            _phantom: PhantomData,
7857        }
7858    }
7859
7860    // Overload: Adapt root type to Box<Root> when Value is Sized (not a container)
7861    pub fn for_box_root(
7862        self,
7863    ) -> WritableKeyPath<
7864        Box<Root>,
7865        Value,
7866        impl for<'r> Fn(&'r mut Box<Root>) -> &'r mut Value + 'static,
7867    >
7868    where
7869        Value: Sized,
7870        F: 'static,
7871        Root: 'static,
7872        Value: 'static,
7873    {
7874        let getter = self.getter;
7875
7876        WritableKeyPath {
7877            getter: move |boxed: &mut Box<Root>| getter(boxed.as_mut()),
7878            _phantom: PhantomData,
7879        }
7880    }
7881
7882    /// Adapt this keypath to work with Option<Root> instead of Root
7883    /// This unwraps the Option and applies the keypath to the Some value
7884    pub fn for_option(
7885        self,
7886    ) -> WritableOptionalKeyPath<
7887        Option<Root>,
7888        Value,
7889        impl for<'r> Fn(&'r mut Option<Root>) -> Option<&'r mut Value> + 'static,
7890    >
7891    where
7892        F: 'static,
7893        Root: 'static,
7894        Value: 'static,
7895    {
7896        let getter = self.getter;
7897
7898        WritableOptionalKeyPath {
7899            getter: move |option: &mut Option<Root>| option.as_mut().map(|root| getter(root)),
7900            _phantom: PhantomData,
7901        }
7902    }
7903
7904    /// Convert a WritableKeyPath to WritableOptionalKeyPath for chaining
7905    /// This allows non-optional writable keypaths to be chained with then()
7906    pub fn to_optional(
7907        self,
7908    ) -> WritableOptionalKeyPath<
7909        Root,
7910        Value,
7911        impl for<'r> Fn(&'r mut Root) -> Option<&'r mut Value> + 'static,
7912    >
7913    where
7914        F: 'static,
7915    {
7916        let getter = self.getter;
7917        WritableOptionalKeyPath::new(move |root: &mut Root| Some(getter(root)))
7918    }
7919
7920    // Instance methods for unwrapping containers (automatically infers Target from Value::Target)
7921    // Box<T> -> T
7922    pub fn for_box<Target>(
7923        self,
7924    ) -> WritableKeyPath<Root, Target, impl for<'r> Fn(&'r mut Root) -> &'r mut Target + 'static>
7925    where
7926        Value: std::ops::DerefMut<Target = Target>,
7927        F: 'static,
7928        Value: 'static,
7929    {
7930        let getter = self.getter;
7931
7932        WritableKeyPath {
7933            getter: move |root: &mut Root| getter(root).deref_mut(),
7934            _phantom: PhantomData,
7935        }
7936    }
7937
7938    // Arc<T> -> T (Note: Arc doesn't support mutable access, but we provide it for consistency)
7939    // This will require interior mutability patterns
7940    pub fn for_arc<Target>(
7941        self,
7942    ) -> WritableKeyPath<Root, Target, impl for<'r> Fn(&'r mut Root) -> &'r mut Target + 'static>
7943    where
7944        Value: std::ops::DerefMut<Target = Target>,
7945        F: 'static,
7946        Value: 'static,
7947    {
7948        let getter = self.getter;
7949
7950        WritableKeyPath {
7951            getter: move |root: &mut Root| getter(root).deref_mut(),
7952            _phantom: PhantomData,
7953        }
7954    }
7955
7956    // Rc<T> -> T (Note: Rc doesn't support mutable access, but we provide it for consistency)
7957    // This will require interior mutability patterns
7958    pub fn for_rc<Target>(
7959        self,
7960    ) -> WritableKeyPath<Root, Target, impl for<'r> Fn(&'r mut Root) -> &'r mut Target + 'static>
7961    where
7962        Value: std::ops::DerefMut<Target = Target>,
7963        F: 'static,
7964        Value: 'static,
7965    {
7966        let getter = self.getter;
7967
7968        WritableKeyPath {
7969            getter: move |root: &mut Root| getter(root).deref_mut(),
7970            _phantom: PhantomData,
7971        }
7972    }
7973
7974    /// Execute a closure with a mutable reference to the value inside a Box
7975    pub fn with_box_mut<Callback, R>(&self, boxed: &mut Box<Root>, f: Callback) -> R
7976    where
7977        F: Clone,
7978        Callback: FnOnce(&mut Value) -> R,
7979    {
7980        let value = self.get_mut(boxed);
7981        f(value)
7982    }
7983
7984    /// Execute a closure with a mutable reference to the value inside a Result
7985    pub fn with_result_mut<Callback, R, E>(
7986        &self,
7987        result: &mut Result<Root, E>,
7988        f: Callback,
7989    ) -> Option<R>
7990    where
7991        F: Clone,
7992        Callback: FnOnce(&mut Value) -> R,
7993    {
7994        result.as_mut().ok().map(|root| {
7995            let value = self.get_mut(root);
7996            f(value)
7997        })
7998    }
7999
8000    /// Execute a closure with a mutable reference to the value inside an Option
8001    pub fn with_option_mut<Callback, R>(&self, option: &mut Option<Root>, f: Callback) -> Option<R>
8002    where
8003        F: Clone,
8004        Callback: FnOnce(&mut Value) -> R,
8005    {
8006        option.as_mut().map(|root| {
8007            let value = self.get_mut(root);
8008            f(value)
8009        })
8010    }
8011
8012    /// Execute a closure with a mutable reference to the value inside a RefCell
8013    pub fn with_refcell_mut<Callback, R>(&self, refcell: &RefCell<Root>, f: Callback) -> Option<R>
8014    where
8015        F: Clone,
8016        Callback: FnOnce(&mut Value) -> R,
8017    {
8018        refcell.try_borrow_mut().ok().map(|mut borrow| {
8019            let value = self.get_mut(&mut *borrow);
8020            f(value)
8021        })
8022    }
8023
8024    /// Execute a closure with a mutable reference to the value inside a Mutex
8025    pub fn with_mutex_mut<Callback, R>(&self, mutex: &mut Mutex<Root>, f: Callback) -> Option<R>
8026    where
8027        F: Clone,
8028        Callback: FnOnce(&mut Value) -> R,
8029    {
8030        mutex.get_mut().ok().map(|root| {
8031            let value = self.get_mut(root);
8032            f(value)
8033        })
8034    }
8035
8036    /// Execute a closure with a mutable reference to the value inside an RwLock
8037    pub fn with_rwlock_mut<Callback, R>(&self, rwlock: &mut RwLock<Root>, f: Callback) -> Option<R>
8038    where
8039        F: Clone,
8040        Callback: FnOnce(&mut Value) -> R,
8041    {
8042        rwlock.write().ok().map(|mut guard| {
8043            let value = self.get_mut(&mut *guard);
8044            f(value)
8045        })
8046    }
8047
8048    /// Get a mutable iterator over a Vec when Value is Vec<T>
8049    /// Returns Some(iterator) if the value is a Vec, None otherwise
8050    pub fn iter_mut<'r, T>(&self, root: &'r mut Root) -> Option<std::slice::IterMut<'r, T>>
8051    where
8052        Value: AsMut<[T]> + 'r,
8053    {
8054        let value_ref: &'r mut Value = self.get_mut(root);
8055        Some(value_ref.as_mut().iter_mut())
8056    }
8057
8058    /// Extract mutable values from a slice of owned mutable values
8059    /// Returns a Vec of mutable references to the extracted values
8060    pub fn extract_mut_from_slice<'r>(&self, slice: &'r mut [Root]) -> Vec<&'r mut Value> {
8061        slice.iter_mut().map(|item| self.get_mut(item)).collect()
8062    }
8063
8064    /// Extract mutable values from a slice of mutable references
8065    /// Returns a Vec of mutable references to the extracted values
8066    pub fn extract_mut_from_ref_slice<'r>(
8067        &self,
8068        slice: &'r mut [&'r mut Root],
8069    ) -> Vec<&'r mut Value> {
8070        slice.iter_mut().map(|item| self.get_mut(*item)).collect()
8071    }
8072
8073    /// Chain this keypath with another writable keypath
8074    /// Returns a WritableKeyPath that chains both keypaths
8075    pub fn then<SubValue, G>(
8076        self,
8077        next: WritableKeyPath<Value, SubValue, G>,
8078    ) -> WritableKeyPath<Root, SubValue, impl for<'r> Fn(&'r mut Root) -> &'r mut SubValue>
8079    where
8080        G: for<'r> Fn(&'r mut Value) -> &'r mut SubValue,
8081        F: 'static,
8082        G: 'static,
8083        Value: 'static,
8084    {
8085        let first = self.getter;
8086        let second = next.getter;
8087
8088        WritableKeyPath::new(move |root: &mut Root| {
8089            let value = first(root);
8090            second(value)
8091        })
8092    }
8093
8094    /// Chain this keypath with a writable optional keypath
8095    /// Returns a WritableOptionalKeyPath that chains both keypaths
8096    pub fn chain_optional<SubValue, G>(
8097        self,
8098        next: WritableOptionalKeyPath<Value, SubValue, G>,
8099    ) -> WritableOptionalKeyPath<
8100        Root,
8101        SubValue,
8102        impl for<'r> Fn(&'r mut Root) -> Option<&'r mut SubValue>,
8103    >
8104    where
8105        G: for<'r> Fn(&'r mut Value) -> Option<&'r mut SubValue>,
8106        F: 'static,
8107        G: 'static,
8108        Value: 'static,
8109    {
8110        let first = self.getter;
8111        let second = next.getter;
8112
8113        WritableOptionalKeyPath::new(move |root: &mut Root| {
8114            let value = first(root);
8115            second(value)
8116        })
8117    }
8118
8119    // ========== LOCK KEYPATH CONVERSION METHODS ==========
8120    // These methods convert keypaths pointing to lock types into chain-ready keypaths
8121
8122    /// Convert this writable keypath to an Arc<RwLock> chain-ready keypath
8123    /// Returns self, but serves as a marker for intent and enables chaining
8124    pub fn to_arc_rwlock_kp<InnerValue>(self) -> Self
8125    where
8126        Value: std::borrow::Borrow<Arc<RwLock<InnerValue>>>,
8127    {
8128        self
8129    }
8130
8131    /// Convert this writable keypath to an Arc<Mutex> chain-ready keypath
8132    /// Returns self, but serves as a marker for intent and enables chaining
8133    pub fn to_arc_mutex_kp<InnerValue>(self) -> Self
8134    where
8135        Value: std::borrow::Borrow<Arc<Mutex<InnerValue>>>,
8136    {
8137        self
8138    }
8139
8140    #[cfg(feature = "parking_lot")]
8141    /// Convert this writable keypath to an Arc<parking_lot::RwLock> chain-ready keypath
8142    /// Returns self, but serves as a marker for intent and enables chaining
8143    pub fn to_arc_parking_rwlock_kp<InnerValue>(self) -> Self
8144    where
8145        Value: std::borrow::Borrow<Arc<parking_lot::RwLock<InnerValue>>>,
8146    {
8147        self
8148    }
8149
8150    #[cfg(feature = "parking_lot")]
8151    /// Convert this writable keypath to an Arc<parking_lot::Mutex> chain-ready keypath
8152    /// Returns self, but serves as a marker for intent and enables chaining
8153    pub fn to_arc_parking_mutex_kp<InnerValue>(self) -> Self
8154    where
8155        Value: std::borrow::Borrow<Arc<parking_lot::Mutex<InnerValue>>>,
8156    {
8157        self
8158    }
8159}
8160
8161// WritableOptionalKeyPath for failable mutable access
8162#[derive(Clone)]
8163pub struct WritableOptionalKeyPath<Root, Value, F>
8164where
8165    F: for<'r> Fn(&'r mut Root) -> Option<&'r mut Value>,
8166{
8167    getter: F,
8168    _phantom: PhantomData<(Root, Value)>,
8169}
8170
8171impl<Root, Value, F> fmt::Display for WritableOptionalKeyPath<Root, Value, F>
8172where
8173    F: for<'r> Fn(&'r mut Root) -> Option<&'r mut Value>,
8174{
8175    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
8176        let root_name = std::any::type_name::<Root>();
8177        let value_name = std::any::type_name::<Value>();
8178        // Simplify type names by removing module paths for cleaner output
8179        let root_short = root_name.split("::").last().unwrap_or(root_name);
8180        let value_short = value_name.split("::").last().unwrap_or(value_name);
8181        write!(
8182            f,
8183            "WritableOptionalKeyPath<{} -> Option<{}>>",
8184            root_short, value_short
8185        )
8186    }
8187}
8188
8189impl<Root, Value, F> fmt::Debug for WritableOptionalKeyPath<Root, Value, F>
8190where
8191    F: for<'r> Fn(&'r mut Root) -> Option<&'r mut Value>,
8192{
8193    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
8194        // Show type information and indicate this is a chain that may fail
8195        let root_name = std::any::type_name::<Root>();
8196        let value_name = std::any::type_name::<Value>();
8197        let root_short = root_name.split("::").last().unwrap_or(root_name);
8198        let value_short = value_name.split("::").last().unwrap_or(value_name);
8199
8200        // Use alternate format for more detailed debugging
8201        if f.alternate() {
8202            writeln!(
8203                f,
8204                "WritableOptionalKeyPath<{} -> Option<{}>>",
8205                root_short, value_short
8206            )?;
8207            writeln!(
8208                f,
8209                "  âš  Chain may break if any intermediate step returns None"
8210            )?;
8211            writeln!(f, "  💡 Use trace_chain() to find where the chain breaks")
8212        } else {
8213            write!(
8214                f,
8215                "WritableOptionalKeyPath<{} -> Option<{}>>",
8216                root_short, value_short
8217            )
8218        }
8219    }
8220}
8221
8222impl<Root> WritableOptionalKeyPath<Root, Root, fn(&mut Root) -> Option<&mut Root>> {
8223    /// Identity writable optional keypath: projects `&mut Root` to `Some(root)`.
8224    pub fn identity() -> Self {
8225        WritableOptionalKeyPath {
8226            getter: identity_opt_mut::<Root>,
8227            _phantom: PhantomData,
8228        }
8229    }
8230}
8231
8232impl<Root, Value, F> WritableOptionalKeyPath<Root, Value, F>
8233where
8234    F: for<'r> Fn(&'r mut Root) -> Option<&'r mut Value>,
8235{
8236    pub fn new(getter: F) -> Self {
8237        Self {
8238            getter,
8239            _phantom: PhantomData,
8240        }
8241    }
8242
8243    pub fn get_mut<'r>(&self, root: &'r mut Root) -> Option<&'r mut Value> {
8244        (self.getter)(root)
8245    }
8246
8247    /// Type-erase the getter into a `Box<dyn Fn>`, so the keypath can be stored without the concrete closure type.
8248    pub fn boxed(
8249        self,
8250    ) -> WritableOptionalKeyPath<
8251        Root,
8252        Value,
8253        Box<dyn for<'r> Fn(&'r mut Root) -> Option<&'r mut Value> + 'static>,
8254    >
8255    where
8256        F: 'static,
8257        Root: 'static,
8258        Value: 'static,
8259    {
8260        WritableOptionalKeyPath {
8261            getter: Box::new(self.getter),
8262            _phantom: PhantomData,
8263        }
8264    }
8265
8266    /// Higher-order function: map the optional mutable value reference through a function.
8267    /// Returns a new `WritableOptionalKeyPath<Root, U, _>` that gets the value and applies `f` when present.
8268    pub fn map<U, G>(
8269        self,
8270        f: G,
8271    ) -> WritableOptionalKeyPath<Root, U, impl for<'r> Fn(&'r mut Root) -> Option<&'r mut U>>
8272    where
8273        G: for<'r> Fn(&'r mut Value) -> &'r mut U,
8274        F: 'static,
8275        G: 'static,
8276        Root: 'static,
8277        Value: 'static,
8278    {
8279        let getter = self.getter;
8280        WritableOptionalKeyPath {
8281            getter: move |root| getter(root).map(|v| f(v)),
8282            _phantom: PhantomData,
8283        }
8284    }
8285
8286    /// Map through a function that returns `Option<&mut U>`, keeping a `WritableOptionalKeyPath`.
8287    /// Use when the inner projection may fail (e.g. `|v: &mut Vec<T>| v.first_mut()`).
8288    pub fn map_optional<U, G>(
8289        self,
8290        f: G,
8291    ) -> WritableOptionalKeyPath<Root, U, impl for<'r> Fn(&'r mut Root) -> Option<&'r mut U>>
8292    where
8293        G: for<'r> Fn(&'r mut Value) -> Option<&'r mut U>,
8294        F: 'static,
8295        G: 'static,
8296        Root: 'static,
8297        Value: 'static,
8298    {
8299        let getter = self.getter;
8300        WritableOptionalKeyPath {
8301            getter: move |root| getter(root).and_then(|v| f(v)),
8302            _phantom: PhantomData,
8303        }
8304    }
8305
8306    /// Trace the chain to find where it breaks
8307    /// Returns Ok(()) if the chain succeeds, or Err with diagnostic information
8308    ///
8309    /// # Example
8310    /// ```rust
8311    /// let path = SomeComplexStruct::scsf_fw()
8312    ///     .then(SomeOtherStruct::sosf_fw())
8313    ///     .then(SomeEnum::b_fw());
8314    ///
8315    /// match path.trace_chain(&mut instance) {
8316    ///     Ok(()) => println!("Chain succeeded"),
8317    ///     Err(msg) => println!("Chain broken: {}", msg),
8318    /// }
8319    /// ```
8320    pub fn trace_chain(&self, root: &mut Root) -> Result<(), String> {
8321        match self.get_mut(root) {
8322            Some(_) => Ok(()),
8323            None => {
8324                let root_name = std::any::type_name::<Root>();
8325                let value_name = std::any::type_name::<Value>();
8326                let root_short = root_name.split("::").last().unwrap_or(root_name);
8327                let value_short = value_name.split("::").last().unwrap_or(value_name);
8328                Err(format!(
8329                    "{} -> Option<{}> returned None (chain broken at this step)",
8330                    root_short, value_short
8331                ))
8332            }
8333        }
8334    }
8335
8336    /// Adapt this keypath to work with Option<Root> instead of Root
8337    /// This unwraps the Option and applies the keypath to the Some value
8338    pub fn for_option(
8339        self,
8340    ) -> WritableOptionalKeyPath<
8341        Option<Root>,
8342        Value,
8343        impl for<'r> Fn(&'r mut Option<Root>) -> Option<&'r mut Value> + 'static,
8344    >
8345    where
8346        F: 'static,
8347        Root: 'static,
8348        Value: 'static,
8349    {
8350        let getter = self.getter;
8351
8352        WritableOptionalKeyPath {
8353            getter: move |option: &mut Option<Root>| option.as_mut().and_then(|root| getter(root)),
8354            _phantom: PhantomData,
8355        }
8356    }
8357
8358    // Swift-like operator for chaining WritableOptionalKeyPath
8359    pub fn then<SubValue, G>(
8360        self,
8361        next: WritableOptionalKeyPath<Value, SubValue, G>,
8362    ) -> WritableOptionalKeyPath<
8363        Root,
8364        SubValue,
8365        impl for<'r> Fn(&'r mut Root) -> Option<&'r mut SubValue>,
8366    >
8367    where
8368        G: for<'r> Fn(&'r mut Value) -> Option<&'r mut SubValue>,
8369        F: 'static,
8370        G: 'static,
8371        Value: 'static,
8372    {
8373        let first = self.getter;
8374        let second = next.getter;
8375
8376        WritableOptionalKeyPath::new(move |root: &mut Root| {
8377            first(root).and_then(|value| second(value))
8378        })
8379    }
8380
8381    // Instance methods for unwrapping containers from Option<Container<T>>
8382    // Option<Box<T>> -> Option<&mut T> (type automatically inferred from Value::Target)
8383    pub fn for_box<Target>(
8384        self,
8385    ) -> WritableOptionalKeyPath<
8386        Root,
8387        Target,
8388        impl for<'r> Fn(&'r mut Root) -> Option<&'r mut Target> + 'static,
8389    >
8390    where
8391        Value: std::ops::DerefMut<Target = Target>,
8392        F: 'static,
8393        Value: 'static,
8394    {
8395        let getter = self.getter;
8396
8397        WritableOptionalKeyPath {
8398            getter: move |root: &mut Root| getter(root).map(|boxed| boxed.deref_mut()),
8399            _phantom: PhantomData,
8400        }
8401    }
8402
8403    // Option<Arc<T>> -> Option<&mut T> (type automatically inferred from Value::Target)
8404    pub fn for_arc<Target>(
8405        self,
8406    ) -> WritableOptionalKeyPath<
8407        Root,
8408        Target,
8409        impl for<'r> Fn(&'r mut Root) -> Option<&'r mut Target> + 'static,
8410    >
8411    where
8412        Value: std::ops::DerefMut<Target = Target>,
8413        F: 'static,
8414        Value: 'static,
8415    {
8416        let getter = self.getter;
8417
8418        WritableOptionalKeyPath {
8419            getter: move |root: &mut Root| getter(root).map(|arc| arc.deref_mut()),
8420            _phantom: PhantomData,
8421        }
8422    }
8423
8424    // Option<Rc<T>> -> Option<&mut T> (type automatically inferred from Value::Target)
8425    pub fn for_rc<Target>(
8426        self,
8427    ) -> WritableOptionalKeyPath<
8428        Root,
8429        Target,
8430        impl for<'r> Fn(&'r mut Root) -> Option<&'r mut Target> + 'static,
8431    >
8432    where
8433        Value: std::ops::DerefMut<Target = Target>,
8434        F: 'static,
8435        Value: 'static,
8436    {
8437        let getter = self.getter;
8438
8439        WritableOptionalKeyPath {
8440            getter: move |root: &mut Root| getter(root).map(|rc| rc.deref_mut()),
8441            _phantom: PhantomData,
8442        }
8443    }
8444
8445    /// Adapt this keypath to work with Result<Root, E> instead of Root
8446    /// This unwraps the Result and applies the keypath to the Ok value
8447    pub fn for_result<E>(
8448        self,
8449    ) -> WritableOptionalKeyPath<
8450        Result<Root, E>,
8451        Value,
8452        impl for<'r> Fn(&'r mut Result<Root, E>) -> Option<&'r mut Value> + 'static,
8453    >
8454    where
8455        F: 'static,
8456        Root: 'static,
8457        Value: 'static,
8458        E: 'static,
8459    {
8460        let getter = self.getter;
8461
8462        WritableOptionalKeyPath {
8463            getter: move |result: &mut Result<Root, E>| {
8464                result.as_mut().ok().and_then(|root| getter(root))
8465            },
8466            _phantom: PhantomData,
8467        }
8468    }
8469
8470    // Overload: Adapt root type to Box<Root> when Value is Sized (not a container)
8471    pub fn for_box_root(
8472        self,
8473    ) -> WritableOptionalKeyPath<
8474        Box<Root>,
8475        Value,
8476        impl for<'r> Fn(&'r mut Box<Root>) -> Option<&'r mut Value> + 'static,
8477    >
8478    where
8479        Value: Sized,
8480        F: 'static,
8481        Root: 'static,
8482        Value: 'static,
8483    {
8484        let getter = self.getter;
8485
8486        WritableOptionalKeyPath {
8487            getter: move |boxed: &mut Box<Root>| getter(boxed.as_mut()),
8488            _phantom: PhantomData,
8489        }
8490    }
8491
8492    // Overload: Adapt root type to Arc<Root> when Value is Sized (not a container)
8493    pub fn for_arc_root(
8494        self,
8495    ) -> WritableOptionalKeyPath<
8496        Arc<Root>,
8497        Value,
8498        impl for<'r> Fn(&'r mut Arc<Root>) -> Option<&'r mut Value> + 'static,
8499    >
8500    where
8501        Value: Sized,
8502        F: 'static,
8503        Root: 'static,
8504        Value: 'static,
8505    {
8506        let getter = self.getter;
8507
8508        WritableOptionalKeyPath {
8509            getter: move |arc: &mut Arc<Root>| {
8510                // Arc doesn't support mutable access without interior mutability
8511                // This will always return None, but we provide it for API consistency
8512                None
8513            },
8514            _phantom: PhantomData,
8515        }
8516    }
8517
8518    // Overload: Adapt root type to Rc<Root> when Value is Sized (not a container)
8519    pub fn for_rc_root(
8520        self,
8521    ) -> WritableOptionalKeyPath<
8522        Rc<Root>,
8523        Value,
8524        impl for<'r> Fn(&'r mut Rc<Root>) -> Option<&'r mut Value> + 'static,
8525    >
8526    where
8527        Value: Sized,
8528        F: 'static,
8529        Root: 'static,
8530        Value: 'static,
8531    {
8532        let getter = self.getter;
8533
8534        WritableOptionalKeyPath {
8535            getter: move |rc: &mut Rc<Root>| {
8536                // Rc doesn't support mutable access without interior mutability
8537                // This will always return None, but we provide it for API consistency
8538                None
8539            },
8540            _phantom: PhantomData,
8541        }
8542    }
8543
8544    // ========== LOCK KEYPATH CONVERSION METHODS ==========
8545    // These methods convert keypaths pointing to lock types into chain-ready keypaths
8546
8547    /// Convert this writable optional keypath to an Arc<RwLock> chain-ready keypath
8548    /// Returns self, but serves as a marker for intent and enables chaining
8549    pub fn to_arc_rwlock_kp<InnerValue>(self) -> Self
8550    where
8551        Value: std::borrow::Borrow<Arc<RwLock<InnerValue>>>,
8552    {
8553        self
8554    }
8555
8556    /// Convert this writable optional keypath to an Arc<Mutex> chain-ready keypath
8557    /// Returns self, but serves as a marker for intent and enables chaining
8558    pub fn to_arc_mutex_kp<InnerValue>(self) -> Self
8559    where
8560        Value: std::borrow::Borrow<Arc<Mutex<InnerValue>>>,
8561    {
8562        self
8563    }
8564
8565    #[cfg(feature = "parking_lot")]
8566    /// Convert this writable optional keypath to an Arc<parking_lot::RwLock> chain-ready keypath
8567    /// Returns self, but serves as a marker for intent and enables chaining
8568    pub fn to_arc_parking_rwlock_kp<InnerValue>(self) -> Self
8569    where
8570        Value: std::borrow::Borrow<Arc<parking_lot::RwLock<InnerValue>>>,
8571    {
8572        self
8573    }
8574
8575    #[cfg(feature = "parking_lot")]
8576    /// Convert this writable optional keypath to an Arc<parking_lot::Mutex> chain-ready keypath
8577    /// Returns self, but serves as a marker for intent and enables chaining
8578    pub fn to_arc_parking_mutex_kp<InnerValue>(self) -> Self
8579    where
8580        Value: std::borrow::Borrow<Arc<parking_lot::Mutex<InnerValue>>>,
8581    {
8582        self
8583    }
8584}
8585
8586// Static factory methods for WritableOptionalKeyPath
8587impl WritableOptionalKeyPath<(), (), fn(&mut ()) -> Option<&mut ()>> {
8588    // Static method for Option<T> -> Option<&mut T>
8589    // Note: This is a factory method. Use instance method `for_option()` to adapt existing keypaths.
8590    pub fn for_option_static<T>() -> WritableOptionalKeyPath<
8591        Option<T>,
8592        T,
8593        impl for<'r> Fn(&'r mut Option<T>) -> Option<&'r mut T>,
8594    > {
8595        WritableOptionalKeyPath::new(|opt: &mut Option<T>| opt.as_mut())
8596    }
8597
8598    /// Backword compatibility method for writable enum keypath
8599    // Create a writable enum keypath for enum variants
8600    /// This allows both reading and writing to enum variant fields
8601    ///
8602    /// # Arguments
8603    /// * `embedder` - Function to embed a value into the enum variant (for API consistency, not used)
8604    /// * `read_extractor` - Function to extract a read reference from the enum (for API consistency, not used)
8605    /// * `write_extractor` - Function to extract a mutable reference from the enum
8606    ///
8607    /// # Example
8608    /// ```rust
8609    /// enum Color { Other(RGBU8) }
8610    /// struct RGBU8(u8, u8, u8);
8611    ///
8612    /// let case_path = WritableOptionalKeyPath::writable_enum(
8613    ///     |v| Color::Other(v),
8614    ///     |p: &Color| match p { Color::Other(rgb) => Some(rgb), _ => None },
8615    ///     |p: &mut Color| match p { Color::Other(rgb) => Some(rgb), _ => None },
8616    /// );
8617    /// ```
8618    pub fn writable_enum<Enum, Variant, EmbedFn, ReadExtractFn, WriteExtractFn>(
8619        _embedder: EmbedFn,
8620        _read_extractor: ReadExtractFn,
8621        write_extractor: WriteExtractFn,
8622    ) -> WritableOptionalKeyPath<
8623        Enum,
8624        Variant,
8625        impl for<'r> Fn(&'r mut Enum) -> Option<&'r mut Variant> + 'static,
8626    >
8627    where
8628        EmbedFn: Fn(Variant) -> Enum + 'static,
8629        ReadExtractFn: for<'r> Fn(&'r Enum) -> Option<&'r Variant> + 'static,
8630        WriteExtractFn: for<'r> Fn(&'r mut Enum) -> Option<&'r mut Variant> + 'static,
8631    {
8632        WritableOptionalKeyPath::new(write_extractor)
8633    }
8634}
8635
8636// Enum-specific keypaths
8637/// EnumKeyPath - A keypath for enum variants that supports both extraction and embedding
8638/// Uses generic type parameters instead of dynamic dispatch for zero-cost abstraction
8639///
8640/// This struct serves dual purpose:
8641/// 1. As a concrete keypath instance: `EnumKeyPath<Enum, Variant, ExtractFn, EmbedFn>`
8642/// 2. As a namespace for static factory methods: `EnumKeyPath::readable_enum(...)`
8643pub struct EnumKeyPath<
8644    Enum = (),
8645    Variant = (),
8646    ExtractFn = fn(&()) -> Option<&()>,
8647    EmbedFn = fn(()) -> (),
8648> where
8649    ExtractFn: for<'r> Fn(&'r Enum) -> Option<&'r Variant> + 'static,
8650    EmbedFn: Fn(Variant) -> Enum + 'static,
8651{
8652    extractor: OptionalKeyPath<Enum, Variant, ExtractFn>,
8653    embedder: EmbedFn,
8654}
8655
8656impl<Enum, Variant, ExtractFn, EmbedFn> EnumKeyPath<Enum, Variant, ExtractFn, EmbedFn>
8657where
8658    ExtractFn: for<'r> Fn(&'r Enum) -> Option<&'r Variant> + 'static,
8659    EmbedFn: Fn(Variant) -> Enum + 'static,
8660{
8661    /// Create a new EnumKeyPath with extractor and embedder functions
8662    pub fn new(extractor: ExtractFn, embedder: EmbedFn) -> Self {
8663        Self {
8664            extractor: OptionalKeyPath::new(extractor),
8665            embedder,
8666        }
8667    }
8668
8669    /// Extract the value from an enum variant
8670    pub fn get<'r>(&self, enum_value: &'r Enum) -> Option<&'r Variant> {
8671        self.extractor.get(enum_value)
8672    }
8673
8674    /// Embed a value into the enum variant
8675    pub fn embed(&self, value: Variant) -> Enum {
8676        (self.embedder)(value)
8677    }
8678
8679    /// Get the underlying OptionalKeyPath for composition
8680    pub fn as_optional(&self) -> &OptionalKeyPath<Enum, Variant, ExtractFn> {
8681        &self.extractor
8682    }
8683
8684    /// Convert to OptionalKeyPath (loses embedding capability but gains composition)
8685    pub fn to_optional(self) -> OptionalKeyPath<Enum, Variant, ExtractFn> {
8686        self.extractor
8687    }
8688}
8689
8690// Static factory methods for EnumKeyPath
8691impl EnumKeyPath {
8692    /// Identity enum keypath: `Enum = Variant`, extract returns `Some(&e)`, embed returns the value unchanged.
8693    pub fn identity<E>() -> EnumKeyPath<E, E, fn(&E) -> Option<&E>, fn(E) -> E> {
8694        EnumKeyPath {
8695            extractor: OptionalKeyPath::new(identity_opt_ref::<E>),
8696            embedder: identity_value::<E>,
8697        }
8698    }
8699
8700    /// Create a readable enum keypath with both extraction and embedding
8701    /// Returns an EnumKeyPath that supports both get() and embed() operations
8702    pub fn readable_enum<Enum, Variant, ExtractFn, EmbedFn>(
8703        embedder: EmbedFn,
8704        extractor: ExtractFn,
8705    ) -> EnumKeyPath<Enum, Variant, ExtractFn, EmbedFn>
8706    where
8707        ExtractFn: for<'r> Fn(&'r Enum) -> Option<&'r Variant> + 'static,
8708        EmbedFn: Fn(Variant) -> Enum + 'static,
8709    {
8710        EnumKeyPath::new(extractor, embedder)
8711    }
8712
8713    /// Extract from a specific enum variant
8714    pub fn for_variant<Enum, Variant, ExtractFn>(
8715        extractor: ExtractFn,
8716    ) -> OptionalKeyPath<Enum, Variant, impl for<'r> Fn(&'r Enum) -> Option<&'r Variant>>
8717    where
8718        ExtractFn: Fn(&Enum) -> Option<&Variant>,
8719    {
8720        OptionalKeyPath::new(extractor)
8721    }
8722
8723    /// Match against multiple variants (returns a tagged union)
8724    pub fn for_match<Enum, Output, MatchFn>(
8725        matcher: MatchFn,
8726    ) -> KeyPath<Enum, Output, impl for<'r> Fn(&'r Enum) -> &'r Output>
8727    where
8728        MatchFn: Fn(&Enum) -> &Output,
8729    {
8730        KeyPath::new(matcher)
8731    }
8732
8733    /// Extract from Result<T, E> - Ok variant
8734    pub fn for_ok<T, E>()
8735    -> OptionalKeyPath<Result<T, E>, T, impl for<'r> Fn(&'r Result<T, E>) -> Option<&'r T>> {
8736        OptionalKeyPath::new(|result: &Result<T, E>| result.as_ref().ok())
8737    }
8738
8739    /// Extract from Result<T, E> - Err variant
8740    pub fn for_err<T, E>()
8741    -> OptionalKeyPath<Result<T, E>, E, impl for<'r> Fn(&'r Result<T, E>) -> Option<&'r E>> {
8742        OptionalKeyPath::new(|result: &Result<T, E>| result.as_ref().err())
8743    }
8744
8745    /// Extract from Option<T> - Some variant
8746    pub fn for_some<T>()
8747    -> OptionalKeyPath<Option<T>, T, impl for<'r> Fn(&'r Option<T>) -> Option<&'r T>> {
8748        OptionalKeyPath::new(|opt: &Option<T>| opt.as_ref())
8749    }
8750
8751    /// Extract from Option<T> - Some variant (alias for for_some for consistency)
8752    pub fn for_option<T>()
8753    -> OptionalKeyPath<Option<T>, T, impl for<'r> Fn(&'r Option<T>) -> Option<&'r T>> {
8754        OptionalKeyPath::new(|opt: &Option<T>| opt.as_ref())
8755    }
8756
8757    /// Unwrap Box<T> -> T
8758    pub fn for_box<T>() -> KeyPath<Box<T>, T, impl for<'r> Fn(&'r Box<T>) -> &'r T> {
8759        KeyPath::new(|b: &Box<T>| b.as_ref())
8760    }
8761
8762    /// Unwrap Arc<T> -> T
8763    pub fn for_arc<T>() -> KeyPath<Arc<T>, T, impl for<'r> Fn(&'r Arc<T>) -> &'r T> {
8764        KeyPath::new(|arc: &Arc<T>| arc.as_ref())
8765    }
8766
8767    /// Unwrap Rc<T> -> T
8768    pub fn for_rc<T>() -> KeyPath<std::rc::Rc<T>, T, impl for<'r> Fn(&'r std::rc::Rc<T>) -> &'r T> {
8769        KeyPath::new(|rc: &std::rc::Rc<T>| rc.as_ref())
8770    }
8771
8772    /// Unwrap Box<T> -> T (mutable)
8773    pub fn for_box_mut<T>()
8774    -> WritableKeyPath<Box<T>, T, impl for<'r> Fn(&'r mut Box<T>) -> &'r mut T> {
8775        WritableKeyPath::new(|b: &mut Box<T>| b.as_mut())
8776    }
8777
8778    // Note: Arc<T> and Rc<T> don't support direct mutable access without interior mutability
8779    // (e.g., Arc<Mutex<T>> or Rc<RefCell<T>>). These methods are not provided as they
8780    // would require unsafe code or interior mutability patterns.
8781}
8782
8783// Helper to create enum variant keypaths with type inference
8784pub fn variant_of<Enum, Variant, F>(extractor: F) -> OptionalKeyPath<Enum, Variant, F>
8785where
8786    F: for<'r> Fn(&'r Enum) -> Option<&'r Variant>,
8787{
8788    OptionalKeyPath::new(extractor)
8789}
8790
8791// ========== PARTIAL KEYPATHS (Hide Value Type) ==========
8792
8793/// PartialKeyPath - Hides the Value type but keeps Root visible
8794/// Useful for storing keypaths in collections without knowing the exact Value type
8795///
8796/// # Why PhantomData<Root>?
8797///
8798/// `PhantomData<Root>` is needed because:
8799/// 1. The `Root` type parameter is not actually stored in the struct (only used in the closure)
8800/// 2. Rust needs to know the generic type parameter for:
8801///    - Type checking at compile time
8802///    - Ensuring correct usage (e.g., `PartialKeyPath<User>` can only be used with `&User`)
8803///    - Preventing mixing different Root types
8804/// 3. Without `PhantomData`, Rust would complain that `Root` is unused
8805/// 4. `PhantomData` is zero-sized - it adds no runtime overhead
8806#[derive(Clone)]
8807pub struct PartialKeyPath<Root> {
8808    getter: Rc<dyn for<'r> Fn(&'r Root) -> &'r dyn Any>,
8809    value_type_id: TypeId,
8810    _phantom: PhantomData<Root>,
8811}
8812
8813impl<Root> PartialKeyPath<Root> {
8814    pub fn new<Value>(
8815        keypath: KeyPath<Root, Value, impl for<'r> Fn(&'r Root) -> &'r Value + 'static>,
8816    ) -> Self
8817    where
8818        Value: Any + 'static,
8819        Root: 'static,
8820    {
8821        let value_type_id = TypeId::of::<Value>();
8822        let getter = Rc::new(keypath.getter);
8823
8824        Self {
8825            getter: Rc::new(move |root: &Root| {
8826                let value: &Value = getter(root);
8827                value as &dyn Any
8828            }),
8829            value_type_id,
8830            _phantom: PhantomData,
8831        }
8832    }
8833
8834    /// Create a PartialKeyPath from a concrete KeyPath
8835    /// Alias for `new()` for consistency with `from()` pattern
8836    pub fn from<Value>(
8837        keypath: KeyPath<Root, Value, impl for<'r> Fn(&'r Root) -> &'r Value + 'static>,
8838    ) -> Self
8839    where
8840        Value: Any + 'static,
8841        Root: 'static,
8842    {
8843        Self::new(keypath)
8844    }
8845
8846    pub fn get<'r>(&self, root: &'r Root) -> &'r dyn Any {
8847        (self.getter)(root)
8848    }
8849
8850    /// Get the TypeId of the Value type
8851    pub fn value_type_id(&self) -> TypeId {
8852        self.value_type_id
8853    }
8854
8855    /// Try to downcast the result to a specific type
8856    pub fn get_as<'a, Value: Any>(&self, root: &'a Root) -> Option<&'a Value> {
8857        if self.value_type_id == TypeId::of::<Value>() {
8858            self.get(root).downcast_ref::<Value>()
8859        } else {
8860            None
8861        }
8862    }
8863
8864    /// Get a human-readable name for the value type
8865    /// Returns a string representation of the TypeId
8866    pub fn kind_name(&self) -> String {
8867        format!("{:?}", self.value_type_id)
8868    }
8869
8870    /// Adapt this keypath to work with Arc<Root> instead of Root
8871    pub fn for_arc(&self) -> PartialOptionalKeyPath<Arc<Root>>
8872    where
8873        Root: 'static,
8874    {
8875        let getter = self.getter.clone();
8876        let value_type_id = self.value_type_id;
8877
8878        PartialOptionalKeyPath {
8879            getter: Rc::new(move |arc: &Arc<Root>| Some(getter(arc.as_ref()))),
8880            value_type_id,
8881            _phantom: PhantomData,
8882        }
8883    }
8884
8885    /// Adapt this keypath to work with Box<Root> instead of Root
8886    pub fn for_box(&self) -> PartialOptionalKeyPath<Box<Root>>
8887    where
8888        Root: 'static,
8889    {
8890        let getter = self.getter.clone();
8891        let value_type_id = self.value_type_id;
8892
8893        PartialOptionalKeyPath {
8894            getter: Rc::new(move |boxed: &Box<Root>| Some(getter(boxed.as_ref()))),
8895            value_type_id,
8896            _phantom: PhantomData,
8897        }
8898    }
8899
8900    /// Adapt this keypath to work with Rc<Root> instead of Root
8901    pub fn for_rc(&self) -> PartialOptionalKeyPath<Rc<Root>>
8902    where
8903        Root: 'static,
8904    {
8905        let getter = self.getter.clone();
8906        let value_type_id = self.value_type_id;
8907
8908        PartialOptionalKeyPath {
8909            getter: Rc::new(move |rc: &Rc<Root>| Some(getter(rc.as_ref()))),
8910            value_type_id,
8911            _phantom: PhantomData,
8912        }
8913    }
8914
8915    /// Adapt this keypath to work with Option<Root> instead of Root
8916    pub fn for_option(&self) -> PartialOptionalKeyPath<Option<Root>>
8917    where
8918        Root: 'static,
8919    {
8920        let getter = self.getter.clone();
8921        let value_type_id = self.value_type_id;
8922
8923        PartialOptionalKeyPath {
8924            getter: Rc::new(move |opt: &Option<Root>| opt.as_ref().map(|root| getter(root))),
8925            value_type_id,
8926            _phantom: PhantomData,
8927        }
8928    }
8929
8930    /// Adapt this keypath to work with Result<Root, E> instead of Root
8931    pub fn for_result<E>(&self) -> PartialOptionalKeyPath<Result<Root, E>>
8932    where
8933        Root: 'static,
8934        E: 'static,
8935    {
8936        let getter = self.getter.clone();
8937        let value_type_id = self.value_type_id;
8938
8939        PartialOptionalKeyPath {
8940            getter: Rc::new(move |result: &Result<Root, E>| {
8941                result.as_ref().ok().map(|root| getter(root))
8942            }),
8943            value_type_id,
8944            _phantom: PhantomData,
8945        }
8946    }
8947
8948    /// Adapt this keypath to work with Arc<RwLock<Root>> instead of Root
8949    /// Note: This requires the Root to be cloned first, then use the keypath on the cloned value
8950    /// Example: `keypath.get_as::<Value>(&arc_rwlock.read().unwrap().clone())`
8951    pub fn for_arc_rwlock(&self) -> PartialOptionalKeyPath<Arc<RwLock<Root>>>
8952    where
8953        Root: Clone + 'static,
8954    {
8955        // We can't return a reference from a guard, so we return None
8956        // Users should clone the root first: arc_rwlock.read().unwrap().clone()
8957        PartialOptionalKeyPath {
8958            getter: Rc::new(move |_arc_rwlock: &Arc<RwLock<Root>>| {
8959                // Cannot return reference from temporary guard
8960                // User should clone the root first and use the keypath on the cloned value
8961                None
8962            }),
8963            value_type_id: self.value_type_id,
8964            _phantom: PhantomData,
8965        }
8966    }
8967
8968    /// Adapt this keypath to work with Arc<Mutex<Root>> instead of Root
8969    /// Note: This requires the Root to be cloned first, then use the keypath on the cloned value
8970    /// Example: `keypath.get_as::<Value>(&arc_mutex.lock().unwrap().clone())`
8971    pub fn for_arc_mutex(&self) -> PartialOptionalKeyPath<Arc<Mutex<Root>>>
8972    where
8973        Root: Clone + 'static,
8974    {
8975        // We can't return a reference from a guard, so we return None
8976        // Users should clone the root first: arc_mutex.lock().unwrap().clone()
8977        PartialOptionalKeyPath {
8978            getter: Rc::new(move |_arc_mutex: &Arc<Mutex<Root>>| {
8979                // Cannot return reference from temporary guard
8980                // User should clone the root first and use the keypath on the cloned value
8981                None
8982            }),
8983            value_type_id: self.value_type_id,
8984            _phantom: PhantomData,
8985        }
8986    }
8987}
8988
8989/// PartialOptionalKeyPath - Hides the Value type but keeps Root visible
8990/// Useful for storing optional keypaths in collections without knowing the exact Value type
8991///
8992/// # Why PhantomData<Root>?
8993///
8994/// See `PartialKeyPath` documentation for explanation of why `PhantomData` is needed.
8995#[derive(Clone)]
8996pub struct PartialOptionalKeyPath<Root> {
8997    getter: Rc<dyn for<'r> Fn(&'r Root) -> Option<&'r dyn Any>>,
8998    value_type_id: TypeId,
8999    _phantom: PhantomData<Root>,
9000}
9001
9002impl<Root> PartialOptionalKeyPath<Root> {
9003    pub fn new<Value>(
9004        keypath: OptionalKeyPath<
9005            Root,
9006            Value,
9007            impl for<'r> Fn(&'r Root) -> Option<&'r Value> + 'static,
9008        >,
9009    ) -> Self
9010    where
9011        Value: Any + 'static,
9012        Root: 'static,
9013    {
9014        let value_type_id = TypeId::of::<Value>();
9015        let getter = Rc::new(keypath.getter);
9016
9017        Self {
9018            getter: Rc::new(move |root: &Root| getter(root).map(|value: &Value| value as &dyn Any)),
9019            value_type_id,
9020            _phantom: PhantomData,
9021        }
9022    }
9023
9024    pub fn get<'r>(&self, root: &'r Root) -> Option<&'r dyn Any> {
9025        (self.getter)(root)
9026    }
9027
9028    /// Get the TypeId of the Value type
9029    pub fn value_type_id(&self) -> TypeId {
9030        self.value_type_id
9031    }
9032
9033    /// Try to downcast the result to a specific type
9034    pub fn get_as<'a, Value: Any>(&self, root: &'a Root) -> Option<Option<&'a Value>> {
9035        if self.value_type_id == TypeId::of::<Value>() {
9036            self.get(root).map(|any| any.downcast_ref::<Value>())
9037        } else {
9038            None
9039        }
9040    }
9041
9042    /// Chain with another PartialOptionalKeyPath
9043    /// Note: This requires the Value type of the first keypath to match the Root type of the second
9044    /// For type-erased chaining, consider using AnyKeyPath instead
9045    pub fn then<MidValue>(
9046        self,
9047        next: PartialOptionalKeyPath<MidValue>,
9048    ) -> PartialOptionalKeyPath<Root>
9049    where
9050        MidValue: Any + 'static,
9051        Root: 'static,
9052    {
9053        let first = self.getter;
9054        let second = next.getter;
9055        let value_type_id = next.value_type_id;
9056
9057        PartialOptionalKeyPath {
9058            getter: Rc::new(move |root: &Root| {
9059                first(root).and_then(|any| {
9060                    if let Some(mid_value) = any.downcast_ref::<MidValue>() {
9061                        second(mid_value)
9062                    } else {
9063                        None
9064                    }
9065                })
9066            }),
9067            value_type_id,
9068            _phantom: PhantomData,
9069        }
9070    }
9071}
9072
9073/// PartialWritableKeyPath - Hides the Value type but keeps Root visible (writable)
9074///
9075/// # Why PhantomData<Root>?
9076///
9077/// See `PartialKeyPath` documentation for explanation of why `PhantomData` is needed.
9078#[derive(Clone)]
9079pub struct PartialWritableKeyPath<Root> {
9080    getter: Rc<dyn for<'r> Fn(&'r mut Root) -> &'r mut dyn Any>,
9081    value_type_id: TypeId,
9082    _phantom: PhantomData<Root>,
9083}
9084
9085impl<Root> PartialWritableKeyPath<Root> {
9086    pub fn new<Value>(
9087        keypath: WritableKeyPath<
9088            Root,
9089            Value,
9090            impl for<'r> Fn(&'r mut Root) -> &'r mut Value + 'static,
9091        >,
9092    ) -> Self
9093    where
9094        Value: Any + 'static,
9095        Root: 'static,
9096    {
9097        let value_type_id = TypeId::of::<Value>();
9098        let getter = Rc::new(keypath.getter);
9099
9100        Self {
9101            getter: Rc::new(move |root: &mut Root| {
9102                let value: &mut Value = getter(root);
9103                value as &mut dyn Any
9104            }),
9105            value_type_id,
9106            _phantom: PhantomData,
9107        }
9108    }
9109
9110    /// Create a PartialWritableKeyPath from a concrete WritableKeyPath
9111    /// Alias for `new()` for consistency with `from()` pattern
9112    pub fn from<Value>(
9113        keypath: WritableKeyPath<
9114            Root,
9115            Value,
9116            impl for<'r> Fn(&'r mut Root) -> &'r mut Value + 'static,
9117        >,
9118    ) -> Self
9119    where
9120        Value: Any + 'static,
9121        Root: 'static,
9122    {
9123        Self::new(keypath)
9124    }
9125
9126    pub fn get_mut<'r>(&self, root: &'r mut Root) -> &'r mut dyn Any {
9127        (self.getter)(root)
9128    }
9129
9130    /// Get the TypeId of the Value type
9131    pub fn value_type_id(&self) -> TypeId {
9132        self.value_type_id
9133    }
9134
9135    /// Try to downcast the result to a specific type
9136    pub fn get_mut_as<'a, Value: Any>(&self, root: &'a mut Root) -> Option<&'a mut Value> {
9137        if self.value_type_id == TypeId::of::<Value>() {
9138            self.get_mut(root).downcast_mut::<Value>()
9139        } else {
9140            None
9141        }
9142    }
9143}
9144
9145/// PartialWritableOptionalKeyPath - Hides the Value type but keeps Root visible (writable optional)
9146///
9147/// # Why PhantomData<Root>?
9148///
9149/// See `PartialKeyPath` documentation for explanation of why `PhantomData` is needed.
9150#[derive(Clone)]
9151pub struct PartialWritableOptionalKeyPath<Root> {
9152    getter: Rc<dyn for<'r> Fn(&'r mut Root) -> Option<&'r mut dyn Any>>,
9153    value_type_id: TypeId,
9154    _phantom: PhantomData<Root>,
9155}
9156
9157impl<Root> PartialWritableOptionalKeyPath<Root> {
9158    pub fn new<Value>(
9159        keypath: WritableOptionalKeyPath<
9160            Root,
9161            Value,
9162            impl for<'r> Fn(&'r mut Root) -> Option<&'r mut Value> + 'static,
9163        >,
9164    ) -> Self
9165    where
9166        Value: Any + 'static,
9167        Root: 'static,
9168    {
9169        let value_type_id = TypeId::of::<Value>();
9170        let getter = Rc::new(keypath.getter);
9171
9172        Self {
9173            getter: Rc::new(move |root: &mut Root| {
9174                getter(root).map(|value: &mut Value| value as &mut dyn Any)
9175            }),
9176            value_type_id,
9177            _phantom: PhantomData,
9178        }
9179    }
9180
9181    pub fn get_mut<'r>(&self, root: &'r mut Root) -> Option<&'r mut dyn Any> {
9182        (self.getter)(root)
9183    }
9184
9185    /// Get the TypeId of the Value type
9186    pub fn value_type_id(&self) -> TypeId {
9187        self.value_type_id
9188    }
9189
9190    /// Try to downcast the result to a specific type
9191    pub fn get_mut_as<'a, Value: Any>(&self, root: &'a mut Root) -> Option<Option<&'a mut Value>> {
9192        if self.value_type_id == TypeId::of::<Value>() {
9193            self.get_mut(root).map(|any| any.downcast_mut::<Value>())
9194        } else {
9195            None
9196        }
9197    }
9198}
9199
9200// ========== ANY KEYPATHS (Hide Both Root and Value Types) ==========
9201
9202/// AnyKeyPath - Hides both Root and Value types
9203/// Equivalent to Swift's AnyKeyPath
9204/// Useful for storing keypaths in collections without knowing either type
9205///
9206/// # Why No PhantomData?
9207///
9208/// Unlike `PartialKeyPath`, `AnyKeyPath` doesn't need `PhantomData` because:
9209/// - Both `Root` and `Value` types are completely erased
9210/// - We store `TypeId` instead for runtime type checking
9211/// - The type information is encoded in the closure's behavior, not the struct
9212/// - There's no generic type parameter to track at compile time
9213#[derive(Clone)]
9214pub struct AnyKeyPath {
9215    getter: Rc<dyn for<'r> Fn(&'r dyn Any) -> Option<&'r dyn Any>>,
9216    root_type_id: TypeId,
9217    value_type_id: TypeId,
9218}
9219
9220impl AnyKeyPath {
9221    pub fn new<Root, Value>(
9222        keypath: OptionalKeyPath<
9223            Root,
9224            Value,
9225            impl for<'r> Fn(&'r Root) -> Option<&'r Value> + 'static,
9226        >,
9227    ) -> Self
9228    where
9229        Root: Any + 'static,
9230        Value: Any + 'static,
9231    {
9232        let root_type_id = TypeId::of::<Root>();
9233        let value_type_id = TypeId::of::<Value>();
9234        let getter = keypath.getter;
9235
9236        Self {
9237            getter: Rc::new(move |any: &dyn Any| {
9238                if let Some(root) = any.downcast_ref::<Root>() {
9239                    getter(root).map(|value: &Value| value as &dyn Any)
9240                } else {
9241                    None
9242                }
9243            }),
9244            root_type_id,
9245            value_type_id,
9246        }
9247    }
9248
9249    /// Create an AnyKeyPath from a concrete OptionalKeyPath
9250    /// Alias for `new()` for consistency with `from()` pattern
9251    pub fn from<Root, Value>(
9252        keypath: OptionalKeyPath<
9253            Root,
9254            Value,
9255            impl for<'r> Fn(&'r Root) -> Option<&'r Value> + 'static,
9256        >,
9257    ) -> Self
9258    where
9259        Root: Any + 'static,
9260        Value: Any + 'static,
9261    {
9262        Self::new(keypath)
9263    }
9264
9265    pub fn get<'r>(&self, root: &'r dyn Any) -> Option<&'r dyn Any> {
9266        (self.getter)(root)
9267    }
9268
9269    /// Get the TypeId of the Root type
9270    pub fn root_type_id(&self) -> TypeId {
9271        self.root_type_id
9272    }
9273
9274    /// Get the TypeId of the Value type
9275    pub fn value_type_id(&self) -> TypeId {
9276        self.value_type_id
9277    }
9278
9279    /// Try to get the value with type checking
9280    pub fn get_as<'a, Root: Any, Value: Any>(&self, root: &'a Root) -> Option<Option<&'a Value>> {
9281        if self.root_type_id == TypeId::of::<Root>() && self.value_type_id == TypeId::of::<Value>()
9282        {
9283            self.get(root as &dyn Any)
9284                .map(|any| any.downcast_ref::<Value>())
9285        } else {
9286            None
9287        }
9288    }
9289
9290    /// Get a human-readable name for the value type
9291    /// Returns a string representation of the TypeId
9292    pub fn kind_name(&self) -> String {
9293        format!("{:?}", self.value_type_id)
9294    }
9295
9296    /// Adapt this keypath to work with Arc<Root> instead of Root
9297    pub fn for_arc<Root>(&self) -> AnyKeyPath
9298    where
9299        Root: Any + 'static,
9300    {
9301        let root_type_id = self.root_type_id;
9302        let value_type_id = self.value_type_id;
9303        let getter = self.getter.clone();
9304
9305        AnyKeyPath {
9306            getter: Rc::new(move |any: &dyn Any| {
9307                if let Some(arc) = any.downcast_ref::<Arc<Root>>() {
9308                    getter(arc.as_ref() as &dyn Any)
9309                } else {
9310                    None
9311                }
9312            }),
9313            root_type_id: TypeId::of::<Arc<Root>>(),
9314            value_type_id,
9315        }
9316    }
9317
9318    /// Adapt this keypath to work with Box<Root> instead of Root
9319    pub fn for_box<Root>(&self) -> AnyKeyPath
9320    where
9321        Root: Any + 'static,
9322    {
9323        let root_type_id = self.root_type_id;
9324        let value_type_id = self.value_type_id;
9325        let getter = self.getter.clone();
9326
9327        AnyKeyPath {
9328            getter: Rc::new(move |any: &dyn Any| {
9329                if let Some(boxed) = any.downcast_ref::<Box<Root>>() {
9330                    getter(boxed.as_ref() as &dyn Any)
9331                } else {
9332                    None
9333                }
9334            }),
9335            root_type_id: TypeId::of::<Box<Root>>(),
9336            value_type_id,
9337        }
9338    }
9339
9340    /// Adapt this keypath to work with Rc<Root> instead of Root
9341    pub fn for_rc<Root>(&self) -> AnyKeyPath
9342    where
9343        Root: Any + 'static,
9344    {
9345        let root_type_id = self.root_type_id;
9346        let value_type_id = self.value_type_id;
9347        let getter = self.getter.clone();
9348
9349        AnyKeyPath {
9350            getter: Rc::new(move |any: &dyn Any| {
9351                if let Some(rc) = any.downcast_ref::<Rc<Root>>() {
9352                    getter(rc.as_ref() as &dyn Any)
9353                } else {
9354                    None
9355                }
9356            }),
9357            root_type_id: TypeId::of::<Rc<Root>>(),
9358            value_type_id,
9359        }
9360    }
9361
9362    /// Adapt this keypath to work with Option<Root> instead of Root
9363    pub fn for_option<Root>(&self) -> AnyKeyPath
9364    where
9365        Root: Any + 'static,
9366    {
9367        let root_type_id = self.root_type_id;
9368        let value_type_id = self.value_type_id;
9369        let getter = self.getter.clone();
9370
9371        AnyKeyPath {
9372            getter: Rc::new(move |any: &dyn Any| {
9373                if let Some(opt) = any.downcast_ref::<Option<Root>>() {
9374                    opt.as_ref().and_then(|root| getter(root as &dyn Any))
9375                } else {
9376                    None
9377                }
9378            }),
9379            root_type_id: TypeId::of::<Option<Root>>(),
9380            value_type_id,
9381        }
9382    }
9383
9384    /// Adapt this keypath to work with Result<Root, E> instead of Root
9385    pub fn for_result<Root, E>(&self) -> AnyKeyPath
9386    where
9387        Root: Any + 'static,
9388        E: Any + 'static,
9389    {
9390        let root_type_id = self.root_type_id;
9391        let value_type_id = self.value_type_id;
9392        let getter = self.getter.clone();
9393
9394        AnyKeyPath {
9395            getter: Rc::new(move |any: &dyn Any| {
9396                if let Some(result) = any.downcast_ref::<Result<Root, E>>() {
9397                    result
9398                        .as_ref()
9399                        .ok()
9400                        .and_then(|root| getter(root as &dyn Any))
9401                } else {
9402                    None
9403                }
9404            }),
9405            root_type_id: TypeId::of::<Result<Root, E>>(),
9406            value_type_id,
9407        }
9408    }
9409
9410    /// Adapt this keypath to work with Arc<RwLock<Root>> instead of Root
9411    /// Note: This requires the Root to be cloned first, then use the keypath on the cloned value
9412    pub fn for_arc_rwlock<Root>(&self) -> AnyKeyPath
9413    where
9414        Root: Any + Clone + 'static,
9415    {
9416        // We can't return a reference from a guard, so we return None
9417        // Users should clone the root first
9418        AnyKeyPath {
9419            getter: Rc::new(move |_any: &dyn Any| {
9420                // Cannot return reference from temporary guard
9421                // User should clone the root first and use the keypath on the cloned value
9422                None
9423            }),
9424            root_type_id: TypeId::of::<Arc<RwLock<Root>>>(),
9425            value_type_id: self.value_type_id,
9426        }
9427    }
9428
9429    /// Adapt this keypath to work with Arc<Mutex<Root>> instead of Root
9430    /// Note: This requires the Root to be cloned first, then use the keypath on the cloned value
9431    pub fn for_arc_mutex<Root>(&self) -> AnyKeyPath
9432    where
9433        Root: Any + Clone + 'static,
9434    {
9435        // We can't return a reference from a guard, so we return None
9436        // Users should clone the root first
9437        AnyKeyPath {
9438            getter: Rc::new(move |_any: &dyn Any| {
9439                // Cannot return reference from temporary guard
9440                // User should clone the root first and use the keypath on the cloned value
9441                None
9442            }),
9443            root_type_id: TypeId::of::<Arc<Mutex<Root>>>(),
9444            value_type_id: self.value_type_id,
9445        }
9446    }
9447}
9448
9449/// AnyWritableKeyPath - Hides both Root and Value types (writable)
9450#[derive(Clone)]
9451pub struct AnyWritableKeyPath {
9452    getter: Rc<dyn for<'r> Fn(&'r mut dyn Any) -> Option<&'r mut dyn Any>>,
9453    root_type_id: TypeId,
9454    value_type_id: TypeId,
9455}
9456
9457/// FailableCombinedKeyPath - A keypath that supports readable, writable, and owned access patterns
9458///
9459/// This keypath type combines the functionality of OptionalKeyPath, WritableOptionalKeyPath,
9460/// and adds owned access. It's useful when you need all three access patterns for the same field.
9461#[derive(Clone)]
9462pub struct FailableCombinedKeyPath<Root, Value, ReadFn, WriteFn, OwnedFn>
9463where
9464    ReadFn: for<'r> Fn(&'r Root) -> Option<&'r Value> + 'static,
9465    WriteFn: for<'r> Fn(&'r mut Root) -> Option<&'r mut Value> + 'static,
9466    OwnedFn: Fn(Root) -> Option<Value> + 'static,
9467{
9468    readable: ReadFn,
9469    writable: WriteFn,
9470    owned: OwnedFn,
9471    _phantom: PhantomData<(Root, Value)>,
9472}
9473
9474impl<Root, Value, ReadFn, WriteFn, OwnedFn>
9475    FailableCombinedKeyPath<Root, Value, ReadFn, WriteFn, OwnedFn>
9476where
9477    ReadFn: for<'r> Fn(&'r Root) -> Option<&'r Value> + 'static,
9478    WriteFn: for<'r> Fn(&'r mut Root) -> Option<&'r mut Value> + 'static,
9479    OwnedFn: Fn(Root) -> Option<Value> + 'static,
9480{
9481    /// Create a new FailableCombinedKeyPath with all three access patterns
9482    pub fn new(readable: ReadFn, writable: WriteFn, owned: OwnedFn) -> Self {
9483        Self {
9484            readable,
9485            writable,
9486            owned,
9487            _phantom: PhantomData,
9488        }
9489    }
9490
9491    /// Get an immutable reference to the value (readable access)
9492    pub fn get<'r>(&self, root: &'r Root) -> Option<&'r Value> {
9493        (self.readable)(root)
9494    }
9495
9496    /// Get a mutable reference to the value (writable access)
9497    pub fn get_mut<'r>(&self, root: &'r mut Root) -> Option<&'r mut Value> {
9498        (self.writable)(root)
9499    }
9500
9501    /// Get an owned value (owned access) - consumes the root
9502    pub fn get_failable_owned(&self, root: Root) -> Option<Value> {
9503        (self.owned)(root)
9504    }
9505
9506    /// Convert to OptionalKeyPath (loses writable and owned capabilities)
9507    pub fn to_optional(self) -> OptionalKeyPath<Root, Value, ReadFn> {
9508        OptionalKeyPath::new(self.readable)
9509    }
9510
9511    /// Convert to WritableOptionalKeyPath (loses owned capability)
9512    pub fn to_writable_optional(self) -> WritableOptionalKeyPath<Root, Value, WriteFn> {
9513        WritableOptionalKeyPath::new(self.writable)
9514    }
9515
9516    /// Compose this keypath with another FailableCombinedKeyPath
9517    /// Returns a new FailableCombinedKeyPath that chains both keypaths
9518    pub fn then<SubValue, SubReadFn, SubWriteFn, SubOwnedFn>(
9519        self,
9520        next: FailableCombinedKeyPath<Value, SubValue, SubReadFn, SubWriteFn, SubOwnedFn>,
9521    ) -> FailableCombinedKeyPath<
9522        Root,
9523        SubValue,
9524        impl for<'r> Fn(&'r Root) -> Option<&'r SubValue> + 'static,
9525        impl for<'r> Fn(&'r mut Root) -> Option<&'r mut SubValue> + 'static,
9526        impl Fn(Root) -> Option<SubValue> + 'static,
9527    >
9528    where
9529        SubReadFn: for<'r> Fn(&'r Value) -> Option<&'r SubValue> + 'static,
9530        SubWriteFn: for<'r> Fn(&'r mut Value) -> Option<&'r mut SubValue> + 'static,
9531        SubOwnedFn: Fn(Value) -> Option<SubValue> + 'static,
9532        ReadFn: 'static,
9533        WriteFn: 'static,
9534        OwnedFn: 'static,
9535        Value: 'static,
9536        Root: 'static,
9537        SubValue: 'static,
9538    {
9539        let first_read = self.readable;
9540        let first_write = self.writable;
9541        let first_owned = self.owned;
9542        let second_read = next.readable;
9543        let second_write = next.writable;
9544        let second_owned = next.owned;
9545
9546        FailableCombinedKeyPath::new(
9547            move |root: &Root| first_read(root).and_then(|value| second_read(value)),
9548            move |root: &mut Root| first_write(root).and_then(|value| second_write(value)),
9549            move |root: Root| first_owned(root).and_then(|value| second_owned(value)),
9550        )
9551    }
9552
9553    /// Compose with OptionalKeyPath (readable only)
9554    /// Returns a FailableCombinedKeyPath that uses the readable from OptionalKeyPath
9555    /// and creates dummy writable/owned closures that return None
9556    pub fn chain_optional<SubValue, SubReadFn>(
9557        self,
9558        next: OptionalKeyPath<Value, SubValue, SubReadFn>,
9559    ) -> FailableCombinedKeyPath<
9560        Root,
9561        SubValue,
9562        impl for<'r> Fn(&'r Root) -> Option<&'r SubValue> + 'static,
9563        impl for<'r> Fn(&'r mut Root) -> Option<&'r mut SubValue> + 'static,
9564        impl Fn(Root) -> Option<SubValue> + 'static,
9565    >
9566    where
9567        SubReadFn: for<'r> Fn(&'r Value) -> Option<&'r SubValue> + 'static,
9568        ReadFn: 'static,
9569        WriteFn: 'static,
9570        OwnedFn: 'static,
9571        Value: 'static,
9572        Root: 'static,
9573        SubValue: 'static,
9574    {
9575        let first_read = self.readable;
9576        let first_write = self.writable;
9577        let first_owned = self.owned;
9578        let second_read = next.getter;
9579
9580        FailableCombinedKeyPath::new(
9581            move |root: &Root| first_read(root).and_then(|value| second_read(value)),
9582            move |_root: &mut Root| {
9583                None // Writable not supported when composing with OptionalKeyPath
9584            },
9585            move |root: Root| {
9586                first_owned(root).and_then(|value| {
9587                    // Try to get owned value, but OptionalKeyPath doesn't support owned
9588                    None
9589                })
9590            },
9591        )
9592    }
9593}
9594
9595// Factory function for FailableCombinedKeyPath
9596impl
9597    FailableCombinedKeyPath<
9598        (),
9599        (),
9600        fn(&()) -> Option<&()>,
9601        fn(&mut ()) -> Option<&mut ()>,
9602        fn(()) -> Option<()>,
9603    >
9604{
9605    /// Create a FailableCombinedKeyPath with all three access patterns
9606    pub fn failable_combined<Root, Value, ReadFn, WriteFn, OwnedFn>(
9607        readable: ReadFn,
9608        writable: WriteFn,
9609        owned: OwnedFn,
9610    ) -> FailableCombinedKeyPath<Root, Value, ReadFn, WriteFn, OwnedFn>
9611    where
9612        ReadFn: for<'r> Fn(&'r Root) -> Option<&'r Value> + 'static,
9613        WriteFn: for<'r> Fn(&'r mut Root) -> Option<&'r mut Value> + 'static,
9614        OwnedFn: Fn(Root) -> Option<Value> + 'static,
9615    {
9616        FailableCombinedKeyPath::new(readable, writable, owned)
9617    }
9618}
9619
9620impl AnyWritableKeyPath {
9621    pub fn new<Root, Value>(
9622        keypath: WritableOptionalKeyPath<
9623            Root,
9624            Value,
9625            impl for<'r> Fn(&'r mut Root) -> Option<&'r mut Value> + 'static,
9626        >,
9627    ) -> Self
9628    where
9629        Root: Any + 'static,
9630        Value: Any + 'static,
9631    {
9632        let root_type_id = TypeId::of::<Root>();
9633        let value_type_id = TypeId::of::<Value>();
9634        let getter = keypath.getter;
9635
9636        Self {
9637            getter: Rc::new(move |any: &mut dyn Any| {
9638                if let Some(root) = any.downcast_mut::<Root>() {
9639                    getter(root).map(|value: &mut Value| value as &mut dyn Any)
9640                } else {
9641                    None
9642                }
9643            }),
9644            root_type_id,
9645            value_type_id,
9646        }
9647    }
9648
9649    pub fn get_mut<'r>(&self, root: &'r mut dyn Any) -> Option<&'r mut dyn Any> {
9650        (self.getter)(root)
9651    }
9652
9653    /// Get the TypeId of the Root type
9654    pub fn root_type_id(&self) -> TypeId {
9655        self.root_type_id
9656    }
9657
9658    /// Get the TypeId of the Value type
9659    pub fn value_type_id(&self) -> TypeId {
9660        self.value_type_id
9661    }
9662
9663    /// Try to get the value with type checking
9664    pub fn get_mut_as<'a, Root: Any, Value: Any>(
9665        &self,
9666        root: &'a mut Root,
9667    ) -> Option<Option<&'a mut Value>> {
9668        if self.root_type_id == TypeId::of::<Root>() && self.value_type_id == TypeId::of::<Value>()
9669        {
9670            self.get_mut(root as &mut dyn Any)
9671                .map(|any| any.downcast_mut::<Value>())
9672        } else {
9673            None
9674        }
9675    }
9676}
9677
9678// Conversion methods from concrete keypaths to partial/any keypaths
9679impl<Root, Value, F> KeyPath<Root, Value, F>
9680where
9681    F: for<'r> Fn(&'r Root) -> &'r Value + 'static,
9682    Root: 'static,
9683    Value: Any + 'static,
9684{
9685    /// Convert to PartialKeyPath (hides Value type)
9686    pub fn to_partial(self) -> PartialKeyPath<Root> {
9687        PartialKeyPath::new(self)
9688    }
9689
9690    /// Alias for `to_partial()` - converts to PartialKeyPath
9691    pub fn to(self) -> PartialKeyPath<Root> {
9692        self.to_partial()
9693    }
9694}
9695
9696impl<Root, Value, F> OptionalKeyPath<Root, Value, F>
9697where
9698    F: for<'r> Fn(&'r Root) -> Option<&'r Value> + 'static,
9699    Root: Any + 'static,
9700    Value: Any + 'static,
9701{
9702    /// Convert to PartialOptionalKeyPath (hides Value type)
9703    pub fn to_partial(self) -> PartialOptionalKeyPath<Root> {
9704        PartialOptionalKeyPath::new(self)
9705    }
9706
9707    /// Convert to AnyKeyPath (hides both Root and Value types)
9708    pub fn to_any(self) -> AnyKeyPath {
9709        AnyKeyPath::new(self)
9710    }
9711
9712    /// Convert to PartialOptionalKeyPath (alias for `to_partial()`)
9713    pub fn to(self) -> PartialOptionalKeyPath<Root> {
9714        self.to_partial()
9715    }
9716}
9717
9718impl<Root, Value, F> WritableKeyPath<Root, Value, F>
9719where
9720    F: for<'r> Fn(&'r mut Root) -> &'r mut Value + 'static,
9721    Root: 'static,
9722    Value: Any + 'static,
9723{
9724    /// Convert to PartialWritableKeyPath (hides Value type)
9725    pub fn to_partial(self) -> PartialWritableKeyPath<Root> {
9726        PartialWritableKeyPath::new(self)
9727    }
9728
9729    /// Alias for `to_partial()` - converts to PartialWritableKeyPath
9730    pub fn to(self) -> PartialWritableKeyPath<Root> {
9731        self.to_partial()
9732    }
9733}
9734
9735impl<Root, Value, F> WritableOptionalKeyPath<Root, Value, F>
9736where
9737    F: for<'r> Fn(&'r mut Root) -> Option<&'r mut Value> + 'static,
9738    Root: Any + 'static,
9739    Value: Any + 'static,
9740{
9741    /// Convert to PartialWritableOptionalKeyPath (hides Value type)
9742    pub fn to_partial(self) -> PartialWritableOptionalKeyPath<Root> {
9743        PartialWritableOptionalKeyPath::new(self)
9744    }
9745
9746    /// Convert to AnyWritableKeyPath (hides both Root and Value types)
9747    pub fn to_any(self) -> AnyWritableKeyPath {
9748        AnyWritableKeyPath::new(self)
9749    }
9750
9751    /// Convert to PartialWritableOptionalKeyPath (alias for `to_partial()`)
9752    pub fn to(self) -> PartialWritableOptionalKeyPath<Root> {
9753        self.to_partial()
9754    }
9755}
9756
9757// pub trait KPTrait<R, V>: {
9758//     fn getter(r: &R) -> Option<&V>;
9759//     fn setter(r: &mut R) -> Option< &mut V>;
9760// }
9761// pub trait KPGTrait<R, V> {
9762//     fn getter(r: &R) -> Option<&V>;
9763// }
9764
9765// pub trait KPSTrait<R, V> {
9766//         fn setter(r: &mut R) -> Option< &mut V>;
9767// }
9768
9769pub fn test<R, V, F>(x: R)
9770where
9771    F: Fn(&R) -> Option<&V>,
9772{
9773}
9774
9775type Getter<R, V> = for<'r> fn(&'r R) -> Option<&'r V>;
9776type Setter<R, V> = for<'r> fn(&'r mut R) -> Option<&'r mut V>;
9777// type LockGetter<R, V> = for<'r> fn(&'r R) -> Option<Arc<&'r V>>;
9778// type LockSetter<R, V> = for<'r> fn(&'r mut R) -> Option<Arc<&'r mut V>>;
9779
9780pub type Kp<R, V> = KpType<
9781    R,
9782    V,
9783    Getter<R, V>,
9784    Setter<R, V>,
9785    //  LockGetter<R, V>,
9786    //  LockSetter<R, V>
9787>;
9788
9789#[derive(Debug)]
9790pub struct KpType<
9791    R,
9792    V,
9793    G,
9794    S,
9795    // LG, SG
9796> where
9797    G: for<'r> Fn(&'r R) -> Option<&'r V>,
9798    S: for<'r> Fn(&'r mut R) -> Option<&'r mut V>,
9799    // LG:for<'r> Fn(&'r R) -> Option<Arc<&'r V>>,
9800    // SG:for<'r> Fn(&'r mut R) -> Option<Arc<&'r mut V>>,
9801{
9802    g: G,
9803    s: S,
9804    // lg: LG,
9805    // sg: SG,
9806    _p: PhantomData<(R, V)>,
9807}
9808
9809impl<
9810    R,
9811    V,
9812    G,
9813    S,
9814    // LG, SG
9815>
9816    KpType<
9817        R,
9818        V,
9819        G,
9820        S,
9821        // LG, SG
9822    >
9823where
9824    G: for<'r> Fn(&'r R) -> Option<&'r V>,
9825    S: for<'r> Fn(&'r mut R) -> Option<&'r mut V>,
9826{
9827    pub fn new(get: G, set: S) -> Self {
9828        Self {
9829            g: get,
9830            s: set,
9831            _p: PhantomData,
9832        }
9833    }
9834
9835    pub fn get<'a>(&self, r: &'a R) -> Option<&'a V> {
9836        (self.g)(r)
9837    }
9838
9839    pub fn get_mut<'a>(&self, r: &'a mut R) -> Option<&'a mut V> {
9840        (self.s)(r)
9841    }
9842
9843    pub fn then<SubValue, G2, S2>(
9844        self,
9845        next: KpType<V, SubValue, G2, S2>,
9846    ) -> KpType<
9847        R,
9848        SubValue,
9849        impl for<'r> Fn(&'r R) -> Option<&'r SubValue>,
9850        impl for<'r> Fn(&'r mut R) -> Option<&'r mut SubValue>,
9851    >
9852    where
9853        G2: for<'r> Fn(&'r V) -> Option<&'r SubValue>,
9854        S2: for<'r> Fn(&'r mut V) -> Option<&'r mut SubValue>,
9855        V: 'static,
9856    {
9857        KpType::new(
9858            move |root: &R| (self.g)(root).and_then(|value| (next.g)(value)),
9859            move |root: &mut R| (self.s)(root).and_then(|value| (next.s)(value)),
9860        )
9861    }
9862
9863    // /// Convert this keypath to an Arc<Mutex> chain-ready keypath
9864    // /// Returns self, but serves as a marker for intent and enables chaining
9865    // pub fn for_arc_mutex<InnerValue>(self) -> Self
9866    // where
9867    //     V: std::borrow::Borrow<Arc<Mutex<InnerValue>>>,
9868    // {
9869    //     self
9870    // }
9871
9872    // /// Convert this keypath to an Arc<RwLock> chain-ready keypath
9873    // /// Returns self, but serves as a marker for intent and enables chaining
9874    // pub fn for_arc_rwlock<InnerValue>(self) -> Self
9875    // where
9876    //     V: std::borrow::Borrow<Arc<RwLock<InnerValue>>>,
9877    // {
9878    //     self
9879    // }
9880}
9881
9882// Add identity as an associated function
9883impl<R> KpType<R, R, Getter<R, R>, Setter<R, R>> {
9884    /// Creates an identity keypath that returns the value itself
9885    pub fn identity() -> Self {
9886        Kp {
9887            g: |r: &R| Some(r),
9888            s: |r: &mut R| Some(r),
9889            _p: PhantomData,
9890        }
9891    }
9892}
9893
9894impl<R, V, G, S> KpType<R, V, G, S>
9895where
9896    G: for<'r> Fn(&'r R) -> Option<&'r V>,
9897    S: for<'r> Fn(&'r mut R) -> Option<&'r mut V>,
9898{
9899    // Converts Kp<R, V> to Kp<Arc<R>, V>
9900    pub fn for_arc(
9901        self,
9902    ) -> KpType<
9903        Arc<R>,
9904        V,
9905        impl for<'r> Fn(&'r Arc<R>) -> Option<&'r V>,
9906        impl for<'r> Fn(&'r mut Arc<R>) -> Option<&'r mut V>,
9907    > {
9908        KpType {
9909            g: move |root: &Arc<R>| {
9910                // Dereference the Arc to get &R, then apply the original getter
9911                (self.g)(&root)
9912            },
9913            s: move |root: &mut Arc<R>| {
9914                // For mutable access, we need to handle Arc's interior mutability carefully
9915                // This assumes R: Send + Sync for thread safety with Arc
9916                // Note: This will only work if the Arc has exactly one strong reference
9917                // Otherwise, we cannot get a mutable reference
9918
9919                // Try to get a mutable reference from Arc
9920                if let Some(r) = Arc::get_mut(root) {
9921                    (self.s)(r)
9922                } else {
9923                    None
9924                }
9925            },
9926            _p: PhantomData,
9927        }
9928    }
9929
9930    // Converts Kp<R, V> to Kp<Rc<R>, V>
9931    pub fn for_rc(
9932        self,
9933    ) -> KpType<
9934        Rc<R>,
9935        V,
9936        impl for<'r> Fn(&'r Rc<R>) -> Option<&'r V>,
9937        impl for<'r> Fn(&'r mut Rc<R>) -> Option<&'r mut V>,
9938    > {
9939        KpType {
9940            g: move |root: &Rc<R>| (self.g)(&root),
9941            s: move |root: &mut Rc<R>| {
9942                if let Some(r) = Rc::get_mut(root) {
9943                    (self.s)(r)
9944                } else {
9945                    None
9946                }
9947            },
9948            _p: PhantomData,
9949        }
9950    }
9951}
9952
9953struct TestKP {
9954    a: String,
9955    b: String,
9956    c: Arc<String>,
9957    d: Mutex<String>,
9958    e: Arc<Mutex<TestKP2>>,
9959    f: Option<TestKP2>,
9960}
9961
9962impl TestKP {
9963    fn new() -> Self {
9964        Self {
9965            a: String::from("a"),
9966            b: String::from("b"),
9967            c: Arc::new(String::from("c")),
9968            d: Mutex::new(String::from("d")),
9969            e: Arc::new(Mutex::new(TestKP2::new())),
9970            f: Some(TestKP2 {
9971                a: String::from("a3"),
9972                b: Arc::new(Mutex::new(TestKP3::new())),
9973            }),
9974        }
9975    }
9976
9977    // Helper to create an identity keypath for TestKP2
9978    fn identity() -> Kp<TestKP2, TestKP2> {
9979        Kp {
9980            g: |r: &TestKP2| Some(r),
9981            s: |r: &mut TestKP2| Some(r),
9982            _p: PhantomData,
9983        }
9984    }
9985}
9986
9987struct TestKP2 {
9988    a: String,
9989    b: Arc<Mutex<TestKP3>>,
9990}
9991
9992impl TestKP2 {
9993    fn new() -> Self {
9994        TestKP2 {
9995            a: String::from("a2"),
9996            b: Arc::new(Mutex::new(TestKP3::new())),
9997        }
9998    }
9999
10000    fn a() -> Kp<TestKP2, String> {
10001        Kp {
10002            g: |r: &TestKP2| Some(&r.a),
10003            s: |r: &mut TestKP2| Some(&mut r.a),
10004            _p: PhantomData,
10005        }
10006    }
10007
10008    fn b() -> Kp<TestKP2, Arc<Mutex<TestKP3>>> {
10009        Kp {
10010            g: |r: &TestKP2| Some(&r.b),
10011            s: |r: &mut TestKP2| Some(&mut r.b),
10012            _p: PhantomData,
10013        }
10014    }
10015
10016    // fn identity() -> Kp<Self, Self> {
10017    //     Kp::identity()
10018    // }
10019}
10020
10021#[derive(Debug)]
10022struct TestKP3 {
10023    a: String,
10024    b: Arc<Mutex<String>>,
10025}
10026
10027impl TestKP3 {
10028    fn new() -> Self {
10029        TestKP3 {
10030            a: String::from("a2"),
10031            b: Arc::new(Mutex::new(String::from("b2"))),
10032        }
10033    }
10034
10035    fn a() -> Kp<TestKP3, String> {
10036        Kp {
10037            g: |r: &TestKP3| Some(&r.a),
10038            s: |r: &mut TestKP3| Some(&mut r.a),
10039            _p: PhantomData,
10040        }
10041    }
10042
10043    fn b_lock() -> LKp<
10044        Kp<TestKP2, TestKP3>, // Root
10045        Kp<TestKP3, String>,  // MutexValue
10046        TestKP3,              // InnerValue
10047        String,               // SubValue
10048        fn(&TestKP3) -> Option<&String>,
10049        fn(&mut TestKP3) -> Option<&mut String>,
10050    > {
10051        todo!()
10052    }
10053
10054    // fn b() -> Kp<Arc<TestKP3>, Arc<Mutex<String>>> {
10055    //         let k = Kp {
10056    //             g: |r: &TestKP3| Some(&r.b),
10057    //             s: |r: &mut TestKP3| Some(&mut r.b),
10058    //             _p: PhantomData,
10059    //         };
10060    //         k.for_arc_mutex()
10061    //     }
10062
10063    // fn identity() -> Kp<Self, Self> {
10064    //     Kp::identity()
10065    // }
10066}
10067
10068impl TestKP3 {
10069    fn b() -> KpType<
10070        // Arc<TestKP3>,
10071        TestKP3,
10072        Arc<Mutex<String>>,
10073        // impl for<'r> Fn(&'r Arc<TestKP3>) -> Option<&'r Arc<Mutex<String>>>,
10074        impl for<'r> Fn(&'r TestKP3) -> Option<&'r Arc<Mutex<String>>>,
10075        impl for<'r> Fn(&'r mut TestKP3) -> Option<&'r mut Arc<Mutex<String>>>,
10076    > {
10077        Kp {
10078            g: |r: &TestKP3| Some(&r.b),
10079            s: |r: &mut TestKP3| Some(&mut r.b),
10080            _p: PhantomData,
10081        }
10082        // k.for_arc()
10083    }
10084}
10085
10086impl TestKP {
10087    fn a() -> Kp<TestKP, String> {
10088        Kp {
10089            g: |r: &TestKP| Some(&r.a),
10090            s: |r: &mut TestKP| Some(&mut r.a),
10091            _p: PhantomData,
10092        }
10093    }
10094
10095    fn b() -> Kp<TestKP, String> {
10096        Kp {
10097            g: |r: &TestKP| Some(&r.b),
10098            s: |r: &mut TestKP| Some(&mut r.b),
10099            _p: PhantomData,
10100        }
10101    }
10102
10103    fn c() -> Kp<TestKP, String> {
10104        Kp {
10105            g: |r: &TestKP| Some(r.c.as_ref()),
10106            s: |r: &mut TestKP| None,
10107            _p: PhantomData,
10108        }
10109    }
10110
10111    fn d() -> Kp<TestKP, Mutex<String>> {
10112        Kp {
10113            g: |r: &TestKP| Some(&r.d),
10114            s: |r: &mut TestKP| Some(&mut r.d),
10115            _p: PhantomData,
10116        }
10117    }
10118
10119    fn e() -> Kp<TestKP, Arc<Mutex<TestKP2>>> {
10120        Kp {
10121            g: |r: &TestKP| Some(&r.e),
10122            s: |r: &mut TestKP| Some(&mut r.e),
10123            _p: PhantomData,
10124        }
10125    }
10126
10127    fn f() -> Kp<TestKP, TestKP2> {
10128        Kp {
10129            g: |r: &TestKP| r.f.as_ref(),
10130            s: |r: &mut TestKP| r.f.as_mut(),
10131            _p: PhantomData,
10132        }
10133    }
10134}
10135
10136#[cfg(test)]
10137mod testsas {
10138    use super::*;
10139
10140    #[test]
10141    fn test_kp_for_struct() {
10142        let mut i = TestKP::new();
10143        let kp = TestKP::f().then(TestKP2::a());
10144        println!("initial value = {:?}", kp.get(&i));
10145        if let Some(x) = kp.get_mut(&mut i) {
10146            *x = "this is also working".to_string();
10147        }
10148        println!("updated value = {:?}", kp.get(&i));
10149        assert_eq!(kp.get(&i), Some(&"this is also working".to_string()));
10150    }
10151
10152    #[test]
10153    fn test_single_mutex_access() {
10154        let mut root = TestKP::new();
10155
10156        // Create LKp for TestKP.e -> TestKP2.a
10157        let lkp = LKp::new(TestKP::e(), TestKP2::a());
10158
10159        // Get value through mutex
10160        let value = lkp.get_cloned(&root);
10161        println!("Single mutex - initial value: {:?}", value);
10162        assert_eq!(value, Some("a2".to_string()));
10163
10164        // Mutate value through mutex
10165        lkp.get_mut(&mut root, |val| {
10166            *val = "modified a2".to_string();
10167        });
10168
10169        let new_value = lkp.get_cloned(&root);
10170        println!("Single mutex - updated value: {:?}", new_value);
10171        assert_eq!(new_value, Some("modified a2".to_string()));
10172    }
10173
10174    #[test]
10175    fn test_chained_mutex_access() {
10176        let mut root = TestKP::new();
10177
10178        // Create LKp for TestKP.e -> TestKP2
10179        let outer_lkp = LKp::new(TestKP::e(), Kp::identity());
10180
10181        // Chain to TestKP2.b (which is Arc<Mutex<String>>)
10182        let chained_lkp = outer_lkp.then(TestKP2::b());
10183        // Now we have: TestKP.e (Arc<Mutex<TestKP2>>) -> TestKP2 -> TestKP2.b (Arc<Mutex<String>>)
10184        // This gives us access to the Arc<Mutex<String>>
10185        let arc_mutex = chained_lkp.get_cloned(&root);
10186        println!("Chained mutex - Arc<Mutex>: {:?}", arc_mutex);
10187
10188        // To access the inner String, we need to lock it
10189        if let Some(am) = arc_mutex {
10190            if let Ok(guard) = am.lock() {
10191                println!("Chained mutex - inner value: {:?}", *guard);
10192                assert_eq!(*guard.a, "a2".to_string());
10193            }
10194        }
10195
10196        // Mutate the Arc<Mutex<String>> reference itself (swap it out)
10197        chained_lkp.get_mut(&mut root, |arc_mutex_ref| {
10198            *arc_mutex_ref = Arc::new(Mutex::new(TestKP3 {
10199                a: "replaced b2".to_string(),
10200                b: Arc::new(Mutex::new(String::new())),
10201            }));
10202        });
10203
10204        // Verify the change
10205        let new_arc_mutex = chained_lkp.get_cloned(&root);
10206        if let Some(am) = new_arc_mutex {
10207            if let Ok(guard) = am.lock() {
10208                println!("Chained mutex - replaced value: {:?}", *guard);
10209                assert_eq!(*guard.a, "replaced b2".to_string());
10210            }
10211        }
10212    }
10213
10214    #[test]
10215    fn test_double_nested_mutex() {
10216        let mut root = TestKP::new();
10217
10218        // First level: TestKP.e -> TestKP2
10219        let first_lkp: LKp<TestKP, Arc<Mutex<TestKP2>>, TestKP2, TestKP2, _, _> = LKp::new(
10220            TestKP::e(),
10221            Kp {
10222                g: |r: &TestKP2| Some(r),
10223                s: |r: &mut TestKP2| Some(r),
10224                _p: PhantomData,
10225            },
10226        );
10227
10228        // Second level: chain to TestKP2.b (Arc<Mutex<String>>)
10229        // This creates: TestKP -> Arc<Mutex<TestKP2>> -> TestKP2.b
10230        // let second_lkp = first_lkp.then(TestKP2::b()).get_mut(&mut root, |next| {
10231        //     let x = &next.lock().ok().unwrap();
10232        //     let result = TestKP3::b().get(x);
10233
10234        // });
10235
10236        // Now create another LKp to go through the second mutex
10237        // TestKP -> Arc<Mutex<TestKP2>> -> Arc<Mutex<String>> -> String
10238        let final_lkp = LKp::new(TestKP::e(), {
10239            let inner_kp = Kp {
10240                g: |r: &TestKP2| Some(&r.b),
10241                s: |r: &mut TestKP2| Some(&mut r.b),
10242                _p: PhantomData,
10243            };
10244            inner_kp
10245        });
10246
10247        // Access the deeply nested String value
10248        // let value = final_lkp.get_cloned(&root);
10249        // println!("Double nested mutex - value: {:?}", value);
10250
10251        // // The value should be cloned from the inner Arc<Mutex<String>>
10252        // if let Some(arc_string) = value {
10253        //     if let Ok(guard) = arc_string.lock() {
10254        //         assert_eq!(*guard, "b2".to_string());
10255        //     }
10256        // }
10257    }
10258
10259    #[test]
10260    fn test_lkp_then_chaining() {
10261        let mut root = TestKP::new();
10262
10263        // Start with TestKP.e -> TestKP2 (identity)
10264        let first_lkp = LKp::new(TestKP::e(), Kp::identity());
10265
10266        // Chain to TestKP2.a to get: TestKP.e -> TestKP2 -> TestKP2.a
10267        let chained = first_lkp.then(TestKP2::a());
10268
10269        // Access the deeply nested String value
10270        let value = chained.get_cloned(&root);
10271        println!("LKp chained - value: {:?}", value);
10272        assert_eq!(value, Some("a2".to_string()));
10273
10274        // Mutate it
10275        chained.get_mut(&mut root, |val| {
10276            *val = "chained modified".to_string();
10277        });
10278
10279        let new_value = chained.get_cloned(&root);
10280        assert_eq!(new_value, Some("chained modified".to_string()));
10281    }
10282
10283    #[test]
10284    fn test_simple_keypath_composition() {
10285        let mut root = TestKP::new();
10286
10287        // Option 1: Direct access without LKp (when you have a direct path)
10288        let direct_kp = TestKP::f().then(TestKP2::a());
10289        assert_eq!(direct_kp.get(&root), Some(&"a3".to_string()));
10290
10291        // Option 2: Through mutex using LKp
10292        let mutex_lkp = LKp::new(TestKP::e(), TestKP2::a());
10293        assert_eq!(mutex_lkp.get_cloned(&root), Some("a2".to_string()));
10294
10295        // Option 3: Chain LKp for deeper access
10296        let deep_lkp = LKp::new(TestKP::e(), Kp::identity()).then(TestKP2::a());
10297
10298        assert_eq!(deep_lkp.get_cloned(&root), Some("a2".to_string()));
10299    }
10300}
10301
10302// ========== SHR OPERATOR IMPLEMENTATIONS (>> operator) ==========
10303//
10304// The `>>` operator provides the same functionality as `then()` methods.
10305// It requires nightly Rust with the `nightly` feature enabled.
10306//
10307// Usage example (requires nightly):
10308// ```rust
10309// #![feature(impl_trait_in_assoc_type)]  // Must be in YOUR code
10310// use rust_keypaths::{keypath, KeyPath};
10311//
10312// struct User { address: Address }
10313// struct Address { street: String }
10314//
10315// let kp1 = keypath!(|u: &User| &u.address);
10316// let kp2 = keypath!(|a: &Address| &a.street);
10317// let chained = kp1 >> kp2; // Works with nightly feature
10318// ```
10319//
10320// On stable Rust, use `keypath1.then(keypath2)` instead.
10321//
10322// Supported combinations (same as `then()` methods):
10323// - `KeyPath >> KeyPath` → `KeyPath`
10324// - `KeyPath >> OptionalKeyPath` → `OptionalKeyPath`
10325// - `OptionalKeyPath >> OptionalKeyPath` → `OptionalKeyPath`
10326// - `WritableKeyPath >> WritableKeyPath` → `WritableKeyPath`
10327// - `WritableKeyPath >> WritableOptionalKeyPath` → `WritableOptionalKeyPath`
10328// - `WritableOptionalKeyPath >> WritableOptionalKeyPath` → `WritableOptionalKeyPath`
10329
10330// #[cfg(feature = "nightly")]
10331// mod shr_impls {
10332//     use super::*;
10333//
10334//     // Implement Shr for KeyPath >> KeyPath: returns KeyPath
10335//     impl<Root, Value, F, SubValue, G> Shr<KeyPath<Value, SubValue, G>> for KeyPath<Root, Value, F>
10336//     where
10337//         F: for<'r> Fn(&'r Root) -> &'r Value + 'static,
10338//         G: for<'r> Fn(&'r Value) -> &'r SubValue + 'static,
10339//         Value: 'static,
10340//     {
10341//         type Output = KeyPath<Root, SubValue, impl for<'r> Fn(&'r Root) -> &'r SubValue>;
10342//
10343//         fn shr(self, rhs: KeyPath<Value, SubValue, G>) -> Self::Output {
10344//             self.then(rhs)
10345//         }
10346//     }
10347//
10348//     // Implement Shr for KeyPath >> OptionalKeyPath: returns OptionalKeyPath
10349//     impl<Root, Value, F, SubValue, G> Shr<OptionalKeyPath<Value, SubValue, G>> for KeyPath<Root, Value, F>
10350//     where
10351//         F: for<'r> Fn(&'r Root) -> &'r Value + 'static,
10352//         G: for<'r> Fn(&'r Value) -> Option<&'r SubValue> + 'static,
10353//         Value: 'static,
10354//     {
10355//         type Output = OptionalKeyPath<Root, SubValue, impl for<'r> Fn(&'r Root) -> Option<&'r SubValue>>;
10356//
10357//         fn shr(self, rhs: OptionalKeyPath<Value, SubValue, G>) -> Self::Output {
10358//             self.chain_optional(rhs)
10359//         }
10360//     }
10361//
10362//     // Implement Shr for OptionalKeyPath >> OptionalKeyPath: returns OptionalKeyPath
10363//     impl<Root, Value, F, SubValue, G> Shr<OptionalKeyPath<Value, SubValue, G>> for OptionalKeyPath<Root, Value, F>
10364//     where
10365//         F: for<'r> Fn(&'r Root) -> Option<&'r Value> + 'static,
10366//         G: for<'r> Fn(&'r Value) -> Option<&'r SubValue> + 'static,
10367//         Value: 'static,
10368//     {
10369//         type Output = OptionalKeyPath<Root, SubValue, impl for<'r> Fn(&'r Root) -> Option<&'r SubValue>>;
10370//
10371//         fn shr(self, rhs: OptionalKeyPath<Value, SubValue, G>) -> Self::Output {
10372//             self.then(rhs)
10373//         }
10374//     }
10375//
10376//     // Implement Shr for WritableKeyPath >> WritableKeyPath: returns WritableKeyPath
10377//     impl<Root, Value, F, SubValue, G> Shr<WritableKeyPath<Value, SubValue, G>> for WritableKeyPath<Root, Value, F>
10378//     where
10379//         F: for<'r> Fn(&'r mut Root) -> &'r mut Value + 'static,
10380//         G: for<'r> Fn(&'r mut Value) -> &'r mut SubValue + 'static,
10381//         Value: 'static,
10382//     {
10383//         type Output = WritableKeyPath<Root, SubValue, impl for<'r> Fn(&'r mut Root) -> &'r mut SubValue>;
10384//
10385//         fn shr(self, rhs: WritableKeyPath<Value, SubValue, G>) -> Self::Output {
10386//             self.then(rhs)
10387//         }
10388//     }
10389//
10390//     // Implement Shr for WritableKeyPath >> WritableOptionalKeyPath: returns WritableOptionalKeyPath
10391//     impl<Root, Value, F, SubValue, G> Shr<WritableOptionalKeyPath<Value, SubValue, G>> for WritableKeyPath<Root, Value, F>
10392//     where
10393//         F: for<'r> Fn(&'r mut Root) -> &'r mut Value + 'static,
10394//         G: for<'r> Fn(&'r mut Value) -> Option<&'r mut SubValue> + 'static,
10395//         Value: 'static,
10396//     {
10397//         type Output = WritableOptionalKeyPath<Root, SubValue, impl for<'r> Fn(&'r mut Root) -> Option<&'r mut SubValue>>;
10398//
10399//         fn shr(self, rhs: WritableOptionalKeyPath<Value, SubValue, G>) -> Self::Output {
10400//             self.chain_optional(rhs)
10401//         }
10402//     }
10403//
10404//     // Implement Shr for WritableOptionalKeyPath >> WritableOptionalKeyPath: returns WritableOptionalKeyPath
10405//     impl<Root, Value, F, SubValue, G> Shr<WritableOptionalKeyPath<Value, SubValue, G>> for WritableOptionalKeyPath<Root, Value, F>
10406//     where
10407//         F: for<'r> Fn(&'r mut Root) -> Option<&'r mut Value> + 'static,
10408//         G: for<'r> Fn(&'r mut Value) -> Option<&'r mut SubValue> + 'static,
10409//         Value: 'static,
10410//     {
10411//         type Output = WritableOptionalKeyPath<Root, SubValue, impl for<'r> Fn(&'r mut Root) -> Option<&'r mut SubValue>>;
10412//
10413//         fn shr(self, rhs: WritableOptionalKeyPath<Value, SubValue, G>) -> Self::Output {
10414//             self.then(rhs)
10415//         }
10416//     }
10417// }
10418
10419#[cfg(test)]
10420mod tests {
10421    use super::*;
10422    use std::rc::Rc;
10423    use std::sync::atomic::{AtomicUsize, Ordering};
10424
10425    // Global counter to track memory allocations/deallocations
10426    static ALLOC_COUNT: AtomicUsize = AtomicUsize::new(0);
10427    static DEALLOC_COUNT: AtomicUsize = AtomicUsize::new(0);
10428
10429    // Type that panics on clone to detect unwanted cloning
10430    #[derive(Debug)]
10431    struct NoCloneType {
10432        id: usize,
10433        data: String,
10434    }
10435
10436    impl NoCloneType {
10437        fn new(data: String) -> Self {
10438            ALLOC_COUNT.fetch_add(1, Ordering::SeqCst);
10439            Self {
10440                id: ALLOC_COUNT.load(Ordering::SeqCst),
10441                data,
10442            }
10443        }
10444    }
10445
10446    impl Clone for NoCloneType {
10447        fn clone(&self) -> Self {
10448            eprintln!("[DEBUG] NoCloneType should not be cloned! ID: {}", self.id);
10449            unreachable!("NoCloneType should not be cloned! ID: {}", self.id);
10450        }
10451    }
10452
10453    impl Drop for NoCloneType {
10454        fn drop(&mut self) {
10455            DEALLOC_COUNT.fetch_add(1, Ordering::SeqCst);
10456        }
10457    }
10458
10459    // Helper functions for testing memory management
10460    fn reset_memory_counters() {
10461        ALLOC_COUNT.store(0, Ordering::SeqCst);
10462        DEALLOC_COUNT.store(0, Ordering::SeqCst);
10463    }
10464
10465    fn get_alloc_count() -> usize {
10466        ALLOC_COUNT.load(Ordering::SeqCst)
10467    }
10468
10469    fn get_dealloc_count() -> usize {
10470        DEALLOC_COUNT.load(Ordering::SeqCst)
10471    }
10472
10473    // Usage example
10474    #[derive(Debug)]
10475    struct User {
10476        name: String,
10477        metadata: Option<Box<UserMetadata>>,
10478        friends: Vec<Arc<User>>,
10479    }
10480
10481    #[derive(Debug)]
10482    struct UserMetadata {
10483        created_at: String,
10484    }
10485
10486    fn some_fn() {
10487        let akash = User {
10488            name: "Akash".to_string(),
10489            metadata: Some(Box::new(UserMetadata {
10490                created_at: "2024-01-01".to_string(),
10491            })),
10492            friends: vec![Arc::new(User {
10493                name: "Bob".to_string(),
10494                metadata: None,
10495                friends: vec![],
10496            })],
10497        };
10498
10499        // Create keypaths
10500        let name_kp = KeyPath::new(|u: &User| &u.name);
10501        let metadata_kp = OptionalKeyPath::new(|u: &User| u.metadata.as_ref());
10502        let friends_kp = KeyPath::new(|u: &User| &u.friends);
10503
10504        // Use them
10505        println!("Name: {}", name_kp.get(&akash));
10506
10507        if let Some(metadata) = metadata_kp.get(&akash) {
10508            println!("Has metadata: {:?}", metadata);
10509        }
10510
10511        // Access first friend's name
10512        if let Some(first_friend) = akash.friends.get(0) {
10513            println!("First friend: {}", name_kp.get(first_friend));
10514        }
10515
10516        // Access metadata through Box using for_box()
10517        let created_at_kp = KeyPath::new(|m: &UserMetadata| &m.created_at);
10518
10519        if let Some(metadata) = akash.metadata.as_ref() {
10520            // Use for_box() to unwrap Box<UserMetadata> to &UserMetadata
10521            let boxed_metadata: &Box<UserMetadata> = metadata;
10522            let unwrapped = boxed_metadata.as_ref();
10523            println!("Created at: {:?}", created_at_kp.get(unwrapped));
10524        }
10525    }
10526
10527    #[test]
10528    fn test_name() {
10529        some_fn();
10530    }
10531
10532    #[test]
10533    fn test_no_cloning_on_keypath_operations() {
10534        reset_memory_counters();
10535
10536        // Create a value that panics on clone
10537        let value = NoCloneType::new("test".to_string());
10538        let boxed = Box::new(value);
10539
10540        // Create keypath - should not clone
10541        let kp = KeyPath::new(|b: &Box<NoCloneType>| b.as_ref());
10542
10543        // Access value - should not clone
10544        let _ref = kp.get(&boxed);
10545
10546        // Clone the keypath itself (this is allowed)
10547        let _kp_clone = kp.clone();
10548
10549        // Access again - should not clone the value
10550        let _ref2 = _kp_clone.get(&boxed);
10551
10552        // Verify no panics occurred (if we got here, no cloning happened)
10553        assert_eq!(get_alloc_count(), 1);
10554    }
10555
10556    #[test]
10557    fn test_no_cloning_on_optional_keypath_operations() {
10558        reset_memory_counters();
10559
10560        let value = NoCloneType::new("test".to_string());
10561        let opt = Some(Box::new(value));
10562
10563        // Create optional keypath
10564        let okp = OptionalKeyPath::new(|o: &Option<Box<NoCloneType>>| o.as_ref());
10565
10566        // Access - should not clone
10567        let _ref = okp.get(&opt);
10568
10569        // Clone keypath (allowed)
10570        let _okp_clone = okp.clone();
10571
10572        // Chain operations - should not clone values
10573        let chained = okp.then(OptionalKeyPath::new(|b: &Box<NoCloneType>| {
10574            Some(b.as_ref())
10575        }));
10576        let _ref2 = chained.get(&opt);
10577
10578        assert_eq!(get_alloc_count(), 1);
10579    }
10580
10581    #[test]
10582    fn test_memory_release() {
10583        reset_memory_counters();
10584
10585        {
10586            let value = NoCloneType::new("test".to_string());
10587            let boxed = Box::new(value);
10588            let kp = KeyPath::new(|b: &Box<NoCloneType>| b.as_ref());
10589
10590            // Use the keypath
10591            let _ref = kp.get(&boxed);
10592
10593            // boxed goes out of scope here
10594        }
10595
10596        // After drop, memory should be released
10597        // Note: This is a best-effort check since drop timing can vary
10598        assert_eq!(get_alloc_count(), 1);
10599        // Deallocation happens when the value is dropped
10600        // We can't reliably test exact timing, but we verify the counter exists
10601    }
10602
10603    #[test]
10604    fn test_keypath_clone_does_not_clone_underlying_data() {
10605        reset_memory_counters();
10606
10607        let value = NoCloneType::new("data".to_string());
10608        let rc_value = Rc::new(value);
10609
10610        // Create keypath
10611        let kp = KeyPath::new(|r: &Rc<NoCloneType>| r.as_ref());
10612
10613        // Clone keypath multiple times
10614        let kp1 = kp.clone();
10615        let kp2 = kp.clone();
10616        let kp3 = kp1.clone();
10617
10618        // All should work without cloning the underlying data
10619        let _ref1 = kp.get(&rc_value);
10620        let _ref2 = kp1.get(&rc_value);
10621        let _ref3 = kp2.get(&rc_value);
10622        let _ref4 = kp3.get(&rc_value);
10623
10624        // Only one allocation should have happened
10625        assert_eq!(get_alloc_count(), 1);
10626    }
10627
10628    #[test]
10629    fn test_optional_keypath_chaining_no_clone() {
10630        reset_memory_counters();
10631
10632        let value = NoCloneType::new("value1".to_string());
10633
10634        struct Container {
10635            inner: Option<Box<NoCloneType>>,
10636        }
10637
10638        let container = Container {
10639            inner: Some(Box::new(value)),
10640        };
10641
10642        // Create chained keypath
10643        let kp1 = OptionalKeyPath::new(|c: &Container| c.inner.as_ref());
10644        let kp2 = OptionalKeyPath::new(|b: &Box<NoCloneType>| Some(b.as_ref()));
10645
10646        // Chain them - should not clone
10647        let chained = kp1.then(kp2);
10648
10649        // Use chained keypath
10650        let _result = chained.get(&container);
10651
10652        // Should only have one allocation
10653        assert_eq!(get_alloc_count(), 1);
10654    }
10655
10656    #[test]
10657    fn test_for_box_no_clone() {
10658        reset_memory_counters();
10659
10660        let value = NoCloneType::new("test".to_string());
10661        let boxed = Box::new(value);
10662        let opt_boxed = Some(boxed);
10663
10664        // Create keypath with for_box
10665        let kp = OptionalKeyPath::new(|o: &Option<Box<NoCloneType>>| o.as_ref());
10666        let unwrapped = kp.for_box();
10667
10668        // Access - should not clone
10669        let _ref = unwrapped.get(&opt_boxed);
10670
10671        assert_eq!(get_alloc_count(), 1);
10672    }
10673
10674    // ========== MACRO USAGE EXAMPLES ==========
10675
10676    #[derive(Debug, PartialEq)]
10677    struct TestUser {
10678        name: String,
10679        age: u32,
10680        metadata: Option<String>,
10681        address: Option<TestAddress>,
10682    }
10683
10684    #[derive(Debug, PartialEq)]
10685    struct TestAddress {
10686        street: String,
10687        city: String,
10688        country: Option<TestCountry>,
10689    }
10690
10691    #[derive(Debug, PartialEq)]
10692    struct TestCountry {
10693        name: String,
10694    }
10695
10696    #[test]
10697    fn test_keypath_macro() {
10698        let user = TestUser {
10699            name: "Akash".to_string(),
10700            age: 30,
10701            metadata: None,
10702            address: None,
10703        };
10704
10705        // Simple field access using closure
10706        let name_kp = keypath!(|u: &TestUser| &u.name);
10707        assert_eq!(name_kp.get(&user), "Akash");
10708
10709        // Nested field access
10710        let user_with_address = TestUser {
10711            name: "Bob".to_string(),
10712            age: 25,
10713            metadata: None,
10714            address: Some(TestAddress {
10715                street: "123 Main St".to_string(),
10716                city: "New York".to_string(),
10717                country: None,
10718            }),
10719        };
10720
10721        let street_kp = keypath!(|u: &TestUser| &u.address.as_ref().unwrap().street);
10722        assert_eq!(street_kp.get(&user_with_address), "123 Main St");
10723
10724        // Deeper nesting
10725        let user_with_country = TestUser {
10726            name: "Charlie".to_string(),
10727            age: 35,
10728            metadata: None,
10729            address: Some(TestAddress {
10730                street: "456 Oak Ave".to_string(),
10731                city: "London".to_string(),
10732                country: Some(TestCountry {
10733                    name: "UK".to_string(),
10734                }),
10735            }),
10736        };
10737
10738        let country_name_kp =
10739            keypath!(|u: &TestUser| &u.address.as_ref().unwrap().country.as_ref().unwrap().name);
10740        assert_eq!(country_name_kp.get(&user_with_country), "UK");
10741
10742        // Fallback: using closure
10743        let age_kp = keypath!(|u: &TestUser| &u.age);
10744        assert_eq!(age_kp.get(&user), &30);
10745    }
10746
10747    #[test]
10748    fn test_opt_keypath_macro() {
10749        let user = TestUser {
10750            name: "Akash".to_string(),
10751            age: 30,
10752            metadata: Some("admin".to_string()),
10753            address: None,
10754        };
10755
10756        // Simple Option field access using closure
10757        let metadata_kp = opt_keypath!(|u: &TestUser| u.metadata.as_ref());
10758        assert_eq!(metadata_kp.get(&user), Some(&"admin".to_string()));
10759
10760        // None case
10761        let user_no_metadata = TestUser {
10762            name: "Bob".to_string(),
10763            age: 25,
10764            metadata: None,
10765            address: None,
10766        };
10767        assert_eq!(metadata_kp.get(&user_no_metadata), None);
10768
10769        // Nested Option access
10770        let user_with_address = TestUser {
10771            name: "Charlie".to_string(),
10772            age: 35,
10773            metadata: None,
10774            address: Some(TestAddress {
10775                street: "789 Pine Rd".to_string(),
10776                city: "Paris".to_string(),
10777                country: None,
10778            }),
10779        };
10780
10781        let street_kp = opt_keypath!(|u: &TestUser| u.address.as_ref().map(|a| &a.street));
10782        assert_eq!(
10783            street_kp.get(&user_with_address),
10784            Some(&"789 Pine Rd".to_string())
10785        );
10786
10787        // Deeper nesting through Options
10788        let user_with_country = TestUser {
10789            name: "David".to_string(),
10790            age: 40,
10791            metadata: None,
10792            address: Some(TestAddress {
10793                street: "321 Elm St".to_string(),
10794                city: "Tokyo".to_string(),
10795                country: Some(TestCountry {
10796                    name: "Japan".to_string(),
10797                }),
10798            }),
10799        };
10800
10801        let country_name_kp = opt_keypath!(|u: &TestUser| u
10802            .address
10803            .as_ref()
10804            .and_then(|a| a.country.as_ref().map(|c| &c.name)));
10805        assert_eq!(
10806            country_name_kp.get(&user_with_country),
10807            Some(&"Japan".to_string())
10808        );
10809
10810        // Fallback: using closure
10811        let metadata_kp2 = opt_keypath!(|u: &TestUser| u.metadata.as_ref());
10812        assert_eq!(metadata_kp2.get(&user), Some(&"admin".to_string()));
10813    }
10814
10815    #[test]
10816    fn test_writable_keypath_macro() {
10817        let mut user = TestUser {
10818            name: "Akash".to_string(),
10819            age: 30,
10820            metadata: None,
10821            address: None,
10822        };
10823
10824        // Simple field mutation using closure
10825        let name_kp = writable_keypath!(|u: &mut TestUser| &mut u.name);
10826        *name_kp.get_mut(&mut user) = "Bob".to_string();
10827        assert_eq!(user.name, "Bob");
10828
10829        // Nested field mutation
10830        let mut user_with_address = TestUser {
10831            name: "Charlie".to_string(),
10832            age: 25,
10833            metadata: None,
10834            address: Some(TestAddress {
10835                street: "123 Main St".to_string(),
10836                city: "New York".to_string(),
10837                country: None,
10838            }),
10839        };
10840
10841        let street_kp =
10842            writable_keypath!(|u: &mut TestUser| &mut u.address.as_mut().unwrap().street);
10843        *street_kp.get_mut(&mut user_with_address) = "456 Oak Ave".to_string();
10844        assert_eq!(
10845            user_with_address.address.as_ref().unwrap().street,
10846            "456 Oak Ave"
10847        );
10848
10849        // Deeper nesting
10850        let mut user_with_country = TestUser {
10851            name: "David".to_string(),
10852            age: 35,
10853            metadata: None,
10854            address: Some(TestAddress {
10855                street: "789 Pine Rd".to_string(),
10856                city: "London".to_string(),
10857                country: Some(TestCountry {
10858                    name: "UK".to_string(),
10859                }),
10860            }),
10861        };
10862
10863        let country_name_kp = writable_keypath!(|u: &mut TestUser| &mut u
10864            .address
10865            .as_mut()
10866            .unwrap()
10867            .country
10868            .as_mut()
10869            .unwrap()
10870            .name);
10871        *country_name_kp.get_mut(&mut user_with_country) = "United Kingdom".to_string();
10872        assert_eq!(
10873            user_with_country
10874                .address
10875                .as_ref()
10876                .unwrap()
10877                .country
10878                .as_ref()
10879                .unwrap()
10880                .name,
10881            "United Kingdom"
10882        );
10883
10884        // Fallback: using closure
10885        let age_kp = writable_keypath!(|u: &mut TestUser| &mut u.age);
10886        *age_kp.get_mut(&mut user) = 31;
10887        assert_eq!(user.age, 31);
10888    }
10889
10890    #[test]
10891    fn test_writable_opt_keypath_macro() {
10892        let mut user = TestUser {
10893            name: "Akash".to_string(),
10894            age: 30,
10895            metadata: Some("user".to_string()),
10896            address: None,
10897        };
10898
10899        // Simple Option field mutation using closure
10900        let metadata_kp = writable_opt_keypath!(|u: &mut TestUser| u.metadata.as_mut());
10901        if let Some(metadata) = metadata_kp.get_mut(&mut user) {
10902            *metadata = "admin".to_string();
10903        }
10904        assert_eq!(user.metadata, Some("admin".to_string()));
10905
10906        // None case - should return None
10907        let mut user_no_metadata = TestUser {
10908            name: "Bob".to_string(),
10909            age: 25,
10910            metadata: None,
10911            address: None,
10912        };
10913        assert_eq!(metadata_kp.get_mut(&mut user_no_metadata), None);
10914
10915        // Nested Option access
10916        let mut user_with_address = TestUser {
10917            name: "Charlie".to_string(),
10918            age: 35,
10919            metadata: None,
10920            address: Some(TestAddress {
10921                street: "123 Main St".to_string(),
10922                city: "New York".to_string(),
10923                country: None,
10924            }),
10925        };
10926
10927        let street_kp =
10928            writable_opt_keypath!(|u: &mut TestUser| u.address.as_mut().map(|a| &mut a.street));
10929        if let Some(street) = street_kp.get_mut(&mut user_with_address) {
10930            *street = "456 Oak Ave".to_string();
10931        }
10932        assert_eq!(
10933            user_with_address.address.as_ref().unwrap().street,
10934            "456 Oak Ave"
10935        );
10936
10937        // Deeper nesting through Options
10938        let mut user_with_country = TestUser {
10939            name: "David".to_string(),
10940            age: 40,
10941            metadata: None,
10942            address: Some(TestAddress {
10943                street: "789 Pine Rd".to_string(),
10944                city: "Tokyo".to_string(),
10945                country: Some(TestCountry {
10946                    name: "Japan".to_string(),
10947                }),
10948            }),
10949        };
10950
10951        let country_name_kp = writable_opt_keypath!(|u: &mut TestUser| u
10952            .address
10953            .as_mut()
10954            .and_then(|a| a.country.as_mut().map(|c| &mut c.name)));
10955        if let Some(country_name) = country_name_kp.get_mut(&mut user_with_country) {
10956            *country_name = "Nippon".to_string();
10957        }
10958        assert_eq!(
10959            user_with_country
10960                .address
10961                .as_ref()
10962                .unwrap()
10963                .country
10964                .as_ref()
10965                .unwrap()
10966                .name,
10967            "Nippon"
10968        );
10969
10970        // Fallback: using closure
10971        let metadata_kp2 = writable_opt_keypath!(|u: &mut TestUser| u.metadata.as_mut());
10972        if let Some(metadata) = metadata_kp2.get_mut(&mut user) {
10973            *metadata = "super_admin".to_string();
10974        }
10975        assert_eq!(user.metadata, Some("super_admin".to_string()));
10976    }
10977
10978    // ========== map HOF tests ==========
10979
10980    #[test]
10981    fn test_keypath_map() {
10982        #[derive(Debug)]
10983        struct WithLen {
10984            name: String,
10985            len: usize,
10986        }
10987        let w = WithLen {
10988            name: "world".to_string(),
10989            len: 5,
10990        };
10991        let kp = KeyPath::new(|w: &WithLen| w);
10992        let len_kp = kp.map(|w: &WithLen| &w.len);
10993        assert_eq!(*len_kp.get(&w), 5);
10994
10995        let kp2 = KeyPath::new(|w: &WithLen| w);
10996        let name_kp = kp2.map(|w: &WithLen| &w.name);
10997        assert_eq!(name_kp.get(&w).as_str(), "world");
10998    }
10999
11000    #[test]
11001    fn test_optional_keypath_map() {
11002        #[derive(Debug)]
11003        struct WithLen {
11004            len: usize,
11005        }
11006        let kp = OptionalKeyPath::new(|o: &Option<WithLen>| o.as_ref());
11007        let len_kp = kp.map(|w: &WithLen| &w.len);
11008        assert_eq!(*len_kp.get(&Some(WithLen { len: 42 })).unwrap(), 42);
11009        assert!(len_kp.get(&None::<WithLen>).is_none());
11010
11011        #[derive(Debug)]
11012        struct WithName {
11013            name: String,
11014        }
11015        let kp2 = OptionalKeyPath::new(|o: &Option<WithName>| o.as_ref());
11016        let name_kp = kp2.map(|w: &WithName| &w.name);
11017        assert_eq!(
11018            name_kp.get(&Some(WithName { name: "foo".to_string() })),
11019            Some(&"foo".to_string())
11020        );
11021    }
11022
11023    #[test]
11024    fn test_writable_keypath_map() {
11025        #[derive(Debug)]
11026        struct Pair {
11027            x: u32,
11028            y: u32,
11029        }
11030        let kp = WritableKeyPath::new(|p: &mut Pair| p);
11031        let y_kp = kp.map(|p: &mut Pair| &mut p.y);
11032        let mut p = Pair { x: 1, y: 2 };
11033        *y_kp.get_mut(&mut p) = 42;
11034        assert_eq!(p.y, 42);
11035        assert_eq!(p.x, 1);
11036    }
11037
11038    #[test]
11039    fn test_writable_optional_keypath_map() {
11040        #[derive(Debug)]
11041        struct Item {
11042            value: i32,
11043        }
11044        let kp = WritableOptionalKeyPath::new(|o: &mut Option<Item>| o.as_mut());
11045        let value_kp = kp.map(|item: &mut Item| &mut item.value);
11046        let mut some_item = Some(Item { value: 10 });
11047        if let Some(v) = value_kp.get_mut(&mut some_item) {
11048            *v = 20;
11049        }
11050        assert_eq!(some_item.unwrap().value, 20);
11051
11052        let mut none_item: Option<Item> = None;
11053        assert!(value_kp.get_mut(&mut none_item).is_none());
11054    }
11055
11056    #[test]
11057    fn test_keypath_map_optional() {
11058        #[derive(Debug)]
11059        struct WithVec {
11060            vec_field: Vec<String>,
11061        }
11062        let vec_kp = KeyPath::new(|w: &WithVec| &w.vec_field);
11063        let first_kp = vec_kp.map_optional(|x: &Vec<String>| x.first());
11064        let value = WithVec {
11065            vec_field: vec!["a".into(), "b".into()],
11066        };
11067        assert_eq!(first_kp.get(&value), Some(&"a".to_string()));
11068        let empty = WithVec {
11069            vec_field: vec![],
11070        };
11071        assert!(first_kp.get(&empty).is_none());
11072    }
11073
11074    #[test]
11075    fn test_optional_keypath_map_optional() {
11076        #[derive(Debug)]
11077        struct WithVec {
11078            vec_field: Vec<String>,
11079        }
11080        let kp = OptionalKeyPath::new(|o: &Option<WithVec>| o.as_ref());
11081        let first_kp = kp.map_optional(|w: &WithVec| w.vec_field.first());
11082        assert_eq!(
11083            first_kp.get(&Some(WithVec {
11084                vec_field: vec!["x".into()]
11085            })),
11086            Some(&"x".to_string())
11087        );
11088        assert!(first_kp.get(&None::<WithVec>).is_none());
11089    }
11090
11091    #[test]
11092    fn test_keypath_identity() {
11093        let kp = KeyPath::<i32, i32, _>::identity();
11094        let x = 42;
11095        assert!(std::ptr::eq(kp.get(&x), &x));
11096        let s = "hello".to_string();
11097        let kp_s = KeyPath::<String, String, _>::identity();
11098        assert!(std::ptr::eq(kp_s.get(&s), &s));
11099    }
11100
11101    #[test]
11102    fn test_optional_keypath_identity() {
11103        let kp = OptionalKeyPath::<i32, i32, _>::identity();
11104        let x = 42;
11105        assert_eq!(kp.get(&x), Some(&x));
11106        assert!(std::ptr::eq(kp.get(&x).unwrap(), &x));
11107    }
11108
11109    #[test]
11110    fn test_writable_keypath_identity() {
11111        let kp = WritableKeyPath::<i32, i32, _>::identity();
11112        let mut x = 42;
11113        assert!(std::ptr::eq(kp.get_mut(&mut x), &mut x));
11114    }
11115
11116    #[test]
11117    fn test_writable_optional_keypath_identity() {
11118        let kp = WritableOptionalKeyPath::<i32, i32, _>::identity();
11119        let mut x = 42;
11120        assert_eq!(kp.get_mut(&mut x).map(|r| *r), Some(42));
11121        assert!(std::ptr::eq(kp.get_mut(&mut x).unwrap(), &mut x));
11122    }
11123
11124    #[test]
11125    fn test_enum_keypath_identity() {
11126        let kp = EnumKeyPath::identity::<i32>();
11127        let x = 42;
11128        assert_eq!(kp.get(&x), Some(&x));
11129        assert!(std::ptr::eq(kp.get(&x).unwrap(), &x));
11130        assert_eq!(kp.embed(100), 100);
11131    }
11132}
11133
11134// ========== WithContainer Trait ==========
11135
11136/// Trait for no-clone callback-based access to container types
11137/// Provides methods to execute closures with references to values inside containers
11138/// without requiring cloning of the values
11139pub trait WithContainer<Root, Value> {
11140    /// Execute a closure with a reference to the value inside an Arc
11141    fn with_arc<F, R>(&self, arc: &Arc<Root>, f: F) -> R
11142    where
11143        F: FnOnce(&Value) -> R;
11144
11145    /// Execute a closure with a reference to the value inside a Box
11146    fn with_box<F, R>(&self, boxed: &Box<Root>, f: F) -> R
11147    where
11148        F: FnOnce(&Value) -> R;
11149
11150    /// Execute a closure with a mutable reference to the value inside a Box
11151    fn with_box_mut<F, R>(&self, boxed: &mut Box<Root>, f: F) -> R
11152    where
11153        F: FnOnce(&mut Value) -> R;
11154
11155    /// Execute a closure with a reference to the value inside an Rc
11156    fn with_rc<F, R>(&self, rc: &Rc<Root>, f: F) -> R
11157    where
11158        F: FnOnce(&Value) -> R;
11159
11160    /// Execute a closure with a reference to the value inside a Result
11161    fn with_result<F, R, E>(&self, result: &Result<Root, E>, f: F) -> Option<R>
11162    where
11163        F: FnOnce(&Value) -> R;
11164
11165    /// Execute a closure with a mutable reference to the value inside a Result
11166    fn with_result_mut<F, R, E>(&self, result: &mut Result<Root, E>, f: F) -> Option<R>
11167    where
11168        F: FnOnce(&mut Value) -> R;
11169
11170    /// Execute a closure with a reference to the value inside an Option
11171    fn with_option<F, R>(&self, option: &Option<Root>, f: F) -> Option<R>
11172    where
11173        F: FnOnce(&Value) -> R;
11174
11175    /// Execute a closure with a mutable reference to the value inside an Option
11176    fn with_option_mut<F, R>(&self, option: &mut Option<Root>, f: F) -> Option<R>
11177    where
11178        F: FnOnce(&mut Value) -> R;
11179
11180    /// Execute a closure with a reference to the value inside a RefCell
11181    fn with_refcell<F, R>(&self, refcell: &RefCell<Root>, f: F) -> Option<R>
11182    where
11183        F: FnOnce(&Value) -> R;
11184
11185    /// Execute a closure with a mutable reference to the value inside a RefCell
11186    fn with_refcell_mut<F, R>(&self, refcell: &RefCell<Root>, f: F) -> Option<R>
11187    where
11188        F: FnOnce(&mut Value) -> R;
11189
11190    #[cfg(feature = "tagged")]
11191    /// Execute a closure with a reference to the value inside a Tagged
11192    fn with_tagged<F, R, Tag>(&self, tagged: &Tagged<Root, Tag>, f: F) -> R
11193    where
11194        Tagged<Root, Tag>: std::ops::Deref<Target = Root>,
11195        F: FnOnce(&Value) -> R;
11196
11197    /// Execute a closure with a reference to the value inside a Mutex
11198    fn with_mutex<F, R>(&self, mutex: &Mutex<Root>, f: F) -> Option<R>
11199    where
11200        F: FnOnce(&Value) -> R;
11201
11202    /// Execute a closure with a mutable reference to the value inside a Mutex
11203    fn with_mutex_mut<F, R>(&self, mutex: &mut Mutex<Root>, f: F) -> Option<R>
11204    where
11205        F: FnOnce(&mut Value) -> R;
11206
11207    /// Execute a closure with a reference to the value inside an RwLock
11208    fn with_rwlock<F, R>(&self, rwlock: &RwLock<Root>, f: F) -> Option<R>
11209    where
11210        F: FnOnce(&Value) -> R;
11211
11212    /// Execute a closure with a mutable reference to the value inside an RwLock
11213    fn with_rwlock_mut<F, R>(&self, rwlock: &mut RwLock<Root>, f: F) -> Option<R>
11214    where
11215        F: FnOnce(&mut Value) -> R;
11216
11217    /// Execute a closure with a reference to the value inside an Arc<RwLock<Root>>
11218    fn with_arc_rwlock<F, R>(&self, arc_rwlock: &Arc<RwLock<Root>>, f: F) -> Option<R>
11219    where
11220        F: FnOnce(&Value) -> R;
11221
11222    /// Execute a closure with a mutable reference to the value inside an Arc<RwLock<Root>>
11223    fn with_arc_rwlock_mut<F, R>(&self, arc_rwlock: &Arc<RwLock<Root>>, f: F) -> Option<R>
11224    where
11225        F: FnOnce(&mut Value) -> R;
11226}
11227
11228// Implement WithContainer for KeyPath
11229impl<Root, Value, F> WithContainer<Root, Value> for KeyPath<Root, Value, F>
11230where
11231    F: for<'r> Fn(&'r Root) -> &'r Value + Clone,
11232{
11233    fn with_arc<Callback, R>(&self, arc: &Arc<Root>, f: Callback) -> R
11234    where
11235        Callback: FnOnce(&Value) -> R,
11236    {
11237        self.with_arc(arc, f)
11238    }
11239
11240    fn with_box<Callback, R>(&self, boxed: &Box<Root>, f: Callback) -> R
11241    where
11242        Callback: FnOnce(&Value) -> R,
11243    {
11244        self.with_box(boxed, f)
11245    }
11246
11247    fn with_box_mut<Callback, R>(&self, _boxed: &mut Box<Root>, _f: Callback) -> R
11248    where
11249        Callback: FnOnce(&mut Value) -> R,
11250    {
11251        eprintln!("[DEBUG] KeyPath does not support mutable access - use WritableKeyPath instead");
11252        unreachable!("KeyPath does not support mutable access - use WritableKeyPath instead")
11253    }
11254
11255    fn with_rc<Callback, R>(&self, rc: &Rc<Root>, f: Callback) -> R
11256    where
11257        Callback: FnOnce(&Value) -> R,
11258    {
11259        self.with_rc(rc, f)
11260    }
11261
11262    fn with_result<Callback, R, E>(&self, result: &Result<Root, E>, f: Callback) -> Option<R>
11263    where
11264        Callback: FnOnce(&Value) -> R,
11265    {
11266        self.with_result(result, f)
11267    }
11268
11269    fn with_result_mut<Callback, R, E>(
11270        &self,
11271        _result: &mut Result<Root, E>,
11272        _f: Callback,
11273    ) -> Option<R>
11274    where
11275        Callback: FnOnce(&mut Value) -> R,
11276    {
11277        None
11278    }
11279
11280    fn with_option<Callback, R>(&self, option: &Option<Root>, f: Callback) -> Option<R>
11281    where
11282        Callback: FnOnce(&Value) -> R,
11283    {
11284        self.with_option(option, f)
11285    }
11286
11287    fn with_option_mut<Callback, R>(&self, _option: &mut Option<Root>, _f: Callback) -> Option<R>
11288    where
11289        Callback: FnOnce(&mut Value) -> R,
11290    {
11291        None
11292    }
11293
11294    fn with_refcell<Callback, R>(&self, refcell: &RefCell<Root>, f: Callback) -> Option<R>
11295    where
11296        Callback: FnOnce(&Value) -> R,
11297    {
11298        self.with_refcell(refcell, f)
11299    }
11300
11301    fn with_refcell_mut<Callback, R>(&self, _refcell: &RefCell<Root>, _f: Callback) -> Option<R>
11302    where
11303        Callback: FnOnce(&mut Value) -> R,
11304    {
11305        None
11306    }
11307
11308    #[cfg(feature = "tagged")]
11309    fn with_tagged<Callback, R, Tag>(&self, tagged: &Tagged<Root, Tag>, f: Callback) -> R
11310    where
11311        Tagged<Root, Tag>: std::ops::Deref<Target = Root>,
11312        Callback: FnOnce(&Value) -> R,
11313    {
11314        self.with_tagged(tagged, f)
11315    }
11316
11317    fn with_mutex<Callback, R>(&self, mutex: &Mutex<Root>, f: Callback) -> Option<R>
11318    where
11319        Callback: FnOnce(&Value) -> R,
11320    {
11321        self.with_mutex(mutex, f)
11322    }
11323
11324    fn with_mutex_mut<Callback, R>(&self, _mutex: &mut Mutex<Root>, _f: Callback) -> Option<R>
11325    where
11326        Callback: FnOnce(&mut Value) -> R,
11327    {
11328        None
11329    }
11330
11331    fn with_rwlock<Callback, R>(&self, rwlock: &RwLock<Root>, f: Callback) -> Option<R>
11332    where
11333        Callback: FnOnce(&Value) -> R,
11334    {
11335        self.with_rwlock(rwlock, f)
11336    }
11337
11338    fn with_rwlock_mut<Callback, R>(&self, _rwlock: &mut RwLock<Root>, _f: Callback) -> Option<R>
11339    where
11340        Callback: FnOnce(&mut Value) -> R,
11341    {
11342        None
11343    }
11344
11345    fn with_arc_rwlock<Callback, R>(&self, arc_rwlock: &Arc<RwLock<Root>>, f: Callback) -> Option<R>
11346    where
11347        Callback: FnOnce(&Value) -> R,
11348    {
11349        self.with_arc_rwlock(arc_rwlock, f)
11350    }
11351
11352    fn with_arc_rwlock_mut<Callback, R>(
11353        &self,
11354        _arc_rwlock: &Arc<RwLock<Root>>,
11355        _f: Callback,
11356    ) -> Option<R>
11357    where
11358        Callback: FnOnce(&mut Value) -> R,
11359    {
11360        None
11361    }
11362}
11363
11364// Implement WithContainer for OptionalKeyPath - read-only operations only
11365impl<Root, Value, F> WithContainer<Root, Value> for OptionalKeyPath<Root, Value, F>
11366where
11367    F: for<'r> Fn(&'r Root) -> Option<&'r Value> + Clone,
11368{
11369    fn with_arc<Callback, R>(&self, arc: &Arc<Root>, f: Callback) -> R
11370    where
11371        Callback: FnOnce(&Value) -> R,
11372    {
11373        self.with_arc(arc, f)
11374    }
11375
11376    fn with_box<Callback, R>(&self, boxed: &Box<Root>, f: Callback) -> R
11377    where
11378        Callback: FnOnce(&Value) -> R,
11379    {
11380        self.with_box(boxed, f)
11381    }
11382
11383    fn with_box_mut<Callback, R>(&self, _boxed: &mut Box<Root>, _f: Callback) -> R
11384    where
11385        Callback: FnOnce(&mut Value) -> R,
11386    {
11387        eprintln!(
11388            "[DEBUG] OptionalKeyPath does not support mutable access - use WritableOptionalKeyPath instead"
11389        );
11390        unreachable!(
11391            "OptionalKeyPath does not support mutable access - use WritableOptionalKeyPath instead"
11392        )
11393    }
11394
11395    fn with_rc<Callback, R>(&self, rc: &Rc<Root>, f: Callback) -> R
11396    where
11397        Callback: FnOnce(&Value) -> R,
11398    {
11399        self.with_rc(rc, f)
11400    }
11401
11402    fn with_result<Callback, R, E>(&self, result: &Result<Root, E>, f: Callback) -> Option<R>
11403    where
11404        Callback: FnOnce(&Value) -> R,
11405    {
11406        self.with_result(result, f)
11407    }
11408
11409    fn with_result_mut<Callback, R, E>(
11410        &self,
11411        _result: &mut Result<Root, E>,
11412        _f: Callback,
11413    ) -> Option<R>
11414    where
11415        Callback: FnOnce(&mut Value) -> R,
11416    {
11417        None // OptionalKeyPath doesn't support mutable access
11418    }
11419
11420    fn with_option<Callback, R>(&self, option: &Option<Root>, f: Callback) -> Option<R>
11421    where
11422        Callback: FnOnce(&Value) -> R,
11423    {
11424        self.with_option(option, f)
11425    }
11426
11427    fn with_option_mut<Callback, R>(&self, _option: &mut Option<Root>, _f: Callback) -> Option<R>
11428    where
11429        Callback: FnOnce(&mut Value) -> R,
11430    {
11431        None // OptionalKeyPath doesn't support mutable access
11432    }
11433
11434    fn with_refcell<Callback, R>(&self, refcell: &RefCell<Root>, f: Callback) -> Option<R>
11435    where
11436        Callback: FnOnce(&Value) -> R,
11437    {
11438        self.with_refcell(refcell, f)
11439    }
11440
11441    fn with_refcell_mut<Callback, R>(&self, _refcell: &RefCell<Root>, _f: Callback) -> Option<R>
11442    where
11443        Callback: FnOnce(&mut Value) -> R,
11444    {
11445        None // OptionalKeyPath doesn't support mutable access
11446    }
11447
11448    #[cfg(feature = "tagged")]
11449    fn with_tagged<Callback, R, Tag>(&self, tagged: &Tagged<Root, Tag>, f: Callback) -> R
11450    where
11451        Tagged<Root, Tag>: std::ops::Deref<Target = Root>,
11452        Callback: FnOnce(&Value) -> R,
11453    {
11454        use std::ops::Deref;
11455        self.get(tagged.deref())
11456            .map(|value| f(value))
11457            .expect("OptionalKeyPath::with_tagged: Tagged should always contain a value that matches the keypath")
11458    }
11459
11460    fn with_mutex<Callback, R>(&self, mutex: &Mutex<Root>, f: Callback) -> Option<R>
11461    where
11462        Callback: FnOnce(&Value) -> R,
11463    {
11464        self.with_mutex(mutex, f)
11465    }
11466
11467    fn with_mutex_mut<Callback, R>(&self, _mutex: &mut Mutex<Root>, _f: Callback) -> Option<R>
11468    where
11469        Callback: FnOnce(&mut Value) -> R,
11470    {
11471        None // OptionalKeyPath doesn't support mutable access
11472    }
11473
11474    fn with_rwlock<Callback, R>(&self, rwlock: &RwLock<Root>, f: Callback) -> Option<R>
11475    where
11476        Callback: FnOnce(&Value) -> R,
11477    {
11478        self.with_rwlock(rwlock, f)
11479    }
11480
11481    fn with_rwlock_mut<Callback, R>(&self, _rwlock: &mut RwLock<Root>, _f: Callback) -> Option<R>
11482    where
11483        Callback: FnOnce(&mut Value) -> R,
11484    {
11485        None // OptionalKeyPath doesn't support mutable access
11486    }
11487
11488    fn with_arc_rwlock<Callback, R>(&self, arc_rwlock: &Arc<RwLock<Root>>, f: Callback) -> Option<R>
11489    where
11490        Callback: FnOnce(&Value) -> R,
11491    {
11492        self.with_arc_rwlock(arc_rwlock, f)
11493    }
11494
11495    fn with_arc_rwlock_mut<Callback, R>(
11496        &self,
11497        _arc_rwlock: &Arc<RwLock<Root>>,
11498        _f: Callback,
11499    ) -> Option<R>
11500    where
11501        Callback: FnOnce(&mut Value) -> R,
11502    {
11503        None // OptionalKeyPath doesn't support mutable access - use WritableOptionalKeyPath instead
11504    }
11505}
11506
11507// Implement WithContainer for WritableKeyPath - supports all mutable operations
11508impl<Root, Value, F> WithContainer<Root, Value> for WritableKeyPath<Root, Value, F>
11509where
11510    F: for<'r> Fn(&'r mut Root) -> &'r mut Value,
11511{
11512    fn with_arc<Callback, R>(&self, _arc: &Arc<Root>, _f: Callback) -> R
11513    where
11514        Callback: FnOnce(&Value) -> R,
11515    {
11516        // Arc doesn't support mutable access without interior mutability
11517        // This method requires &mut Arc<Root> which we don't have
11518        eprintln!(
11519            "[DEBUG] WritableKeyPath::with_arc requires &mut Arc<Root> or interior mutability"
11520        );
11521        unreachable!("WritableKeyPath::with_arc requires &mut Arc<Root> or interior mutability")
11522    }
11523
11524    fn with_box<Callback, R>(&self, boxed: &Box<Root>, f: Callback) -> R
11525    where
11526        Callback: FnOnce(&Value) -> R,
11527    {
11528        // Box doesn't support getting mutable reference from immutable reference
11529        // This is a limitation - we'd need &mut Box<Root> for mutable access
11530        eprintln!(
11531            "[DEBUG] WritableKeyPath::with_box requires &mut Box<Root> - use with_box_mut instead"
11532        );
11533        unreachable!("WritableKeyPath::with_box requires &mut Box<Root> - use with_box_mut instead")
11534    }
11535
11536    fn with_box_mut<Callback, R>(&self, boxed: &mut Box<Root>, f: Callback) -> R
11537    where
11538        Callback: FnOnce(&mut Value) -> R,
11539    {
11540        let value = self.get_mut(boxed.as_mut());
11541        f(value)
11542    }
11543
11544    fn with_rc<Callback, R>(&self, _rc: &Rc<Root>, _f: Callback) -> R
11545    where
11546        Callback: FnOnce(&Value) -> R,
11547    {
11548        // Rc doesn't support mutable access without interior mutability
11549        // This method requires &mut Rc<Root> which we don't have
11550        eprintln!("[DEBUG] WritableKeyPath::with_rc requires &mut Rc<Root> or interior mutability");
11551        unreachable!("WritableKeyPath::with_rc requires &mut Rc<Root> or interior mutability")
11552    }
11553
11554    fn with_result<Callback, R, E>(&self, _result: &Result<Root, E>, _f: Callback) -> Option<R>
11555    where
11556        Callback: FnOnce(&Value) -> R,
11557    {
11558        // WritableKeyPath requires &mut Root, but we only have &Result<Root, E>
11559        // This is a limitation - use with_result_mut for mutable access
11560        None
11561    }
11562
11563    fn with_result_mut<Callback, R, E>(
11564        &self,
11565        result: &mut Result<Root, E>,
11566        f: Callback,
11567    ) -> Option<R>
11568    where
11569        Callback: FnOnce(&mut Value) -> R,
11570    {
11571        result.as_mut().ok().map(|root| {
11572            let value = self.get_mut(root);
11573            f(value)
11574        })
11575    }
11576
11577    fn with_option<Callback, R>(&self, _option: &Option<Root>, _f: Callback) -> Option<R>
11578    where
11579        Callback: FnOnce(&Value) -> R,
11580    {
11581        // WritableKeyPath requires &mut Root, but we only have &Option<Root>
11582        // This is a limitation - use with_option_mut for mutable access
11583        None
11584    }
11585
11586    fn with_option_mut<Callback, R>(&self, option: &mut Option<Root>, f: Callback) -> Option<R>
11587    where
11588        Callback: FnOnce(&mut Value) -> R,
11589    {
11590        option.as_mut().map(|root| {
11591            let value = self.get_mut(root);
11592            f(value)
11593        })
11594    }
11595
11596    fn with_refcell<Callback, R>(&self, refcell: &RefCell<Root>, f: Callback) -> Option<R>
11597    where
11598        Callback: FnOnce(&Value) -> R,
11599    {
11600        // RefCell doesn't allow getting mutable reference from immutable borrow
11601        // This is a limitation - we'd need try_borrow_mut for mutable access
11602        None
11603    }
11604
11605    fn with_refcell_mut<Callback, R>(&self, refcell: &RefCell<Root>, f: Callback) -> Option<R>
11606    where
11607        Callback: FnOnce(&mut Value) -> R,
11608    {
11609        refcell.try_borrow_mut().ok().map(|mut borrow| {
11610            let value = self.get_mut(&mut *borrow);
11611            f(value)
11612        })
11613    }
11614
11615    #[cfg(feature = "tagged")]
11616    fn with_tagged<Callback, R, Tag>(&self, _tagged: &Tagged<Root, Tag>, _f: Callback) -> R
11617    where
11618        Tagged<Root, Tag>: std::ops::Deref<Target = Root>,
11619        Callback: FnOnce(&Value) -> R,
11620    {
11621        // WritableKeyPath requires &mut Root, but we only have &Tagged<Root, Tag>
11622        // This is a limitation - Tagged doesn't support mutable access without interior mutability
11623        eprintln!(
11624            "[DEBUG] WritableKeyPath::with_tagged requires &mut Tagged<Root, Tag> or interior mutability"
11625        );
11626        unreachable!(
11627            "WritableKeyPath::with_tagged requires &mut Tagged<Root, Tag> or interior mutability"
11628        )
11629    }
11630
11631    fn with_mutex<Callback, R>(&self, mutex: &Mutex<Root>, f: Callback) -> Option<R>
11632    where
11633        Callback: FnOnce(&Value) -> R,
11634    {
11635        mutex.lock().ok().map(|mut guard| {
11636            let value = self.get_mut(&mut *guard);
11637            f(value)
11638        })
11639    }
11640
11641    fn with_mutex_mut<Callback, R>(&self, mutex: &mut Mutex<Root>, f: Callback) -> Option<R>
11642    where
11643        Callback: FnOnce(&mut Value) -> R,
11644    {
11645        // Mutex::get_mut returns Result<&mut Root, PoisonError>
11646        mutex.get_mut().ok().map(|root| {
11647            let value = self.get_mut(root);
11648            f(value)
11649        })
11650    }
11651
11652    fn with_rwlock<Callback, R>(&self, rwlock: &RwLock<Root>, f: Callback) -> Option<R>
11653    where
11654        Callback: FnOnce(&Value) -> R,
11655    {
11656        // RwLock read guard doesn't allow mutable access
11657        // This is a limitation - we'd need write() for mutable access
11658        None
11659    }
11660
11661    fn with_rwlock_mut<Callback, R>(&self, rwlock: &mut RwLock<Root>, f: Callback) -> Option<R>
11662    where
11663        Callback: FnOnce(&mut Value) -> R,
11664    {
11665        // RwLock::get_mut returns Result<&mut Root, PoisonError>
11666        rwlock.get_mut().ok().map(|root| {
11667            let value = self.get_mut(root);
11668            f(value)
11669        })
11670    }
11671
11672    fn with_arc_rwlock<Callback, R>(&self, arc_rwlock: &Arc<RwLock<Root>>, f: Callback) -> Option<R>
11673    where
11674        Callback: FnOnce(&Value) -> R,
11675    {
11676        // Arc<RwLock> read guard doesn't allow mutable access
11677        // This is a limitation - we'd need write() for mutable access
11678        None
11679    }
11680
11681    fn with_arc_rwlock_mut<Callback, R>(
11682        &self,
11683        arc_rwlock: &Arc<RwLock<Root>>,
11684        f: Callback,
11685    ) -> Option<R>
11686    where
11687        Callback: FnOnce(&mut Value) -> R,
11688    {
11689        arc_rwlock.write().ok().map(|mut guard| {
11690            let value = self.get_mut(&mut *guard);
11691            f(value)
11692        })
11693    }
11694}
11695
11696// Implement WithContainer for WritableOptionalKeyPath - supports all mutable operations
11697impl<Root, Value, F> WithContainer<Root, Value> for WritableOptionalKeyPath<Root, Value, F>
11698where
11699    F: for<'r> Fn(&'r mut Root) -> Option<&'r mut Value>,
11700{
11701    fn with_arc<Callback, R>(&self, _arc: &Arc<Root>, _f: Callback) -> R
11702    where
11703        Callback: FnOnce(&Value) -> R,
11704    {
11705        // Arc doesn't support mutable access without interior mutability
11706        // This method requires &mut Arc<Root> which we don't have
11707        eprintln!(
11708            "[DEBUG] WritableOptionalKeyPath::with_arc requires &mut Arc<Root> or interior mutability"
11709        );
11710        unreachable!(
11711            "WritableOptionalKeyPath::with_arc requires &mut Arc<Root> or interior mutability"
11712        )
11713    }
11714
11715    fn with_box<Callback, R>(&self, _boxed: &Box<Root>, _f: Callback) -> R
11716    where
11717        Callback: FnOnce(&Value) -> R,
11718    {
11719        // WritableOptionalKeyPath requires &mut Root, but we only have &Box<Root>
11720        // This is a limitation - use with_box_mut for mutable access
11721        eprintln!(
11722            "[DEBUG] WritableOptionalKeyPath::with_box requires &mut Box<Root> - use with_box_mut instead"
11723        );
11724        unreachable!(
11725            "WritableOptionalKeyPath::with_box requires &mut Box<Root> - use with_box_mut instead"
11726        )
11727    }
11728
11729    fn with_box_mut<Callback, R>(&self, boxed: &mut Box<Root>, f: Callback) -> R
11730    where
11731        Callback: FnOnce(&mut Value) -> R,
11732    {
11733        if let Some(value) = self.get_mut(boxed.as_mut()) {
11734            f(value)
11735        } else {
11736            eprintln!("[DEBUG] WritableOptionalKeyPath failed to get value from Box");
11737            unreachable!("WritableOptionalKeyPath failed to get value from Box")
11738        }
11739    }
11740
11741    fn with_rc<Callback, R>(&self, _rc: &Rc<Root>, _f: Callback) -> R
11742    where
11743        Callback: FnOnce(&Value) -> R,
11744    {
11745        // Rc doesn't support mutable access without interior mutability
11746        // This method requires &mut Rc<Root> which we don't have
11747        eprintln!(
11748            "[DEBUG] WritableOptionalKeyPath::with_rc requires &mut Rc<Root> or interior mutability"
11749        );
11750        unreachable!(
11751            "WritableOptionalKeyPath::with_rc requires &mut Rc<Root> or interior mutability"
11752        )
11753    }
11754
11755    fn with_result<Callback, R, E>(&self, _result: &Result<Root, E>, _f: Callback) -> Option<R>
11756    where
11757        Callback: FnOnce(&Value) -> R,
11758    {
11759        // WritableOptionalKeyPath requires &mut Root, but we only have &Result<Root, E>
11760        // This is a limitation - use with_result_mut for mutable access
11761        None
11762    }
11763
11764    fn with_result_mut<Callback, R, E>(
11765        &self,
11766        result: &mut Result<Root, E>,
11767        f: Callback,
11768    ) -> Option<R>
11769    where
11770        Callback: FnOnce(&mut Value) -> R,
11771    {
11772        result
11773            .as_mut()
11774            .ok()
11775            .and_then(|root| self.get_mut(root).map(|value| f(value)))
11776    }
11777
11778    fn with_option<Callback, R>(&self, _option: &Option<Root>, _f: Callback) -> Option<R>
11779    where
11780        Callback: FnOnce(&Value) -> R,
11781    {
11782        // WritableOptionalKeyPath requires &mut Root, but we only have &Option<Root>
11783        // This is a limitation - use with_option_mut for mutable access
11784        None
11785    }
11786
11787    fn with_option_mut<Callback, R>(&self, option: &mut Option<Root>, f: Callback) -> Option<R>
11788    where
11789        Callback: FnOnce(&mut Value) -> R,
11790    {
11791        option
11792            .as_mut()
11793            .and_then(|root| self.get_mut(root).map(|value| f(value)))
11794    }
11795
11796    fn with_refcell<Callback, R>(&self, _refcell: &RefCell<Root>, _f: Callback) -> Option<R>
11797    where
11798        Callback: FnOnce(&Value) -> R,
11799    {
11800        // RefCell doesn't allow getting mutable reference from immutable borrow
11801        // This is a limitation - we'd need try_borrow_mut for mutable access
11802        None
11803    }
11804
11805    fn with_refcell_mut<Callback, R>(&self, refcell: &RefCell<Root>, f: Callback) -> Option<R>
11806    where
11807        Callback: FnOnce(&mut Value) -> R,
11808    {
11809        refcell
11810            .try_borrow_mut()
11811            .ok()
11812            .and_then(|mut borrow| self.get_mut(&mut *borrow).map(|value| f(value)))
11813    }
11814
11815    #[cfg(feature = "tagged")]
11816    fn with_tagged<Callback, R, Tag>(&self, _tagged: &Tagged<Root, Tag>, _f: Callback) -> R
11817    where
11818        Tagged<Root, Tag>: std::ops::Deref<Target = Root>,
11819        Callback: FnOnce(&Value) -> R,
11820    {
11821        // WritableOptionalKeyPath requires &mut Root, but we only have &Tagged<Root, Tag>
11822        // This is a limitation - Tagged doesn't support mutable access without interior mutability
11823        eprintln!(
11824            "[DEBUG] WritableOptionalKeyPath::with_tagged requires &mut Tagged<Root, Tag> or interior mutability"
11825        );
11826        unreachable!(
11827            "WritableOptionalKeyPath::with_tagged requires &mut Tagged<Root, Tag> or interior mutability"
11828        )
11829    }
11830
11831    fn with_mutex<Callback, R>(&self, mutex: &Mutex<Root>, f: Callback) -> Option<R>
11832    where
11833        Callback: FnOnce(&Value) -> R,
11834    {
11835        mutex
11836            .lock()
11837            .ok()
11838            .and_then(|mut guard| self.get_mut(&mut *guard).map(|value| f(value)))
11839    }
11840
11841    fn with_mutex_mut<Callback, R>(&self, mutex: &mut Mutex<Root>, f: Callback) -> Option<R>
11842    where
11843        Callback: FnOnce(&mut Value) -> R,
11844    {
11845        // Mutex::get_mut returns Result<&mut Root, PoisonError>
11846        mutex
11847            .get_mut()
11848            .ok()
11849            .and_then(|root| self.get_mut(root).map(|value| f(value)))
11850    }
11851
11852    fn with_rwlock<Callback, R>(&self, _rwlock: &RwLock<Root>, _f: Callback) -> Option<R>
11853    where
11854        Callback: FnOnce(&Value) -> R,
11855    {
11856        // RwLock read guard doesn't allow mutable access
11857        // This is a limitation - we'd need write() for mutable access
11858        None
11859    }
11860
11861    fn with_rwlock_mut<Callback, R>(&self, rwlock: &mut RwLock<Root>, f: Callback) -> Option<R>
11862    where
11863        Callback: FnOnce(&mut Value) -> R,
11864    {
11865        // RwLock::get_mut returns Result<&mut Root, PoisonError>
11866        rwlock
11867            .get_mut()
11868            .ok()
11869            .and_then(|root| self.get_mut(root).map(|value| f(value)))
11870    }
11871
11872    fn with_arc_rwlock<Callback, R>(
11873        &self,
11874        _arc_rwlock: &Arc<RwLock<Root>>,
11875        _f: Callback,
11876    ) -> Option<R>
11877    where
11878        Callback: FnOnce(&Value) -> R,
11879    {
11880        // Arc<RwLock> read guard doesn't allow mutable access
11881        // This is a limitation - we'd need write() for mutable access
11882        None
11883    }
11884
11885    fn with_arc_rwlock_mut<Callback, R>(
11886        &self,
11887        arc_rwlock: &Arc<RwLock<Root>>,
11888        f: Callback,
11889    ) -> Option<R>
11890    where
11891        Callback: FnOnce(&mut Value) -> R,
11892    {
11893        arc_rwlock
11894            .write()
11895            .ok()
11896            .and_then(|mut guard| self.get_mut(&mut *guard).map(|value| f(value)))
11897    }
11898}