rust_keypaths/
lib.rs

1// Enable feature gate when nightly feature is enabled
2// NOTE: This will only work with nightly Rust toolchain
3// #![cfg_attr(feature = "nightly", feature(impl_trait_in_assoc_type))]
4
5use std::sync::{Arc, Mutex, RwLock};
6use std::marker::PhantomData;
7use std::any::{Any, TypeId};
8use std::rc::Rc;
9use std::cell::RefCell;
10use std::ops::Shr;
11use std::fmt;
12
13// ========== FUNCTIONAL KEYPATH CHAIN (Compose first, apply container at get) ==========
14
15/// A composed keypath chain through Arc<Mutex<T>> - functional style
16/// Build the chain first, then apply container at get() time
17/// 
18/// # Example
19/// ```rust
20/// // Functional style: compose first, then apply container at get()
21/// ContainerTest::mutex_data_r()
22///     .then_arc_mutex_at_kp(SomeStruct::data_r())
23///     .get(&container, |value| println!("Value: {}", value));
24/// ```
25pub struct ArcMutexKeyPathChain<Root, MutexValue, InnerValue, SubValue, F, G>
26where
27    F: for<'r> Fn(&'r Root) -> &'r MutexValue,
28    G: for<'r> Fn(&'r InnerValue) -> &'r SubValue,
29{
30    outer_keypath: KeyPath<Root, MutexValue, F>,
31    inner_keypath: KeyPath<InnerValue, SubValue, G>,
32}
33
34impl<Root, MutexValue, InnerValue, SubValue, F, G> ArcMutexKeyPathChain<Root, MutexValue, InnerValue, SubValue, F, G>
35where
36    F: for<'r> Fn(&'r Root) -> &'r MutexValue,
37    G: for<'r> Fn(&'r InnerValue) -> &'r SubValue,
38    MutexValue: std::borrow::Borrow<Arc<Mutex<InnerValue>>>,
39{
40    /// Apply the composed keypath chain to a container, executing callback with the value (read)
41    /// Consumes self - functional style (compose once, apply once)
42    pub fn get<Callback>(self, container: &Root, callback: Callback) -> Option<()>
43    where
44        Callback: FnOnce(&SubValue) -> (),
45    {
46        let arc_mutex_ref = self.outer_keypath.get(container);
47        arc_mutex_ref.borrow().lock().ok().map(|guard| {
48            let value = self.inner_keypath.get(&*guard);
49            callback(value)
50        })
51    }
52}
53
54// ========== WRITABLE MUTEX KEYPATH CHAINS ==========
55
56/// A composed writable keypath chain through Arc<Mutex<T>> - functional style
57/// Build the chain first, then apply container at get_mut() time
58pub struct ArcMutexWritableKeyPathChain<Root, MutexValue, InnerValue, SubValue, F, G>
59where
60    F: for<'r> Fn(&'r Root) -> &'r MutexValue,
61    G: for<'r> Fn(&'r mut InnerValue) -> &'r mut SubValue,
62{
63    outer_keypath: KeyPath<Root, MutexValue, F>,
64    inner_keypath: WritableKeyPath<InnerValue, SubValue, G>,
65}
66
67impl<Root, MutexValue, InnerValue, SubValue, F, G> ArcMutexWritableKeyPathChain<Root, MutexValue, InnerValue, SubValue, F, G>
68where
69    F: for<'r> Fn(&'r Root) -> &'r MutexValue,
70    G: for<'r> Fn(&'r mut InnerValue) -> &'r mut SubValue,
71    MutexValue: std::borrow::Borrow<Arc<Mutex<InnerValue>>>,
72{
73    /// Apply the composed keypath chain to a container with mutable access
74    /// Consumes self - functional style (compose once, apply once)
75    pub fn get_mut<Callback, R>(self, container: &Root, callback: Callback) -> Option<R>
76    where
77        Callback: FnOnce(&mut SubValue) -> R,
78    {
79        let arc_mutex_ref = self.outer_keypath.get(container);
80        arc_mutex_ref.borrow().lock().ok().map(|mut guard| {
81            let value_ref = self.inner_keypath.get_mut(&mut *guard);
82            callback(value_ref)
83        })
84    }
85}
86
87/// A composed writable optional keypath chain through Arc<Mutex<T>> - functional style
88pub struct ArcMutexWritableOptionalKeyPathChain<Root, MutexValue, InnerValue, SubValue, F, G>
89where
90    F: for<'r> Fn(&'r Root) -> &'r MutexValue,
91    G: for<'r> Fn(&'r mut InnerValue) -> Option<&'r mut SubValue>,
92{
93    outer_keypath: KeyPath<Root, MutexValue, F>,
94    inner_keypath: WritableOptionalKeyPath<InnerValue, SubValue, G>,
95}
96
97impl<Root, MutexValue, InnerValue, SubValue, F, G> ArcMutexWritableOptionalKeyPathChain<Root, MutexValue, InnerValue, SubValue, F, G>
98where
99    F: for<'r> Fn(&'r Root) -> &'r MutexValue,
100    G: for<'r> Fn(&'r mut InnerValue) -> Option<&'r mut SubValue>,
101    MutexValue: std::borrow::Borrow<Arc<Mutex<InnerValue>>>,
102{
103    /// Apply the composed keypath chain to a container with mutable access (if value exists)
104    /// Consumes self - functional style (compose once, apply once)
105    pub fn get_mut<Callback, R>(self, container: &Root, callback: Callback) -> Option<R>
106    where
107        Callback: FnOnce(&mut SubValue) -> R,
108    {
109        let arc_mutex_ref = self.outer_keypath.get(container);
110        arc_mutex_ref.borrow().lock().ok().and_then(|mut guard| {
111            self.inner_keypath.get_mut(&mut *guard).map(|value_ref| callback(value_ref))
112        })
113    }
114}
115
116/// A composed optional keypath chain through Arc<Mutex<T>> - functional style
117pub struct ArcMutexOptionalKeyPathChain<Root, MutexValue, InnerValue, SubValue, F, G>
118where
119    F: for<'r> Fn(&'r Root) -> &'r MutexValue,
120    G: for<'r> Fn(&'r InnerValue) -> Option<&'r SubValue>,
121{
122    outer_keypath: KeyPath<Root, MutexValue, F>,
123    inner_keypath: OptionalKeyPath<InnerValue, SubValue, G>,
124}
125
126impl<Root, MutexValue, InnerValue, SubValue, F, G> ArcMutexOptionalKeyPathChain<Root, MutexValue, InnerValue, SubValue, F, G>
127where
128    F: for<'r> Fn(&'r Root) -> &'r MutexValue,
129    G: for<'r> Fn(&'r InnerValue) -> Option<&'r SubValue>,
130    MutexValue: std::borrow::Borrow<Arc<Mutex<InnerValue>>>,
131{
132    /// Apply the composed keypath chain to a container, executing callback with the value
133    /// Consumes self - functional style (compose once, apply once)
134    pub fn get<Callback>(self, container: &Root, callback: Callback) -> Option<()>
135    where
136        Callback: FnOnce(&SubValue) -> (),
137    {
138        let arc_mutex_ref = self.outer_keypath.get(container);
139        arc_mutex_ref.borrow().lock().ok().and_then(|guard| {
140            self.inner_keypath.get(&*guard).map(|value| callback(value))
141        })
142    }
143}
144
145/// A composed keypath chain from OptionalKeyPath through Arc<Mutex<T>> - functional style
146pub struct OptionalArcMutexKeyPathChain<Root, MutexValue, InnerValue, SubValue, F, G>
147where
148    F: for<'r> Fn(&'r Root) -> Option<&'r MutexValue>,
149    G: for<'r> Fn(&'r InnerValue) -> &'r SubValue,
150{
151    outer_keypath: OptionalKeyPath<Root, MutexValue, F>,
152    inner_keypath: KeyPath<InnerValue, SubValue, G>,
153}
154
155impl<Root, MutexValue, InnerValue, SubValue, F, G> OptionalArcMutexKeyPathChain<Root, MutexValue, InnerValue, SubValue, F, G>
156where
157    F: for<'r> Fn(&'r Root) -> Option<&'r MutexValue>,
158    G: for<'r> Fn(&'r InnerValue) -> &'r SubValue,
159    MutexValue: std::borrow::Borrow<Arc<Mutex<InnerValue>>>,
160{
161    /// Apply the composed keypath chain to a container, executing callback with the value
162    /// Consumes self - functional style (compose once, apply once)
163    pub fn get<Callback>(self, container: &Root, callback: Callback) -> Option<()>
164    where
165        Callback: FnOnce(&SubValue) -> (),
166    {
167        self.outer_keypath.get(container).and_then(|arc_mutex_ref| {
168            arc_mutex_ref.borrow().lock().ok().map(|guard| {
169                let value = self.inner_keypath.get(&*guard);
170                callback(value)
171            })
172        })
173    }
174}
175
176/// A composed optional keypath chain from OptionalKeyPath through Arc<Mutex<T>> - functional style
177pub struct OptionalArcMutexOptionalKeyPathChain<Root, MutexValue, InnerValue, SubValue, F, G>
178where
179    F: for<'r> Fn(&'r Root) -> Option<&'r MutexValue>,
180    G: for<'r> Fn(&'r InnerValue) -> Option<&'r SubValue>,
181{
182    outer_keypath: OptionalKeyPath<Root, MutexValue, F>,
183    inner_keypath: OptionalKeyPath<InnerValue, SubValue, G>,
184}
185
186impl<Root, MutexValue, InnerValue, SubValue, F, G> OptionalArcMutexOptionalKeyPathChain<Root, MutexValue, InnerValue, SubValue, F, G>
187where
188    F: for<'r> Fn(&'r Root) -> Option<&'r MutexValue>,
189    G: for<'r> Fn(&'r InnerValue) -> Option<&'r SubValue>,
190    MutexValue: std::borrow::Borrow<Arc<Mutex<InnerValue>>>,
191{
192    /// Apply the composed keypath chain to a container, executing callback with the value
193    /// Consumes self - functional style (compose once, apply once)
194    pub fn get<Callback>(self, container: &Root, callback: Callback) -> Option<()>
195    where
196        Callback: FnOnce(&SubValue) -> (),
197    {
198        self.outer_keypath.get(container).and_then(|arc_mutex_ref| {
199            arc_mutex_ref.borrow().lock().ok().and_then(|guard| {
200                self.inner_keypath.get(&*guard).map(|value| callback(value))
201            })
202        })
203    }
204}
205
206// ========== FUNCTIONAL RWLOCK KEYPATH CHAINS ==========
207
208/// A composed keypath chain through Arc<RwLock<T>> - functional style
209/// Build the chain first, then apply container at get() time
210/// 
211/// # Example
212/// ```rust
213/// // Functional style: compose first, then apply container at get()
214/// ContainerTest::rwlock_data_r()
215///     .then_arc_rwlock_at_kp(SomeStruct::data_r())
216///     .get(&container, |value| println!("Value: {}", value));
217/// ```
218pub struct ArcRwLockKeyPathChain<Root, RwLockValue, InnerValue, SubValue, F, G>
219where
220    F: for<'r> Fn(&'r Root) -> &'r RwLockValue,
221    G: for<'r> Fn(&'r InnerValue) -> &'r SubValue,
222{
223    outer_keypath: KeyPath<Root, RwLockValue, F>,
224    inner_keypath: KeyPath<InnerValue, SubValue, G>,
225}
226
227impl<Root, RwLockValue, InnerValue, SubValue, F, G> ArcRwLockKeyPathChain<Root, RwLockValue, InnerValue, SubValue, F, G>
228where
229    F: for<'r> Fn(&'r Root) -> &'r RwLockValue,
230    G: for<'r> Fn(&'r InnerValue) -> &'r SubValue,
231    RwLockValue: std::borrow::Borrow<Arc<RwLock<InnerValue>>>,
232{
233    /// Apply the composed keypath chain to a container, executing callback with the value (read lock)
234    /// Consumes self - functional style (compose once, apply once)
235    pub fn get<Callback>(self, container: &Root, callback: Callback) -> Option<()>
236    where
237        Callback: FnOnce(&SubValue) -> (),
238    {
239        let arc_rwlock_ref = self.outer_keypath.get(container);
240        arc_rwlock_ref.borrow().read().ok().map(|guard| {
241            let value = self.inner_keypath.get(&*guard);
242            callback(value)
243        })
244    }
245}
246
247/// A composed optional keypath chain through Arc<RwLock<T>> - functional style
248pub struct ArcRwLockOptionalKeyPathChain<Root, RwLockValue, InnerValue, SubValue, F, G>
249where
250    F: for<'r> Fn(&'r Root) -> &'r RwLockValue,
251    G: for<'r> Fn(&'r InnerValue) -> Option<&'r SubValue>,
252{
253    outer_keypath: KeyPath<Root, RwLockValue, F>,
254    inner_keypath: OptionalKeyPath<InnerValue, SubValue, G>,
255}
256
257impl<Root, RwLockValue, InnerValue, SubValue, F, G> ArcRwLockOptionalKeyPathChain<Root, RwLockValue, InnerValue, SubValue, F, G>
258where
259    F: for<'r> Fn(&'r Root) -> &'r RwLockValue,
260    G: for<'r> Fn(&'r InnerValue) -> Option<&'r SubValue>,
261    RwLockValue: std::borrow::Borrow<Arc<RwLock<InnerValue>>>,
262{
263    /// Apply the composed keypath chain to a container, executing callback with the value (read lock)
264    /// Consumes self - functional style (compose once, apply once)
265    pub fn get<Callback>(self, container: &Root, callback: Callback) -> Option<()>
266    where
267        Callback: FnOnce(&SubValue) -> (),
268    {
269        let arc_rwlock_ref = self.outer_keypath.get(container);
270        arc_rwlock_ref.borrow().read().ok().and_then(|guard| {
271            self.inner_keypath.get(&*guard).map(|value| callback(value))
272        })
273    }
274}
275
276/// A composed keypath chain from OptionalKeyPath through Arc<RwLock<T>> - functional style
277pub struct OptionalArcRwLockKeyPathChain<Root, RwLockValue, InnerValue, SubValue, F, G>
278where
279    F: for<'r> Fn(&'r Root) -> Option<&'r RwLockValue>,
280    G: for<'r> Fn(&'r InnerValue) -> &'r SubValue,
281{
282    outer_keypath: OptionalKeyPath<Root, RwLockValue, F>,
283    inner_keypath: KeyPath<InnerValue, SubValue, G>,
284}
285
286impl<Root, RwLockValue, InnerValue, SubValue, F, G> OptionalArcRwLockKeyPathChain<Root, RwLockValue, InnerValue, SubValue, F, G>
287where
288    F: for<'r> Fn(&'r Root) -> Option<&'r RwLockValue>,
289    G: for<'r> Fn(&'r InnerValue) -> &'r SubValue,
290    RwLockValue: std::borrow::Borrow<Arc<RwLock<InnerValue>>>,
291{
292    /// Apply the composed keypath chain to a container, executing callback with the value (read lock)
293    /// Consumes self - functional style (compose once, apply once)
294    pub fn get<Callback>(self, container: &Root, callback: Callback) -> Option<()>
295    where
296        Callback: FnOnce(&SubValue) -> (),
297    {
298        self.outer_keypath.get(container).and_then(|arc_rwlock_ref| {
299            arc_rwlock_ref.borrow().read().ok().map(|guard| {
300                let value = self.inner_keypath.get(&*guard);
301                callback(value)
302            })
303        })
304    }
305}
306
307/// A composed optional keypath chain from OptionalKeyPath through Arc<RwLock<T>> - functional style
308pub struct OptionalArcRwLockOptionalKeyPathChain<Root, RwLockValue, InnerValue, SubValue, F, G>
309where
310    F: for<'r> Fn(&'r Root) -> Option<&'r RwLockValue>,
311    G: for<'r> Fn(&'r InnerValue) -> Option<&'r SubValue>,
312{
313    outer_keypath: OptionalKeyPath<Root, RwLockValue, F>,
314    inner_keypath: OptionalKeyPath<InnerValue, SubValue, G>,
315}
316
317impl<Root, RwLockValue, InnerValue, SubValue, F, G> OptionalArcRwLockOptionalKeyPathChain<Root, RwLockValue, InnerValue, SubValue, F, G>
318where
319    F: for<'r> Fn(&'r Root) -> Option<&'r RwLockValue>,
320    G: for<'r> Fn(&'r InnerValue) -> Option<&'r SubValue>,
321    RwLockValue: std::borrow::Borrow<Arc<RwLock<InnerValue>>>,
322{
323    /// Apply the composed keypath chain to a container, executing callback with the value (read lock)
324    /// Consumes self - functional style (compose once, apply once)
325    pub fn get<Callback>(self, container: &Root, callback: Callback) -> Option<()>
326    where
327        Callback: FnOnce(&SubValue) -> (),
328    {
329        self.outer_keypath.get(container).and_then(|arc_rwlock_ref| {
330            arc_rwlock_ref.borrow().read().ok().and_then(|guard| {
331                self.inner_keypath.get(&*guard).map(|value| callback(value))
332            })
333        })
334    }
335}
336
337// ========== WRITABLE MUTEX KEYPATH CHAINS FROM OPTIONAL KEYPATHS ==========
338
339/// A composed writable keypath chain from optional keypath through Arc<Mutex<T>> - functional style
340/// Build the chain first, then apply container at get_mut() time
341pub struct OptionalArcMutexWritableKeyPathChain<Root, MutexValue, InnerValue, SubValue, F, G>
342where
343    F: for<'r> Fn(&'r Root) -> Option<&'r MutexValue>,
344    G: for<'r> Fn(&'r mut InnerValue) -> &'r mut SubValue,
345{
346    outer_keypath: OptionalKeyPath<Root, MutexValue, F>,
347    inner_keypath: WritableKeyPath<InnerValue, SubValue, G>,
348}
349
350impl<Root, MutexValue, InnerValue, SubValue, F, G> OptionalArcMutexWritableKeyPathChain<Root, MutexValue, InnerValue, SubValue, F, G>
351where
352    F: for<'r> Fn(&'r Root) -> Option<&'r MutexValue>,
353    G: for<'r> Fn(&'r mut InnerValue) -> &'r mut SubValue,
354    MutexValue: std::borrow::Borrow<Arc<Mutex<InnerValue>>>,
355{
356    /// Apply the composed keypath chain to a container with mutable access
357    /// Consumes self - functional style (compose once, apply once)
358    pub fn get_mut<Callback, R>(self, container: &Root, callback: Callback) -> Option<R>
359    where
360        Callback: FnOnce(&mut SubValue) -> R,
361    {
362        self.outer_keypath.get(container).and_then(|arc_mutex_ref| {
363            arc_mutex_ref.borrow().lock().ok().map(|mut guard| {
364                let value_ref = self.inner_keypath.get_mut(&mut *guard);
365                callback(value_ref)
366            })
367        })
368    }
369}
370
371/// A composed writable optional keypath chain from optional keypath through Arc<Mutex<T>> - functional style
372/// Build the chain first, then apply container at get_mut() time
373pub struct OptionalArcMutexWritableOptionalKeyPathChain<Root, MutexValue, InnerValue, SubValue, F, G>
374where
375    F: for<'r> Fn(&'r Root) -> Option<&'r MutexValue>,
376    G: for<'r> Fn(&'r mut InnerValue) -> Option<&'r mut SubValue>,
377{
378    outer_keypath: OptionalKeyPath<Root, MutexValue, F>,
379    inner_keypath: WritableOptionalKeyPath<InnerValue, SubValue, G>,
380}
381
382impl<Root, MutexValue, InnerValue, SubValue, F, G> OptionalArcMutexWritableOptionalKeyPathChain<Root, MutexValue, InnerValue, SubValue, F, G>
383where
384    F: for<'r> Fn(&'r Root) -> Option<&'r MutexValue>,
385    G: for<'r> Fn(&'r mut InnerValue) -> Option<&'r mut SubValue>,
386    MutexValue: std::borrow::Borrow<Arc<Mutex<InnerValue>>>,
387{
388    /// Apply the composed keypath chain to a container with mutable access (if value exists)
389    /// Consumes self - functional style (compose once, apply once)
390    pub fn get_mut<Callback, R>(self, container: &Root, callback: Callback) -> Option<R>
391    where
392        Callback: FnOnce(&mut SubValue) -> R,
393    {
394        self.outer_keypath.get(container).and_then(|arc_mutex_ref| {
395            arc_mutex_ref.borrow().lock().ok().and_then(|mut guard| {
396                self.inner_keypath.get_mut(&mut *guard).map(|value_ref| callback(value_ref))
397            })
398        })
399    }
400}
401
402// ========== WRITABLE RWLOCK KEYPATH CHAINS FROM OPTIONAL KEYPATHS ==========
403
404/// A composed writable keypath chain from optional keypath through Arc<RwLock<T>> - functional style
405/// Build the chain first, then apply container at get_mut() time (uses write lock)
406pub struct OptionalArcRwLockWritableKeyPathChain<Root, RwLockValue, InnerValue, SubValue, F, G>
407where
408    F: for<'r> Fn(&'r Root) -> Option<&'r RwLockValue>,
409    G: for<'r> Fn(&'r mut InnerValue) -> &'r mut SubValue,
410{
411    outer_keypath: OptionalKeyPath<Root, RwLockValue, F>,
412    inner_keypath: WritableKeyPath<InnerValue, SubValue, G>,
413}
414
415impl<Root, RwLockValue, InnerValue, SubValue, F, G> OptionalArcRwLockWritableKeyPathChain<Root, RwLockValue, InnerValue, SubValue, F, G>
416where
417    F: for<'r> Fn(&'r Root) -> Option<&'r RwLockValue>,
418    G: for<'r> Fn(&'r mut InnerValue) -> &'r mut SubValue,
419    RwLockValue: std::borrow::Borrow<Arc<RwLock<InnerValue>>>,
420{
421    /// Apply the composed keypath chain to a container with mutable access (write lock)
422    /// Consumes self - functional style (compose once, apply once)
423    pub fn get_mut<Callback, R>(self, container: &Root, callback: Callback) -> Option<R>
424    where
425        Callback: FnOnce(&mut SubValue) -> R,
426    {
427        self.outer_keypath.get(container).and_then(|arc_rwlock_ref| {
428            arc_rwlock_ref.borrow().write().ok().map(|mut guard| {
429                let value_ref = self.inner_keypath.get_mut(&mut *guard);
430                callback(value_ref)
431            })
432        })
433    }
434}
435
436/// A composed writable optional keypath chain from optional keypath through Arc<RwLock<T>> - functional style
437/// Build the chain first, then apply container at get_mut() time (uses write lock)
438pub struct OptionalArcRwLockWritableOptionalKeyPathChain<Root, RwLockValue, InnerValue, SubValue, F, G>
439where
440    F: for<'r> Fn(&'r Root) -> Option<&'r RwLockValue>,
441    G: for<'r> Fn(&'r mut InnerValue) -> Option<&'r mut SubValue>,
442{
443    outer_keypath: OptionalKeyPath<Root, RwLockValue, F>,
444    inner_keypath: WritableOptionalKeyPath<InnerValue, SubValue, G>,
445}
446
447impl<Root, RwLockValue, InnerValue, SubValue, F, G> OptionalArcRwLockWritableOptionalKeyPathChain<Root, RwLockValue, InnerValue, SubValue, F, G>
448where
449    F: for<'r> Fn(&'r Root) -> Option<&'r RwLockValue>,
450    G: for<'r> Fn(&'r mut InnerValue) -> Option<&'r mut SubValue>,
451    RwLockValue: std::borrow::Borrow<Arc<RwLock<InnerValue>>>,
452{
453    /// Apply the composed keypath chain to a container with mutable access (write lock, if value exists)
454    /// Consumes self - functional style (compose once, apply once)
455    pub fn get_mut<Callback, R>(self, container: &Root, callback: Callback) -> Option<R>
456    where
457        Callback: FnOnce(&mut SubValue) -> R,
458    {
459        self.outer_keypath.get(container).and_then(|arc_rwlock_ref| {
460            arc_rwlock_ref.borrow().write().ok().and_then(|mut guard| {
461                self.inner_keypath.get_mut(&mut *guard).map(|value_ref| callback(value_ref))
462            })
463        })
464    }
465}
466
467// ========== WRITABLE RWLOCK KEYPATH CHAINS ==========
468
469/// A composed writable keypath chain through Arc<RwLock<T>> - functional style
470/// Build the chain first, then apply container at get_mut() time (uses write lock)
471pub struct ArcRwLockWritableKeyPathChain<Root, RwLockValue, InnerValue, SubValue, F, G>
472where
473    F: for<'r> Fn(&'r Root) -> &'r RwLockValue,
474    G: for<'r> Fn(&'r mut InnerValue) -> &'r mut SubValue,
475{
476    outer_keypath: KeyPath<Root, RwLockValue, F>,
477    inner_keypath: WritableKeyPath<InnerValue, SubValue, G>,
478}
479
480impl<Root, RwLockValue, InnerValue, SubValue, F, G> ArcRwLockWritableKeyPathChain<Root, RwLockValue, InnerValue, SubValue, F, G>
481where
482    F: for<'r> Fn(&'r Root) -> &'r RwLockValue,
483    G: for<'r> Fn(&'r mut InnerValue) -> &'r mut SubValue,
484    RwLockValue: std::borrow::Borrow<Arc<RwLock<InnerValue>>>,
485{
486    /// Apply the composed keypath chain to a container with mutable access (write lock)
487    /// Consumes self - functional style (compose once, apply once)
488    pub fn get_mut<Callback, R>(self, container: &Root, callback: Callback) -> Option<R>
489    where
490        Callback: FnOnce(&mut SubValue) -> R,
491    {
492        let arc_rwlock_ref = self.outer_keypath.get(container);
493        arc_rwlock_ref.borrow().write().ok().map(|mut guard| {
494            let value_ref = self.inner_keypath.get_mut(&mut *guard);
495            callback(value_ref)
496        })
497    }
498}
499
500/// A composed writable optional keypath chain through Arc<RwLock<T>> - functional style
501/// Build the chain first, then apply container at get_mut() time (uses write lock)
502pub struct ArcRwLockWritableOptionalKeyPathChain<Root, RwLockValue, InnerValue, SubValue, F, G>
503where
504    F: for<'r> Fn(&'r Root) -> &'r RwLockValue,
505    G: for<'r> Fn(&'r mut InnerValue) -> Option<&'r mut SubValue>,
506{
507    outer_keypath: KeyPath<Root, RwLockValue, F>,
508    inner_keypath: WritableOptionalKeyPath<InnerValue, SubValue, G>,
509}
510
511impl<Root, RwLockValue, InnerValue, SubValue, F, G> ArcRwLockWritableOptionalKeyPathChain<Root, RwLockValue, InnerValue, SubValue, F, G>
512where
513    F: for<'r> Fn(&'r Root) -> &'r RwLockValue,
514    G: for<'r> Fn(&'r mut InnerValue) -> Option<&'r mut SubValue>,
515    RwLockValue: std::borrow::Borrow<Arc<RwLock<InnerValue>>>,
516{
517    /// Apply the composed keypath chain to a container with mutable access (write lock, if value exists)
518    /// Consumes self - functional style (compose once, apply once)
519    pub fn get_mut<Callback, R>(self, container: &Root, callback: Callback) -> Option<R>
520    where
521        Callback: FnOnce(&mut SubValue) -> R,
522    {
523        let arc_rwlock_ref = self.outer_keypath.get(container);
524        arc_rwlock_ref.borrow().write().ok().and_then(|mut guard| {
525            self.inner_keypath.get_mut(&mut *guard).map(|value_ref| callback(value_ref))
526        })
527    }
528}
529
530// ========== PARKING_LOT MUTEX/RWLOCK CHAIN TYPES ==========
531
532#[cfg(feature = "parking_lot")]
533use parking_lot::{Mutex as ParkingMutex, RwLock as ParkingRwLock};
534
535/// A composed keypath chain through Arc<parking_lot::Mutex<T>> - functional style
536#[cfg(feature = "parking_lot")]
537pub struct ArcParkingMutexKeyPathChain<Root, InnerValue, SubValue, F, G>
538where
539    F: for<'r> Fn(&'r Root) -> &'r Arc<parking_lot::Mutex<InnerValue>>,
540    G: for<'r> Fn(&'r InnerValue) -> &'r SubValue,
541{
542    outer_keypath: KeyPath<Root, Arc<parking_lot::Mutex<InnerValue>>, F>,
543    inner_keypath: KeyPath<InnerValue, SubValue, G>,
544}
545
546#[cfg(feature = "parking_lot")]
547impl<Root, InnerValue, SubValue, F, G> ArcParkingMutexKeyPathChain<Root, InnerValue, SubValue, F, G>
548where
549    F: for<'r> Fn(&'r Root) -> &'r Arc<parking_lot::Mutex<InnerValue>>,
550    G: for<'r> Fn(&'r InnerValue) -> &'r SubValue,
551{
552    /// Apply the composed keypath chain to a container (read)
553    pub fn get<Callback>(self, container: &Root, callback: Callback)
554    where
555        Callback: FnOnce(&SubValue) -> (),
556    {
557        let arc_mutex_ref = self.outer_keypath.get(container);
558        let guard = arc_mutex_ref.lock();
559        let value = self.inner_keypath.get(&*guard);
560        callback(value);
561    }
562}
563
564/// A composed optional keypath chain through Arc<parking_lot::Mutex<T>> - functional style
565#[cfg(feature = "parking_lot")]
566pub struct ArcParkingMutexOptionalKeyPathChain<Root, InnerValue, SubValue, F, G>
567where
568    F: for<'r> Fn(&'r Root) -> &'r Arc<parking_lot::Mutex<InnerValue>>,
569    G: for<'r> Fn(&'r InnerValue) -> Option<&'r SubValue>,
570{
571    outer_keypath: KeyPath<Root, Arc<parking_lot::Mutex<InnerValue>>, F>,
572    inner_keypath: OptionalKeyPath<InnerValue, SubValue, G>,
573}
574
575#[cfg(feature = "parking_lot")]
576impl<Root, InnerValue, SubValue, F, G> ArcParkingMutexOptionalKeyPathChain<Root, InnerValue, SubValue, F, G>
577where
578    F: for<'r> Fn(&'r Root) -> &'r Arc<parking_lot::Mutex<InnerValue>>,
579    G: for<'r> Fn(&'r InnerValue) -> Option<&'r SubValue>,
580{
581    /// Apply the composed keypath chain to a container (read, if value exists)
582    pub fn get<Callback>(self, container: &Root, callback: Callback) -> Option<()>
583    where
584        Callback: FnOnce(&SubValue) -> (),
585    {
586        let arc_mutex_ref = self.outer_keypath.get(container);
587        let guard = arc_mutex_ref.lock();
588        self.inner_keypath.get(&*guard).map(|value| callback(value))
589    }
590}
591
592/// A composed writable keypath chain through Arc<parking_lot::Mutex<T>> - functional style
593#[cfg(feature = "parking_lot")]
594pub struct ArcParkingMutexWritableKeyPathChain<Root, InnerValue, SubValue, F, G>
595where
596    F: for<'r> Fn(&'r Root) -> &'r Arc<parking_lot::Mutex<InnerValue>>,
597    G: for<'r> Fn(&'r mut InnerValue) -> &'r mut SubValue,
598{
599    outer_keypath: KeyPath<Root, Arc<parking_lot::Mutex<InnerValue>>, F>,
600    inner_keypath: WritableKeyPath<InnerValue, SubValue, G>,
601}
602
603#[cfg(feature = "parking_lot")]
604impl<Root, InnerValue, SubValue, F, G> ArcParkingMutexWritableKeyPathChain<Root, InnerValue, SubValue, F, G>
605where
606    F: for<'r> Fn(&'r Root) -> &'r Arc<parking_lot::Mutex<InnerValue>>,
607    G: for<'r> Fn(&'r mut InnerValue) -> &'r mut SubValue,
608{
609    /// Apply the composed keypath chain to a container with mutable access
610    pub fn get_mut<Callback, R>(self, container: &Root, callback: Callback) -> R
611    where
612        Callback: FnOnce(&mut SubValue) -> R,
613    {
614        let arc_mutex_ref = self.outer_keypath.get(container);
615        let mut guard = arc_mutex_ref.lock();
616        let value_ref = self.inner_keypath.get_mut(&mut *guard);
617        callback(value_ref)
618    }
619}
620
621/// A composed writable optional keypath chain through Arc<parking_lot::Mutex<T>> - functional style
622#[cfg(feature = "parking_lot")]
623pub struct ArcParkingMutexWritableOptionalKeyPathChain<Root, InnerValue, SubValue, F, G>
624where
625    F: for<'r> Fn(&'r Root) -> &'r Arc<parking_lot::Mutex<InnerValue>>,
626    G: for<'r> Fn(&'r mut InnerValue) -> Option<&'r mut SubValue>,
627{
628    outer_keypath: KeyPath<Root, Arc<parking_lot::Mutex<InnerValue>>, F>,
629    inner_keypath: WritableOptionalKeyPath<InnerValue, SubValue, G>,
630}
631
632#[cfg(feature = "parking_lot")]
633impl<Root, InnerValue, SubValue, F, G> ArcParkingMutexWritableOptionalKeyPathChain<Root, InnerValue, SubValue, F, G>
634where
635    F: for<'r> Fn(&'r Root) -> &'r Arc<parking_lot::Mutex<InnerValue>>,
636    G: for<'r> Fn(&'r mut InnerValue) -> Option<&'r mut SubValue>,
637{
638    /// Apply the composed keypath chain to a container with mutable access (if value exists)
639    pub fn get_mut<Callback, R>(self, container: &Root, callback: Callback) -> Option<R>
640    where
641        Callback: FnOnce(&mut SubValue) -> R,
642    {
643        let arc_mutex_ref = self.outer_keypath.get(container);
644        let mut guard = arc_mutex_ref.lock();
645        self.inner_keypath.get_mut(&mut *guard).map(|value_ref| callback(value_ref))
646    }
647}
648
649/// A composed keypath chain through Arc<parking_lot::RwLock<T>> - functional style
650#[cfg(feature = "parking_lot")]
651pub struct ArcParkingRwLockKeyPathChain<Root, InnerValue, SubValue, F, G>
652where
653    F: for<'r> Fn(&'r Root) -> &'r Arc<parking_lot::RwLock<InnerValue>>,
654    G: for<'r> Fn(&'r InnerValue) -> &'r SubValue,
655{
656    outer_keypath: KeyPath<Root, Arc<parking_lot::RwLock<InnerValue>>, F>,
657    inner_keypath: KeyPath<InnerValue, SubValue, G>,
658}
659
660#[cfg(feature = "parking_lot")]
661impl<Root, InnerValue, SubValue, F, G> ArcParkingRwLockKeyPathChain<Root, InnerValue, SubValue, F, G>
662where
663    F: for<'r> Fn(&'r Root) -> &'r Arc<parking_lot::RwLock<InnerValue>>,
664    G: for<'r> Fn(&'r InnerValue) -> &'r SubValue,
665{
666    /// Apply the composed keypath chain to a container (read lock)
667    pub fn get<Callback>(self, container: &Root, callback: Callback)
668    where
669        Callback: FnOnce(&SubValue) -> (),
670    {
671        let arc_rwlock_ref = self.outer_keypath.get(container);
672        let guard = arc_rwlock_ref.read();
673        let value = self.inner_keypath.get(&*guard);
674        callback(value);
675    }
676}
677
678/// A composed optional keypath chain through Arc<parking_lot::RwLock<T>> - functional style
679#[cfg(feature = "parking_lot")]
680pub struct ArcParkingRwLockOptionalKeyPathChain<Root, InnerValue, SubValue, F, G>
681where
682    F: for<'r> Fn(&'r Root) -> &'r Arc<parking_lot::RwLock<InnerValue>>,
683    G: for<'r> Fn(&'r InnerValue) -> Option<&'r SubValue>,
684{
685    outer_keypath: KeyPath<Root, Arc<parking_lot::RwLock<InnerValue>>, F>,
686    inner_keypath: OptionalKeyPath<InnerValue, SubValue, G>,
687}
688
689#[cfg(feature = "parking_lot")]
690impl<Root, InnerValue, SubValue, F, G> ArcParkingRwLockOptionalKeyPathChain<Root, InnerValue, SubValue, F, G>
691where
692    F: for<'r> Fn(&'r Root) -> &'r Arc<parking_lot::RwLock<InnerValue>>,
693    G: for<'r> Fn(&'r InnerValue) -> Option<&'r SubValue>,
694{
695    /// Apply the composed keypath chain to a container (read lock, if value exists)
696    pub fn get<Callback>(self, container: &Root, callback: Callback) -> Option<()>
697    where
698        Callback: FnOnce(&SubValue) -> (),
699    {
700        let arc_rwlock_ref = self.outer_keypath.get(container);
701        let guard = arc_rwlock_ref.read();
702        self.inner_keypath.get(&*guard).map(|value| callback(value))
703    }
704}
705
706/// A composed writable keypath chain through Arc<parking_lot::RwLock<T>> - functional style
707#[cfg(feature = "parking_lot")]
708pub struct ArcParkingRwLockWritableKeyPathChain<Root, InnerValue, SubValue, F, G>
709where
710    F: for<'r> Fn(&'r Root) -> &'r Arc<parking_lot::RwLock<InnerValue>>,
711    G: for<'r> Fn(&'r mut InnerValue) -> &'r mut SubValue,
712{
713    outer_keypath: KeyPath<Root, Arc<parking_lot::RwLock<InnerValue>>, F>,
714    inner_keypath: WritableKeyPath<InnerValue, SubValue, G>,
715}
716
717#[cfg(feature = "parking_lot")]
718impl<Root, InnerValue, SubValue, F, G> ArcParkingRwLockWritableKeyPathChain<Root, InnerValue, SubValue, F, G>
719where
720    F: for<'r> Fn(&'r Root) -> &'r Arc<parking_lot::RwLock<InnerValue>>,
721    G: for<'r> Fn(&'r mut InnerValue) -> &'r mut SubValue,
722{
723    /// Apply the composed keypath chain to a container with mutable access (write lock)
724    pub fn get_mut<Callback, R>(self, container: &Root, callback: Callback) -> R
725    where
726        Callback: FnOnce(&mut SubValue) -> R,
727    {
728        let arc_rwlock_ref = self.outer_keypath.get(container);
729        let mut guard = arc_rwlock_ref.write();
730        let value_ref = self.inner_keypath.get_mut(&mut *guard);
731        callback(value_ref)
732    }
733}
734
735/// A composed writable optional keypath chain through Arc<parking_lot::RwLock<T>> - functional style
736#[cfg(feature = "parking_lot")]
737pub struct ArcParkingRwLockWritableOptionalKeyPathChain<Root, InnerValue, SubValue, F, G>
738where
739    F: for<'r> Fn(&'r Root) -> &'r Arc<parking_lot::RwLock<InnerValue>>,
740    G: for<'r> Fn(&'r mut InnerValue) -> Option<&'r mut SubValue>,
741{
742    outer_keypath: KeyPath<Root, Arc<parking_lot::RwLock<InnerValue>>, F>,
743    inner_keypath: WritableOptionalKeyPath<InnerValue, SubValue, G>,
744}
745
746#[cfg(feature = "parking_lot")]
747impl<Root, InnerValue, SubValue, F, G> ArcParkingRwLockWritableOptionalKeyPathChain<Root, InnerValue, SubValue, F, G>
748where
749    F: for<'r> Fn(&'r Root) -> &'r Arc<parking_lot::RwLock<InnerValue>>,
750    G: for<'r> Fn(&'r mut InnerValue) -> Option<&'r mut SubValue>,
751{
752    /// Apply the composed keypath chain to a container with mutable access (write lock, if value exists)
753    pub fn get_mut<Callback, R>(self, container: &Root, callback: Callback) -> Option<R>
754    where
755        Callback: FnOnce(&mut SubValue) -> R,
756    {
757        let arc_rwlock_ref = self.outer_keypath.get(container);
758        let mut guard = arc_rwlock_ref.write();
759        self.inner_keypath.get_mut(&mut *guard).map(|value_ref| callback(value_ref))
760    }
761}
762
763// ========== OPTIONAL PARKING_LOT MUTEX KEYPATH CHAINS (from OptionalKeyPath) ==========
764
765/// A composed keypath chain from optional keypath through Arc<parking_lot::Mutex<T>> - functional style
766#[cfg(feature = "parking_lot")]
767pub struct OptionalArcParkingMutexKeyPathChain<Root, InnerValue, SubValue, F, G>
768where
769    F: for<'r> Fn(&'r Root) -> Option<&'r Arc<parking_lot::Mutex<InnerValue>>>,
770    G: for<'r> Fn(&'r InnerValue) -> &'r SubValue,
771{
772    outer_keypath: OptionalKeyPath<Root, Arc<parking_lot::Mutex<InnerValue>>, F>,
773    inner_keypath: KeyPath<InnerValue, SubValue, G>,
774}
775
776#[cfg(feature = "parking_lot")]
777impl<Root, InnerValue, SubValue, F, G> OptionalArcParkingMutexKeyPathChain<Root, InnerValue, SubValue, F, G>
778where
779    F: for<'r> Fn(&'r Root) -> Option<&'r Arc<parking_lot::Mutex<InnerValue>>>,
780    G: for<'r> Fn(&'r InnerValue) -> &'r SubValue,
781{
782    /// Apply the composed keypath chain to a container
783    pub fn get<Callback>(self, container: &Root, callback: Callback) -> Option<()>
784    where
785        Callback: FnOnce(&SubValue) -> (),
786    {
787        self.outer_keypath.get(container).map(|arc_mutex_ref| {
788            let guard = arc_mutex_ref.lock();
789            let value = self.inner_keypath.get(&*guard);
790            callback(value)
791        })
792    }
793}
794
795/// A composed optional keypath chain from optional keypath through Arc<parking_lot::Mutex<T>>
796#[cfg(feature = "parking_lot")]
797pub struct OptionalArcParkingMutexOptionalKeyPathChain<Root, InnerValue, SubValue, F, G>
798where
799    F: for<'r> Fn(&'r Root) -> Option<&'r Arc<parking_lot::Mutex<InnerValue>>>,
800    G: for<'r> Fn(&'r InnerValue) -> Option<&'r SubValue>,
801{
802    outer_keypath: OptionalKeyPath<Root, Arc<parking_lot::Mutex<InnerValue>>, F>,
803    inner_keypath: OptionalKeyPath<InnerValue, SubValue, G>,
804}
805
806#[cfg(feature = "parking_lot")]
807impl<Root, InnerValue, SubValue, F, G> OptionalArcParkingMutexOptionalKeyPathChain<Root, InnerValue, SubValue, F, G>
808where
809    F: for<'r> Fn(&'r Root) -> Option<&'r Arc<parking_lot::Mutex<InnerValue>>>,
810    G: for<'r> Fn(&'r InnerValue) -> Option<&'r SubValue>,
811{
812    /// Apply the composed keypath chain to a container
813    pub fn get<Callback>(self, container: &Root, callback: Callback) -> Option<()>
814    where
815        Callback: FnOnce(&SubValue) -> (),
816    {
817        self.outer_keypath.get(container).and_then(|arc_mutex_ref| {
818            let guard = arc_mutex_ref.lock();
819            self.inner_keypath.get(&*guard).map(|value| callback(value))
820        })
821    }
822}
823
824/// A composed writable keypath chain from optional keypath through Arc<parking_lot::Mutex<T>>
825#[cfg(feature = "parking_lot")]
826pub struct OptionalArcParkingMutexWritableKeyPathChain<Root, InnerValue, SubValue, F, G>
827where
828    F: for<'r> Fn(&'r Root) -> Option<&'r Arc<parking_lot::Mutex<InnerValue>>>,
829    G: for<'r> Fn(&'r mut InnerValue) -> &'r mut SubValue,
830{
831    outer_keypath: OptionalKeyPath<Root, Arc<parking_lot::Mutex<InnerValue>>, F>,
832    inner_keypath: WritableKeyPath<InnerValue, SubValue, G>,
833}
834
835#[cfg(feature = "parking_lot")]
836impl<Root, InnerValue, SubValue, F, G> OptionalArcParkingMutexWritableKeyPathChain<Root, InnerValue, SubValue, F, G>
837where
838    F: for<'r> Fn(&'r Root) -> Option<&'r Arc<parking_lot::Mutex<InnerValue>>>,
839    G: for<'r> Fn(&'r mut InnerValue) -> &'r mut SubValue,
840{
841    /// Apply the composed keypath chain to a container with mutable access
842    pub fn get_mut<Callback, R>(self, container: &Root, callback: Callback) -> Option<R>
843    where
844        Callback: FnOnce(&mut SubValue) -> R,
845    {
846        self.outer_keypath.get(container).map(|arc_mutex_ref| {
847            let mut guard = arc_mutex_ref.lock();
848            let value_ref = self.inner_keypath.get_mut(&mut *guard);
849            callback(value_ref)
850        })
851    }
852}
853
854/// A composed writable optional keypath chain from optional keypath through Arc<parking_lot::Mutex<T>>
855#[cfg(feature = "parking_lot")]
856pub struct OptionalArcParkingMutexWritableOptionalKeyPathChain<Root, InnerValue, SubValue, F, G>
857where
858    F: for<'r> Fn(&'r Root) -> Option<&'r Arc<parking_lot::Mutex<InnerValue>>>,
859    G: for<'r> Fn(&'r mut InnerValue) -> Option<&'r mut SubValue>,
860{
861    outer_keypath: OptionalKeyPath<Root, Arc<parking_lot::Mutex<InnerValue>>, F>,
862    inner_keypath: WritableOptionalKeyPath<InnerValue, SubValue, G>,
863}
864
865#[cfg(feature = "parking_lot")]
866impl<Root, InnerValue, SubValue, F, G> OptionalArcParkingMutexWritableOptionalKeyPathChain<Root, InnerValue, SubValue, F, G>
867where
868    F: for<'r> Fn(&'r Root) -> Option<&'r Arc<parking_lot::Mutex<InnerValue>>>,
869    G: for<'r> Fn(&'r mut InnerValue) -> Option<&'r mut SubValue>,
870{
871    /// Apply the composed keypath chain to a container with mutable access (if value exists)
872    pub fn get_mut<Callback, R>(self, container: &Root, callback: Callback) -> Option<R>
873    where
874        Callback: FnOnce(&mut SubValue) -> R,
875    {
876        self.outer_keypath.get(container).and_then(|arc_mutex_ref| {
877            let mut guard = arc_mutex_ref.lock();
878            self.inner_keypath.get_mut(&mut *guard).map(|value_ref| callback(value_ref))
879        })
880    }
881}
882
883// ========== OPTIONAL PARKING_LOT RWLOCK KEYPATH CHAINS (from OptionalKeyPath) ==========
884
885/// A composed keypath chain from optional keypath through Arc<parking_lot::RwLock<T>> - functional style
886#[cfg(feature = "parking_lot")]
887pub struct OptionalArcParkingRwLockKeyPathChain<Root, InnerValue, SubValue, F, G>
888where
889    F: for<'r> Fn(&'r Root) -> Option<&'r Arc<parking_lot::RwLock<InnerValue>>>,
890    G: for<'r> Fn(&'r InnerValue) -> &'r SubValue,
891{
892    outer_keypath: OptionalKeyPath<Root, Arc<parking_lot::RwLock<InnerValue>>, F>,
893    inner_keypath: KeyPath<InnerValue, SubValue, G>,
894}
895
896#[cfg(feature = "parking_lot")]
897impl<Root, InnerValue, SubValue, F, G> OptionalArcParkingRwLockKeyPathChain<Root, InnerValue, SubValue, F, G>
898where
899    F: for<'r> Fn(&'r Root) -> Option<&'r Arc<parking_lot::RwLock<InnerValue>>>,
900    G: for<'r> Fn(&'r InnerValue) -> &'r SubValue,
901{
902    /// Apply the composed keypath chain to a container (read lock)
903    pub fn get<Callback>(self, container: &Root, callback: Callback) -> Option<()>
904    where
905        Callback: FnOnce(&SubValue) -> (),
906    {
907        self.outer_keypath.get(container).map(|arc_rwlock_ref| {
908            let guard = arc_rwlock_ref.read();
909            let value = self.inner_keypath.get(&*guard);
910            callback(value)
911        })
912    }
913}
914
915/// A composed optional keypath chain from optional keypath through Arc<parking_lot::RwLock<T>>
916#[cfg(feature = "parking_lot")]
917pub struct OptionalArcParkingRwLockOptionalKeyPathChain<Root, InnerValue, SubValue, F, G>
918where
919    F: for<'r> Fn(&'r Root) -> Option<&'r Arc<parking_lot::RwLock<InnerValue>>>,
920    G: for<'r> Fn(&'r InnerValue) -> Option<&'r SubValue>,
921{
922    outer_keypath: OptionalKeyPath<Root, Arc<parking_lot::RwLock<InnerValue>>, F>,
923    inner_keypath: OptionalKeyPath<InnerValue, SubValue, G>,
924}
925
926#[cfg(feature = "parking_lot")]
927impl<Root, InnerValue, SubValue, F, G> OptionalArcParkingRwLockOptionalKeyPathChain<Root, InnerValue, SubValue, F, G>
928where
929    F: for<'r> Fn(&'r Root) -> Option<&'r Arc<parking_lot::RwLock<InnerValue>>>,
930    G: for<'r> Fn(&'r InnerValue) -> Option<&'r SubValue>,
931{
932    /// Apply the composed keypath chain to a container (read lock)
933    pub fn get<Callback>(self, container: &Root, callback: Callback) -> Option<()>
934    where
935        Callback: FnOnce(&SubValue) -> (),
936    {
937        self.outer_keypath.get(container).and_then(|arc_rwlock_ref| {
938            let guard = arc_rwlock_ref.read();
939            self.inner_keypath.get(&*guard).map(|value| callback(value))
940        })
941    }
942}
943
944/// A composed writable keypath chain from optional keypath through Arc<parking_lot::RwLock<T>>
945#[cfg(feature = "parking_lot")]
946pub struct OptionalArcParkingRwLockWritableKeyPathChain<Root, InnerValue, SubValue, F, G>
947where
948    F: for<'r> Fn(&'r Root) -> Option<&'r Arc<parking_lot::RwLock<InnerValue>>>,
949    G: for<'r> Fn(&'r mut InnerValue) -> &'r mut SubValue,
950{
951    outer_keypath: OptionalKeyPath<Root, Arc<parking_lot::RwLock<InnerValue>>, F>,
952    inner_keypath: WritableKeyPath<InnerValue, SubValue, G>,
953}
954
955#[cfg(feature = "parking_lot")]
956impl<Root, InnerValue, SubValue, F, G> OptionalArcParkingRwLockWritableKeyPathChain<Root, InnerValue, SubValue, F, G>
957where
958    F: for<'r> Fn(&'r Root) -> Option<&'r Arc<parking_lot::RwLock<InnerValue>>>,
959    G: for<'r> Fn(&'r mut InnerValue) -> &'r mut SubValue,
960{
961    /// Apply the composed keypath chain to a container with mutable access (write lock)
962    pub fn get_mut<Callback, R>(self, container: &Root, callback: Callback) -> Option<R>
963    where
964        Callback: FnOnce(&mut SubValue) -> R,
965    {
966        self.outer_keypath.get(container).map(|arc_rwlock_ref| {
967            let mut guard = arc_rwlock_ref.write();
968            let value_ref = self.inner_keypath.get_mut(&mut *guard);
969            callback(value_ref)
970        })
971    }
972}
973
974/// A composed writable optional keypath chain from optional keypath through Arc<parking_lot::RwLock<T>>
975#[cfg(feature = "parking_lot")]
976pub struct OptionalArcParkingRwLockWritableOptionalKeyPathChain<Root, InnerValue, SubValue, F, G>
977where
978    F: for<'r> Fn(&'r Root) -> Option<&'r Arc<parking_lot::RwLock<InnerValue>>>,
979    G: for<'r> Fn(&'r mut InnerValue) -> Option<&'r mut SubValue>,
980{
981    outer_keypath: OptionalKeyPath<Root, Arc<parking_lot::RwLock<InnerValue>>, F>,
982    inner_keypath: WritableOptionalKeyPath<InnerValue, SubValue, G>,
983}
984
985#[cfg(feature = "parking_lot")]
986impl<Root, InnerValue, SubValue, F, G> OptionalArcParkingRwLockWritableOptionalKeyPathChain<Root, InnerValue, SubValue, F, G>
987where
988    F: for<'r> Fn(&'r Root) -> Option<&'r Arc<parking_lot::RwLock<InnerValue>>>,
989    G: for<'r> Fn(&'r mut InnerValue) -> Option<&'r mut SubValue>,
990{
991    /// Apply the composed keypath chain to a container with mutable access (write lock, if value exists)
992    pub fn get_mut<Callback, R>(self, container: &Root, callback: Callback) -> Option<R>
993    where
994        Callback: FnOnce(&mut SubValue) -> R,
995    {
996        self.outer_keypath.get(container).and_then(|arc_rwlock_ref| {
997            let mut guard = arc_rwlock_ref.write();
998            self.inner_keypath.get_mut(&mut *guard).map(|value_ref| callback(value_ref))
999        })
1000    }
1001}
1002
1003#[cfg(feature = "tagged")]
1004use tagged_core::Tagged;
1005
1006
1007// ========== HELPER MACROS FOR KEYPATH CREATION ==========
1008
1009/// Macro to create a `KeyPath` (readable, non-optional)
1010/// 
1011/// # Examples
1012/// 
1013/// ```rust
1014/// use rust_keypaths::keypath;
1015/// 
1016/// struct User { name: String, address: Address }
1017/// struct Address { street: String }
1018/// 
1019/// // Using a closure with type annotation
1020/// let kp = keypath!(|u: &User| &u.name);
1021/// 
1022/// // Nested field access
1023/// let kp = keypath!(|u: &User| &u.address.street);
1024/// 
1025/// // Or with automatic type inference
1026/// let kp = keypath!(|u| &u.name);
1027/// ```
1028#[macro_export]
1029macro_rules! keypath {
1030    // Accept a closure directly
1031    ($closure:expr) => {
1032        $crate::KeyPath::new($closure)
1033    };
1034}
1035
1036/// Macro to create an `OptionalKeyPath` (readable, optional)
1037/// 
1038/// # Examples
1039/// 
1040/// ```rust
1041/// use rust_keypaths::opt_keypath;
1042/// 
1043/// struct User { metadata: Option<String>, address: Option<Address> }
1044/// struct Address { street: String }
1045/// 
1046/// // Using a closure with type annotation
1047/// let kp = opt_keypath!(|u: &User| u.metadata.as_ref());
1048/// 
1049/// // Nested field access through Option
1050/// let kp = opt_keypath!(|u: &User| u.address.as_ref().map(|a| &a.street));
1051/// 
1052/// // Or with automatic type inference
1053/// let kp = opt_keypath!(|u| u.metadata.as_ref());
1054/// ```
1055#[macro_export]
1056macro_rules! opt_keypath {
1057    // Accept a closure directly
1058    ($closure:expr) => {
1059        $crate::OptionalKeyPath::new($closure)
1060    };
1061}
1062
1063/// Macro to create a `WritableKeyPath` (writable, non-optional)
1064/// 
1065/// # Examples
1066/// 
1067/// ```rust
1068/// use rust_keypaths::writable_keypath;
1069/// 
1070/// struct User { name: String, address: Address }
1071/// struct Address { street: String }
1072/// 
1073/// // Using a closure with type annotation
1074/// let kp = writable_keypath!(|u: &mut User| &mut u.name);
1075/// 
1076/// // Nested field access
1077/// let kp = writable_keypath!(|u: &mut User| &mut u.address.street);
1078/// 
1079/// // Or with automatic type inference
1080/// let kp = writable_keypath!(|u| &mut u.name);
1081/// ```
1082#[macro_export]
1083macro_rules! writable_keypath {
1084    // Accept a closure directly
1085    ($closure:expr) => {
1086        $crate::WritableKeyPath::new($closure)
1087    };
1088}
1089
1090/// Macro to create a `WritableOptionalKeyPath` (writable, optional)
1091/// 
1092/// # Examples
1093/// 
1094/// ```rust
1095/// use rust_keypaths::writable_opt_keypath;
1096/// 
1097/// struct User { metadata: Option<String>, address: Option<Address> }
1098/// struct Address { street: String }
1099/// 
1100/// // Using a closure with type annotation
1101/// let kp = writable_opt_keypath!(|u: &mut User| u.metadata.as_mut());
1102/// 
1103/// // Nested field access through Option
1104/// let kp = writable_opt_keypath!(|u: &mut User| u.address.as_mut().map(|a| &mut a.street));
1105/// 
1106/// // Or with automatic type inference
1107/// let kp = writable_opt_keypath!(|u| u.metadata.as_mut());
1108/// ```
1109#[macro_export]
1110macro_rules! writable_opt_keypath {
1111    // Accept a closure directly
1112    ($closure:expr) => {
1113        $crate::WritableOptionalKeyPath::new($closure)
1114    };
1115}
1116
1117// ========== BASE KEYPATH TYPES ==========
1118
1119// Base KeyPath
1120#[derive(Clone)]
1121pub struct KeyPath<Root, Value, F>
1122where
1123    F: for<'r> Fn(&'r Root) -> &'r Value,
1124{
1125    getter: F,
1126    _phantom: PhantomData<(Root, Value)>,
1127}
1128
1129impl<Root, Value, F> fmt::Display for KeyPath<Root, Value, F>
1130where
1131    F: for<'r> Fn(&'r Root) -> &'r Value,
1132{
1133    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1134        let root_name = std::any::type_name::<Root>();
1135        let value_name = std::any::type_name::<Value>();
1136        // Simplify type names by removing module paths for cleaner output
1137        let root_short = root_name.split("::").last().unwrap_or(root_name);
1138        let value_short = value_name.split("::").last().unwrap_or(value_name);
1139        write!(f, "KeyPath<{} -> {}>", root_short, value_short)
1140    }
1141}
1142
1143impl<Root, Value, F> fmt::Debug for KeyPath<Root, Value, F>
1144where
1145    F: for<'r> Fn(&'r Root) -> &'r Value,
1146{
1147    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1148        fmt::Display::fmt(self, f)
1149    }
1150}
1151
1152impl<Root, Value, F> KeyPath<Root, Value, F>
1153where
1154    F: for<'r> Fn(&'r Root) -> &'r Value,
1155{
1156    pub fn new(getter: F) -> Self {
1157        Self {
1158            getter,
1159            _phantom: PhantomData,
1160        }
1161    }
1162    
1163    pub fn get<'r>(&self, root: &'r Root) -> &'r Value {
1164        (self.getter)(root)
1165    }
1166    
1167    /// Chain this keypath with an inner keypath through Arc<Mutex<T>> - functional style
1168    /// Compose first, then apply container at get() time
1169    /// 
1170    /// # Example
1171    /// ```rust
1172    /// let container = ContainerTest { mutex_data: Arc::new(Mutex::new(SomeStruct { data: "test".to_string() })) };
1173    /// 
1174    /// // Functional style: compose first, apply container at get()
1175    /// ContainerTest::mutex_data_r()
1176    ///     .then_arc_mutex_at_kp(SomeStruct::data_r())
1177    ///     .get(&container, |value| println!("Data: {}", value));
1178    /// ```
1179    pub fn then_arc_mutex_at_kp<InnerValue, SubValue, G>(
1180        self,
1181        inner_keypath: KeyPath<InnerValue, SubValue, G>,
1182    ) -> ArcMutexKeyPathChain<Root, Value, InnerValue, SubValue, F, G>
1183    where
1184        G: for<'r> Fn(&'r InnerValue) -> &'r SubValue,
1185    {
1186        ArcMutexKeyPathChain {
1187            outer_keypath: self,
1188            inner_keypath,
1189        }
1190    }
1191    
1192    /// Chain this keypath with an optional inner keypath through Arc<Mutex<T>> - functional style
1193    /// Compose first, then apply container at get() time
1194    /// 
1195    /// # Example
1196    /// ```rust
1197    /// let container = ContainerTest { mutex_data: Arc::new(Mutex::new(SomeStruct { optional_field: Some("test".to_string()) })) };
1198    /// 
1199    /// // Functional style: compose first, apply container at get()
1200    /// ContainerTest::mutex_data_r()
1201    ///     .then_arc_mutex_optional_at_kp(SomeStruct::optional_field_fr())
1202    ///     .get(&container, |value| println!("Value: {}", value));
1203    /// ```
1204    pub fn then_arc_mutex_optional_at_kp<InnerValue, SubValue, G>(
1205        self,
1206        inner_keypath: OptionalKeyPath<InnerValue, SubValue, G>,
1207    ) -> ArcMutexOptionalKeyPathChain<Root, Value, InnerValue, SubValue, F, G>
1208    where
1209        G: for<'r> Fn(&'r InnerValue) -> Option<&'r SubValue>,
1210    {
1211        ArcMutexOptionalKeyPathChain {
1212            outer_keypath: self,
1213            inner_keypath,
1214        }
1215    }
1216    
1217    /// Chain this keypath with an inner keypath through Arc<RwLock<T>> - functional style
1218    /// Compose first, then apply container at get() time (uses read lock)
1219    /// 
1220    /// # Example
1221    /// ```rust
1222    /// let container = ContainerTest { rwlock_data: Arc::new(RwLock::new(SomeStruct { data: "test".to_string() })) };
1223    /// 
1224    /// // Functional style: compose first, apply container at get()
1225    /// ContainerTest::rwlock_data_r()
1226    ///     .then_arc_rwlock_at_kp(SomeStruct::data_r())
1227    ///     .get(&container, |value| println!("Data: {}", value));
1228    /// ```
1229    pub fn then_arc_rwlock_at_kp<InnerValue, SubValue, G>(
1230        self,
1231        inner_keypath: KeyPath<InnerValue, SubValue, G>,
1232    ) -> ArcRwLockKeyPathChain<Root, Value, InnerValue, SubValue, F, G>
1233    where
1234        G: for<'r> Fn(&'r InnerValue) -> &'r SubValue,
1235    {
1236        ArcRwLockKeyPathChain {
1237            outer_keypath: self,
1238            inner_keypath,
1239        }
1240    }
1241    
1242    /// Chain this keypath with an optional inner keypath through Arc<RwLock<T>> - functional style
1243    /// Compose first, then apply container at get() time (uses read lock)
1244    /// 
1245    /// # Example
1246    /// ```rust
1247    /// let container = ContainerTest { rwlock_data: Arc::new(RwLock::new(SomeStruct { optional_field: Some("test".to_string()) })) };
1248    /// 
1249    /// // Functional style: compose first, apply container at get()
1250    /// ContainerTest::rwlock_data_r()
1251    ///     .then_arc_rwlock_optional_at_kp(SomeStruct::optional_field_fr())
1252    ///     .get(&container, |value| println!("Value: {}", value));
1253    /// ```
1254    pub fn then_arc_rwlock_optional_at_kp<InnerValue, SubValue, G>(
1255        self,
1256        inner_keypath: OptionalKeyPath<InnerValue, SubValue, G>,
1257    ) -> ArcRwLockOptionalKeyPathChain<Root, Value, InnerValue, SubValue, F, G>
1258    where
1259        G: for<'r> Fn(&'r InnerValue) -> Option<&'r SubValue>,
1260    {
1261        ArcRwLockOptionalKeyPathChain {
1262            outer_keypath: self,
1263            inner_keypath,
1264        }
1265    }
1266    
1267    /// Chain this keypath with a writable inner keypath through Arc<Mutex<T>> - functional style
1268    /// Compose first, then apply container at get_mut() time
1269    /// 
1270    /// # Example
1271    /// ```rust
1272    /// ContainerTest::mutex_data_r()
1273    ///     .then_arc_mutex_writable_at_kp(SomeStruct::data_w())
1274    ///     .get_mut(&container, |value| *value = "new".to_string());
1275    /// ```
1276    pub fn then_arc_mutex_writable_at_kp<InnerValue, SubValue, G>(
1277        self,
1278        inner_keypath: WritableKeyPath<InnerValue, SubValue, G>,
1279    ) -> ArcMutexWritableKeyPathChain<Root, Value, InnerValue, SubValue, F, G>
1280    where
1281        G: for<'r> Fn(&'r mut InnerValue) -> &'r mut SubValue,
1282    {
1283        ArcMutexWritableKeyPathChain {
1284            outer_keypath: self,
1285            inner_keypath,
1286        }
1287    }
1288    
1289    /// Chain this keypath with a writable optional inner keypath through Arc<Mutex<T>> - functional style
1290    /// Compose first, then apply container at get_mut() time
1291    /// 
1292    /// # Example
1293    /// ```rust
1294    /// ContainerTest::mutex_data_r()
1295    ///     .then_arc_mutex_writable_optional_at_kp(SomeStruct::optional_field_fw())
1296    ///     .get_mut(&container, |value| *value = "new".to_string());
1297    /// ```
1298    pub fn then_arc_mutex_writable_optional_at_kp<InnerValue, SubValue, G>(
1299        self,
1300        inner_keypath: WritableOptionalKeyPath<InnerValue, SubValue, G>,
1301    ) -> ArcMutexWritableOptionalKeyPathChain<Root, Value, InnerValue, SubValue, F, G>
1302    where
1303        G: for<'r> Fn(&'r mut InnerValue) -> Option<&'r mut SubValue>,
1304    {
1305        ArcMutexWritableOptionalKeyPathChain {
1306            outer_keypath: self,
1307            inner_keypath,
1308        }
1309    }
1310    
1311    /// Chain this keypath with a writable inner keypath through Arc<RwLock<T>> - functional style
1312    /// Compose first, then apply container at get_mut() time (uses write lock)
1313    /// 
1314    /// # Example
1315    /// ```rust
1316    /// ContainerTest::rwlock_data_r()
1317    ///     .then_arc_rwlock_writable_at_kp(SomeStruct::data_w())
1318    ///     .get_mut(&container, |value| *value = "new".to_string());
1319    /// ```
1320    pub fn then_arc_rwlock_writable_at_kp<InnerValue, SubValue, G>(
1321        self,
1322        inner_keypath: WritableKeyPath<InnerValue, SubValue, G>,
1323    ) -> ArcRwLockWritableKeyPathChain<Root, Value, InnerValue, SubValue, F, G>
1324    where
1325        G: for<'r> Fn(&'r mut InnerValue) -> &'r mut SubValue,
1326    {
1327        ArcRwLockWritableKeyPathChain {
1328            outer_keypath: self,
1329            inner_keypath,
1330        }
1331    }
1332    
1333    /// Chain this keypath with a writable optional inner keypath through Arc<RwLock<T>> - functional style
1334    /// Compose first, then apply container at get_mut() time (uses write lock)
1335    /// 
1336    /// # Example
1337    /// ```rust
1338    /// ContainerTest::rwlock_data_r()
1339    ///     .then_arc_rwlock_writable_optional_at_kp(SomeStruct::optional_field_fw())
1340    ///     .get_mut(&container, |value| *value = "new".to_string());
1341    /// ```
1342    pub fn then_arc_rwlock_writable_optional_at_kp<InnerValue, SubValue, G>(
1343        self,
1344        inner_keypath: WritableOptionalKeyPath<InnerValue, SubValue, G>,
1345    ) -> ArcRwLockWritableOptionalKeyPathChain<Root, Value, InnerValue, SubValue, F, G>
1346    where
1347        G: for<'r> Fn(&'r mut InnerValue) -> Option<&'r mut SubValue>,
1348    {
1349        ArcRwLockWritableOptionalKeyPathChain {
1350            outer_keypath: self,
1351            inner_keypath,
1352        }
1353    }
1354
1355    // Instance methods for unwrapping containers (automatically infers Target from Value::Target)
1356    // Box<T> -> T
1357    pub fn for_box<Target>(self) -> KeyPath<Root, Target, impl for<'r> Fn(&'r Root) -> &'r Target + 'static>
1358    where
1359        Value: std::ops::Deref<Target = Target>,
1360        F: 'static,
1361        Value: 'static,
1362    {
1363        let getter = self.getter;
1364        
1365        KeyPath {
1366            getter: move |root: &Root| {
1367                getter(root).deref()
1368            },
1369            _phantom: PhantomData,
1370        }
1371    }
1372    
1373    // Arc<T> -> T
1374    pub fn for_arc<Target>(self) -> KeyPath<Root, Target, impl for<'r> Fn(&'r Root) -> &'r Target + 'static>
1375    where
1376        Value: std::ops::Deref<Target = Target>,
1377        F: 'static,
1378        Value: 'static,
1379    {
1380        let getter = self.getter;
1381        
1382        KeyPath {
1383            getter: move |root: &Root| {
1384                getter(root).deref()
1385            },
1386            _phantom: PhantomData,
1387        }
1388    }
1389    
1390    // Rc<T> -> T
1391    pub fn for_rc<Target>(self) -> KeyPath<Root, Target, impl for<'r> Fn(&'r Root) -> &'r Target + 'static>
1392    where
1393        Value: std::ops::Deref<Target = Target>,
1394        F: 'static,
1395        Value: 'static,
1396    {
1397        let getter = self.getter;
1398        
1399        KeyPath {
1400            getter: move |root: &Root| {
1401                getter(root).deref()
1402            },
1403            _phantom: PhantomData,
1404        }
1405    }
1406    
1407    // Overload: Adapt root type to Arc<Root> when Value is Sized (not a container)
1408    pub fn for_arc_root(self) -> OptionalKeyPath<Arc<Root>, Value, impl for<'r> Fn(&'r Arc<Root>) -> Option<&'r Value> + 'static>
1409    where
1410        Value: Sized,
1411        F: 'static,
1412        Root: 'static,
1413        Value: 'static,
1414    {
1415        let getter = self.getter;
1416        
1417        OptionalKeyPath {
1418            getter: move |arc: &Arc<Root>| {
1419                Some(getter(arc.as_ref()))
1420            },
1421            _phantom: PhantomData,
1422        }
1423    }
1424    
1425    // Overload: Adapt root type to Box<Root> when Value is Sized (not a container)
1426    pub fn for_box_root(self) -> OptionalKeyPath<Box<Root>, Value, impl for<'r> Fn(&'r Box<Root>) -> Option<&'r Value> + 'static>
1427    where
1428        Value: Sized,
1429        F: 'static,
1430        Root: 'static,
1431        Value: 'static,
1432    {
1433        let getter = self.getter;
1434        
1435        OptionalKeyPath {
1436            getter: move |boxed: &Box<Root>| {
1437                Some(getter(boxed.as_ref()))
1438            },
1439            _phantom: PhantomData,
1440        }
1441    }
1442    
1443    // Overload: Adapt root type to Rc<Root> when Value is Sized (not a container)
1444    pub fn for_rc_root(self) -> OptionalKeyPath<Rc<Root>, Value, impl for<'r> Fn(&'r Rc<Root>) -> Option<&'r Value> + 'static>
1445    where
1446        Value: Sized,
1447        F: 'static,
1448        Root: 'static,
1449        Value: 'static,
1450    {
1451        let getter = self.getter;
1452        
1453        OptionalKeyPath {
1454            getter: move |rc: &Rc<Root>| {
1455                Some(getter(rc.as_ref()))
1456            },
1457            _phantom: PhantomData,
1458        }
1459    }
1460    
1461    /// Adapt this keypath to work with Result<Root, E> instead of Root
1462    /// This unwraps the Result and applies the keypath to the Ok value
1463    pub fn for_result<E>(self) -> OptionalKeyPath<Result<Root, E>, Value, impl for<'r> Fn(&'r Result<Root, E>) -> Option<&'r Value> + 'static>
1464    where
1465        F: 'static,
1466        Root: 'static,
1467        Value: 'static,
1468        E: 'static,
1469    {
1470        let getter = self.getter;
1471        
1472        OptionalKeyPath {
1473            getter: move |result: &Result<Root, E>| {
1474                result.as_ref().ok().map(|root| getter(root))
1475            },
1476            _phantom: PhantomData,
1477        }
1478    }
1479    
1480    /// Convert a KeyPath to OptionalKeyPath for chaining
1481    /// This allows non-optional keypaths to be chained with then()
1482    pub fn to_optional(self) -> OptionalKeyPath<Root, Value, impl for<'r> Fn(&'r Root) -> Option<&'r Value> + 'static>
1483    where
1484        F: 'static,
1485    {
1486        let getter = self.getter;
1487        OptionalKeyPath::new(move |root: &Root| Some(getter(root)))
1488    }
1489    
1490    /// Execute a closure with a reference to the value inside an Option
1491    pub fn with_option<Callback, R>(&self, option: &Option<Root>, f: Callback) -> Option<R>
1492    where
1493        F: Clone,
1494        Callback: FnOnce(&Value) -> R,
1495    {
1496        option.as_ref().map(|root| {
1497            let value = self.get(root);
1498            f(value)
1499        })
1500    }
1501    
1502    /// Execute a closure with a reference to the value inside a Result
1503    pub fn with_result<Callback, R, E>(&self, result: &Result<Root, E>, f: Callback) -> Option<R>
1504    where
1505        F: Clone,
1506        Callback: FnOnce(&Value) -> R,
1507    {
1508        result.as_ref().ok().map(|root| {
1509            let value = self.get(root);
1510            f(value)
1511        })
1512    }
1513    
1514    /// Execute a closure with a reference to the value inside a Box
1515    pub fn with_box<Callback, R>(&self, boxed: &Box<Root>, f: Callback) -> R
1516    where
1517        F: Clone,
1518        Callback: FnOnce(&Value) -> R,
1519    {
1520        let value = self.get(boxed);
1521        f(value)
1522    }
1523    
1524    /// Execute a closure with a reference to the value inside an Arc
1525    pub fn with_arc<Callback, R>(&self, arc: &Arc<Root>, f: Callback) -> R
1526    where
1527        F: Clone,
1528        Callback: FnOnce(&Value) -> R,
1529    {
1530        let value = self.get(arc);
1531        f(value)
1532    }
1533    
1534    /// Execute a closure with a reference to the value inside an Rc
1535    pub fn with_rc<Callback, R>(&self, rc: &Rc<Root>, f: Callback) -> R
1536    where
1537        F: Clone,
1538        Callback: FnOnce(&Value) -> R,
1539    {
1540        let value = self.get(rc);
1541        f(value)
1542    }
1543    
1544    /// Execute a closure with a reference to the value inside a RefCell
1545    pub fn with_refcell<Callback, R>(&self, refcell: &RefCell<Root>, f: Callback) -> Option<R>
1546    where
1547        F: Clone,
1548        Callback: FnOnce(&Value) -> R,
1549    {
1550        refcell.try_borrow().ok().map(|borrow| {
1551            let value = self.get(&*borrow);
1552            f(value)
1553        })
1554    }
1555    
1556    /// Execute a closure with a reference to the value inside a Mutex
1557    pub fn with_mutex<Callback, R>(&self, mutex: &Mutex<Root>, f: Callback) -> Option<R>
1558    where
1559        F: Clone,
1560        Callback: FnOnce(&Value) -> R,
1561    {
1562        mutex.lock().ok().map(|guard| {
1563            let value = self.get(&*guard);
1564            f(value)
1565        })
1566    }
1567    
1568    /// Execute a closure with a reference to the value inside an RwLock
1569    pub fn with_rwlock<Callback, R>(&self, rwlock: &RwLock<Root>, f: Callback) -> Option<R>
1570    where
1571        F: Clone,
1572        Callback: FnOnce(&Value) -> R,
1573    {
1574        rwlock.read().ok().map(|guard| {
1575            let value = self.get(&*guard);
1576            f(value)
1577        })
1578    }
1579    
1580    /// Execute a closure with a reference to the value inside an Arc<RwLock<Root>>
1581    pub fn with_arc_rwlock<Callback, R>(&self, arc_rwlock: &Arc<RwLock<Root>>, f: Callback) -> Option<R>
1582    where
1583        F: Clone,
1584        Callback: FnOnce(&Value) -> R,
1585    {
1586        arc_rwlock.read().ok().map(|guard| {
1587            let value = self.get(&*guard);
1588            f(value)
1589        })
1590    }
1591    
1592    /// Execute a closure with a reference to the value inside an Arc<Mutex<Root>>
1593    pub fn with_arc_mutex<Callback, R>(&self, arc_mutex: &Arc<Mutex<Root>>, f: Callback) -> Option<R>
1594    where
1595        F: Clone,
1596        Callback: FnOnce(&Value) -> R,
1597    {
1598        arc_mutex.lock().ok().map(|guard| {
1599            let value = self.get(&*guard);
1600            f(value)
1601        })
1602    }
1603    
1604    #[cfg(feature = "tagged")]
1605    /// Adapt this keypath to work with Tagged<Root, Tag> instead of Root
1606    /// This unwraps the Tagged wrapper and applies the keypath to the inner value
1607    pub fn for_tagged<Tag>(self) -> KeyPath<Tagged<Root, Tag>, Value, impl for<'r> Fn(&'r Tagged<Root, Tag>) -> &'r Value + 'static>
1608    where
1609        Tagged<Root, Tag>: std::ops::Deref<Target = Root>,
1610        F: 'static,
1611        Root: 'static,
1612        Value: 'static,
1613        Tag: 'static,
1614    {
1615        use std::ops::Deref;
1616        let getter = self.getter;
1617        
1618        KeyPath {
1619            getter: move |tagged: &Tagged<Root, Tag>| {
1620                getter(tagged.deref())
1621            },
1622            _phantom: PhantomData,
1623        }
1624    }
1625    
1626    #[cfg(feature = "tagged")]
1627    /// Execute a closure with a reference to the value inside a Tagged
1628    /// This avoids cloning by working with references directly
1629    pub fn with_tagged<Tag, Callback, R>(&self, tagged: &Tagged<Root, Tag>, f: Callback) -> R
1630    where
1631        Tagged<Root, Tag>: std::ops::Deref<Target = Root>,
1632        Callback: FnOnce(&Value) -> R,
1633    {
1634        use std::ops::Deref;
1635        let value = self.get(tagged.deref());
1636        f(value)
1637    }
1638    
1639    /// Adapt this keypath to work with Option<Root> instead of Root
1640    /// This converts the KeyPath to an OptionalKeyPath and unwraps the Option
1641    pub fn for_option(self) -> OptionalKeyPath<Option<Root>, Value, impl for<'r> Fn(&'r Option<Root>) -> Option<&'r Value> + 'static>
1642    where
1643        F: 'static,
1644        Root: 'static,
1645        Value: 'static,
1646    {
1647        let getter = self.getter;
1648        
1649        OptionalKeyPath {
1650            getter: move |opt: &Option<Root>| {
1651                opt.as_ref().map(|root| getter(root))
1652            },
1653            _phantom: PhantomData,
1654        }
1655    }
1656    
1657    /// Get an iterator over a Vec when Value is Vec<T>
1658    /// Returns Some(iterator) if the value is a Vec, None otherwise
1659    pub fn iter<'r, T>(&self, root: &'r Root) -> Option<std::slice::Iter<'r, T>>
1660    where
1661        Value: AsRef<[T]> + 'r,
1662    {
1663        let value_ref: &'r Value = self.get(root);
1664        Some(value_ref.as_ref().iter())
1665    }
1666    
1667    /// Extract values from a slice of owned values
1668    /// Returns a Vec of references to the extracted values
1669    pub fn extract_from_slice<'r>(&self, slice: &'r [Root]) -> Vec<&'r Value> {
1670        slice.iter().map(|item| self.get(item)).collect()
1671    }
1672    
1673    /// Extract values from a slice of references
1674    /// Returns a Vec of references to the extracted values
1675    pub fn extract_from_ref_slice<'r>(&self, slice: &'r [&Root]) -> Vec<&'r Value> {
1676        slice.iter().map(|item| self.get(item)).collect()
1677    }
1678    
1679    /// Chain this keypath with another keypath
1680    /// Returns a KeyPath that chains both keypaths
1681    pub fn then<SubValue, G>(
1682        self,
1683        next: KeyPath<Value, SubValue, G>,
1684    ) -> KeyPath<Root, SubValue, impl for<'r> Fn(&'r Root) -> &'r SubValue>
1685    where
1686        G: for<'r> Fn(&'r Value) -> &'r SubValue,
1687        F: 'static,
1688        G: 'static,
1689        Value: 'static,
1690    {
1691        let first = self.getter;
1692        let second = next.getter;
1693        
1694        KeyPath::new(move |root: &Root| {
1695            let value = first(root);
1696            second(value)
1697        })
1698    }
1699    
1700    /// Chain this keypath with an optional keypath
1701    /// Returns an OptionalKeyPath that chains both keypaths
1702    pub fn then_optional<SubValue, G>(
1703        self,
1704        next: OptionalKeyPath<Value, SubValue, G>,
1705    ) -> OptionalKeyPath<Root, SubValue, impl for<'r> Fn(&'r Root) -> Option<&'r SubValue>>
1706    where
1707        G: for<'r> Fn(&'r Value) -> Option<&'r SubValue>,
1708        F: 'static,
1709        G: 'static,
1710        Value: 'static,
1711    {
1712        let first = self.getter;
1713        let second = next.getter;
1714        
1715        OptionalKeyPath::new(move |root: &Root| {
1716            let value = first(root);
1717            second(value)
1718        })
1719    }
1720    
1721}
1722
1723// Extension methods for KeyPath to support Arc<RwLock> and Arc<Mutex> directly
1724impl<Root, Value, F> KeyPath<Root, Value, F>
1725where
1726    F: for<'r> Fn(&'r Root) -> &'r Value,
1727{
1728    /// Execute a closure with a reference to the value inside an Arc<RwLock<Root>>
1729    /// This is a convenience method that works directly with Arc<RwLock<T>>
1730    pub fn with_arc_rwlock_direct<Callback, R>(&self, arc_rwlock: &Arc<RwLock<Root>>, f: Callback) -> Option<R>
1731    where
1732        Callback: FnOnce(&Value) -> R,
1733    {
1734        arc_rwlock.read().ok().map(|guard| {
1735            let value = self.get(&*guard);
1736            f(value)
1737        })
1738    }
1739    
1740    /// Execute a closure with a reference to the value inside an Arc<Mutex<Root>>
1741    /// This is a convenience method that works directly with Arc<Mutex<T>>
1742    pub fn with_arc_mutex_direct<Callback, R>(&self, arc_mutex: &Arc<Mutex<Root>>, f: Callback) -> Option<R>
1743    where
1744        Callback: FnOnce(&Value) -> R,
1745    {
1746        arc_mutex.lock().ok().map(|guard| {
1747            let value = self.get(&*guard);
1748            f(value)
1749        })
1750    }
1751}
1752
1753// Utility function for slice access (kept as standalone function)
1754pub fn for_slice<T>() -> impl for<'r> Fn(&'r [T], usize) -> Option<&'r T> {
1755    |slice: &[T], index: usize| slice.get(index)
1756}
1757
1758// Container access utilities
1759pub mod containers {
1760    use super::{OptionalKeyPath, WritableOptionalKeyPath, KeyPath, WritableKeyPath};
1761    use std::collections::{HashMap, BTreeMap, HashSet, BTreeSet, VecDeque, LinkedList, BinaryHeap};
1762    use std::sync::{Mutex, RwLock, Weak as StdWeak, Arc};
1763    use std::rc::{Weak as RcWeak, Rc};
1764    use std::ops::{Deref, DerefMut};
1765
1766    #[cfg(feature = "parking_lot")]
1767    use parking_lot::{Mutex as ParkingMutex, RwLock as ParkingRwLock};
1768
1769    #[cfg(feature = "tagged")]
1770    use tagged_core::Tagged;
1771
1772    /// Create a keypath for indexed access in Vec<T>
1773    pub fn for_vec_index<T>(index: usize) -> OptionalKeyPath<Vec<T>, T, impl for<'r> Fn(&'r Vec<T>) -> Option<&'r T>> {
1774        OptionalKeyPath::new(move |vec: &Vec<T>| vec.get(index))
1775    }
1776
1777    /// Create a keypath for indexed access in VecDeque<T>
1778    pub fn for_vecdeque_index<T>(index: usize) -> OptionalKeyPath<VecDeque<T>, T, impl for<'r> Fn(&'r VecDeque<T>) -> Option<&'r T>> {
1779        OptionalKeyPath::new(move |deque: &VecDeque<T>| deque.get(index))
1780    }
1781
1782    /// Create a keypath for indexed access in LinkedList<T>
1783    pub fn for_linkedlist_index<T>(index: usize) -> OptionalKeyPath<LinkedList<T>, T, impl for<'r> Fn(&'r LinkedList<T>) -> Option<&'r T>> {
1784        OptionalKeyPath::new(move |list: &LinkedList<T>| {
1785            list.iter().nth(index)
1786        })
1787    }
1788
1789    /// Create a keypath for key-based access in HashMap<K, V>
1790    pub fn for_hashmap_key<K, V>(key: K) -> OptionalKeyPath<HashMap<K, V>, V, impl for<'r> Fn(&'r HashMap<K, V>) -> Option<&'r V>>
1791    where
1792        K: std::hash::Hash + Eq + Clone + 'static,
1793        V: 'static,
1794    {
1795        OptionalKeyPath::new(move |map: &HashMap<K, V>| map.get(&key))
1796    }
1797
1798    /// Create a keypath for key-based access in BTreeMap<K, V>
1799    pub fn for_btreemap_key<K, V>(key: K) -> OptionalKeyPath<BTreeMap<K, V>, V, impl for<'r> Fn(&'r BTreeMap<K, V>) -> Option<&'r V>>
1800    where
1801        K: Ord + Clone + 'static,
1802        V: 'static,
1803    {
1804        OptionalKeyPath::new(move |map: &BTreeMap<K, V>| map.get(&key))
1805    }
1806
1807    /// Create a keypath for getting a value from HashSet<T> (returns Option<&T>)
1808    pub fn for_hashset_get<T>(value: T) -> OptionalKeyPath<HashSet<T>, T, impl for<'r> Fn(&'r HashSet<T>) -> Option<&'r T>>
1809    where
1810        T: std::hash::Hash + Eq + Clone + 'static,
1811    {
1812        OptionalKeyPath::new(move |set: &HashSet<T>| set.get(&value))
1813    }
1814
1815    /// Create a keypath for checking membership in BTreeSet<T>
1816    pub fn for_btreeset_get<T>(value: T) -> OptionalKeyPath<BTreeSet<T>, T, impl for<'r> Fn(&'r BTreeSet<T>) -> Option<&'r T>>
1817    where
1818        T: Ord + Clone + 'static,
1819    {
1820        OptionalKeyPath::new(move |set: &BTreeSet<T>| set.get(&value))
1821    }
1822
1823    /// Create a keypath for peeking at the top of BinaryHeap<T>
1824    pub fn for_binaryheap_peek<T>() -> OptionalKeyPath<BinaryHeap<T>, T, impl for<'r> Fn(&'r BinaryHeap<T>) -> Option<&'r T>>
1825    where
1826        T: Ord + 'static,
1827    {
1828        OptionalKeyPath::new(|heap: &BinaryHeap<T>| heap.peek())
1829    }
1830
1831    // ========== WRITABLE VERSIONS ==========
1832
1833    /// Create a writable keypath for indexed access in Vec<T>
1834    pub fn for_vec_index_mut<T>(index: usize) -> WritableOptionalKeyPath<Vec<T>, T, impl for<'r> Fn(&'r mut Vec<T>) -> Option<&'r mut T>> {
1835        WritableOptionalKeyPath::new(move |vec: &mut Vec<T>| vec.get_mut(index))
1836    }
1837
1838    /// Create a writable keypath for indexed access in VecDeque<T>
1839    pub fn for_vecdeque_index_mut<T>(index: usize) -> WritableOptionalKeyPath<VecDeque<T>, T, impl for<'r> Fn(&'r mut VecDeque<T>) -> Option<&'r mut T>> {
1840        WritableOptionalKeyPath::new(move |deque: &mut VecDeque<T>| deque.get_mut(index))
1841    }
1842
1843    /// Create a writable keypath for indexed access in LinkedList<T>
1844    pub fn for_linkedlist_index_mut<T>(index: usize) -> WritableOptionalKeyPath<LinkedList<T>, T, impl for<'r> Fn(&'r mut LinkedList<T>) -> Option<&'r mut T>> {
1845        WritableOptionalKeyPath::new(move |list: &mut LinkedList<T>| {
1846            // LinkedList doesn't have get_mut, so we need to iterate
1847            let mut iter = list.iter_mut();
1848            iter.nth(index)
1849        })
1850    }
1851
1852    /// Create a writable keypath for key-based access in HashMap<K, V>
1853    pub fn for_hashmap_key_mut<K, V>(key: K) -> WritableOptionalKeyPath<HashMap<K, V>, V, impl for<'r> Fn(&'r mut HashMap<K, V>) -> Option<&'r mut V>>
1854    where
1855        K: std::hash::Hash + Eq + Clone + 'static,
1856        V: 'static,
1857    {
1858        WritableOptionalKeyPath::new(move |map: &mut HashMap<K, V>| map.get_mut(&key))
1859    }
1860
1861    /// Create a writable keypath for key-based access in BTreeMap<K, V>
1862    pub fn for_btreemap_key_mut<K, V>(key: K) -> WritableOptionalKeyPath<BTreeMap<K, V>, V, impl for<'r> Fn(&'r mut BTreeMap<K, V>) -> Option<&'r mut V>>
1863    where
1864        K: Ord + Clone + 'static,
1865        V: 'static,
1866    {
1867        WritableOptionalKeyPath::new(move |map: &mut BTreeMap<K, V>| map.get_mut(&key))
1868    }
1869
1870    /// Create a writable keypath for getting a mutable value from HashSet<T>
1871    /// Note: HashSet doesn't support mutable access to elements, but we provide it for consistency
1872    pub fn for_hashset_get_mut<T>(value: T) -> WritableOptionalKeyPath<HashSet<T>, T, impl for<'r> Fn(&'r mut HashSet<T>) -> Option<&'r mut T>>
1873    where
1874        T: std::hash::Hash + Eq + Clone + 'static,
1875    {
1876        WritableOptionalKeyPath::new(move |set: &mut HashSet<T>| {
1877            // HashSet doesn't have get_mut, so we need to check and return None
1878            // This is a limitation of HashSet's design
1879            if set.contains(&value) {
1880                // We can't return a mutable reference to the value in the set
1881                // This is a fundamental limitation of HashSet
1882                None
1883            } else {
1884                None
1885            }
1886        })
1887    }
1888
1889    /// Create a writable keypath for getting a mutable value from BTreeSet<T>
1890    /// Note: BTreeSet doesn't support mutable access to elements, but we provide it for consistency
1891    pub fn for_btreeset_get_mut<T>(value: T) -> WritableOptionalKeyPath<BTreeSet<T>, T, impl for<'r> Fn(&'r mut BTreeSet<T>) -> Option<&'r mut T>>
1892    where
1893        T: Ord + Clone + 'static,
1894    {
1895        WritableOptionalKeyPath::new(move |set: &mut BTreeSet<T>| {
1896            // BTreeSet doesn't have get_mut, so we need to check and return None
1897            // This is a limitation of BTreeSet's design
1898            if set.contains(&value) {
1899                // We can't return a mutable reference to the value in the set
1900                // This is a fundamental limitation of BTreeSet
1901                None
1902            } else {
1903                None
1904            }
1905        })
1906    }
1907
1908    /// Create a writable keypath for peeking at the top of BinaryHeap<T>
1909    /// Note: BinaryHeap.peek_mut() returns PeekMut which is a guard type.
1910    /// Due to Rust's borrowing rules, we cannot return &mut T directly from PeekMut.
1911    /// This function returns None as BinaryHeap doesn't support direct mutable access
1912    /// through keypaths. Use heap.peek_mut() directly for mutable access.
1913    pub fn for_binaryheap_peek_mut<T>() -> WritableOptionalKeyPath<BinaryHeap<T>, T, impl for<'r> Fn(&'r mut BinaryHeap<T>) -> Option<&'r mut T>>
1914    where
1915        T: Ord + 'static,
1916    {
1917        // BinaryHeap.peek_mut() returns PeekMut which is a guard type that owns the mutable reference.
1918        // We cannot return &mut T from it due to lifetime constraints.
1919        // This is a fundamental limitation - use heap.peek_mut() directly instead.
1920        WritableOptionalKeyPath::new(|_heap: &mut BinaryHeap<T>| {
1921            None
1922        })
1923    }
1924
1925    // ========== SYNCHRONIZATION PRIMITIVES ==========
1926    // Note: Mutex and RwLock return guards that own the lock, not references.
1927    // We cannot create keypaths that return references from guards due to lifetime constraints.
1928    // These helper functions are provided for convenience, but direct lock()/read()/write() calls are recommended.
1929
1930    /// Helper function to lock a Mutex<T> and access its value
1931    /// Returns None if the mutex is poisoned
1932    /// Note: This returns a guard, not a reference, so it cannot be used in keypaths directly
1933    pub fn lock_mutex<T>(mutex: &Mutex<T>) -> Option<std::sync::MutexGuard<'_, T>> {
1934        mutex.lock().ok()
1935    }
1936
1937    /// Helper function to read-lock an RwLock<T> and access its value
1938    /// Returns None if the lock is poisoned
1939    /// Note: This returns a guard, not a reference, so it cannot be used in keypaths directly
1940    pub fn read_rwlock<T>(rwlock: &RwLock<T>) -> Option<std::sync::RwLockReadGuard<'_, T>> {
1941        rwlock.read().ok()
1942    }
1943
1944    /// Helper function to write-lock an RwLock<T> and access its value
1945    /// Returns None if the lock is poisoned
1946    /// Note: This returns a guard, not a reference, so it cannot be used in keypaths directly
1947    pub fn write_rwlock<T>(rwlock: &RwLock<T>) -> Option<std::sync::RwLockWriteGuard<'_, T>> {
1948        rwlock.write().ok()
1949    }
1950
1951    /// Helper function to lock an Arc<Mutex<T>> and access its value
1952    /// Returns None if the mutex is poisoned
1953    /// Note: This returns a guard, not a reference, so it cannot be used in keypaths directly
1954    pub fn lock_arc_mutex<T>(arc_mutex: &Arc<Mutex<T>>) -> Option<std::sync::MutexGuard<'_, T>> {
1955        arc_mutex.lock().ok()
1956    }
1957
1958    /// Helper function to read-lock an Arc<RwLock<T>> and access its value
1959    /// Returns None if the lock is poisoned
1960    /// Note: This returns a guard, not a reference, so it cannot be used in keypaths directly
1961    pub fn read_arc_rwlock<T>(arc_rwlock: &Arc<RwLock<T>>) -> Option<std::sync::RwLockReadGuard<'_, T>> {
1962        arc_rwlock.read().ok()
1963    }
1964
1965    /// Helper function to write-lock an Arc<RwLock<T>> and access its value
1966    /// Returns None if the lock is poisoned
1967    /// Note: This returns a guard, not a reference, so it cannot be used in keypaths directly
1968    pub fn write_arc_rwlock<T>(arc_rwlock: &Arc<RwLock<T>>) -> Option<std::sync::RwLockWriteGuard<'_, T>> {
1969        arc_rwlock.write().ok()
1970    }
1971
1972    /// Helper function to upgrade a Weak<T> to Arc<T>
1973    /// Returns None if the Arc has been dropped
1974    /// Note: This returns an owned Arc, not a reference, so it cannot be used in keypaths directly
1975    pub fn upgrade_weak<T>(weak: &StdWeak<T>) -> Option<Arc<T>> {
1976        weak.upgrade()
1977    }
1978
1979    /// Helper function to upgrade an Rc::Weak<T> to Rc<T>
1980    /// Returns None if the Rc has been dropped
1981    /// Note: This returns an owned Rc, not a reference, so it cannot be used in keypaths directly
1982    pub fn upgrade_rc_weak<T>(weak: &RcWeak<T>) -> Option<Rc<T>> {
1983        weak.upgrade()
1984    }
1985
1986    #[cfg(feature = "parking_lot")]
1987    /// Helper function to lock a parking_lot::Mutex<T> and access its value
1988    /// Note: This returns a guard, not a reference, so it cannot be used in keypaths directly
1989    pub fn lock_parking_mutex<T>(mutex: &ParkingMutex<T>) -> parking_lot::MutexGuard<'_, T> {
1990        mutex.lock()
1991    }
1992
1993    #[cfg(feature = "parking_lot")]
1994    /// Helper function to read-lock a parking_lot::RwLock<T> and access its value
1995    /// Note: This returns a guard, not a reference, so it cannot be used in keypaths directly
1996    pub fn read_parking_rwlock<T>(rwlock: &ParkingRwLock<T>) -> parking_lot::RwLockReadGuard<'_, T> {
1997        rwlock.read()
1998    }
1999
2000    #[cfg(feature = "parking_lot")]
2001    /// Helper function to write-lock a parking_lot::RwLock<T> and access its value
2002    /// Note: This returns a guard, not a reference, so it cannot be used in keypaths directly
2003    pub fn write_parking_rwlock<T>(rwlock: &ParkingRwLock<T>) -> parking_lot::RwLockWriteGuard<'_, T> {
2004        rwlock.write()
2005    }
2006
2007    #[cfg(feature = "tagged")]
2008    /// Create a keypath for accessing the inner value of Tagged<Tag, T>
2009    /// Tagged implements Deref, so we can access the inner value directly
2010    pub fn for_tagged<Tag, T>() -> KeyPath<Tagged<Tag, T>, T, impl for<'r> Fn(&'r Tagged<Tag, T>) -> &'r T>
2011    where
2012        Tagged<Tag, T>: std::ops::Deref<Target = T>,
2013        Tag: 'static,
2014        T: 'static,
2015    {
2016        KeyPath::new(|tagged: &Tagged<Tag, T>| tagged.deref())
2017    }
2018
2019    #[cfg(feature = "tagged")]
2020    /// Create a writable keypath for accessing the inner value of Tagged<Tag, T>
2021    /// Tagged implements DerefMut, so we can access the inner value directly
2022    pub fn for_tagged_mut<Tag, T>() -> WritableKeyPath<Tagged<Tag, T>, T, impl for<'r> Fn(&'r mut Tagged<Tag, T>) -> &'r mut T>
2023    where
2024        Tagged<Tag, T>: std::ops::DerefMut<Target = T>,
2025        Tag: 'static,
2026        T: 'static,
2027    {
2028        WritableKeyPath::new(|tagged: &mut Tagged<Tag, T>| tagged.deref_mut())
2029    }
2030}
2031
2032// ========== PARKING_LOT CHAIN METHODS FOR KEYPATH ==========
2033
2034#[cfg(feature = "parking_lot")]
2035impl<Root, InnerValue, F> KeyPath<Root, Arc<parking_lot::Mutex<InnerValue>>, F>
2036where
2037    F: for<'r> Fn(&'r Root) -> &'r Arc<parking_lot::Mutex<InnerValue>>,
2038{
2039    /// Chain this keypath with an inner keypath through Arc<parking_lot::Mutex<T>> - functional style
2040    pub fn then_arc_parking_mutex_at_kp<SubValue, G>(
2041        self,
2042        inner_keypath: KeyPath<InnerValue, SubValue, G>,
2043    ) -> ArcParkingMutexKeyPathChain<Root, InnerValue, SubValue, F, G>
2044    where
2045        G: for<'r> Fn(&'r InnerValue) -> &'r SubValue,
2046    {
2047        ArcParkingMutexKeyPathChain {
2048            outer_keypath: self,
2049            inner_keypath,
2050        }
2051    }
2052    
2053    /// Chain this keypath with an optional inner keypath through Arc<parking_lot::Mutex<T>>
2054    pub fn then_arc_parking_mutex_optional_at_kp<SubValue, G>(
2055        self,
2056        inner_keypath: OptionalKeyPath<InnerValue, SubValue, G>,
2057    ) -> ArcParkingMutexOptionalKeyPathChain<Root, InnerValue, SubValue, F, G>
2058    where
2059        G: for<'r> Fn(&'r InnerValue) -> Option<&'r SubValue>,
2060    {
2061        ArcParkingMutexOptionalKeyPathChain {
2062            outer_keypath: self,
2063            inner_keypath,
2064        }
2065    }
2066    
2067    /// Chain this keypath with a writable inner keypath through Arc<parking_lot::Mutex<T>>
2068    pub fn then_arc_parking_mutex_writable_at_kp<SubValue, G>(
2069        self,
2070        inner_keypath: WritableKeyPath<InnerValue, SubValue, G>,
2071    ) -> ArcParkingMutexWritableKeyPathChain<Root, InnerValue, SubValue, F, G>
2072    where
2073        G: for<'r> Fn(&'r mut InnerValue) -> &'r mut SubValue,
2074    {
2075        ArcParkingMutexWritableKeyPathChain {
2076            outer_keypath: self,
2077            inner_keypath,
2078        }
2079    }
2080    
2081    /// Chain this keypath with a writable optional inner keypath through Arc<parking_lot::Mutex<T>>
2082    pub fn then_arc_parking_mutex_writable_optional_at_kp<SubValue, G>(
2083        self,
2084        inner_keypath: WritableOptionalKeyPath<InnerValue, SubValue, G>,
2085    ) -> ArcParkingMutexWritableOptionalKeyPathChain<Root, InnerValue, SubValue, F, G>
2086    where
2087        G: for<'r> Fn(&'r mut InnerValue) -> Option<&'r mut SubValue>,
2088    {
2089        ArcParkingMutexWritableOptionalKeyPathChain {
2090            outer_keypath: self,
2091            inner_keypath,
2092        }
2093    }
2094}
2095
2096#[cfg(feature = "parking_lot")]
2097impl<Root, InnerValue, F> KeyPath<Root, Arc<parking_lot::RwLock<InnerValue>>, F>
2098where
2099    F: for<'r> Fn(&'r Root) -> &'r Arc<parking_lot::RwLock<InnerValue>>,
2100{
2101    /// Chain this keypath with an inner keypath through Arc<parking_lot::RwLock<T>> - functional style
2102    pub fn then_arc_parking_rwlock_at_kp<SubValue, G>(
2103        self,
2104        inner_keypath: KeyPath<InnerValue, SubValue, G>,
2105    ) -> ArcParkingRwLockKeyPathChain<Root, InnerValue, SubValue, F, G>
2106    where
2107        G: for<'r> Fn(&'r InnerValue) -> &'r SubValue,
2108    {
2109        ArcParkingRwLockKeyPathChain {
2110            outer_keypath: self,
2111            inner_keypath,
2112        }
2113    }
2114    
2115    /// Chain this keypath with an optional inner keypath through Arc<parking_lot::RwLock<T>>
2116    pub fn then_arc_parking_rwlock_optional_at_kp<SubValue, G>(
2117        self,
2118        inner_keypath: OptionalKeyPath<InnerValue, SubValue, G>,
2119    ) -> ArcParkingRwLockOptionalKeyPathChain<Root, InnerValue, SubValue, F, G>
2120    where
2121        G: for<'r> Fn(&'r InnerValue) -> Option<&'r SubValue>,
2122    {
2123        ArcParkingRwLockOptionalKeyPathChain {
2124            outer_keypath: self,
2125            inner_keypath,
2126        }
2127    }
2128    
2129    /// Chain this keypath with a writable inner keypath through Arc<parking_lot::RwLock<T>>
2130    pub fn then_arc_parking_rwlock_writable_at_kp<SubValue, G>(
2131        self,
2132        inner_keypath: WritableKeyPath<InnerValue, SubValue, G>,
2133    ) -> ArcParkingRwLockWritableKeyPathChain<Root, InnerValue, SubValue, F, G>
2134    where
2135        G: for<'r> Fn(&'r mut InnerValue) -> &'r mut SubValue,
2136    {
2137        ArcParkingRwLockWritableKeyPathChain {
2138            outer_keypath: self,
2139            inner_keypath,
2140        }
2141    }
2142    
2143    /// Chain this keypath with a writable optional inner keypath through Arc<parking_lot::RwLock<T>>
2144    pub fn then_arc_parking_rwlock_writable_optional_at_kp<SubValue, G>(
2145        self,
2146        inner_keypath: WritableOptionalKeyPath<InnerValue, SubValue, G>,
2147    ) -> ArcParkingRwLockWritableOptionalKeyPathChain<Root, InnerValue, SubValue, F, G>
2148    where
2149        G: for<'r> Fn(&'r mut InnerValue) -> Option<&'r mut SubValue>,
2150    {
2151        ArcParkingRwLockWritableOptionalKeyPathChain {
2152            outer_keypath: self,
2153            inner_keypath,
2154        }
2155    }
2156}
2157
2158// OptionalKeyPath for Option<T>
2159#[derive(Clone)]
2160pub struct OptionalKeyPath<Root, Value, F>
2161where
2162    F: for<'r> Fn(&'r Root) -> Option<&'r Value>,
2163{
2164    getter: F,
2165    _phantom: PhantomData<(Root, Value)>,
2166}
2167
2168impl<Root, Value, F> fmt::Display for OptionalKeyPath<Root, Value, F>
2169where
2170    F: for<'r> Fn(&'r Root) -> Option<&'r Value>,
2171{
2172    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2173        let root_name = std::any::type_name::<Root>();
2174        let value_name = std::any::type_name::<Value>();
2175        // Simplify type names by removing module paths for cleaner output
2176        let root_short = root_name.split("::").last().unwrap_or(root_name);
2177        let value_short = value_name.split("::").last().unwrap_or(value_name);
2178        write!(f, "OptionalKeyPath<{} -> Option<{}>>", root_short, value_short)
2179    }
2180}
2181
2182impl<Root, Value, F> fmt::Debug for OptionalKeyPath<Root, Value, F>
2183where
2184    F: for<'r> Fn(&'r Root) -> Option<&'r Value>,
2185{
2186    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2187        fmt::Display::fmt(self, f)
2188    }
2189}
2190
2191impl<Root, Value, F> OptionalKeyPath<Root, Value, F>
2192where
2193    F: for<'r> Fn(&'r Root) -> Option<&'r Value>,
2194{
2195    pub fn new(getter: F) -> Self {
2196        Self {
2197            getter,
2198            _phantom: PhantomData,
2199        }
2200    }
2201    
2202    pub fn get<'r>(&self, root: &'r Root) -> Option<&'r Value> {
2203        (self.getter)(root)
2204    }
2205    
2206    /// Chain this optional keypath with an inner keypath through Arc<Mutex<T>> - functional style
2207    /// Compose first, then apply container at get() time
2208    /// 
2209    /// # Example
2210    /// ```rust
2211    /// let container = ContainerTest { mutex_data: Some(Arc::new(Mutex::new(SomeStruct { data: "test".to_string() }))) };
2212    /// 
2213    /// // Functional style: compose first, apply container at get()
2214    /// ContainerTest::mutex_data_fr()
2215    ///     .then_arc_mutex_at_kp(SomeStruct::data_r())
2216    ///     .get(&container, |value| println!("Data: {}", value));
2217    /// ```
2218    pub fn then_arc_mutex_at_kp<InnerValue, SubValue, G>(
2219        self,
2220        inner_keypath: KeyPath<InnerValue, SubValue, G>,
2221    ) -> OptionalArcMutexKeyPathChain<Root, Value, InnerValue, SubValue, F, G>
2222    where
2223        G: for<'r> Fn(&'r InnerValue) -> &'r SubValue,
2224    {
2225        OptionalArcMutexKeyPathChain {
2226            outer_keypath: self,
2227            inner_keypath,
2228        }
2229    }
2230    
2231    /// Chain this optional keypath with an optional inner keypath through Arc<Mutex<T>> - functional style
2232    /// Compose first, then apply container at get() time
2233    /// 
2234    /// # Example
2235    /// ```rust
2236    /// let container = ContainerTest { mutex_data: Some(Arc::new(Mutex::new(SomeStruct { optional_field: Some("test".to_string()) }))) };
2237    /// 
2238    /// // Functional style: compose first, apply container at get()
2239    /// ContainerTest::mutex_data_fr()
2240    ///     .then_arc_mutex_optional_at_kp(SomeStruct::optional_field_fr())
2241    ///     .get(&container, |value| println!("Value: {}", value));
2242    /// ```
2243    pub fn then_arc_mutex_optional_at_kp<InnerValue, SubValue, G>(
2244        self,
2245        inner_keypath: OptionalKeyPath<InnerValue, SubValue, G>,
2246    ) -> OptionalArcMutexOptionalKeyPathChain<Root, Value, InnerValue, SubValue, F, G>
2247    where
2248        G: for<'r> Fn(&'r InnerValue) -> Option<&'r SubValue>,
2249    {
2250        OptionalArcMutexOptionalKeyPathChain {
2251            outer_keypath: self,
2252            inner_keypath,
2253        }
2254    }
2255    
2256    /// Chain this optional keypath with an inner keypath through Arc<RwLock<T>> - functional style
2257    /// Compose first, then apply container at get() time (uses read lock)
2258    /// 
2259    /// # Example
2260    /// ```rust
2261    /// let container = ContainerTest { rwlock_data: Some(Arc::new(RwLock::new(SomeStruct { data: "test".to_string() }))) };
2262    /// 
2263    /// // Functional style: compose first, apply container at get()
2264    /// ContainerTest::rwlock_data_fr()
2265    ///     .then_arc_rwlock_at_kp(SomeStruct::data_r())
2266    ///     .get(&container, |value| println!("Data: {}", value));
2267    /// ```
2268    pub fn then_arc_rwlock_at_kp<InnerValue, SubValue, G>(
2269        self,
2270        inner_keypath: KeyPath<InnerValue, SubValue, G>,
2271    ) -> OptionalArcRwLockKeyPathChain<Root, Value, InnerValue, SubValue, F, G>
2272    where
2273        G: for<'r> Fn(&'r InnerValue) -> &'r SubValue,
2274    {
2275        OptionalArcRwLockKeyPathChain {
2276            outer_keypath: self,
2277            inner_keypath,
2278        }
2279    }
2280    
2281    /// Chain this optional keypath with an optional inner keypath through Arc<RwLock<T>> - functional style
2282    /// Compose first, then apply container at get() time (uses read lock)
2283    /// 
2284    /// # Example
2285    /// ```rust
2286    /// let container = ContainerTest { rwlock_data: Some(Arc::new(RwLock::new(SomeStruct { optional_field: Some("test".to_string()) }))) };
2287    /// 
2288    /// // Functional style: compose first, apply container at get()
2289    /// ContainerTest::rwlock_data_fr()
2290    ///     .then_arc_rwlock_optional_at_kp(SomeStruct::optional_field_fr())
2291    ///     .get(&container, |value| println!("Value: {}", value));
2292    /// ```
2293    pub fn then_arc_rwlock_optional_at_kp<InnerValue, SubValue, G>(
2294        self,
2295        inner_keypath: OptionalKeyPath<InnerValue, SubValue, G>,
2296    ) -> OptionalArcRwLockOptionalKeyPathChain<Root, Value, InnerValue, SubValue, F, G>
2297    where
2298        G: for<'r> Fn(&'r InnerValue) -> Option<&'r SubValue>,
2299    {
2300        OptionalArcRwLockOptionalKeyPathChain {
2301            outer_keypath: self,
2302            inner_keypath,
2303        }
2304    }
2305    
2306    /// Chain this optional keypath with a writable inner keypath through Arc<Mutex<T>> - functional style
2307    /// Compose first, then apply container at get_mut() time
2308    /// 
2309    /// # Example
2310    /// ```rust
2311    /// let container = ContainerTest { mutex_data: Some(Arc::new(Mutex::new(SomeStruct { data: "test".to_string() }))) };
2312    /// 
2313    /// // Functional style: compose first, apply container at get_mut()
2314    /// ContainerTest::mutex_data_fr()
2315    ///     .then_arc_mutex_writable_at_kp(SomeStruct::data_w())
2316    ///     .get_mut(&container, |value| *value = "new".to_string());
2317    /// ```
2318    pub fn then_arc_mutex_writable_at_kp<InnerValue, SubValue, G>(
2319        self,
2320        inner_keypath: WritableKeyPath<InnerValue, SubValue, G>,
2321    ) -> OptionalArcMutexWritableKeyPathChain<Root, Value, InnerValue, SubValue, F, G>
2322    where
2323        G: for<'r> Fn(&'r mut InnerValue) -> &'r mut SubValue,
2324    {
2325        OptionalArcMutexWritableKeyPathChain {
2326            outer_keypath: self,
2327            inner_keypath,
2328        }
2329    }
2330    
2331    /// Chain this optional keypath with a writable optional inner keypath through Arc<Mutex<T>> - functional style
2332    /// Compose first, then apply container at get_mut() time
2333    /// 
2334    /// # Example
2335    /// ```rust
2336    /// let container = ContainerTest { mutex_data: Some(Arc::new(Mutex::new(SomeStruct { optional_field: Some("test".to_string()) }))) };
2337    /// 
2338    /// // Functional style: compose first, apply container at get_mut()
2339    /// ContainerTest::mutex_data_fr()
2340    ///     .then_arc_mutex_writable_optional_at_kp(SomeStruct::optional_field_fw())
2341    ///     .get_mut(&container, |value| *value = "new".to_string());
2342    /// ```
2343    pub fn then_arc_mutex_writable_optional_at_kp<InnerValue, SubValue, G>(
2344        self,
2345        inner_keypath: WritableOptionalKeyPath<InnerValue, SubValue, G>,
2346    ) -> OptionalArcMutexWritableOptionalKeyPathChain<Root, Value, InnerValue, SubValue, F, G>
2347    where
2348        G: for<'r> Fn(&'r mut InnerValue) -> Option<&'r mut SubValue>,
2349    {
2350        OptionalArcMutexWritableOptionalKeyPathChain {
2351            outer_keypath: self,
2352            inner_keypath,
2353        }
2354    }
2355    
2356    /// Chain this optional keypath with a writable inner keypath through Arc<RwLock<T>> - functional style
2357    /// Compose first, then apply container at get_mut() time (uses write lock)
2358    /// 
2359    /// # Example
2360    /// ```rust
2361    /// let container = ContainerTest { rwlock_data: Some(Arc::new(RwLock::new(SomeStruct { data: "test".to_string() }))) };
2362    /// 
2363    /// // Functional style: compose first, apply container at get_mut()
2364    /// ContainerTest::rwlock_data_fr()
2365    ///     .then_arc_rwlock_writable_at_kp(SomeStruct::data_w())
2366    ///     .get_mut(&container, |value| *value = "new".to_string());
2367    /// ```
2368    pub fn then_arc_rwlock_writable_at_kp<InnerValue, SubValue, G>(
2369        self,
2370        inner_keypath: WritableKeyPath<InnerValue, SubValue, G>,
2371    ) -> OptionalArcRwLockWritableKeyPathChain<Root, Value, InnerValue, SubValue, F, G>
2372    where
2373        G: for<'r> Fn(&'r mut InnerValue) -> &'r mut SubValue,
2374    {
2375        OptionalArcRwLockWritableKeyPathChain {
2376            outer_keypath: self,
2377            inner_keypath,
2378        }
2379    }
2380    
2381    /// Chain this optional keypath with a writable optional inner keypath through Arc<RwLock<T>> - functional style
2382    /// Compose first, then apply container at get_mut() time (uses write lock)
2383    /// 
2384    /// # Example
2385    /// ```rust
2386    /// let container = ContainerTest { rwlock_data: Some(Arc::new(RwLock::new(SomeStruct { optional_field: Some("test".to_string()) }))) };
2387    /// 
2388    /// // Functional style: compose first, apply container at get_mut()
2389    /// ContainerTest::rwlock_data_fr()
2390    ///     .then_arc_rwlock_writable_optional_at_kp(SomeStruct::optional_field_fw())
2391    ///     .get_mut(&container, |value| *value = "new".to_string());
2392    /// ```
2393    pub fn then_arc_rwlock_writable_optional_at_kp<InnerValue, SubValue, G>(
2394        self,
2395        inner_keypath: WritableOptionalKeyPath<InnerValue, SubValue, G>,
2396    ) -> OptionalArcRwLockWritableOptionalKeyPathChain<Root, Value, InnerValue, SubValue, F, G>
2397    where
2398        G: for<'r> Fn(&'r mut InnerValue) -> Option<&'r mut SubValue>,
2399    {
2400        OptionalArcRwLockWritableOptionalKeyPathChain {
2401            outer_keypath: self,
2402            inner_keypath,
2403        }
2404    }
2405    
2406    // Swift-like operator for chaining OptionalKeyPath
2407    pub fn then<SubValue, G>(
2408        self,
2409        next: OptionalKeyPath<Value, SubValue, G>,
2410    ) -> OptionalKeyPath<Root, SubValue, impl for<'r> Fn(&'r Root) -> Option<&'r SubValue>>
2411    where
2412        G: for<'r> Fn(&'r Value) -> Option<&'r SubValue>,
2413        F: 'static,
2414        G: 'static,
2415        Value: 'static,
2416    {
2417        let first = self.getter;
2418        let second = next.getter;
2419        
2420        OptionalKeyPath::new(move |root: &Root| {
2421            first(root).and_then(|value| second(value))
2422        })
2423    }
2424    
2425    // Instance methods for unwrapping containers from Option<Container<T>>
2426    // Option<Box<T>> -> Option<&T> (type automatically inferred from Value::Target)
2427    pub fn for_box<Target>(self) -> OptionalKeyPath<Root, Target, impl for<'r> Fn(&'r Root) -> Option<&'r Target> + 'static>
2428    where
2429        Value: std::ops::Deref<Target = Target>,
2430        F: 'static,
2431        Value: 'static,
2432    {
2433        let getter = self.getter;
2434        
2435        OptionalKeyPath {
2436            getter: move |root: &Root| {
2437                getter(root).map(|boxed| boxed.deref())
2438            },
2439            _phantom: PhantomData,
2440        }
2441    }
2442    
2443    // Option<Arc<T>> -> Option<&T> (type automatically inferred from Value::Target)
2444    pub fn for_arc<Target>(self) -> OptionalKeyPath<Root, Target, impl for<'r> Fn(&'r Root) -> Option<&'r Target> + 'static>
2445    where
2446        Value: std::ops::Deref<Target = Target>,
2447        F: 'static,
2448        Value: 'static,
2449    {
2450        let getter = self.getter;
2451        
2452        OptionalKeyPath {
2453            getter: move |root: &Root| {
2454                getter(root).map(|arc| arc.deref())
2455            },
2456            _phantom: PhantomData,
2457        }
2458    }
2459    
2460    // Option<Rc<T>> -> Option<&T> (type automatically inferred from Value::Target)
2461    pub fn for_rc<Target>(self) -> OptionalKeyPath<Root, Target, impl for<'r> Fn(&'r Root) -> Option<&'r Target> + 'static>
2462    where
2463        Value: std::ops::Deref<Target = Target>,
2464        F: 'static,
2465        Value: 'static,
2466    {
2467        let getter = self.getter;
2468        
2469        OptionalKeyPath {
2470            getter: move |root: &Root| {
2471                getter(root).map(|rc| rc.deref())
2472            },
2473            _phantom: PhantomData,
2474        }
2475    }
2476    
2477    #[cfg(feature = "tagged")]
2478    /// Adapt this keypath to work with Tagged<Root, Tag> instead of Root
2479    /// This unwraps the Tagged wrapper and applies the keypath to the inner value
2480    pub fn for_tagged<Tag>(self) -> OptionalKeyPath<Tagged<Root, Tag>, Value, impl for<'r> Fn(&'r Tagged<Root, Tag>) -> Option<&'r Value> + 'static>
2481    where
2482        Tagged<Root, Tag>: std::ops::Deref<Target = Root>,
2483        F: 'static,
2484        Root: 'static,
2485        Value: 'static,
2486        Tag: 'static,
2487    {
2488        use std::ops::Deref;
2489        let getter = self.getter;
2490        
2491        OptionalKeyPath {
2492            getter: move |tagged: &Tagged<Root, Tag>| {
2493                getter(tagged.deref())
2494            },
2495            _phantom: PhantomData,
2496        }
2497    }
2498    
2499    #[cfg(feature = "tagged")]
2500    /// Execute a closure with a reference to the value inside a Tagged
2501    /// This avoids cloning by working with references directly
2502    pub fn with_tagged<Tag, Callback, R>(&self, tagged: &Tagged<Root, Tag>, f: Callback) -> Option<R>
2503    where
2504        Tagged<Root, Tag>: std::ops::Deref<Target = Root>,
2505        F: Clone,
2506        Callback: FnOnce(&Value) -> R,
2507    {
2508        use std::ops::Deref;
2509        self.get(tagged.deref()).map(|value| f(value))
2510    }
2511    
2512    /// Adapt this keypath to work with Option<Root> instead of Root
2513    /// This unwraps the Option and applies the keypath to the inner value
2514    pub fn for_option(self) -> OptionalKeyPath<Option<Root>, Value, impl for<'r> Fn(&'r Option<Root>) -> Option<&'r Value> + 'static>
2515    where
2516        F: 'static,
2517        Root: 'static,
2518        Value: 'static,
2519    {
2520        let getter = self.getter;
2521        
2522        OptionalKeyPath {
2523            getter: move |opt: &Option<Root>| {
2524                opt.as_ref().and_then(|root| getter(root))
2525            },
2526            _phantom: PhantomData,
2527        }
2528    }
2529    
2530    /// Adapt this keypath to work with Result<Root, E> instead of Root
2531    /// This unwraps the Result and applies the keypath to the Ok value
2532    pub fn for_result<E>(self) -> OptionalKeyPath<Result<Root, E>, Value, impl for<'r> Fn(&'r Result<Root, E>) -> Option<&'r Value> + 'static>
2533    where
2534        F: 'static,
2535        Root: 'static,
2536        Value: 'static,
2537        E: 'static,
2538    {
2539        let getter = self.getter;
2540        
2541        OptionalKeyPath {
2542            getter: move |result: &Result<Root, E>| {
2543                result.as_ref().ok().and_then(|root| getter(root))
2544            },
2545            _phantom: PhantomData,
2546        }
2547    }
2548    
2549    // Overload: Adapt root type to Arc<Root> when Value is Sized (not a container)
2550    pub fn for_arc_root(self) -> OptionalKeyPath<Arc<Root>, Value, impl for<'r> Fn(&'r Arc<Root>) -> Option<&'r Value> + 'static>
2551    where
2552        Value: Sized,
2553        F: 'static,
2554        Root: 'static,
2555        Value: 'static,
2556    {
2557        let getter = self.getter;
2558        
2559        OptionalKeyPath {
2560            getter: move |arc: &Arc<Root>| {
2561                getter(arc.as_ref())
2562            },
2563            _phantom: PhantomData,
2564        }
2565    }
2566    
2567    // Overload: Adapt root type to Rc<Root> when Value is Sized (not a container)
2568    pub fn for_rc_root(self) -> OptionalKeyPath<Rc<Root>, Value, impl for<'r> Fn(&'r Rc<Root>) -> Option<&'r Value> + 'static>
2569    where
2570        Value: Sized,
2571        F: 'static,
2572        Root: 'static,
2573        Value: 'static,
2574    {
2575        let getter = self.getter;
2576        
2577        OptionalKeyPath {
2578            getter: move |rc: &Rc<Root>| {
2579                getter(rc.as_ref())
2580            },
2581            _phantom: PhantomData,
2582        }
2583    }
2584    
2585    /// Execute a closure with a reference to the value inside an Option
2586    pub fn with_option<Callback, R>(&self, option: &Option<Root>, f: Callback) -> Option<R>
2587    where
2588        F: Clone,
2589        Callback: FnOnce(&Value) -> R,
2590    {
2591        option.as_ref().and_then(|root| {
2592            self.get(root).map(|value| f(value))
2593        })
2594    }
2595    
2596    /// Execute a closure with a reference to the value inside a Mutex
2597    pub fn with_mutex<Callback, R>(&self, mutex: &Mutex<Root>, f: Callback) -> Option<R>
2598    where
2599        F: Clone,
2600        Callback: FnOnce(&Value) -> R,
2601    {
2602        mutex.lock().ok().and_then(|guard| {
2603            self.get(&*guard).map(|value| f(value))
2604        })
2605    }
2606    
2607    /// Execute a closure with a reference to the value inside an RwLock
2608    pub fn with_rwlock<Callback, R>(&self, rwlock: &RwLock<Root>, f: Callback) -> Option<R>
2609    where
2610        F: Clone,
2611        Callback: FnOnce(&Value) -> R,
2612    {
2613        rwlock.read().ok().and_then(|guard| {
2614            self.get(&*guard).map(|value| f(value))
2615        })
2616    }
2617    
2618    /// Execute a closure with a reference to the value inside an Arc<RwLock<Root>>
2619    pub fn with_arc_rwlock<Callback, R>(&self, arc_rwlock: &Arc<RwLock<Root>>, f: Callback) -> Option<R>
2620    where
2621        F: Clone,
2622        Callback: FnOnce(&Value) -> R,
2623    {
2624        arc_rwlock.read().ok().and_then(|guard| {
2625            self.get(&*guard).map(|value| f(value))
2626        })
2627    }
2628    
2629    /// Execute a closure with a reference to the value inside an Arc<RwLock<Root>>
2630    /// This is a convenience method that works directly with Arc<RwLock<T>>
2631    /// Unlike with_arc_rwlock, this doesn't require F: Clone
2632    pub fn with_arc_rwlock_direct<Callback, R>(&self, arc_rwlock: &Arc<RwLock<Root>>, f: Callback) -> Option<R>
2633    where
2634        Callback: FnOnce(&Value) -> R,
2635    {
2636        arc_rwlock.read().ok().and_then(|guard| {
2637            self.get(&*guard).map(|value| f(value))
2638        })
2639    }
2640    
2641    /// Execute a closure with a reference to the value inside an Arc<Mutex<Root>>
2642    pub fn with_arc_mutex<Callback, R>(&self, arc_mutex: &Arc<Mutex<Root>>, f: Callback) -> Option<R>
2643    where
2644        F: Clone,
2645        Callback: FnOnce(&Value) -> R,
2646    {
2647        arc_mutex.lock().ok().and_then(|guard| {
2648            self.get(&*guard).map(|value| f(value))
2649        })
2650    }
2651}
2652
2653// ========== PARKING_LOT CHAIN METHODS FOR OPTIONAL KEYPATH ==========
2654
2655#[cfg(feature = "parking_lot")]
2656impl<Root, InnerValue, F> OptionalKeyPath<Root, Arc<parking_lot::Mutex<InnerValue>>, F>
2657where
2658    F: for<'r> Fn(&'r Root) -> Option<&'r Arc<parking_lot::Mutex<InnerValue>>>,
2659{
2660    /// Chain this optional keypath with an inner keypath through Arc<parking_lot::Mutex<T>>
2661    pub fn then_arc_parking_mutex_at_kp<SubValue, G>(
2662        self,
2663        inner_keypath: KeyPath<InnerValue, SubValue, G>,
2664    ) -> OptionalArcParkingMutexKeyPathChain<Root, InnerValue, SubValue, F, G>
2665    where
2666        G: for<'r> Fn(&'r InnerValue) -> &'r SubValue,
2667    {
2668        OptionalArcParkingMutexKeyPathChain {
2669            outer_keypath: self,
2670            inner_keypath,
2671        }
2672    }
2673    
2674    /// Chain this optional keypath with an optional inner keypath through Arc<parking_lot::Mutex<T>>
2675    pub fn then_arc_parking_mutex_optional_at_kp<SubValue, G>(
2676        self,
2677        inner_keypath: OptionalKeyPath<InnerValue, SubValue, G>,
2678    ) -> OptionalArcParkingMutexOptionalKeyPathChain<Root, InnerValue, SubValue, F, G>
2679    where
2680        G: for<'r> Fn(&'r InnerValue) -> Option<&'r SubValue>,
2681    {
2682        OptionalArcParkingMutexOptionalKeyPathChain {
2683            outer_keypath: self,
2684            inner_keypath,
2685        }
2686    }
2687    
2688    /// Chain this optional keypath with a writable inner keypath through Arc<parking_lot::Mutex<T>>
2689    pub fn then_arc_parking_mutex_writable_at_kp<SubValue, G>(
2690        self,
2691        inner_keypath: WritableKeyPath<InnerValue, SubValue, G>,
2692    ) -> OptionalArcParkingMutexWritableKeyPathChain<Root, InnerValue, SubValue, F, G>
2693    where
2694        G: for<'r> Fn(&'r mut InnerValue) -> &'r mut SubValue,
2695    {
2696        OptionalArcParkingMutexWritableKeyPathChain {
2697            outer_keypath: self,
2698            inner_keypath,
2699        }
2700    }
2701    
2702    /// Chain this optional keypath with a writable optional inner keypath through Arc<parking_lot::Mutex<T>>
2703    pub fn then_arc_parking_mutex_writable_optional_at_kp<SubValue, G>(
2704        self,
2705        inner_keypath: WritableOptionalKeyPath<InnerValue, SubValue, G>,
2706    ) -> OptionalArcParkingMutexWritableOptionalKeyPathChain<Root, InnerValue, SubValue, F, G>
2707    where
2708        G: for<'r> Fn(&'r mut InnerValue) -> Option<&'r mut SubValue>,
2709    {
2710        OptionalArcParkingMutexWritableOptionalKeyPathChain {
2711            outer_keypath: self,
2712            inner_keypath,
2713        }
2714    }
2715}
2716
2717#[cfg(feature = "parking_lot")]
2718impl<Root, InnerValue, F> OptionalKeyPath<Root, Arc<parking_lot::RwLock<InnerValue>>, F>
2719where
2720    F: for<'r> Fn(&'r Root) -> Option<&'r Arc<parking_lot::RwLock<InnerValue>>>,
2721{
2722    /// Chain this optional keypath with an inner keypath through Arc<parking_lot::RwLock<T>>
2723    pub fn then_arc_parking_rwlock_at_kp<SubValue, G>(
2724        self,
2725        inner_keypath: KeyPath<InnerValue, SubValue, G>,
2726    ) -> OptionalArcParkingRwLockKeyPathChain<Root, InnerValue, SubValue, F, G>
2727    where
2728        G: for<'r> Fn(&'r InnerValue) -> &'r SubValue,
2729    {
2730        OptionalArcParkingRwLockKeyPathChain {
2731            outer_keypath: self,
2732            inner_keypath,
2733        }
2734    }
2735    
2736    /// Chain this optional keypath with an optional inner keypath through Arc<parking_lot::RwLock<T>>
2737    pub fn then_arc_parking_rwlock_optional_at_kp<SubValue, G>(
2738        self,
2739        inner_keypath: OptionalKeyPath<InnerValue, SubValue, G>,
2740    ) -> OptionalArcParkingRwLockOptionalKeyPathChain<Root, InnerValue, SubValue, F, G>
2741    where
2742        G: for<'r> Fn(&'r InnerValue) -> Option<&'r SubValue>,
2743    {
2744        OptionalArcParkingRwLockOptionalKeyPathChain {
2745            outer_keypath: self,
2746            inner_keypath,
2747        }
2748    }
2749    
2750    /// Chain this optional keypath with a writable inner keypath through Arc<parking_lot::RwLock<T>>
2751    pub fn then_arc_parking_rwlock_writable_at_kp<SubValue, G>(
2752        self,
2753        inner_keypath: WritableKeyPath<InnerValue, SubValue, G>,
2754    ) -> OptionalArcParkingRwLockWritableKeyPathChain<Root, InnerValue, SubValue, F, G>
2755    where
2756        G: for<'r> Fn(&'r mut InnerValue) -> &'r mut SubValue,
2757    {
2758        OptionalArcParkingRwLockWritableKeyPathChain {
2759            outer_keypath: self,
2760            inner_keypath,
2761        }
2762    }
2763    
2764    /// Chain this optional keypath with a writable optional inner keypath through Arc<parking_lot::RwLock<T>>
2765    pub fn then_arc_parking_rwlock_writable_optional_at_kp<SubValue, G>(
2766        self,
2767        inner_keypath: WritableOptionalKeyPath<InnerValue, SubValue, G>,
2768    ) -> OptionalArcParkingRwLockWritableOptionalKeyPathChain<Root, InnerValue, SubValue, F, G>
2769    where
2770        G: for<'r> Fn(&'r mut InnerValue) -> Option<&'r mut SubValue>,
2771    {
2772        OptionalArcParkingRwLockWritableOptionalKeyPathChain {
2773            outer_keypath: self,
2774            inner_keypath,
2775        }
2776    }
2777}
2778
2779
2780// WritableKeyPath for mutable access
2781#[derive(Clone)]
2782pub struct WritableKeyPath<Root, Value, F>
2783where
2784    F: for<'r> Fn(&'r mut Root) -> &'r mut Value,
2785{
2786    getter: F,
2787    _phantom: PhantomData<(Root, Value)>,
2788}
2789
2790impl<Root, Value, F> fmt::Display for WritableKeyPath<Root, Value, F>
2791where
2792    F: for<'r> Fn(&'r mut Root) -> &'r mut Value,
2793{
2794    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2795        let root_name = std::any::type_name::<Root>();
2796        let value_name = std::any::type_name::<Value>();
2797        // Simplify type names by removing module paths for cleaner output
2798        let root_short = root_name.split("::").last().unwrap_or(root_name);
2799        let value_short = value_name.split("::").last().unwrap_or(value_name);
2800        write!(f, "WritableKeyPath<{} -> {}>", root_short, value_short)
2801    }
2802}
2803
2804impl<Root, Value, F> fmt::Debug for WritableKeyPath<Root, Value, F>
2805where
2806    F: for<'r> Fn(&'r mut Root) -> &'r mut Value,
2807{
2808    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2809        fmt::Display::fmt(self, f)
2810    }
2811}
2812
2813impl<Root, Value, F> WritableKeyPath<Root, Value, F>
2814where
2815    F: for<'r> Fn(&'r mut Root) -> &'r mut Value,
2816{
2817    pub fn new(getter: F) -> Self {
2818        Self {
2819            getter,
2820            _phantom: PhantomData,
2821        }
2822    }
2823    
2824    pub fn get_mut<'r>(&self, root: &'r mut Root) -> &'r mut Value {
2825        (self.getter)(root)
2826    }
2827    
2828    /// Adapt this keypath to work with Result<Root, E> instead of Root
2829    /// This unwraps the Result and applies the keypath to the Ok value
2830    pub fn for_result<E>(self) -> WritableOptionalKeyPath<Result<Root, E>, Value, impl for<'r> Fn(&'r mut Result<Root, E>) -> Option<&'r mut Value> + 'static>
2831    where
2832        F: 'static,
2833        Root: 'static,
2834        Value: 'static,
2835        E: 'static,
2836    {
2837        let getter = self.getter;
2838        
2839        WritableOptionalKeyPath {
2840            getter: move |result: &mut Result<Root, E>| {
2841                result.as_mut().ok().map(|root| getter(root))
2842            },
2843            _phantom: PhantomData,
2844        }
2845    }
2846    
2847    // Overload: Adapt root type to Box<Root> when Value is Sized (not a container)
2848    pub fn for_box_root(self) -> WritableKeyPath<Box<Root>, Value, impl for<'r> Fn(&'r mut Box<Root>) -> &'r mut Value + 'static>
2849    where
2850        Value: Sized,
2851        F: 'static,
2852        Root: 'static,
2853        Value: 'static,
2854    {
2855        let getter = self.getter;
2856        
2857        WritableKeyPath {
2858            getter: move |boxed: &mut Box<Root>| {
2859                getter(boxed.as_mut())
2860            },
2861            _phantom: PhantomData,
2862        }
2863    }
2864    
2865    /// Adapt this keypath to work with Option<Root> instead of Root
2866    /// This unwraps the Option and applies the keypath to the Some value
2867    pub fn for_option(self) -> WritableOptionalKeyPath<Option<Root>, Value, impl for<'r> Fn(&'r mut Option<Root>) -> Option<&'r mut Value> + 'static>
2868    where
2869        F: 'static,
2870        Root: 'static,
2871        Value: 'static,
2872    {
2873        let getter = self.getter;
2874        
2875        WritableOptionalKeyPath {
2876            getter: move |option: &mut Option<Root>| {
2877                option.as_mut().map(|root| getter(root))
2878            },
2879            _phantom: PhantomData,
2880        }
2881    }
2882    
2883    /// Convert a WritableKeyPath to WritableOptionalKeyPath for chaining
2884    /// This allows non-optional writable keypaths to be chained with then()
2885    pub fn to_optional(self) -> WritableOptionalKeyPath<Root, Value, impl for<'r> Fn(&'r mut Root) -> Option<&'r mut Value> + 'static>
2886    where
2887        F: 'static,
2888    {
2889        let getter = self.getter;
2890        WritableOptionalKeyPath::new(move |root: &mut Root| Some(getter(root)))
2891    }
2892    
2893    // Instance methods for unwrapping containers (automatically infers Target from Value::Target)
2894    // Box<T> -> T
2895    pub fn for_box<Target>(self) -> WritableKeyPath<Root, Target, impl for<'r> Fn(&'r mut Root) -> &'r mut Target + 'static>
2896    where
2897        Value: std::ops::DerefMut<Target = Target>,
2898        F: 'static,
2899        Value: 'static,
2900    {
2901        let getter = self.getter;
2902        
2903        WritableKeyPath {
2904            getter: move |root: &mut Root| {
2905                getter(root).deref_mut()
2906            },
2907            _phantom: PhantomData,
2908        }
2909    }
2910    
2911    // Arc<T> -> T (Note: Arc doesn't support mutable access, but we provide it for consistency)
2912    // This will require interior mutability patterns
2913    pub fn for_arc<Target>(self) -> WritableKeyPath<Root, Target, impl for<'r> Fn(&'r mut Root) -> &'r mut Target + 'static>
2914    where
2915        Value: std::ops::DerefMut<Target = Target>,
2916        F: 'static,
2917        Value: 'static,
2918    {
2919        let getter = self.getter;
2920        
2921        WritableKeyPath {
2922            getter: move |root: &mut Root| {
2923                getter(root).deref_mut()
2924            },
2925            _phantom: PhantomData,
2926        }
2927    }
2928    
2929    // Rc<T> -> T (Note: Rc doesn't support mutable access, but we provide it for consistency)
2930    // This will require interior mutability patterns
2931    pub fn for_rc<Target>(self) -> WritableKeyPath<Root, Target, impl for<'r> Fn(&'r mut Root) -> &'r mut Target + 'static>
2932    where
2933        Value: std::ops::DerefMut<Target = Target>,
2934        F: 'static,
2935        Value: 'static,
2936    {
2937        let getter = self.getter;
2938        
2939        WritableKeyPath {
2940            getter: move |root: &mut Root| {
2941                getter(root).deref_mut()
2942            },
2943            _phantom: PhantomData,
2944        }
2945    }
2946    
2947    /// Execute a closure with a mutable reference to the value inside a Box
2948    pub fn with_box_mut<Callback, R>(&self, boxed: &mut Box<Root>, f: Callback) -> R
2949    where
2950        F: Clone,
2951        Callback: FnOnce(&mut Value) -> R,
2952    {
2953        let value = self.get_mut(boxed);
2954        f(value)
2955    }
2956    
2957    /// Execute a closure with a mutable reference to the value inside a Result
2958    pub fn with_result_mut<Callback, R, E>(&self, result: &mut Result<Root, E>, f: Callback) -> Option<R>
2959    where
2960        F: Clone,
2961        Callback: FnOnce(&mut Value) -> R,
2962    {
2963        result.as_mut().ok().map(|root| {
2964            let value = self.get_mut(root);
2965            f(value)
2966        })
2967    }
2968    
2969    /// Execute a closure with a mutable reference to the value inside an Option
2970    pub fn with_option_mut<Callback, R>(&self, option: &mut Option<Root>, f: Callback) -> Option<R>
2971    where
2972        F: Clone,
2973        Callback: FnOnce(&mut Value) -> R,
2974    {
2975        option.as_mut().map(|root| {
2976            let value = self.get_mut(root);
2977            f(value)
2978        })
2979    }
2980    
2981    /// Execute a closure with a mutable reference to the value inside a RefCell
2982    pub fn with_refcell_mut<Callback, R>(&self, refcell: &RefCell<Root>, f: Callback) -> Option<R>
2983    where
2984        F: Clone,
2985        Callback: FnOnce(&mut Value) -> R,
2986    {
2987        refcell.try_borrow_mut().ok().map(|mut borrow| {
2988            let value = self.get_mut(&mut *borrow);
2989            f(value)
2990        })
2991    }
2992    
2993    /// Execute a closure with a mutable reference to the value inside a Mutex
2994    pub fn with_mutex_mut<Callback, R>(&self, mutex: &mut Mutex<Root>, f: Callback) -> Option<R>
2995    where
2996        F: Clone,
2997        Callback: FnOnce(&mut Value) -> R,
2998    {
2999        mutex.get_mut().ok().map(|root| {
3000            let value = self.get_mut(root);
3001            f(value)
3002        })
3003    }
3004    
3005    /// Execute a closure with a mutable reference to the value inside an RwLock
3006    pub fn with_rwlock_mut<Callback, R>(&self, rwlock: &mut RwLock<Root>, f: Callback) -> Option<R>
3007    where
3008        F: Clone,
3009        Callback: FnOnce(&mut Value) -> R,
3010    {
3011        rwlock.write().ok().map(|mut guard| {
3012            let value = self.get_mut(&mut *guard);
3013            f(value)
3014        })
3015    }
3016    
3017    /// Get a mutable iterator over a Vec when Value is Vec<T>
3018    /// Returns Some(iterator) if the value is a Vec, None otherwise
3019    pub fn iter_mut<'r, T>(&self, root: &'r mut Root) -> Option<std::slice::IterMut<'r, T>>
3020    where
3021        Value: AsMut<[T]> + 'r,
3022    {
3023        let value_ref: &'r mut Value = self.get_mut(root);
3024        Some(value_ref.as_mut().iter_mut())
3025    }
3026    
3027    /// Extract mutable values from a slice of owned mutable values
3028    /// Returns a Vec of mutable references to the extracted values
3029    pub fn extract_mut_from_slice<'r>(&self, slice: &'r mut [Root]) -> Vec<&'r mut Value> {
3030        slice.iter_mut().map(|item| self.get_mut(item)).collect()
3031    }
3032    
3033    /// Extract mutable values from a slice of mutable references
3034    /// Returns a Vec of mutable references to the extracted values
3035    pub fn extract_mut_from_ref_slice<'r>(&self, slice: &'r mut [&'r mut Root]) -> Vec<&'r mut Value> {
3036        slice.iter_mut().map(|item| self.get_mut(*item)).collect()
3037    }
3038    
3039    /// Chain this keypath with another writable keypath
3040    /// Returns a WritableKeyPath that chains both keypaths
3041    pub fn then<SubValue, G>(
3042        self,
3043        next: WritableKeyPath<Value, SubValue, G>,
3044    ) -> WritableKeyPath<Root, SubValue, impl for<'r> Fn(&'r mut Root) -> &'r mut SubValue>
3045    where
3046        G: for<'r> Fn(&'r mut Value) -> &'r mut SubValue,
3047        F: 'static,
3048        G: 'static,
3049        Value: 'static,
3050    {
3051        let first = self.getter;
3052        let second = next.getter;
3053        
3054        WritableKeyPath::new(move |root: &mut Root| {
3055            let value = first(root);
3056            second(value)
3057        })
3058    }
3059    
3060    /// Chain this keypath with a writable optional keypath
3061    /// Returns a WritableOptionalKeyPath that chains both keypaths
3062    pub fn then_optional<SubValue, G>(
3063        self,
3064        next: WritableOptionalKeyPath<Value, SubValue, G>,
3065    ) -> WritableOptionalKeyPath<Root, SubValue, impl for<'r> Fn(&'r mut Root) -> Option<&'r mut SubValue>>
3066    where
3067        G: for<'r> Fn(&'r mut Value) -> Option<&'r mut SubValue>,
3068        F: 'static,
3069        G: 'static,
3070        Value: 'static,
3071    {
3072        let first = self.getter;
3073        let second = next.getter;
3074        
3075        WritableOptionalKeyPath::new(move |root: &mut Root| {
3076            let value = first(root);
3077            second(value)
3078        })
3079    }
3080}
3081
3082// WritableOptionalKeyPath for failable mutable access
3083#[derive(Clone)]
3084pub struct WritableOptionalKeyPath<Root, Value, F>
3085where
3086    F: for<'r> Fn(&'r mut Root) -> Option<&'r mut Value>,
3087{
3088    getter: F,
3089    _phantom: PhantomData<(Root, Value)>,
3090}
3091
3092impl<Root, Value, F> fmt::Display for WritableOptionalKeyPath<Root, Value, F>
3093where
3094    F: for<'r> Fn(&'r mut Root) -> Option<&'r mut Value>,
3095{
3096    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3097        let root_name = std::any::type_name::<Root>();
3098        let value_name = std::any::type_name::<Value>();
3099        // Simplify type names by removing module paths for cleaner output
3100        let root_short = root_name.split("::").last().unwrap_or(root_name);
3101        let value_short = value_name.split("::").last().unwrap_or(value_name);
3102        write!(f, "WritableOptionalKeyPath<{} -> Option<{}>>", root_short, value_short)
3103    }
3104}
3105
3106impl<Root, Value, F> fmt::Debug for WritableOptionalKeyPath<Root, Value, F>
3107where
3108    F: for<'r> Fn(&'r mut Root) -> Option<&'r mut Value>,
3109{
3110    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3111        // Show type information and indicate this is a chain that may fail
3112        let root_name = std::any::type_name::<Root>();
3113        let value_name = std::any::type_name::<Value>();
3114        let root_short = root_name.split("::").last().unwrap_or(root_name);
3115        let value_short = value_name.split("::").last().unwrap_or(value_name);
3116        
3117        // Use alternate format for more detailed debugging
3118        if f.alternate() {
3119            writeln!(f, "WritableOptionalKeyPath<{} -> Option<{}>>", root_short, value_short)?;
3120            writeln!(f, "  âš  Chain may break if any intermediate step returns None")?;
3121            writeln!(f, "  💡 Use trace_chain() to find where the chain breaks")
3122        } else {
3123            write!(f, "WritableOptionalKeyPath<{} -> Option<{}>>", root_short, value_short)
3124        }
3125    }
3126}
3127
3128impl<Root, Value, F> WritableOptionalKeyPath<Root, Value, F>
3129where
3130    F: for<'r> Fn(&'r mut Root) -> Option<&'r mut Value>,
3131{
3132    pub fn new(getter: F) -> Self {
3133        Self {
3134            getter,
3135            _phantom: PhantomData,
3136        }
3137    }
3138    
3139    pub fn get_mut<'r>(&self, root: &'r mut Root) -> Option<&'r mut Value> {
3140        (self.getter)(root)
3141    }
3142    
3143    /// Trace the chain to find where it breaks
3144    /// Returns Ok(()) if the chain succeeds, or Err with diagnostic information
3145    /// 
3146    /// # Example
3147    /// ```rust
3148    /// let path = SomeComplexStruct::scsf_fw()
3149    ///     .then(SomeOtherStruct::sosf_fw())
3150    ///     .then(SomeEnum::b_case_fw());
3151    /// 
3152    /// match path.trace_chain(&mut instance) {
3153    ///     Ok(()) => println!("Chain succeeded"),
3154    ///     Err(msg) => println!("Chain broken: {}", msg),
3155    /// }
3156    /// ```
3157    pub fn trace_chain(&self, root: &mut Root) -> Result<(), String> {
3158        match self.get_mut(root) {
3159            Some(_) => Ok(()),
3160            None => {
3161                let root_name = std::any::type_name::<Root>();
3162                let value_name = std::any::type_name::<Value>();
3163                let root_short = root_name.split("::").last().unwrap_or(root_name);
3164                let value_short = value_name.split("::").last().unwrap_or(value_name);
3165                Err(format!("{} -> Option<{}> returned None (chain broken at this step)", root_short, value_short))
3166            }
3167        }
3168    }
3169    
3170    /// Adapt this keypath to work with Option<Root> instead of Root
3171    /// This unwraps the Option and applies the keypath to the Some value
3172    pub fn for_option(self) -> WritableOptionalKeyPath<Option<Root>, Value, impl for<'r> Fn(&'r mut Option<Root>) -> Option<&'r mut Value> + 'static>
3173    where
3174        F: 'static,
3175        Root: 'static,
3176        Value: 'static,
3177    {
3178        let getter = self.getter;
3179        
3180        WritableOptionalKeyPath {
3181            getter: move |option: &mut Option<Root>| {
3182                option.as_mut().and_then(|root| getter(root))
3183            },
3184            _phantom: PhantomData,
3185        }
3186    }
3187    
3188    // Swift-like operator for chaining WritableOptionalKeyPath
3189    pub fn then<SubValue, G>(
3190        self,
3191        next: WritableOptionalKeyPath<Value, SubValue, G>,
3192    ) -> WritableOptionalKeyPath<Root, SubValue, impl for<'r> Fn(&'r mut Root) -> Option<&'r mut SubValue>>
3193    where
3194        G: for<'r> Fn(&'r mut Value) -> Option<&'r mut SubValue>,
3195        F: 'static,
3196        G: 'static,
3197        Value: 'static,
3198    {
3199        let first = self.getter;
3200        let second = next.getter;
3201        
3202        WritableOptionalKeyPath::new(move |root: &mut Root| {
3203            first(root).and_then(|value| second(value))
3204        })
3205    }
3206    
3207    // Instance methods for unwrapping containers from Option<Container<T>>
3208    // Option<Box<T>> -> Option<&mut T> (type automatically inferred from Value::Target)
3209    pub fn for_box<Target>(self) -> WritableOptionalKeyPath<Root, Target, impl for<'r> Fn(&'r mut Root) -> Option<&'r mut Target> + 'static>
3210    where
3211        Value: std::ops::DerefMut<Target = Target>,
3212        F: 'static,
3213        Value: 'static,
3214    {
3215        let getter = self.getter;
3216        
3217        WritableOptionalKeyPath {
3218            getter: move |root: &mut Root| {
3219                getter(root).map(|boxed| boxed.deref_mut())
3220            },
3221            _phantom: PhantomData,
3222        }
3223    }
3224    
3225    // Option<Arc<T>> -> Option<&mut T> (type automatically inferred from Value::Target)
3226    pub fn for_arc<Target>(self) -> WritableOptionalKeyPath<Root, Target, impl for<'r> Fn(&'r mut Root) -> Option<&'r mut Target> + 'static>
3227    where
3228        Value: std::ops::DerefMut<Target = Target>,
3229        F: 'static,
3230        Value: 'static,
3231    {
3232        let getter = self.getter;
3233        
3234        WritableOptionalKeyPath {
3235            getter: move |root: &mut Root| {
3236                getter(root).map(|arc| arc.deref_mut())
3237            },
3238            _phantom: PhantomData,
3239        }
3240    }
3241    
3242    // Option<Rc<T>> -> Option<&mut T> (type automatically inferred from Value::Target)
3243    pub fn for_rc<Target>(self) -> WritableOptionalKeyPath<Root, Target, impl for<'r> Fn(&'r mut Root) -> Option<&'r mut Target> + 'static>
3244    where
3245        Value: std::ops::DerefMut<Target = Target>,
3246        F: 'static,
3247        Value: 'static,
3248    {
3249        let getter = self.getter;
3250        
3251        WritableOptionalKeyPath {
3252            getter: move |root: &mut Root| {
3253                getter(root).map(|rc| rc.deref_mut())
3254            },
3255            _phantom: PhantomData,
3256        }
3257    }
3258    
3259    /// Adapt this keypath to work with Result<Root, E> instead of Root
3260    /// This unwraps the Result and applies the keypath to the Ok value
3261    pub fn for_result<E>(self) -> WritableOptionalKeyPath<Result<Root, E>, Value, impl for<'r> Fn(&'r mut Result<Root, E>) -> Option<&'r mut Value> + 'static>
3262    where
3263        F: 'static,
3264        Root: 'static,
3265        Value: 'static,
3266        E: 'static,
3267    {
3268        let getter = self.getter;
3269        
3270        WritableOptionalKeyPath {
3271            getter: move |result: &mut Result<Root, E>| {
3272                result.as_mut().ok().and_then(|root| getter(root))
3273            },
3274            _phantom: PhantomData,
3275        }
3276    }
3277    
3278    // Overload: Adapt root type to Box<Root> when Value is Sized (not a container)
3279    pub fn for_box_root(self) -> WritableOptionalKeyPath<Box<Root>, Value, impl for<'r> Fn(&'r mut Box<Root>) -> Option<&'r mut Value> + 'static>
3280    where
3281        Value: Sized,
3282        F: 'static,
3283        Root: 'static,
3284        Value: 'static,
3285    {
3286        let getter = self.getter;
3287        
3288        WritableOptionalKeyPath {
3289            getter: move |boxed: &mut Box<Root>| {
3290                getter(boxed.as_mut())
3291            },
3292            _phantom: PhantomData,
3293        }
3294    }
3295    
3296    // Overload: Adapt root type to Arc<Root> when Value is Sized (not a container)
3297    pub fn for_arc_root(self) -> WritableOptionalKeyPath<Arc<Root>, Value, impl for<'r> Fn(&'r mut Arc<Root>) -> Option<&'r mut Value> + 'static>
3298    where
3299        Value: Sized,
3300        F: 'static,
3301        Root: 'static,
3302        Value: 'static,
3303    {
3304        let getter = self.getter;
3305        
3306        WritableOptionalKeyPath {
3307            getter: move |arc: &mut Arc<Root>| {
3308                // Arc doesn't support mutable access without interior mutability
3309                // This will always return None, but we provide it for API consistency
3310                None
3311            },
3312            _phantom: PhantomData,
3313        }
3314    }
3315    
3316    // Overload: Adapt root type to Rc<Root> when Value is Sized (not a container)
3317    pub fn for_rc_root(self) -> WritableOptionalKeyPath<Rc<Root>, Value, impl for<'r> Fn(&'r mut Rc<Root>) -> Option<&'r mut Value> + 'static>
3318    where
3319        Value: Sized,
3320        F: 'static,
3321        Root: 'static,
3322        Value: 'static,
3323    {
3324        let getter = self.getter;
3325        
3326        WritableOptionalKeyPath {
3327            getter: move |rc: &mut Rc<Root>| {
3328                // Rc doesn't support mutable access without interior mutability
3329                // This will always return None, but we provide it for API consistency
3330                None
3331            },
3332            _phantom: PhantomData,
3333        }
3334    }
3335}
3336
3337// Static factory methods for WritableOptionalKeyPath
3338impl WritableOptionalKeyPath<(), (), fn(&mut ()) -> Option<&mut ()>> {
3339    // Static method for Option<T> -> Option<&mut T>
3340    // Note: This is a factory method. Use instance method `for_option()` to adapt existing keypaths.
3341    pub fn for_option_static<T>() -> WritableOptionalKeyPath<Option<T>, T, impl for<'r> Fn(&'r mut Option<T>) -> Option<&'r mut T>> {
3342        WritableOptionalKeyPath::new(|opt: &mut Option<T>| opt.as_mut())
3343    }
3344    
3345    /// Backword compatibility method for writable enum keypath
3346    // Create a writable enum keypath for enum variants
3347    /// This allows both reading and writing to enum variant fields
3348    /// 
3349    /// # Arguments
3350    /// * `embedder` - Function to embed a value into the enum variant (for API consistency, not used)
3351    /// * `read_extractor` - Function to extract a read reference from the enum (for API consistency, not used)
3352    /// * `write_extractor` - Function to extract a mutable reference from the enum
3353    /// 
3354    /// # Example
3355    /// ```rust
3356    /// enum Color { Other(RGBU8) }
3357    /// struct RGBU8(u8, u8, u8);
3358    /// 
3359    /// let case_path = WritableOptionalKeyPath::writable_enum(
3360    ///     |v| Color::Other(v),
3361    ///     |p: &Color| match p { Color::Other(rgb) => Some(rgb), _ => None },
3362    ///     |p: &mut Color| match p { Color::Other(rgb) => Some(rgb), _ => None },
3363    /// );
3364    /// ```
3365    pub fn writable_enum<Enum, Variant, EmbedFn, ReadExtractFn, WriteExtractFn>(
3366        _embedder: EmbedFn,
3367        _read_extractor: ReadExtractFn,
3368        write_extractor: WriteExtractFn,
3369    ) -> WritableOptionalKeyPath<Enum, Variant, impl for<'r> Fn(&'r mut Enum) -> Option<&'r mut Variant> + 'static>
3370    where
3371        EmbedFn: Fn(Variant) -> Enum + 'static,
3372        ReadExtractFn: for<'r> Fn(&'r Enum) -> Option<&'r Variant> + 'static,
3373        WriteExtractFn: for<'r> Fn(&'r mut Enum) -> Option<&'r mut Variant> + 'static,
3374    {
3375        WritableOptionalKeyPath::new(write_extractor)
3376    }
3377}
3378
3379// Enum-specific keypaths
3380/// EnumKeyPath - A keypath for enum variants that supports both extraction and embedding
3381/// Uses generic type parameters instead of dynamic dispatch for zero-cost abstraction
3382/// 
3383/// This struct serves dual purpose:
3384/// 1. As a concrete keypath instance: `EnumKeyPath<Enum, Variant, ExtractFn, EmbedFn>`
3385/// 2. As a namespace for static factory methods: `EnumKeyPath::readable_enum(...)`
3386pub struct EnumKeyPath<Enum = (), Variant = (), ExtractFn = fn(&()) -> Option<&()>, EmbedFn = fn(()) -> ()> 
3387where
3388    ExtractFn: for<'r> Fn(&'r Enum) -> Option<&'r Variant> + 'static,
3389    EmbedFn: Fn(Variant) -> Enum + 'static,
3390{
3391    extractor: OptionalKeyPath<Enum, Variant, ExtractFn>,
3392    embedder: EmbedFn,
3393}
3394
3395impl<Enum, Variant, ExtractFn, EmbedFn> EnumKeyPath<Enum, Variant, ExtractFn, EmbedFn>
3396where
3397    ExtractFn: for<'r> Fn(&'r Enum) -> Option<&'r Variant> + 'static,
3398    EmbedFn: Fn(Variant) -> Enum + 'static,
3399{
3400    /// Create a new EnumKeyPath with extractor and embedder functions
3401    pub fn new(
3402        extractor: ExtractFn,
3403        embedder: EmbedFn,
3404    ) -> Self {
3405        Self {
3406            extractor: OptionalKeyPath::new(extractor),
3407            embedder,
3408        }
3409    }
3410    
3411    /// Extract the value from an enum variant
3412    pub fn get<'r>(&self, enum_value: &'r Enum) -> Option<&'r Variant> {
3413        self.extractor.get(enum_value)
3414    }
3415    
3416    /// Embed a value into the enum variant
3417    pub fn embed(&self, value: Variant) -> Enum {
3418        (self.embedder)(value)
3419    }
3420    
3421    /// Get the underlying OptionalKeyPath for composition
3422    pub fn as_optional(&self) -> &OptionalKeyPath<Enum, Variant, ExtractFn> {
3423        &self.extractor
3424    }
3425    
3426    /// Convert to OptionalKeyPath (loses embedding capability but gains composition)
3427    pub fn to_optional(self) -> OptionalKeyPath<Enum, Variant, ExtractFn> {
3428        self.extractor
3429    }
3430}
3431
3432// Static factory methods for EnumKeyPath
3433impl EnumKeyPath {
3434    /// Create a readable enum keypath with both extraction and embedding
3435    /// Returns an EnumKeyPath that supports both get() and embed() operations
3436    pub fn readable_enum<Enum, Variant, ExtractFn, EmbedFn>(
3437        embedder: EmbedFn,
3438        extractor: ExtractFn,
3439    ) -> EnumKeyPath<Enum, Variant, ExtractFn, EmbedFn>
3440    where
3441        ExtractFn: for<'r> Fn(&'r Enum) -> Option<&'r Variant> + 'static,
3442        EmbedFn: Fn(Variant) -> Enum + 'static,
3443    {
3444        EnumKeyPath::new(extractor, embedder)
3445    }
3446    
3447    /// Extract from a specific enum variant
3448    pub fn for_variant<Enum, Variant, ExtractFn>(
3449        extractor: ExtractFn
3450    ) -> OptionalKeyPath<Enum, Variant, impl for<'r> Fn(&'r Enum) -> Option<&'r Variant>>
3451    where
3452        ExtractFn: Fn(&Enum) -> Option<&Variant>,
3453    {
3454        OptionalKeyPath::new(extractor)
3455    }
3456    
3457    /// Match against multiple variants (returns a tagged union)
3458    pub fn for_match<Enum, Output, MatchFn>(
3459        matcher: MatchFn
3460    ) -> KeyPath<Enum, Output, impl for<'r> Fn(&'r Enum) -> &'r Output>
3461    where
3462        MatchFn: Fn(&Enum) -> &Output,
3463    {
3464        KeyPath::new(matcher)
3465    }
3466    
3467    /// Extract from Result<T, E> - Ok variant
3468    pub fn for_ok<T, E>() -> OptionalKeyPath<Result<T, E>, T, impl for<'r> Fn(&'r Result<T, E>) -> Option<&'r T>> {
3469        OptionalKeyPath::new(|result: &Result<T, E>| result.as_ref().ok())
3470    }
3471    
3472    /// Extract from Result<T, E> - Err variant
3473    pub fn for_err<T, E>() -> OptionalKeyPath<Result<T, E>, E, impl for<'r> Fn(&'r Result<T, E>) -> Option<&'r E>> {
3474        OptionalKeyPath::new(|result: &Result<T, E>| result.as_ref().err())
3475    }
3476    
3477    /// Extract from Option<T> - Some variant
3478    pub fn for_some<T>() -> OptionalKeyPath<Option<T>, T, impl for<'r> Fn(&'r Option<T>) -> Option<&'r T>> {
3479        OptionalKeyPath::new(|opt: &Option<T>| opt.as_ref())
3480    }
3481    
3482    /// Extract from Option<T> - Some variant (alias for for_some for consistency)
3483    pub fn for_option<T>() -> OptionalKeyPath<Option<T>, T, impl for<'r> Fn(&'r Option<T>) -> Option<&'r T>> {
3484        OptionalKeyPath::new(|opt: &Option<T>| opt.as_ref())
3485    }
3486    
3487    /// Unwrap Box<T> -> T
3488    pub fn for_box<T>() -> KeyPath<Box<T>, T, impl for<'r> Fn(&'r Box<T>) -> &'r T> {
3489        KeyPath::new(|b: &Box<T>| b.as_ref())
3490    }
3491    
3492    /// Unwrap Arc<T> -> T
3493    pub fn for_arc<T>() -> KeyPath<Arc<T>, T, impl for<'r> Fn(&'r Arc<T>) -> &'r T> {
3494        KeyPath::new(|arc: &Arc<T>| arc.as_ref())
3495    }
3496    
3497    /// Unwrap Rc<T> -> T
3498    pub fn for_rc<T>() -> KeyPath<std::rc::Rc<T>, T, impl for<'r> Fn(&'r std::rc::Rc<T>) -> &'r T> {
3499        KeyPath::new(|rc: &std::rc::Rc<T>| rc.as_ref())
3500    }
3501
3502    /// Unwrap Box<T> -> T (mutable)
3503    pub fn for_box_mut<T>() -> WritableKeyPath<Box<T>, T, impl for<'r> Fn(&'r mut Box<T>) -> &'r mut T> {
3504        WritableKeyPath::new(|b: &mut Box<T>| b.as_mut())
3505    }
3506
3507    // Note: Arc<T> and Rc<T> don't support direct mutable access without interior mutability
3508    // (e.g., Arc<Mutex<T>> or Rc<RefCell<T>>). These methods are not provided as they
3509    // would require unsafe code or interior mutability patterns.
3510}
3511
3512// Helper to create enum variant keypaths with type inference
3513pub fn variant_of<Enum, Variant, F>(extractor: F) -> OptionalKeyPath<Enum, Variant, F>
3514where
3515    F: for<'r> Fn(&'r Enum) -> Option<&'r Variant>,
3516{
3517    OptionalKeyPath::new(extractor)
3518}
3519
3520// ========== PARTIAL KEYPATHS (Hide Value Type) ==========
3521
3522/// PartialKeyPath - Hides the Value type but keeps Root visible
3523/// Useful for storing keypaths in collections without knowing the exact Value type
3524/// 
3525/// # Why PhantomData<Root>?
3526/// 
3527/// `PhantomData<Root>` is needed because:
3528/// 1. The `Root` type parameter is not actually stored in the struct (only used in the closure)
3529/// 2. Rust needs to know the generic type parameter for:
3530///    - Type checking at compile time
3531///    - Ensuring correct usage (e.g., `PartialKeyPath<User>` can only be used with `&User`)
3532///    - Preventing mixing different Root types
3533/// 3. Without `PhantomData`, Rust would complain that `Root` is unused
3534/// 4. `PhantomData` is zero-sized - it adds no runtime overhead
3535#[derive(Clone)]
3536pub struct PartialKeyPath<Root> {
3537    getter: Rc<dyn for<'r> Fn(&'r Root) -> &'r dyn Any>,
3538    value_type_id: TypeId,
3539    _phantom: PhantomData<Root>,
3540}
3541
3542impl<Root> PartialKeyPath<Root> {
3543    pub fn new<Value>(keypath: KeyPath<Root, Value, impl for<'r> Fn(&'r Root) -> &'r Value + 'static>) -> Self
3544    where
3545        Value: Any + 'static,
3546        Root: 'static,
3547    {
3548        let value_type_id = TypeId::of::<Value>();
3549        let getter = Rc::new(keypath.getter);
3550        
3551        Self {
3552            getter: Rc::new(move |root: &Root| {
3553                let value: &Value = getter(root);
3554                value as &dyn Any
3555            }),
3556            value_type_id,
3557            _phantom: PhantomData,
3558        }
3559    }
3560    
3561    /// Create a PartialKeyPath from a concrete KeyPath
3562    /// Alias for `new()` for consistency with `from()` pattern
3563    pub fn from<Value>(keypath: KeyPath<Root, Value, impl for<'r> Fn(&'r Root) -> &'r Value + 'static>) -> Self
3564    where
3565        Value: Any + 'static,
3566        Root: 'static,
3567    {
3568        Self::new(keypath)
3569    }
3570    
3571    pub fn get<'r>(&self, root: &'r Root) -> &'r dyn Any {
3572        (self.getter)(root)
3573    }
3574    
3575    /// Get the TypeId of the Value type
3576    pub fn value_type_id(&self) -> TypeId {
3577        self.value_type_id
3578    }
3579    
3580    /// Try to downcast the result to a specific type
3581    pub fn get_as<'a, Value: Any>(&self, root: &'a Root) -> Option<&'a Value> {
3582        if self.value_type_id == TypeId::of::<Value>() {
3583            self.get(root).downcast_ref::<Value>()
3584        } else {
3585            None
3586        }
3587    }
3588    
3589    /// Get a human-readable name for the value type
3590    /// Returns a string representation of the TypeId
3591    pub fn kind_name(&self) -> String {
3592        format!("{:?}", self.value_type_id)
3593    }
3594    
3595    /// Adapt this keypath to work with Arc<Root> instead of Root
3596    pub fn for_arc(&self) -> PartialOptionalKeyPath<Arc<Root>>
3597    where
3598        Root: 'static,
3599    {
3600        let getter = self.getter.clone();
3601        let value_type_id = self.value_type_id;
3602        
3603        PartialOptionalKeyPath {
3604            getter: Rc::new(move |arc: &Arc<Root>| {
3605                Some(getter(arc.as_ref()))
3606            }),
3607            value_type_id,
3608            _phantom: PhantomData,
3609        }
3610    }
3611    
3612    /// Adapt this keypath to work with Box<Root> instead of Root
3613    pub fn for_box(&self) -> PartialOptionalKeyPath<Box<Root>>
3614    where
3615        Root: 'static,
3616    {
3617        let getter = self.getter.clone();
3618        let value_type_id = self.value_type_id;
3619        
3620        PartialOptionalKeyPath {
3621            getter: Rc::new(move |boxed: &Box<Root>| {
3622                Some(getter(boxed.as_ref()))
3623            }),
3624            value_type_id,
3625            _phantom: PhantomData,
3626        }
3627    }
3628    
3629    /// Adapt this keypath to work with Rc<Root> instead of Root
3630    pub fn for_rc(&self) -> PartialOptionalKeyPath<Rc<Root>>
3631    where
3632        Root: 'static,
3633    {
3634        let getter = self.getter.clone();
3635        let value_type_id = self.value_type_id;
3636        
3637        PartialOptionalKeyPath {
3638            getter: Rc::new(move |rc: &Rc<Root>| {
3639                Some(getter(rc.as_ref()))
3640            }),
3641            value_type_id,
3642            _phantom: PhantomData,
3643        }
3644    }
3645    
3646    /// Adapt this keypath to work with Option<Root> instead of Root
3647    pub fn for_option(&self) -> PartialOptionalKeyPath<Option<Root>>
3648    where
3649        Root: 'static,
3650    {
3651        let getter = self.getter.clone();
3652        let value_type_id = self.value_type_id;
3653        
3654        PartialOptionalKeyPath {
3655            getter: Rc::new(move |opt: &Option<Root>| {
3656                opt.as_ref().map(|root| getter(root))
3657            }),
3658            value_type_id,
3659            _phantom: PhantomData,
3660        }
3661    }
3662    
3663    /// Adapt this keypath to work with Result<Root, E> instead of Root
3664    pub fn for_result<E>(&self) -> PartialOptionalKeyPath<Result<Root, E>>
3665    where
3666        Root: 'static,
3667        E: 'static,
3668    {
3669        let getter = self.getter.clone();
3670        let value_type_id = self.value_type_id;
3671        
3672        PartialOptionalKeyPath {
3673            getter: Rc::new(move |result: &Result<Root, E>| {
3674                result.as_ref().ok().map(|root| getter(root))
3675            }),
3676            value_type_id,
3677            _phantom: PhantomData,
3678        }
3679    }
3680    
3681    /// Adapt this keypath to work with Arc<RwLock<Root>> instead of Root
3682    /// Note: This requires the Root to be cloned first, then use the keypath on the cloned value
3683    /// Example: `keypath.get_as::<Value>(&arc_rwlock.read().unwrap().clone())`
3684    pub fn for_arc_rwlock(&self) -> PartialOptionalKeyPath<Arc<RwLock<Root>>>
3685    where
3686        Root: Clone + 'static,
3687    {
3688        // We can't return a reference from a guard, so we return None
3689        // Users should clone the root first: arc_rwlock.read().unwrap().clone()
3690        PartialOptionalKeyPath {
3691            getter: Rc::new(move |_arc_rwlock: &Arc<RwLock<Root>>| {
3692                // Cannot return reference from temporary guard
3693                // User should clone the root first and use the keypath on the cloned value
3694                None
3695            }),
3696            value_type_id: self.value_type_id,
3697            _phantom: PhantomData,
3698        }
3699    }
3700    
3701    /// Adapt this keypath to work with Arc<Mutex<Root>> instead of Root
3702    /// Note: This requires the Root to be cloned first, then use the keypath on the cloned value
3703    /// Example: `keypath.get_as::<Value>(&arc_mutex.lock().unwrap().clone())`
3704    pub fn for_arc_mutex(&self) -> PartialOptionalKeyPath<Arc<Mutex<Root>>>
3705    where
3706        Root: Clone + 'static,
3707    {
3708        // We can't return a reference from a guard, so we return None
3709        // Users should clone the root first: arc_mutex.lock().unwrap().clone()
3710        PartialOptionalKeyPath {
3711            getter: Rc::new(move |_arc_mutex: &Arc<Mutex<Root>>| {
3712                // Cannot return reference from temporary guard
3713                // User should clone the root first and use the keypath on the cloned value
3714                None
3715            }),
3716            value_type_id: self.value_type_id,
3717            _phantom: PhantomData,
3718        }
3719    }
3720}
3721
3722/// PartialOptionalKeyPath - Hides the Value type but keeps Root visible
3723/// Useful for storing optional keypaths in collections without knowing the exact Value type
3724/// 
3725/// # Why PhantomData<Root>?
3726/// 
3727/// See `PartialKeyPath` documentation for explanation of why `PhantomData` is needed.
3728#[derive(Clone)]
3729pub struct PartialOptionalKeyPath<Root> {
3730    getter: Rc<dyn for<'r> Fn(&'r Root) -> Option<&'r dyn Any>>,
3731    value_type_id: TypeId,
3732    _phantom: PhantomData<Root>,
3733}
3734
3735impl<Root> PartialOptionalKeyPath<Root> {
3736    pub fn new<Value>(keypath: OptionalKeyPath<Root, Value, impl for<'r> Fn(&'r Root) -> Option<&'r Value> + 'static>) -> Self
3737    where
3738        Value: Any + 'static,
3739        Root: 'static,
3740    {
3741        let value_type_id = TypeId::of::<Value>();
3742        let getter = Rc::new(keypath.getter);
3743        
3744        Self {
3745            getter: Rc::new(move |root: &Root| {
3746                getter(root).map(|value: &Value| value as &dyn Any)
3747            }),
3748            value_type_id,
3749            _phantom: PhantomData,
3750        }
3751    }
3752    
3753    pub fn get<'r>(&self, root: &'r Root) -> Option<&'r dyn Any> {
3754        (self.getter)(root)
3755    }
3756    
3757    /// Get the TypeId of the Value type
3758    pub fn value_type_id(&self) -> TypeId {
3759        self.value_type_id
3760    }
3761    
3762    /// Try to downcast the result to a specific type
3763    pub fn get_as<'a, Value: Any>(&self, root: &'a Root) -> Option<Option<&'a Value>> {
3764        if self.value_type_id == TypeId::of::<Value>() {
3765            self.get(root).map(|any| any.downcast_ref::<Value>())
3766        } else {
3767            None
3768        }
3769    }
3770    
3771    /// Chain with another PartialOptionalKeyPath
3772    /// Note: This requires the Value type of the first keypath to match the Root type of the second
3773    /// For type-erased chaining, consider using AnyKeyPath instead
3774    pub fn then<MidValue>(
3775        self,
3776        next: PartialOptionalKeyPath<MidValue>,
3777    ) -> PartialOptionalKeyPath<Root>
3778    where
3779        MidValue: Any + 'static,
3780        Root: 'static,
3781    {
3782        let first = self.getter;
3783        let second = next.getter;
3784        let value_type_id = next.value_type_id;
3785        
3786        PartialOptionalKeyPath {
3787            getter: Rc::new(move |root: &Root| {
3788                first(root).and_then(|any| {
3789                    if let Some(mid_value) = any.downcast_ref::<MidValue>() {
3790                        second(mid_value)
3791                    } else {
3792                        None
3793                    }
3794                })
3795            }),
3796            value_type_id,
3797            _phantom: PhantomData,
3798        }
3799    }
3800}
3801
3802/// PartialWritableKeyPath - Hides the Value type but keeps Root visible (writable)
3803/// 
3804/// # Why PhantomData<Root>?
3805/// 
3806/// See `PartialKeyPath` documentation for explanation of why `PhantomData` is needed.
3807#[derive(Clone)]
3808pub struct PartialWritableKeyPath<Root> {
3809    getter: Rc<dyn for<'r> Fn(&'r mut Root) -> &'r mut dyn Any>,
3810    value_type_id: TypeId,
3811    _phantom: PhantomData<Root>,
3812}
3813
3814impl<Root> PartialWritableKeyPath<Root> {
3815    pub fn new<Value>(keypath: WritableKeyPath<Root, Value, impl for<'r> Fn(&'r mut Root) -> &'r mut Value + 'static>) -> Self
3816    where
3817        Value: Any + 'static,
3818        Root: 'static,
3819    {
3820        let value_type_id = TypeId::of::<Value>();
3821        let getter = Rc::new(keypath.getter);
3822        
3823        Self {
3824            getter: Rc::new(move |root: &mut Root| {
3825                let value: &mut Value = getter(root);
3826                value as &mut dyn Any
3827            }),
3828            value_type_id,
3829            _phantom: PhantomData,
3830        }
3831    }
3832    
3833    /// Create a PartialWritableKeyPath from a concrete WritableKeyPath
3834    /// Alias for `new()` for consistency with `from()` pattern
3835    pub fn from<Value>(keypath: WritableKeyPath<Root, Value, impl for<'r> Fn(&'r mut Root) -> &'r mut Value + 'static>) -> Self
3836    where
3837        Value: Any + 'static,
3838        Root: 'static,
3839    {
3840        Self::new(keypath)
3841    }
3842    
3843    pub fn get_mut<'r>(&self, root: &'r mut Root) -> &'r mut dyn Any {
3844        (self.getter)(root)
3845    }
3846    
3847    /// Get the TypeId of the Value type
3848    pub fn value_type_id(&self) -> TypeId {
3849        self.value_type_id
3850    }
3851    
3852    /// Try to downcast the result to a specific type
3853    pub fn get_mut_as<'a, Value: Any>(&self, root: &'a mut Root) -> Option<&'a mut Value> {
3854        if self.value_type_id == TypeId::of::<Value>() {
3855            self.get_mut(root).downcast_mut::<Value>()
3856        } else {
3857            None
3858        }
3859    }
3860}
3861
3862/// PartialWritableOptionalKeyPath - Hides the Value type but keeps Root visible (writable optional)
3863/// 
3864/// # Why PhantomData<Root>?
3865/// 
3866/// See `PartialKeyPath` documentation for explanation of why `PhantomData` is needed.
3867#[derive(Clone)]
3868pub struct PartialWritableOptionalKeyPath<Root> {
3869    getter: Rc<dyn for<'r> Fn(&'r mut Root) -> Option<&'r mut dyn Any>>,
3870    value_type_id: TypeId,
3871    _phantom: PhantomData<Root>,
3872}
3873
3874impl<Root> PartialWritableOptionalKeyPath<Root> {
3875    pub fn new<Value>(keypath: WritableOptionalKeyPath<Root, Value, impl for<'r> Fn(&'r mut Root) -> Option<&'r mut Value> + 'static>) -> Self
3876    where
3877        Value: Any + 'static,
3878        Root: 'static,
3879    {
3880        let value_type_id = TypeId::of::<Value>();
3881        let getter = Rc::new(keypath.getter);
3882        
3883        Self {
3884            getter: Rc::new(move |root: &mut Root| {
3885                getter(root).map(|value: &mut Value| value as &mut dyn Any)
3886            }),
3887            value_type_id,
3888            _phantom: PhantomData,
3889        }
3890    }
3891    
3892    pub fn get_mut<'r>(&self, root: &'r mut Root) -> Option<&'r mut dyn Any> {
3893        (self.getter)(root)
3894    }
3895    
3896    /// Get the TypeId of the Value type
3897    pub fn value_type_id(&self) -> TypeId {
3898        self.value_type_id
3899    }
3900    
3901    /// Try to downcast the result to a specific type
3902    pub fn get_mut_as<'a, Value: Any>(&self, root: &'a mut Root) -> Option<Option<&'a mut Value>> {
3903        if self.value_type_id == TypeId::of::<Value>() {
3904            self.get_mut(root).map(|any| any.downcast_mut::<Value>())
3905        } else {
3906            None
3907        }
3908    }
3909}
3910
3911// ========== ANY KEYPATHS (Hide Both Root and Value Types) ==========
3912
3913/// AnyKeyPath - Hides both Root and Value types
3914/// Equivalent to Swift's AnyKeyPath
3915/// Useful for storing keypaths in collections without knowing either type
3916/// 
3917/// # Why No PhantomData?
3918/// 
3919/// Unlike `PartialKeyPath`, `AnyKeyPath` doesn't need `PhantomData` because:
3920/// - Both `Root` and `Value` types are completely erased
3921/// - We store `TypeId` instead for runtime type checking
3922/// - The type information is encoded in the closure's behavior, not the struct
3923/// - There's no generic type parameter to track at compile time
3924#[derive(Clone)]
3925pub struct AnyKeyPath {
3926    getter: Rc<dyn for<'r> Fn(&'r dyn Any) -> Option<&'r dyn Any>>,
3927    root_type_id: TypeId,
3928    value_type_id: TypeId,
3929}
3930
3931impl AnyKeyPath {
3932    pub fn new<Root, Value>(keypath: OptionalKeyPath<Root, Value, impl for<'r> Fn(&'r Root) -> Option<&'r Value> + 'static>) -> Self
3933    where
3934        Root: Any + 'static,
3935        Value: Any + 'static,
3936    {
3937        let root_type_id = TypeId::of::<Root>();
3938        let value_type_id = TypeId::of::<Value>();
3939        let getter = keypath.getter;
3940        
3941        Self {
3942            getter: Rc::new(move |any: &dyn Any| {
3943                if let Some(root) = any.downcast_ref::<Root>() {
3944                    getter(root).map(|value: &Value| value as &dyn Any)
3945                } else {
3946                    None
3947                }
3948            }),
3949            root_type_id,
3950            value_type_id,
3951        }
3952    }
3953    
3954    /// Create an AnyKeyPath from a concrete OptionalKeyPath
3955    /// Alias for `new()` for consistency with `from()` pattern
3956    pub fn from<Root, Value>(keypath: OptionalKeyPath<Root, Value, impl for<'r> Fn(&'r Root) -> Option<&'r Value> + 'static>) -> Self
3957    where
3958        Root: Any + 'static,
3959        Value: Any + 'static,
3960    {
3961        Self::new(keypath)
3962    }
3963    
3964    pub fn get<'r>(&self, root: &'r dyn Any) -> Option<&'r dyn Any> {
3965        (self.getter)(root)
3966    }
3967    
3968    /// Get the TypeId of the Root type
3969    pub fn root_type_id(&self) -> TypeId {
3970        self.root_type_id
3971    }
3972    
3973    /// Get the TypeId of the Value type
3974    pub fn value_type_id(&self) -> TypeId {
3975        self.value_type_id
3976    }
3977    
3978    /// Try to get the value with type checking
3979    pub fn get_as<'a, Root: Any, Value: Any>(&self, root: &'a Root) -> Option<Option<&'a Value>> {
3980        if self.root_type_id == TypeId::of::<Root>() && self.value_type_id == TypeId::of::<Value>() {
3981            self.get(root as &dyn Any).map(|any| any.downcast_ref::<Value>())
3982        } else {
3983            None
3984        }
3985    }
3986    
3987    /// Get a human-readable name for the value type
3988    /// Returns a string representation of the TypeId
3989    pub fn kind_name(&self) -> String {
3990        format!("{:?}", self.value_type_id)
3991    }
3992    
3993    /// Adapt this keypath to work with Arc<Root> instead of Root
3994    pub fn for_arc<Root>(&self) -> AnyKeyPath
3995    where
3996        Root: Any + 'static,
3997    {
3998        let root_type_id = self.root_type_id;
3999        let value_type_id = self.value_type_id;
4000        let getter = self.getter.clone();
4001        
4002        AnyKeyPath {
4003            getter: Rc::new(move |any: &dyn Any| {
4004                if let Some(arc) = any.downcast_ref::<Arc<Root>>() {
4005                    getter(arc.as_ref() as &dyn Any)
4006                } else {
4007                    None
4008                }
4009            }),
4010            root_type_id: TypeId::of::<Arc<Root>>(),
4011            value_type_id,
4012        }
4013    }
4014    
4015    /// Adapt this keypath to work with Box<Root> instead of Root
4016    pub fn for_box<Root>(&self) -> AnyKeyPath
4017    where
4018        Root: Any + 'static,
4019    {
4020        let root_type_id = self.root_type_id;
4021        let value_type_id = self.value_type_id;
4022        let getter = self.getter.clone();
4023        
4024        AnyKeyPath {
4025            getter: Rc::new(move |any: &dyn Any| {
4026                if let Some(boxed) = any.downcast_ref::<Box<Root>>() {
4027                    getter(boxed.as_ref() as &dyn Any)
4028                } else {
4029                    None
4030                }
4031            }),
4032            root_type_id: TypeId::of::<Box<Root>>(),
4033            value_type_id,
4034        }
4035    }
4036    
4037    /// Adapt this keypath to work with Rc<Root> instead of Root
4038    pub fn for_rc<Root>(&self) -> AnyKeyPath
4039    where
4040        Root: Any + 'static,
4041    {
4042        let root_type_id = self.root_type_id;
4043        let value_type_id = self.value_type_id;
4044        let getter = self.getter.clone();
4045        
4046        AnyKeyPath {
4047            getter: Rc::new(move |any: &dyn Any| {
4048                if let Some(rc) = any.downcast_ref::<Rc<Root>>() {
4049                    getter(rc.as_ref() as &dyn Any)
4050                } else {
4051                    None
4052                }
4053            }),
4054            root_type_id: TypeId::of::<Rc<Root>>(),
4055            value_type_id,
4056        }
4057    }
4058    
4059    /// Adapt this keypath to work with Option<Root> instead of Root
4060    pub fn for_option<Root>(&self) -> AnyKeyPath
4061    where
4062        Root: Any + 'static,
4063    {
4064        let root_type_id = self.root_type_id;
4065        let value_type_id = self.value_type_id;
4066        let getter = self.getter.clone();
4067        
4068        AnyKeyPath {
4069            getter: Rc::new(move |any: &dyn Any| {
4070                if let Some(opt) = any.downcast_ref::<Option<Root>>() {
4071                    opt.as_ref().and_then(|root| getter(root as &dyn Any))
4072                } else {
4073                    None
4074                }
4075            }),
4076            root_type_id: TypeId::of::<Option<Root>>(),
4077            value_type_id,
4078        }
4079    }
4080    
4081    /// Adapt this keypath to work with Result<Root, E> instead of Root
4082    pub fn for_result<Root, E>(&self) -> AnyKeyPath
4083    where
4084        Root: Any + 'static,
4085        E: Any + 'static,
4086    {
4087        let root_type_id = self.root_type_id;
4088        let value_type_id = self.value_type_id;
4089        let getter = self.getter.clone();
4090        
4091        AnyKeyPath {
4092            getter: Rc::new(move |any: &dyn Any| {
4093                if let Some(result) = any.downcast_ref::<Result<Root, E>>() {
4094                    result.as_ref().ok().and_then(|root| getter(root as &dyn Any))
4095                } else {
4096                    None
4097                }
4098            }),
4099            root_type_id: TypeId::of::<Result<Root, E>>(),
4100            value_type_id,
4101        }
4102    }
4103    
4104    /// Adapt this keypath to work with Arc<RwLock<Root>> instead of Root
4105    /// Note: This requires the Root to be cloned first, then use the keypath on the cloned value
4106    pub fn for_arc_rwlock<Root>(&self) -> AnyKeyPath
4107    where
4108        Root: Any + Clone + 'static,
4109    {
4110        // We can't return a reference from a guard, so we return None
4111        // Users should clone the root first
4112        AnyKeyPath {
4113            getter: Rc::new(move |_any: &dyn Any| {
4114                // Cannot return reference from temporary guard
4115                // User should clone the root first and use the keypath on the cloned value
4116                None
4117            }),
4118            root_type_id: TypeId::of::<Arc<RwLock<Root>>>(),
4119            value_type_id: self.value_type_id,
4120        }
4121    }
4122    
4123    /// Adapt this keypath to work with Arc<Mutex<Root>> instead of Root
4124    /// Note: This requires the Root to be cloned first, then use the keypath on the cloned value
4125    pub fn for_arc_mutex<Root>(&self) -> AnyKeyPath
4126    where
4127        Root: Any + Clone + 'static,
4128    {
4129        // We can't return a reference from a guard, so we return None
4130        // Users should clone the root first
4131        AnyKeyPath {
4132            getter: Rc::new(move |_any: &dyn Any| {
4133                // Cannot return reference from temporary guard
4134                // User should clone the root first and use the keypath on the cloned value
4135                None
4136            }),
4137            root_type_id: TypeId::of::<Arc<Mutex<Root>>>(),
4138            value_type_id: self.value_type_id,
4139        }
4140    }
4141}
4142
4143/// AnyWritableKeyPath - Hides both Root and Value types (writable)
4144#[derive(Clone)]
4145pub struct AnyWritableKeyPath {
4146    getter: Rc<dyn for<'r> Fn(&'r mut dyn Any) -> Option<&'r mut dyn Any>>,
4147    root_type_id: TypeId,
4148    value_type_id: TypeId,
4149}
4150
4151/// FailableCombinedKeyPath - A keypath that supports readable, writable, and owned access patterns
4152/// 
4153/// This keypath type combines the functionality of OptionalKeyPath, WritableOptionalKeyPath,
4154/// and adds owned access. It's useful when you need all three access patterns for the same field.
4155#[derive(Clone)]
4156pub struct FailableCombinedKeyPath<Root, Value, ReadFn, WriteFn, OwnedFn>
4157where
4158    ReadFn: for<'r> Fn(&'r Root) -> Option<&'r Value> + 'static,
4159    WriteFn: for<'r> Fn(&'r mut Root) -> Option<&'r mut Value> + 'static,
4160    OwnedFn: Fn(Root) -> Option<Value> + 'static,
4161{
4162    readable: ReadFn,
4163    writable: WriteFn,
4164    owned: OwnedFn,
4165    _phantom: PhantomData<(Root, Value)>,
4166}
4167
4168impl<Root, Value, ReadFn, WriteFn, OwnedFn> FailableCombinedKeyPath<Root, Value, ReadFn, WriteFn, OwnedFn>
4169where
4170    ReadFn: for<'r> Fn(&'r Root) -> Option<&'r Value> + 'static,
4171    WriteFn: for<'r> Fn(&'r mut Root) -> Option<&'r mut Value> + 'static,
4172    OwnedFn: Fn(Root) -> Option<Value> + 'static,
4173{
4174    /// Create a new FailableCombinedKeyPath with all three access patterns
4175    pub fn new(readable: ReadFn, writable: WriteFn, owned: OwnedFn) -> Self {
4176        Self {
4177            readable,
4178            writable,
4179            owned,
4180            _phantom: PhantomData,
4181        }
4182    }
4183    
4184    /// Get an immutable reference to the value (readable access)
4185    pub fn get<'r>(&self, root: &'r Root) -> Option<&'r Value> {
4186        (self.readable)(root)
4187    }
4188    
4189    /// Get a mutable reference to the value (writable access)
4190    pub fn get_mut<'r>(&self, root: &'r mut Root) -> Option<&'r mut Value> {
4191        (self.writable)(root)
4192    }
4193    
4194    /// Get an owned value (owned access) - consumes the root
4195    pub fn get_failable_owned(&self, root: Root) -> Option<Value> {
4196        (self.owned)(root)
4197    }
4198    
4199    /// Convert to OptionalKeyPath (loses writable and owned capabilities)
4200    pub fn to_optional(self) -> OptionalKeyPath<Root, Value, ReadFn> {
4201        OptionalKeyPath::new(self.readable)
4202    }
4203    
4204    /// Convert to WritableOptionalKeyPath (loses owned capability)
4205    pub fn to_writable_optional(self) -> WritableOptionalKeyPath<Root, Value, WriteFn> {
4206        WritableOptionalKeyPath::new(self.writable)
4207    }
4208    
4209    /// Compose this keypath with another FailableCombinedKeyPath
4210    /// Returns a new FailableCombinedKeyPath that chains both keypaths
4211    pub fn then<SubValue, SubReadFn, SubWriteFn, SubOwnedFn>(
4212        self,
4213        next: FailableCombinedKeyPath<Value, SubValue, SubReadFn, SubWriteFn, SubOwnedFn>,
4214    ) -> FailableCombinedKeyPath<Root, SubValue, impl for<'r> Fn(&'r Root) -> Option<&'r SubValue> + 'static, impl for<'r> Fn(&'r mut Root) -> Option<&'r mut SubValue> + 'static, impl Fn(Root) -> Option<SubValue> + 'static>
4215    where
4216        SubReadFn: for<'r> Fn(&'r Value) -> Option<&'r SubValue> + 'static,
4217        SubWriteFn: for<'r> Fn(&'r mut Value) -> Option<&'r mut SubValue> + 'static,
4218        SubOwnedFn: Fn(Value) -> Option<SubValue> + 'static,
4219        ReadFn: 'static,
4220        WriteFn: 'static,
4221        OwnedFn: 'static,
4222        Value: 'static,
4223        Root: 'static,
4224        SubValue: 'static,
4225    {
4226        let first_read = self.readable;
4227        let first_write = self.writable;
4228        let first_owned = self.owned;
4229        let second_read = next.readable;
4230        let second_write = next.writable;
4231        let second_owned = next.owned;
4232        
4233        FailableCombinedKeyPath::new(
4234            move |root: &Root| {
4235                first_read(root).and_then(|value| second_read(value))
4236            },
4237            move |root: &mut Root| {
4238                first_write(root).and_then(|value| second_write(value))
4239            },
4240            move |root: Root| {
4241                first_owned(root).and_then(|value| second_owned(value))
4242            },
4243        )
4244    }
4245    
4246    /// Compose with OptionalKeyPath (readable only)
4247    /// Returns a FailableCombinedKeyPath that uses the readable from OptionalKeyPath
4248    /// and creates dummy writable/owned closures that return None
4249    pub fn then_optional<SubValue, SubReadFn>(
4250        self,
4251        next: OptionalKeyPath<Value, SubValue, SubReadFn>,
4252    ) -> FailableCombinedKeyPath<Root, SubValue, impl for<'r> Fn(&'r Root) -> Option<&'r SubValue> + 'static, impl for<'r> Fn(&'r mut Root) -> Option<&'r mut SubValue> + 'static, impl Fn(Root) -> Option<SubValue> + 'static>
4253    where
4254        SubReadFn: for<'r> Fn(&'r Value) -> Option<&'r SubValue> + 'static,
4255        ReadFn: 'static,
4256        WriteFn: 'static,
4257        OwnedFn: 'static,
4258        Value: 'static,
4259        Root: 'static,
4260        SubValue: 'static,
4261    {
4262        let first_read = self.readable;
4263        let first_write = self.writable;
4264        let first_owned = self.owned;
4265        let second_read = next.getter;
4266        
4267        FailableCombinedKeyPath::new(
4268            move |root: &Root| {
4269                first_read(root).and_then(|value| second_read(value))
4270            },
4271            move |_root: &mut Root| {
4272                None // Writable not supported when composing with OptionalKeyPath
4273            },
4274            move |root: Root| {
4275                first_owned(root).and_then(|value| {
4276                    // Try to get owned value, but OptionalKeyPath doesn't support owned
4277                    None
4278                })
4279            },
4280        )
4281    }
4282}
4283
4284// Factory function for FailableCombinedKeyPath
4285impl FailableCombinedKeyPath<(), (), fn(&()) -> Option<&()>, fn(&mut ()) -> Option<&mut ()>, fn(()) -> Option<()>> {
4286    /// Create a FailableCombinedKeyPath with all three access patterns
4287    pub fn failable_combined<Root, Value, ReadFn, WriteFn, OwnedFn>(
4288        readable: ReadFn,
4289        writable: WriteFn,
4290        owned: OwnedFn,
4291    ) -> FailableCombinedKeyPath<Root, Value, ReadFn, WriteFn, OwnedFn>
4292    where
4293        ReadFn: for<'r> Fn(&'r Root) -> Option<&'r Value> + 'static,
4294        WriteFn: for<'r> Fn(&'r mut Root) -> Option<&'r mut Value> + 'static,
4295        OwnedFn: Fn(Root) -> Option<Value> + 'static,
4296    {
4297        FailableCombinedKeyPath::new(readable, writable, owned)
4298    }
4299}
4300
4301impl AnyWritableKeyPath {
4302    pub fn new<Root, Value>(keypath: WritableOptionalKeyPath<Root, Value, impl for<'r> Fn(&'r mut Root) -> Option<&'r mut Value> + 'static>) -> Self
4303    where
4304        Root: Any + 'static,
4305        Value: Any + 'static,
4306    {
4307        let root_type_id = TypeId::of::<Root>();
4308        let value_type_id = TypeId::of::<Value>();
4309        let getter = keypath.getter;
4310        
4311        Self {
4312            getter: Rc::new(move |any: &mut dyn Any| {
4313                if let Some(root) = any.downcast_mut::<Root>() {
4314                    getter(root).map(|value: &mut Value| value as &mut dyn Any)
4315                } else {
4316                    None
4317                }
4318            }),
4319            root_type_id,
4320            value_type_id,
4321        }
4322    }
4323    
4324    pub fn get_mut<'r>(&self, root: &'r mut dyn Any) -> Option<&'r mut dyn Any> {
4325        (self.getter)(root)
4326    }
4327    
4328    /// Get the TypeId of the Root type
4329    pub fn root_type_id(&self) -> TypeId {
4330        self.root_type_id
4331    }
4332    
4333    /// Get the TypeId of the Value type
4334    pub fn value_type_id(&self) -> TypeId {
4335        self.value_type_id
4336    }
4337    
4338    /// Try to get the value with type checking
4339    pub fn get_mut_as<'a, Root: Any, Value: Any>(&self, root: &'a mut Root) -> Option<Option<&'a mut Value>> {
4340        if self.root_type_id == TypeId::of::<Root>() && self.value_type_id == TypeId::of::<Value>() {
4341            self.get_mut(root as &mut dyn Any).map(|any| any.downcast_mut::<Value>())
4342        } else {
4343            None
4344        }
4345    }
4346}
4347
4348// Conversion methods from concrete keypaths to partial/any keypaths
4349impl<Root, Value, F> KeyPath<Root, Value, F>
4350where
4351    F: for<'r> Fn(&'r Root) -> &'r Value + 'static,
4352    Root: 'static,
4353    Value: Any + 'static,
4354{
4355    /// Convert to PartialKeyPath (hides Value type)
4356    pub fn to_partial(self) -> PartialKeyPath<Root> {
4357        PartialKeyPath::new(self)
4358    }
4359    
4360    /// Alias for `to_partial()` - converts to PartialKeyPath
4361    pub fn to(self) -> PartialKeyPath<Root> {
4362        self.to_partial()
4363    }
4364}
4365
4366impl<Root, Value, F> OptionalKeyPath<Root, Value, F>
4367where
4368    F: for<'r> Fn(&'r Root) -> Option<&'r Value> + 'static,
4369    Root: Any + 'static,
4370    Value: Any + 'static,
4371{
4372    /// Convert to PartialOptionalKeyPath (hides Value type)
4373    pub fn to_partial(self) -> PartialOptionalKeyPath<Root> {
4374        PartialOptionalKeyPath::new(self)
4375    }
4376    
4377    /// Convert to AnyKeyPath (hides both Root and Value types)
4378    pub fn to_any(self) -> AnyKeyPath {
4379        AnyKeyPath::new(self)
4380    }
4381    
4382    /// Convert to PartialOptionalKeyPath (alias for `to_partial()`)
4383    pub fn to(self) -> PartialOptionalKeyPath<Root> {
4384        self.to_partial()
4385    }
4386}
4387
4388impl<Root, Value, F> WritableKeyPath<Root, Value, F>
4389where
4390    F: for<'r> Fn(&'r mut Root) -> &'r mut Value + 'static,
4391    Root: 'static,
4392    Value: Any + 'static,
4393{
4394    /// Convert to PartialWritableKeyPath (hides Value type)
4395    pub fn to_partial(self) -> PartialWritableKeyPath<Root> {
4396        PartialWritableKeyPath::new(self)
4397    }
4398    
4399    /// Alias for `to_partial()` - converts to PartialWritableKeyPath
4400    pub fn to(self) -> PartialWritableKeyPath<Root> {
4401        self.to_partial()
4402    }
4403}
4404
4405impl<Root, Value, F> WritableOptionalKeyPath<Root, Value, F>
4406where
4407    F: for<'r> Fn(&'r mut Root) -> Option<&'r mut Value> + 'static,
4408    Root: Any + 'static,
4409    Value: Any + 'static,
4410{
4411    /// Convert to PartialWritableOptionalKeyPath (hides Value type)
4412    pub fn to_partial(self) -> PartialWritableOptionalKeyPath<Root> {
4413        PartialWritableOptionalKeyPath::new(self)
4414    }
4415    
4416    /// Convert to AnyWritableKeyPath (hides both Root and Value types)
4417    pub fn to_any(self) -> AnyWritableKeyPath {
4418        AnyWritableKeyPath::new(self)
4419    }
4420    
4421    /// Convert to PartialWritableOptionalKeyPath (alias for `to_partial()`)
4422    pub fn to(self) -> PartialWritableOptionalKeyPath<Root> {
4423        self.to_partial()
4424    }
4425}
4426
4427// ========== SHR OPERATOR IMPLEMENTATIONS (>> operator) ==========
4428// 
4429// The `>>` operator provides the same functionality as `then()` methods.
4430// It requires nightly Rust with the `nightly` feature enabled.
4431//
4432// Usage example (requires nightly):
4433// ```rust
4434// #![feature(impl_trait_in_assoc_type)]  // Must be in YOUR code
4435// use rust_keypaths::{keypath, KeyPath};
4436// 
4437// struct User { address: Address }
4438// struct Address { street: String }
4439// 
4440// let kp1 = keypath!(|u: &User| &u.address);
4441// let kp2 = keypath!(|a: &Address| &a.street);
4442// let chained = kp1 >> kp2; // Works with nightly feature
4443// ```
4444//
4445// On stable Rust, use `keypath1.then(keypath2)` instead.
4446//
4447// Supported combinations (same as `then()` methods):
4448// - `KeyPath >> KeyPath` → `KeyPath`
4449// - `KeyPath >> OptionalKeyPath` → `OptionalKeyPath`
4450// - `OptionalKeyPath >> OptionalKeyPath` → `OptionalKeyPath`
4451// - `WritableKeyPath >> WritableKeyPath` → `WritableKeyPath`
4452// - `WritableKeyPath >> WritableOptionalKeyPath` → `WritableOptionalKeyPath`
4453// - `WritableOptionalKeyPath >> WritableOptionalKeyPath` → `WritableOptionalKeyPath`
4454
4455// #[cfg(feature = "nightly")]
4456// mod shr_impls {
4457//     use super::*;
4458//
4459//     // Implement Shr for KeyPath >> KeyPath: returns KeyPath
4460//     impl<Root, Value, F, SubValue, G> Shr<KeyPath<Value, SubValue, G>> for KeyPath<Root, Value, F>
4461//     where
4462//         F: for<'r> Fn(&'r Root) -> &'r Value + 'static,
4463//         G: for<'r> Fn(&'r Value) -> &'r SubValue + 'static,
4464//         Value: 'static,
4465//     {
4466//         type Output = KeyPath<Root, SubValue, impl for<'r> Fn(&'r Root) -> &'r SubValue>;
4467//
4468//         fn shr(self, rhs: KeyPath<Value, SubValue, G>) -> Self::Output {
4469//             self.then(rhs)
4470//         }
4471//     }
4472//
4473//     // Implement Shr for KeyPath >> OptionalKeyPath: returns OptionalKeyPath
4474//     impl<Root, Value, F, SubValue, G> Shr<OptionalKeyPath<Value, SubValue, G>> for KeyPath<Root, Value, F>
4475//     where
4476//         F: for<'r> Fn(&'r Root) -> &'r Value + 'static,
4477//         G: for<'r> Fn(&'r Value) -> Option<&'r SubValue> + 'static,
4478//         Value: 'static,
4479//     {
4480//         type Output = OptionalKeyPath<Root, SubValue, impl for<'r> Fn(&'r Root) -> Option<&'r SubValue>>;
4481//
4482//         fn shr(self, rhs: OptionalKeyPath<Value, SubValue, G>) -> Self::Output {
4483//             self.then_optional(rhs)
4484//         }
4485//     }
4486//
4487//     // Implement Shr for OptionalKeyPath >> OptionalKeyPath: returns OptionalKeyPath
4488//     impl<Root, Value, F, SubValue, G> Shr<OptionalKeyPath<Value, SubValue, G>> for OptionalKeyPath<Root, Value, F>
4489//     where
4490//         F: for<'r> Fn(&'r Root) -> Option<&'r Value> + 'static,
4491//         G: for<'r> Fn(&'r Value) -> Option<&'r SubValue> + 'static,
4492//         Value: 'static,
4493//     {
4494//         type Output = OptionalKeyPath<Root, SubValue, impl for<'r> Fn(&'r Root) -> Option<&'r SubValue>>;
4495//
4496//         fn shr(self, rhs: OptionalKeyPath<Value, SubValue, G>) -> Self::Output {
4497//             self.then(rhs)
4498//         }
4499//     }
4500//
4501//     // Implement Shr for WritableKeyPath >> WritableKeyPath: returns WritableKeyPath
4502//     impl<Root, Value, F, SubValue, G> Shr<WritableKeyPath<Value, SubValue, G>> for WritableKeyPath<Root, Value, F>
4503//     where
4504//         F: for<'r> Fn(&'r mut Root) -> &'r mut Value + 'static,
4505//         G: for<'r> Fn(&'r mut Value) -> &'r mut SubValue + 'static,
4506//         Value: 'static,
4507//     {
4508//         type Output = WritableKeyPath<Root, SubValue, impl for<'r> Fn(&'r mut Root) -> &'r mut SubValue>;
4509//
4510//         fn shr(self, rhs: WritableKeyPath<Value, SubValue, G>) -> Self::Output {
4511//             self.then(rhs)
4512//         }
4513//     }
4514//
4515//     // Implement Shr for WritableKeyPath >> WritableOptionalKeyPath: returns WritableOptionalKeyPath
4516//     impl<Root, Value, F, SubValue, G> Shr<WritableOptionalKeyPath<Value, SubValue, G>> for WritableKeyPath<Root, Value, F>
4517//     where
4518//         F: for<'r> Fn(&'r mut Root) -> &'r mut Value + 'static,
4519//         G: for<'r> Fn(&'r mut Value) -> Option<&'r mut SubValue> + 'static,
4520//         Value: 'static,
4521//     {
4522//         type Output = WritableOptionalKeyPath<Root, SubValue, impl for<'r> Fn(&'r mut Root) -> Option<&'r mut SubValue>>;
4523//
4524//         fn shr(self, rhs: WritableOptionalKeyPath<Value, SubValue, G>) -> Self::Output {
4525//             self.then_optional(rhs)
4526//         }
4527//     }
4528//
4529//     // Implement Shr for WritableOptionalKeyPath >> WritableOptionalKeyPath: returns WritableOptionalKeyPath
4530//     impl<Root, Value, F, SubValue, G> Shr<WritableOptionalKeyPath<Value, SubValue, G>> for WritableOptionalKeyPath<Root, Value, F>
4531//     where
4532//         F: for<'r> Fn(&'r mut Root) -> Option<&'r mut Value> + 'static,
4533//         G: for<'r> Fn(&'r mut Value) -> Option<&'r mut SubValue> + 'static,
4534//         Value: 'static,
4535//     {
4536//         type Output = WritableOptionalKeyPath<Root, SubValue, impl for<'r> Fn(&'r mut Root) -> Option<&'r mut SubValue>>;
4537//
4538//         fn shr(self, rhs: WritableOptionalKeyPath<Value, SubValue, G>) -> Self::Output {
4539//             self.then(rhs)
4540//         }
4541//     }
4542// }
4543
4544#[cfg(test)]
4545mod tests {
4546    use super::*;
4547    use std::sync::atomic::{AtomicUsize, Ordering};
4548    use std::rc::Rc;
4549
4550    // Global counter to track memory allocations/deallocations
4551    static ALLOC_COUNT: AtomicUsize = AtomicUsize::new(0);
4552    static DEALLOC_COUNT: AtomicUsize = AtomicUsize::new(0);
4553
4554    // Type that panics on clone to detect unwanted cloning
4555    #[derive(Debug)]
4556    struct NoCloneType {
4557        id: usize,
4558        data: String,
4559    }
4560
4561    impl NoCloneType {
4562        fn new(data: String) -> Self {
4563            ALLOC_COUNT.fetch_add(1, Ordering::SeqCst);
4564            Self {
4565                id: ALLOC_COUNT.load(Ordering::SeqCst),
4566                data,
4567            }
4568        }
4569    }
4570
4571    impl Clone for NoCloneType {
4572        fn clone(&self) -> Self {
4573            eprintln!("[DEBUG] NoCloneType should not be cloned! ID: {}", self.id);
4574            unreachable!("NoCloneType should not be cloned! ID: {}", self.id);
4575        }
4576    }
4577
4578    impl Drop for NoCloneType {
4579        fn drop(&mut self) {
4580            DEALLOC_COUNT.fetch_add(1, Ordering::SeqCst);
4581        }
4582    }
4583
4584    // Helper functions for testing memory management
4585    fn reset_memory_counters() {
4586        ALLOC_COUNT.store(0, Ordering::SeqCst);
4587        DEALLOC_COUNT.store(0, Ordering::SeqCst);
4588    }
4589
4590    fn get_alloc_count() -> usize {
4591        ALLOC_COUNT.load(Ordering::SeqCst)
4592    }
4593
4594    fn get_dealloc_count() -> usize {
4595        DEALLOC_COUNT.load(Ordering::SeqCst)
4596    }
4597
4598// Usage example
4599#[derive(Debug)]
4600struct User {
4601    name: String,
4602    metadata: Option<Box<UserMetadata>>,
4603    friends: Vec<Arc<User>>,
4604}
4605
4606#[derive(Debug)]
4607struct UserMetadata {
4608    created_at: String,
4609}
4610
4611fn some_fn() {
4612        let akash = User {
4613        name: "Alice".to_string(),
4614        metadata: Some(Box::new(UserMetadata {
4615            created_at: "2024-01-01".to_string(),
4616        })),
4617        friends: vec![
4618            Arc::new(User {
4619                name: "Bob".to_string(),
4620                metadata: None,
4621                friends: vec![],
4622            }),
4623        ],
4624    };
4625    
4626    // Create keypaths
4627    let name_kp = KeyPath::new(|u: &User| &u.name);
4628    let metadata_kp = OptionalKeyPath::new(|u: &User| u.metadata.as_ref());
4629    let friends_kp = KeyPath::new(|u: &User| &u.friends);
4630    
4631    // Use them
4632        println!("Name: {}", name_kp.get(&akash));
4633    
4634        if let Some(metadata) = metadata_kp.get(&akash) {
4635        println!("Has metadata: {:?}", metadata);
4636    }
4637    
4638    // Access first friend's name
4639        if let Some(first_friend) = akash.friends.get(0) {
4640        println!("First friend: {}", name_kp.get(first_friend));
4641    }
4642    
4643        // Access metadata through Box using for_box()
4644    let created_at_kp = KeyPath::new(|m: &UserMetadata| &m.created_at);
4645    
4646        if let Some(metadata) = akash.metadata.as_ref() {
4647            // Use for_box() to unwrap Box<UserMetadata> to &UserMetadata
4648            let boxed_metadata: &Box<UserMetadata> = metadata;
4649            let unwrapped = boxed_metadata.as_ref();
4650            println!("Created at: {:?}", created_at_kp.get(unwrapped));
4651        }
4652    }
4653
4654    #[test]
4655    fn test_name() {
4656        some_fn();
4657    }
4658    
4659    #[test]
4660    fn test_no_cloning_on_keypath_operations() {
4661        reset_memory_counters();
4662        
4663        // Create a value that panics on clone
4664        let value = NoCloneType::new("test".to_string());
4665        let boxed = Box::new(value);
4666        
4667        // Create keypath - should not clone
4668        let kp = KeyPath::new(|b: &Box<NoCloneType>| b.as_ref());
4669        
4670        // Access value - should not clone
4671        let _ref = kp.get(&boxed);
4672        
4673        // Clone the keypath itself (this is allowed)
4674        let _kp_clone = kp.clone();
4675        
4676        // Access again - should not clone the value
4677        let _ref2 = _kp_clone.get(&boxed);
4678        
4679        // Verify no panics occurred (if we got here, no cloning happened)
4680        assert_eq!(get_alloc_count(), 1);
4681    }
4682    
4683    #[test]
4684    fn test_no_cloning_on_optional_keypath_operations() {
4685        reset_memory_counters();
4686        
4687        let value = NoCloneType::new("test".to_string());
4688        let opt = Some(Box::new(value));
4689        
4690        // Create optional keypath
4691        let okp = OptionalKeyPath::new(|o: &Option<Box<NoCloneType>>| o.as_ref());
4692        
4693        // Access - should not clone
4694        let _ref = okp.get(&opt);
4695        
4696        // Clone keypath (allowed)
4697        let _okp_clone = okp.clone();
4698        
4699        // Chain operations - should not clone values
4700        let chained = okp.then(OptionalKeyPath::new(|b: &Box<NoCloneType>| Some(b.as_ref())));
4701        let _ref2 = chained.get(&opt);
4702        
4703        assert_eq!(get_alloc_count(), 1);
4704    }
4705    
4706    #[test]
4707    fn test_memory_release() {
4708        reset_memory_counters();
4709        
4710        {
4711            let value = NoCloneType::new("test".to_string());
4712            let boxed = Box::new(value);
4713            let kp = KeyPath::new(|b: &Box<NoCloneType>| b.as_ref());
4714            
4715            // Use the keypath
4716            let _ref = kp.get(&boxed);
4717            
4718            // boxed goes out of scope here
4719        }
4720        
4721        // After drop, memory should be released
4722        // Note: This is a best-effort check since drop timing can vary
4723        assert_eq!(get_alloc_count(), 1);
4724        // Deallocation happens when the value is dropped
4725        // We can't reliably test exact timing, but we verify the counter exists
4726    }
4727    
4728    #[test]
4729    fn test_keypath_clone_does_not_clone_underlying_data() {
4730        reset_memory_counters();
4731        
4732        let value = NoCloneType::new("data".to_string());
4733        let rc_value = Rc::new(value);
4734        
4735        // Create keypath
4736        let kp = KeyPath::new(|r: &Rc<NoCloneType>| r.as_ref());
4737        
4738        // Clone keypath multiple times
4739        let kp1 = kp.clone();
4740        let kp2 = kp.clone();
4741        let kp3 = kp1.clone();
4742        
4743        // All should work without cloning the underlying data
4744        let _ref1 = kp.get(&rc_value);
4745        let _ref2 = kp1.get(&rc_value);
4746        let _ref3 = kp2.get(&rc_value);
4747        let _ref4 = kp3.get(&rc_value);
4748        
4749        // Only one allocation should have happened
4750        assert_eq!(get_alloc_count(), 1);
4751    }
4752    
4753    #[test]
4754    fn test_optional_keypath_chaining_no_clone() {
4755        reset_memory_counters();
4756        
4757        let value = NoCloneType::new("value1".to_string());
4758        
4759        struct Container {
4760            inner: Option<Box<NoCloneType>>,
4761        }
4762        
4763        let container = Container {
4764            inner: Some(Box::new(value)),
4765        };
4766        
4767        // Create chained keypath
4768        let kp1 = OptionalKeyPath::new(|c: &Container| c.inner.as_ref());
4769        let kp2 = OptionalKeyPath::new(|b: &Box<NoCloneType>| Some(b.as_ref()));
4770        
4771        // Chain them - should not clone
4772        let chained = kp1.then(kp2);
4773        
4774        // Use chained keypath
4775        let _result = chained.get(&container);
4776        
4777        // Should only have one allocation
4778        assert_eq!(get_alloc_count(), 1);
4779    }
4780    
4781    #[test]
4782    fn test_for_box_no_clone() {
4783        reset_memory_counters();
4784        
4785        let value = NoCloneType::new("test".to_string());
4786        let boxed = Box::new(value);
4787        let opt_boxed = Some(boxed);
4788        
4789        // Create keypath with for_box
4790        let kp = OptionalKeyPath::new(|o: &Option<Box<NoCloneType>>| o.as_ref());
4791        let unwrapped = kp.for_box();
4792        
4793        // Access - should not clone
4794        let _ref = unwrapped.get(&opt_boxed);
4795        
4796        assert_eq!(get_alloc_count(), 1);
4797    }
4798    
4799    // ========== MACRO USAGE EXAMPLES ==========
4800    
4801    #[derive(Debug, PartialEq)]
4802    struct TestUser {
4803        name: String,
4804        age: u32,
4805        metadata: Option<String>,
4806        address: Option<TestAddress>,
4807    }
4808    
4809    #[derive(Debug, PartialEq)]
4810    struct TestAddress {
4811        street: String,
4812        city: String,
4813        country: Option<TestCountry>,
4814    }
4815    
4816    #[derive(Debug, PartialEq)]
4817    struct TestCountry {
4818        name: String,
4819    }
4820    
4821    #[test]
4822    fn test_keypath_macro() {
4823        let user = TestUser {
4824            name: "Alice".to_string(),
4825            age: 30,
4826            metadata: None,
4827            address: None,
4828        };
4829        
4830        // Simple field access using closure
4831        let name_kp = keypath!(|u: &TestUser| &u.name);
4832        assert_eq!(name_kp.get(&user), "Alice");
4833        
4834        // Nested field access
4835        let user_with_address = TestUser {
4836            name: "Bob".to_string(),
4837            age: 25,
4838            metadata: None,
4839            address: Some(TestAddress {
4840                street: "123 Main St".to_string(),
4841                city: "New York".to_string(),
4842                country: None,
4843            }),
4844        };
4845        
4846        let street_kp = keypath!(|u: &TestUser| &u.address.as_ref().unwrap().street);
4847        assert_eq!(street_kp.get(&user_with_address), "123 Main St");
4848        
4849        // Deeper nesting
4850        let user_with_country = TestUser {
4851            name: "Charlie".to_string(),
4852            age: 35,
4853            metadata: None,
4854            address: Some(TestAddress {
4855                street: "456 Oak Ave".to_string(),
4856                city: "London".to_string(),
4857                country: Some(TestCountry {
4858                    name: "UK".to_string(),
4859                }),
4860            }),
4861        };
4862        
4863        let country_name_kp = keypath!(|u: &TestUser| &u.address.as_ref().unwrap().country.as_ref().unwrap().name);
4864        assert_eq!(country_name_kp.get(&user_with_country), "UK");
4865        
4866        // Fallback: using closure
4867        let age_kp = keypath!(|u: &TestUser| &u.age);
4868        assert_eq!(age_kp.get(&user), &30);
4869    }
4870    
4871    #[test]
4872    fn test_opt_keypath_macro() {
4873        let user = TestUser {
4874            name: "Alice".to_string(),
4875            age: 30,
4876            metadata: Some("admin".to_string()),
4877            address: None,
4878        };
4879        
4880        // Simple Option field access using closure
4881        let metadata_kp = opt_keypath!(|u: &TestUser| u.metadata.as_ref());
4882        assert_eq!(metadata_kp.get(&user), Some(&"admin".to_string()));
4883        
4884        // None case
4885        let user_no_metadata = TestUser {
4886            name: "Bob".to_string(),
4887            age: 25,
4888            metadata: None,
4889            address: None,
4890        };
4891        assert_eq!(metadata_kp.get(&user_no_metadata), None);
4892        
4893        // Nested Option access
4894        let user_with_address = TestUser {
4895            name: "Charlie".to_string(),
4896            age: 35,
4897            metadata: None,
4898            address: Some(TestAddress {
4899                street: "789 Pine Rd".to_string(),
4900                city: "Paris".to_string(),
4901                country: None,
4902            }),
4903        };
4904        
4905        let street_kp = opt_keypath!(|u: &TestUser| u.address.as_ref().map(|a| &a.street));
4906        assert_eq!(street_kp.get(&user_with_address), Some(&"789 Pine Rd".to_string()));
4907        
4908        // Deeper nesting through Options
4909        let user_with_country = TestUser {
4910            name: "David".to_string(),
4911            age: 40,
4912            metadata: None,
4913            address: Some(TestAddress {
4914                street: "321 Elm St".to_string(),
4915                city: "Tokyo".to_string(),
4916                country: Some(TestCountry {
4917                    name: "Japan".to_string(),
4918                }),
4919            }),
4920        };
4921        
4922        let country_name_kp = opt_keypath!(|u: &TestUser| u.address.as_ref().and_then(|a| a.country.as_ref().map(|c| &c.name)));
4923        assert_eq!(country_name_kp.get(&user_with_country), Some(&"Japan".to_string()));
4924        
4925        // Fallback: using closure
4926        let metadata_kp2 = opt_keypath!(|u: &TestUser| u.metadata.as_ref());
4927        assert_eq!(metadata_kp2.get(&user), Some(&"admin".to_string()));
4928    }
4929    
4930    #[test]
4931    fn test_writable_keypath_macro() {
4932        let mut user = TestUser {
4933            name: "Alice".to_string(),
4934            age: 30,
4935            metadata: None,
4936            address: None,
4937        };
4938        
4939        // Simple field mutation using closure
4940        let name_kp = writable_keypath!(|u: &mut TestUser| &mut u.name);
4941        *name_kp.get_mut(&mut user) = "Bob".to_string();
4942        assert_eq!(user.name, "Bob");
4943        
4944        // Nested field mutation
4945        let mut user_with_address = TestUser {
4946            name: "Charlie".to_string(),
4947            age: 25,
4948            metadata: None,
4949            address: Some(TestAddress {
4950                street: "123 Main St".to_string(),
4951                city: "New York".to_string(),
4952                country: None,
4953            }),
4954        };
4955        
4956        let street_kp = writable_keypath!(|u: &mut TestUser| &mut u.address.as_mut().unwrap().street);
4957        *street_kp.get_mut(&mut user_with_address) = "456 Oak Ave".to_string();
4958        assert_eq!(user_with_address.address.as_ref().unwrap().street, "456 Oak Ave");
4959        
4960        // Deeper nesting
4961        let mut user_with_country = TestUser {
4962            name: "David".to_string(),
4963            age: 35,
4964            metadata: None,
4965            address: Some(TestAddress {
4966                street: "789 Pine Rd".to_string(),
4967                city: "London".to_string(),
4968                country: Some(TestCountry {
4969                    name: "UK".to_string(),
4970                }),
4971            }),
4972        };
4973        
4974        let country_name_kp = writable_keypath!(|u: &mut TestUser| &mut u.address.as_mut().unwrap().country.as_mut().unwrap().name);
4975        *country_name_kp.get_mut(&mut user_with_country) = "United Kingdom".to_string();
4976        assert_eq!(user_with_country.address.as_ref().unwrap().country.as_ref().unwrap().name, "United Kingdom");
4977        
4978        // Fallback: using closure
4979        let age_kp = writable_keypath!(|u: &mut TestUser| &mut u.age);
4980        *age_kp.get_mut(&mut user) = 31;
4981        assert_eq!(user.age, 31);
4982    }
4983    
4984    #[test]
4985    fn test_writable_opt_keypath_macro() {
4986        let mut user = TestUser {
4987            name: "Alice".to_string(),
4988            age: 30,
4989            metadata: Some("user".to_string()),
4990            address: None,
4991        };
4992        
4993        // Simple Option field mutation using closure
4994        let metadata_kp = writable_opt_keypath!(|u: &mut TestUser| u.metadata.as_mut());
4995        if let Some(metadata) = metadata_kp.get_mut(&mut user) {
4996            *metadata = "admin".to_string();
4997        }
4998        assert_eq!(user.metadata, Some("admin".to_string()));
4999        
5000        // None case - should return None
5001        let mut user_no_metadata = TestUser {
5002            name: "Bob".to_string(),
5003            age: 25,
5004            metadata: None,
5005            address: None,
5006        };
5007        assert_eq!(metadata_kp.get_mut(&mut user_no_metadata), None);
5008        
5009        // Nested Option access
5010        let mut user_with_address = TestUser {
5011            name: "Charlie".to_string(),
5012            age: 35,
5013            metadata: None,
5014            address: Some(TestAddress {
5015                street: "123 Main St".to_string(),
5016                city: "New York".to_string(),
5017                country: None,
5018            }),
5019        };
5020        
5021        let street_kp = writable_opt_keypath!(|u: &mut TestUser| u.address.as_mut().map(|a| &mut a.street));
5022        if let Some(street) = street_kp.get_mut(&mut user_with_address) {
5023            *street = "456 Oak Ave".to_string();
5024        }
5025        assert_eq!(user_with_address.address.as_ref().unwrap().street, "456 Oak Ave");
5026        
5027        // Deeper nesting through Options
5028        let mut user_with_country = TestUser {
5029            name: "David".to_string(),
5030            age: 40,
5031            metadata: None,
5032            address: Some(TestAddress {
5033                street: "789 Pine Rd".to_string(),
5034                city: "Tokyo".to_string(),
5035                country: Some(TestCountry {
5036                    name: "Japan".to_string(),
5037                }),
5038            }),
5039        };
5040        
5041        let country_name_kp = writable_opt_keypath!(|u: &mut TestUser| u.address.as_mut().and_then(|a| a.country.as_mut().map(|c| &mut c.name)));
5042        if let Some(country_name) = country_name_kp.get_mut(&mut user_with_country) {
5043            *country_name = "Nippon".to_string();
5044        }
5045        assert_eq!(user_with_country.address.as_ref().unwrap().country.as_ref().unwrap().name, "Nippon");
5046        
5047        // Fallback: using closure
5048        let metadata_kp2 = writable_opt_keypath!(|u: &mut TestUser| u.metadata.as_mut());
5049        if let Some(metadata) = metadata_kp2.get_mut(&mut user) {
5050            *metadata = "super_admin".to_string();
5051        }
5052        assert_eq!(user.metadata, Some("super_admin".to_string()));
5053    }
5054}
5055
5056// ========== WithContainer Trait ==========
5057
5058/// Trait for no-clone callback-based access to container types
5059/// Provides methods to execute closures with references to values inside containers
5060/// without requiring cloning of the values
5061pub trait WithContainer<Root, Value> {
5062    /// Execute a closure with a reference to the value inside an Arc
5063    fn with_arc<F, R>(&self, arc: &Arc<Root>, f: F) -> R
5064    where
5065        F: FnOnce(&Value) -> R;
5066
5067    /// Execute a closure with a reference to the value inside a Box
5068    fn with_box<F, R>(&self, boxed: &Box<Root>, f: F) -> R
5069    where
5070        F: FnOnce(&Value) -> R;
5071
5072    /// Execute a closure with a mutable reference to the value inside a Box
5073    fn with_box_mut<F, R>(&self, boxed: &mut Box<Root>, f: F) -> R
5074    where
5075        F: FnOnce(&mut Value) -> R;
5076
5077    /// Execute a closure with a reference to the value inside an Rc
5078    fn with_rc<F, R>(&self, rc: &Rc<Root>, f: F) -> R
5079    where
5080        F: FnOnce(&Value) -> R;
5081
5082    /// Execute a closure with a reference to the value inside a Result
5083    fn with_result<F, R, E>(&self, result: &Result<Root, E>, f: F) -> Option<R>
5084    where
5085        F: FnOnce(&Value) -> R;
5086
5087    /// Execute a closure with a mutable reference to the value inside a Result
5088    fn with_result_mut<F, R, E>(&self, result: &mut Result<Root, E>, f: F) -> Option<R>
5089    where
5090        F: FnOnce(&mut Value) -> R;
5091
5092    /// Execute a closure with a reference to the value inside an Option
5093    fn with_option<F, R>(&self, option: &Option<Root>, f: F) -> Option<R>
5094    where
5095        F: FnOnce(&Value) -> R;
5096
5097    /// Execute a closure with a mutable reference to the value inside an Option
5098    fn with_option_mut<F, R>(&self, option: &mut Option<Root>, f: F) -> Option<R>
5099    where
5100        F: FnOnce(&mut Value) -> R;
5101
5102    /// Execute a closure with a reference to the value inside a RefCell
5103    fn with_refcell<F, R>(&self, refcell: &RefCell<Root>, f: F) -> Option<R>
5104    where
5105        F: FnOnce(&Value) -> R;
5106
5107    /// Execute a closure with a mutable reference to the value inside a RefCell
5108    fn with_refcell_mut<F, R>(&self, refcell: &RefCell<Root>, f: F) -> Option<R>
5109    where
5110        F: FnOnce(&mut Value) -> R;
5111
5112    #[cfg(feature = "tagged")]
5113    /// Execute a closure with a reference to the value inside a Tagged
5114    fn with_tagged<F, R, Tag>(&self, tagged: &Tagged<Root, Tag>, f: F) -> R
5115    where
5116        Tagged<Root, Tag>: std::ops::Deref<Target = Root>,
5117        F: FnOnce(&Value) -> R;
5118
5119    /// Execute a closure with a reference to the value inside a Mutex
5120    fn with_mutex<F, R>(&self, mutex: &Mutex<Root>, f: F) -> Option<R>
5121    where
5122        F: FnOnce(&Value) -> R;
5123
5124    /// Execute a closure with a mutable reference to the value inside a Mutex
5125    fn with_mutex_mut<F, R>(&self, mutex: &mut Mutex<Root>, f: F) -> Option<R>
5126    where
5127        F: FnOnce(&mut Value) -> R;
5128
5129    /// Execute a closure with a reference to the value inside an RwLock
5130    fn with_rwlock<F, R>(&self, rwlock: &RwLock<Root>, f: F) -> Option<R>
5131    where
5132        F: FnOnce(&Value) -> R;
5133
5134    /// Execute a closure with a mutable reference to the value inside an RwLock
5135    fn with_rwlock_mut<F, R>(&self, rwlock: &mut RwLock<Root>, f: F) -> Option<R>
5136    where
5137        F: FnOnce(&mut Value) -> R;
5138
5139    /// Execute a closure with a reference to the value inside an Arc<RwLock<Root>>
5140    fn with_arc_rwlock<F, R>(&self, arc_rwlock: &Arc<RwLock<Root>>, f: F) -> Option<R>
5141    where
5142        F: FnOnce(&Value) -> R;
5143
5144    /// Execute a closure with a mutable reference to the value inside an Arc<RwLock<Root>>
5145    fn with_arc_rwlock_mut<F, R>(&self, arc_rwlock: &Arc<RwLock<Root>>, f: F) -> Option<R>
5146    where
5147        F: FnOnce(&mut Value) -> R;
5148}
5149
5150// Implement WithContainer for KeyPath
5151impl<Root, Value, F> WithContainer<Root, Value> for KeyPath<Root, Value, F>
5152where
5153    F: for<'r> Fn(&'r Root) -> &'r Value + Clone,
5154{
5155    fn with_arc<Callback, R>(&self, arc: &Arc<Root>, f: Callback) -> R
5156    where
5157        Callback: FnOnce(&Value) -> R,
5158    {
5159        self.with_arc(arc, f)
5160    }
5161
5162    fn with_box<Callback, R>(&self, boxed: &Box<Root>, f: Callback) -> R
5163    where
5164        Callback: FnOnce(&Value) -> R,
5165    {
5166        self.with_box(boxed, f)
5167    }
5168
5169    fn with_box_mut<Callback, R>(&self, _boxed: &mut Box<Root>, _f: Callback) -> R
5170    where
5171        Callback: FnOnce(&mut Value) -> R,
5172    {
5173        eprintln!("[DEBUG] KeyPath does not support mutable access - use WritableKeyPath instead");
5174        unreachable!("KeyPath does not support mutable access - use WritableKeyPath instead")
5175    }
5176
5177    fn with_rc<Callback, R>(&self, rc: &Rc<Root>, f: Callback) -> R
5178    where
5179        Callback: FnOnce(&Value) -> R,
5180    {
5181        self.with_rc(rc, f)
5182    }
5183
5184    fn with_result<Callback, R, E>(&self, result: &Result<Root, E>, f: Callback) -> Option<R>
5185    where
5186        Callback: FnOnce(&Value) -> R,
5187    {
5188        self.with_result(result, f)
5189    }
5190
5191    fn with_result_mut<Callback, R, E>(&self, _result: &mut Result<Root, E>, _f: Callback) -> Option<R>
5192    where
5193        Callback: FnOnce(&mut Value) -> R,
5194    {
5195        None
5196    }
5197
5198    fn with_option<Callback, R>(&self, option: &Option<Root>, f: Callback) -> Option<R>
5199    where
5200        Callback: FnOnce(&Value) -> R,
5201    {
5202        self.with_option(option, f)
5203    }
5204
5205    fn with_option_mut<Callback, R>(&self, _option: &mut Option<Root>, _f: Callback) -> Option<R>
5206    where
5207        Callback: FnOnce(&mut Value) -> R,
5208    {
5209        None
5210    }
5211
5212    fn with_refcell<Callback, R>(&self, refcell: &RefCell<Root>, f: Callback) -> Option<R>
5213    where
5214        Callback: FnOnce(&Value) -> R,
5215    {
5216        self.with_refcell(refcell, f)
5217    }
5218
5219    fn with_refcell_mut<Callback, R>(&self, _refcell: &RefCell<Root>, _f: Callback) -> Option<R>
5220    where
5221        Callback: FnOnce(&mut Value) -> R,
5222    {
5223        None
5224    }
5225
5226    #[cfg(feature = "tagged")]
5227    fn with_tagged<Callback, R, Tag>(&self, tagged: &Tagged<Root, Tag>, f: Callback) -> R
5228    where
5229        Tagged<Root, Tag>: std::ops::Deref<Target = Root>,
5230        Callback: FnOnce(&Value) -> R,
5231    {
5232        self.with_tagged(tagged, f)
5233    }
5234
5235    fn with_mutex<Callback, R>(&self, mutex: &Mutex<Root>, f: Callback) -> Option<R>
5236    where
5237        Callback: FnOnce(&Value) -> R,
5238    {
5239        self.with_mutex(mutex, f)
5240    }
5241
5242    fn with_mutex_mut<Callback, R>(&self, _mutex: &mut Mutex<Root>, _f: Callback) -> Option<R>
5243    where
5244        Callback: FnOnce(&mut Value) -> R,
5245    {
5246        None
5247    }
5248
5249    fn with_rwlock<Callback, R>(&self, rwlock: &RwLock<Root>, f: Callback) -> Option<R>
5250    where
5251        Callback: FnOnce(&Value) -> R,
5252    {
5253        self.with_rwlock(rwlock, f)
5254    }
5255
5256    fn with_rwlock_mut<Callback, R>(&self, _rwlock: &mut RwLock<Root>, _f: Callback) -> Option<R>
5257    where
5258        Callback: FnOnce(&mut Value) -> R,
5259    {
5260        None
5261    }
5262
5263    fn with_arc_rwlock<Callback, R>(&self, arc_rwlock: &Arc<RwLock<Root>>, f: Callback) -> Option<R>
5264    where
5265        Callback: FnOnce(&Value) -> R,
5266    {
5267        self.with_arc_rwlock(arc_rwlock, f)
5268    }
5269
5270    fn with_arc_rwlock_mut<Callback, R>(&self, _arc_rwlock: &Arc<RwLock<Root>>, _f: Callback) -> Option<R>
5271    where
5272        Callback: FnOnce(&mut Value) -> R,
5273    {
5274        None
5275    }
5276}
5277
5278// Implement WithContainer for OptionalKeyPath - read-only operations only
5279impl<Root, Value, F> WithContainer<Root, Value> for OptionalKeyPath<Root, Value, F>
5280where
5281    F: for<'r> Fn(&'r Root) -> Option<&'r Value> + Clone,
5282{
5283    fn with_arc<Callback, R>(&self, arc: &Arc<Root>, f: Callback) -> R
5284    where
5285        Callback: FnOnce(&Value) -> R,
5286    {
5287        self.with_arc(arc, f)
5288    }
5289
5290    fn with_box<Callback, R>(&self, boxed: &Box<Root>, f: Callback) -> R
5291    where
5292        Callback: FnOnce(&Value) -> R,
5293    {
5294        self.with_box(boxed, f)
5295    }
5296
5297    fn with_box_mut<Callback, R>(&self, _boxed: &mut Box<Root>, _f: Callback) -> R
5298    where
5299        Callback: FnOnce(&mut Value) -> R,
5300    {
5301        eprintln!("[DEBUG] OptionalKeyPath does not support mutable access - use WritableOptionalKeyPath instead");
5302        unreachable!("OptionalKeyPath does not support mutable access - use WritableOptionalKeyPath instead")
5303    }
5304
5305    fn with_rc<Callback, R>(&self, rc: &Rc<Root>, f: Callback) -> R
5306    where
5307        Callback: FnOnce(&Value) -> R,
5308    {
5309        self.with_rc(rc, f)
5310    }
5311
5312    fn with_result<Callback, R, E>(&self, result: &Result<Root, E>, f: Callback) -> Option<R>
5313    where
5314        Callback: FnOnce(&Value) -> R,
5315    {
5316        self.with_result(result, f)
5317    }
5318
5319    fn with_result_mut<Callback, R, E>(&self, _result: &mut Result<Root, E>, _f: Callback) -> Option<R>
5320    where
5321        Callback: FnOnce(&mut Value) -> R,
5322    {
5323        None // OptionalKeyPath doesn't support mutable access
5324    }
5325
5326    fn with_option<Callback, R>(&self, option: &Option<Root>, f: Callback) -> Option<R>
5327    where
5328        Callback: FnOnce(&Value) -> R,
5329    {
5330        self.with_option(option, f)
5331    }
5332
5333    fn with_option_mut<Callback, R>(&self, _option: &mut Option<Root>, _f: Callback) -> Option<R>
5334    where
5335        Callback: FnOnce(&mut Value) -> R,
5336    {
5337        None // OptionalKeyPath doesn't support mutable access
5338    }
5339
5340    fn with_refcell<Callback, R>(&self, refcell: &RefCell<Root>, f: Callback) -> Option<R>
5341    where
5342        Callback: FnOnce(&Value) -> R,
5343    {
5344        self.with_refcell(refcell, f)
5345    }
5346
5347    fn with_refcell_mut<Callback, R>(&self, _refcell: &RefCell<Root>, _f: Callback) -> Option<R>
5348    where
5349        Callback: FnOnce(&mut Value) -> R,
5350    {
5351        None // OptionalKeyPath doesn't support mutable access
5352    }
5353
5354    #[cfg(feature = "tagged")]
5355    fn with_tagged<Callback, R, Tag>(&self, tagged: &Tagged<Root, Tag>, f: Callback) -> R
5356    where
5357        Tagged<Root, Tag>: std::ops::Deref<Target = Root>,
5358        Callback: FnOnce(&Value) -> R,
5359    {
5360        use std::ops::Deref;
5361        self.get(tagged.deref())
5362            .map(|value| f(value))
5363            .expect("OptionalKeyPath::with_tagged: Tagged should always contain a value that matches the keypath")
5364    }
5365
5366    fn with_mutex<Callback, R>(&self, mutex: &Mutex<Root>, f: Callback) -> Option<R>
5367    where
5368        Callback: FnOnce(&Value) -> R,
5369    {
5370        self.with_mutex(mutex, f)
5371    }
5372
5373    fn with_mutex_mut<Callback, R>(&self, _mutex: &mut Mutex<Root>, _f: Callback) -> Option<R>
5374    where
5375        Callback: FnOnce(&mut Value) -> R,
5376    {
5377        None // OptionalKeyPath doesn't support mutable access
5378    }
5379
5380    fn with_rwlock<Callback, R>(&self, rwlock: &RwLock<Root>, f: Callback) -> Option<R>
5381    where
5382        Callback: FnOnce(&Value) -> R,
5383    {
5384        self.with_rwlock(rwlock, f)
5385    }
5386
5387    fn with_rwlock_mut<Callback, R>(&self, _rwlock: &mut RwLock<Root>, _f: Callback) -> Option<R>
5388    where
5389        Callback: FnOnce(&mut Value) -> R,
5390    {
5391        None // OptionalKeyPath doesn't support mutable access
5392    }
5393
5394    fn with_arc_rwlock<Callback, R>(&self, arc_rwlock: &Arc<RwLock<Root>>, f: Callback) -> Option<R>
5395    where
5396        Callback: FnOnce(&Value) -> R,
5397    {
5398        self.with_arc_rwlock(arc_rwlock, f)
5399    }
5400
5401    fn with_arc_rwlock_mut<Callback, R>(&self, _arc_rwlock: &Arc<RwLock<Root>>, _f: Callback) -> Option<R>
5402    where
5403        Callback: FnOnce(&mut Value) -> R,
5404    {
5405        None // OptionalKeyPath doesn't support mutable access - use WritableOptionalKeyPath instead
5406    }
5407}
5408
5409// Implement WithContainer for WritableKeyPath - supports all mutable operations
5410impl<Root, Value, F> WithContainer<Root, Value> for WritableKeyPath<Root, Value, F>
5411where
5412    F: for<'r> Fn(&'r mut Root) -> &'r mut Value,
5413{
5414    fn with_arc<Callback, R>(&self, _arc: &Arc<Root>, _f: Callback) -> R
5415    where
5416        Callback: FnOnce(&Value) -> R,
5417    {
5418        // Arc doesn't support mutable access without interior mutability
5419        // This method requires &mut Arc<Root> which we don't have
5420        eprintln!("[DEBUG] WritableKeyPath::with_arc requires &mut Arc<Root> or interior mutability");
5421        unreachable!("WritableKeyPath::with_arc requires &mut Arc<Root> or interior mutability")
5422    }
5423
5424    fn with_box<Callback, R>(&self, boxed: &Box<Root>, f: Callback) -> R
5425    where
5426        Callback: FnOnce(&Value) -> R,
5427    {
5428        // Box doesn't support getting mutable reference from immutable reference
5429        // This is a limitation - we'd need &mut Box<Root> for mutable access
5430        eprintln!("[DEBUG] WritableKeyPath::with_box requires &mut Box<Root> - use with_box_mut instead");
5431        unreachable!("WritableKeyPath::with_box requires &mut Box<Root> - use with_box_mut instead")
5432    }
5433
5434    fn with_box_mut<Callback, R>(&self, boxed: &mut Box<Root>, f: Callback) -> R
5435    where
5436        Callback: FnOnce(&mut Value) -> R,
5437    {
5438        let value = self.get_mut(boxed.as_mut());
5439        f(value)
5440    }
5441
5442    fn with_rc<Callback, R>(&self, _rc: &Rc<Root>, _f: Callback) -> R
5443    where
5444        Callback: FnOnce(&Value) -> R,
5445    {
5446        // Rc doesn't support mutable access without interior mutability
5447        // This method requires &mut Rc<Root> which we don't have
5448        eprintln!("[DEBUG] WritableKeyPath::with_rc requires &mut Rc<Root> or interior mutability");
5449        unreachable!("WritableKeyPath::with_rc requires &mut Rc<Root> or interior mutability")
5450    }
5451
5452    fn with_result<Callback, R, E>(&self, _result: &Result<Root, E>, _f: Callback) -> Option<R>
5453    where
5454        Callback: FnOnce(&Value) -> R,
5455    {
5456        // WritableKeyPath requires &mut Root, but we only have &Result<Root, E>
5457        // This is a limitation - use with_result_mut for mutable access
5458        None
5459    }
5460
5461    fn with_result_mut<Callback, R, E>(&self, result: &mut Result<Root, E>, f: Callback) -> Option<R>
5462    where
5463        Callback: FnOnce(&mut Value) -> R,
5464    {
5465        result.as_mut().ok().map(|root| {
5466            let value = self.get_mut(root);
5467            f(value)
5468        })
5469    }
5470
5471    fn with_option<Callback, R>(&self, _option: &Option<Root>, _f: Callback) -> Option<R>
5472    where
5473        Callback: FnOnce(&Value) -> R,
5474    {
5475        // WritableKeyPath requires &mut Root, but we only have &Option<Root>
5476        // This is a limitation - use with_option_mut for mutable access
5477        None
5478    }
5479
5480    fn with_option_mut<Callback, R>(&self, option: &mut Option<Root>, f: Callback) -> Option<R>
5481    where
5482        Callback: FnOnce(&mut Value) -> R,
5483    {
5484        option.as_mut().map(|root| {
5485            let value = self.get_mut(root);
5486            f(value)
5487        })
5488    }
5489
5490    fn with_refcell<Callback, R>(&self, refcell: &RefCell<Root>, f: Callback) -> Option<R>
5491    where
5492        Callback: FnOnce(&Value) -> R,
5493    {
5494        // RefCell doesn't allow getting mutable reference from immutable borrow
5495        // This is a limitation - we'd need try_borrow_mut for mutable access
5496        None
5497    }
5498
5499    fn with_refcell_mut<Callback, R>(&self, refcell: &RefCell<Root>, f: Callback) -> Option<R>
5500    where
5501        Callback: FnOnce(&mut Value) -> R,
5502    {
5503        refcell.try_borrow_mut().ok().map(|mut borrow| {
5504            let value = self.get_mut(&mut *borrow);
5505            f(value)
5506        })
5507    }
5508
5509    #[cfg(feature = "tagged")]
5510    fn with_tagged<Callback, R, Tag>(&self, _tagged: &Tagged<Root, Tag>, _f: Callback) -> R
5511    where
5512        Tagged<Root, Tag>: std::ops::Deref<Target = Root>,
5513        Callback: FnOnce(&Value) -> R,
5514    {
5515        // WritableKeyPath requires &mut Root, but we only have &Tagged<Root, Tag>
5516        // This is a limitation - Tagged doesn't support mutable access without interior mutability
5517        eprintln!("[DEBUG] WritableKeyPath::with_tagged requires &mut Tagged<Root, Tag> or interior mutability");
5518        unreachable!("WritableKeyPath::with_tagged requires &mut Tagged<Root, Tag> or interior mutability")
5519    }
5520
5521    fn with_mutex<Callback, R>(&self, mutex: &Mutex<Root>, f: Callback) -> Option<R>
5522    where
5523        Callback: FnOnce(&Value) -> R,
5524    {
5525        mutex.lock().ok().map(|mut guard| {
5526            let value = self.get_mut(&mut *guard);
5527            f(value)
5528        })
5529    }
5530
5531    fn with_mutex_mut<Callback, R>(&self, mutex: &mut Mutex<Root>, f: Callback) -> Option<R>
5532    where
5533        Callback: FnOnce(&mut Value) -> R,
5534    {
5535        // Mutex::get_mut returns Result<&mut Root, PoisonError>
5536        mutex.get_mut().ok().map(|root| {
5537            let value = self.get_mut(root);
5538            f(value)
5539        })
5540    }
5541
5542    fn with_rwlock<Callback, R>(&self, rwlock: &RwLock<Root>, f: Callback) -> Option<R>
5543    where
5544        Callback: FnOnce(&Value) -> R,
5545    {
5546        // RwLock read guard doesn't allow mutable access
5547        // This is a limitation - we'd need write() for mutable access
5548        None
5549    }
5550
5551    fn with_rwlock_mut<Callback, R>(&self, rwlock: &mut RwLock<Root>, f: Callback) -> Option<R>
5552    where
5553        Callback: FnOnce(&mut Value) -> R,
5554    {
5555        // RwLock::get_mut returns Result<&mut Root, PoisonError>
5556        rwlock.get_mut().ok().map(|root| {
5557            let value = self.get_mut(root);
5558            f(value)
5559        })
5560    }
5561
5562    fn with_arc_rwlock<Callback, R>(&self, arc_rwlock: &Arc<RwLock<Root>>, f: Callback) -> Option<R>
5563    where
5564        Callback: FnOnce(&Value) -> R,
5565    {
5566        // Arc<RwLock> read guard doesn't allow mutable access
5567        // This is a limitation - we'd need write() for mutable access
5568        None
5569    }
5570
5571    fn with_arc_rwlock_mut<Callback, R>(&self, arc_rwlock: &Arc<RwLock<Root>>, f: Callback) -> Option<R>
5572    where
5573        Callback: FnOnce(&mut Value) -> R,
5574    {
5575        arc_rwlock.write().ok().map(|mut guard| {
5576            let value = self.get_mut(&mut *guard);
5577            f(value)
5578        })
5579    }
5580}
5581
5582// Implement WithContainer for WritableOptionalKeyPath - supports all mutable operations
5583impl<Root, Value, F> WithContainer<Root, Value> for WritableOptionalKeyPath<Root, Value, F>
5584where
5585    F: for<'r> Fn(&'r mut Root) -> Option<&'r mut Value>,
5586{
5587    fn with_arc<Callback, R>(&self, _arc: &Arc<Root>, _f: Callback) -> R
5588    where
5589        Callback: FnOnce(&Value) -> R,
5590    {
5591        // Arc doesn't support mutable access without interior mutability
5592        // This method requires &mut Arc<Root> which we don't have
5593        eprintln!("[DEBUG] WritableOptionalKeyPath::with_arc requires &mut Arc<Root> or interior mutability");
5594        unreachable!("WritableOptionalKeyPath::with_arc requires &mut Arc<Root> or interior mutability")
5595    }
5596
5597    fn with_box<Callback, R>(&self, _boxed: &Box<Root>, _f: Callback) -> R
5598    where
5599        Callback: FnOnce(&Value) -> R,
5600    {
5601        // WritableOptionalKeyPath requires &mut Root, but we only have &Box<Root>
5602        // This is a limitation - use with_box_mut for mutable access
5603        eprintln!("[DEBUG] WritableOptionalKeyPath::with_box requires &mut Box<Root> - use with_box_mut instead");
5604        unreachable!("WritableOptionalKeyPath::with_box requires &mut Box<Root> - use with_box_mut instead")
5605    }
5606
5607    fn with_box_mut<Callback, R>(&self, boxed: &mut Box<Root>, f: Callback) -> R
5608    where
5609        Callback: FnOnce(&mut Value) -> R,
5610    {
5611        if let Some(value) = self.get_mut(boxed.as_mut()) {
5612            f(value)
5613        } else {
5614            eprintln!("[DEBUG] WritableOptionalKeyPath failed to get value from Box");
5615            unreachable!("WritableOptionalKeyPath failed to get value from Box")
5616        }
5617    }
5618
5619    fn with_rc<Callback, R>(&self, _rc: &Rc<Root>, _f: Callback) -> R
5620    where
5621        Callback: FnOnce(&Value) -> R,
5622    {
5623        // Rc doesn't support mutable access without interior mutability
5624        // This method requires &mut Rc<Root> which we don't have
5625        eprintln!("[DEBUG] WritableOptionalKeyPath::with_rc requires &mut Rc<Root> or interior mutability");
5626        unreachable!("WritableOptionalKeyPath::with_rc requires &mut Rc<Root> or interior mutability")
5627    }
5628
5629    fn with_result<Callback, R, E>(&self, _result: &Result<Root, E>, _f: Callback) -> Option<R>
5630    where
5631        Callback: FnOnce(&Value) -> R,
5632    {
5633        // WritableOptionalKeyPath requires &mut Root, but we only have &Result<Root, E>
5634        // This is a limitation - use with_result_mut for mutable access
5635        None
5636    }
5637
5638    fn with_result_mut<Callback, R, E>(&self, result: &mut Result<Root, E>, f: Callback) -> Option<R>
5639    where
5640        Callback: FnOnce(&mut Value) -> R,
5641    {
5642        result.as_mut().ok().and_then(|root| {
5643            self.get_mut(root).map(|value| f(value))
5644        })
5645    }
5646
5647    fn with_option<Callback, R>(&self, _option: &Option<Root>, _f: Callback) -> Option<R>
5648    where
5649        Callback: FnOnce(&Value) -> R,
5650    {
5651        // WritableOptionalKeyPath requires &mut Root, but we only have &Option<Root>
5652        // This is a limitation - use with_option_mut for mutable access
5653        None
5654    }
5655
5656    fn with_option_mut<Callback, R>(&self, option: &mut Option<Root>, f: Callback) -> Option<R>
5657    where
5658        Callback: FnOnce(&mut Value) -> R,
5659    {
5660        option.as_mut().and_then(|root| {
5661            self.get_mut(root).map(|value| f(value))
5662        })
5663    }
5664
5665    fn with_refcell<Callback, R>(&self, _refcell: &RefCell<Root>, _f: Callback) -> Option<R>
5666    where
5667        Callback: FnOnce(&Value) -> R,
5668    {
5669        // RefCell doesn't allow getting mutable reference from immutable borrow
5670        // This is a limitation - we'd need try_borrow_mut for mutable access
5671        None
5672    }
5673
5674    fn with_refcell_mut<Callback, R>(&self, refcell: &RefCell<Root>, f: Callback) -> Option<R>
5675    where
5676        Callback: FnOnce(&mut Value) -> R,
5677    {
5678        refcell.try_borrow_mut().ok().and_then(|mut borrow| {
5679            self.get_mut(&mut *borrow).map(|value| f(value))
5680        })
5681    }
5682
5683    #[cfg(feature = "tagged")]
5684    fn with_tagged<Callback, R, Tag>(&self, _tagged: &Tagged<Root, Tag>, _f: Callback) -> R
5685    where
5686        Tagged<Root, Tag>: std::ops::Deref<Target = Root>,
5687        Callback: FnOnce(&Value) -> R,
5688    {
5689        // WritableOptionalKeyPath requires &mut Root, but we only have &Tagged<Root, Tag>
5690        // This is a limitation - Tagged doesn't support mutable access without interior mutability
5691        eprintln!("[DEBUG] WritableOptionalKeyPath::with_tagged requires &mut Tagged<Root, Tag> or interior mutability");
5692        unreachable!("WritableOptionalKeyPath::with_tagged requires &mut Tagged<Root, Tag> or interior mutability")
5693    }
5694
5695    fn with_mutex<Callback, R>(&self, mutex: &Mutex<Root>, f: Callback) -> Option<R>
5696    where
5697        Callback: FnOnce(&Value) -> R,
5698    {
5699        mutex.lock().ok().and_then(|mut guard| {
5700            self.get_mut(&mut *guard).map(|value| f(value))
5701        })
5702    }
5703
5704    fn with_mutex_mut<Callback, R>(&self, mutex: &mut Mutex<Root>, f: Callback) -> Option<R>
5705    where
5706        Callback: FnOnce(&mut Value) -> R,
5707    {
5708        // Mutex::get_mut returns Result<&mut Root, PoisonError>
5709        mutex.get_mut().ok().and_then(|root| {
5710            self.get_mut(root).map(|value| f(value))
5711        })
5712    }
5713
5714    fn with_rwlock<Callback, R>(&self, _rwlock: &RwLock<Root>, _f: Callback) -> Option<R>
5715    where
5716        Callback: FnOnce(&Value) -> R,
5717    {
5718        // RwLock read guard doesn't allow mutable access
5719        // This is a limitation - we'd need write() for mutable access
5720        None
5721    }
5722
5723    fn with_rwlock_mut<Callback, R>(&self, rwlock: &mut RwLock<Root>, f: Callback) -> Option<R>
5724    where
5725        Callback: FnOnce(&mut Value) -> R,
5726    {
5727        // RwLock::get_mut returns Result<&mut Root, PoisonError>
5728        rwlock.get_mut().ok().and_then(|root| {
5729            self.get_mut(root).map(|value| f(value))
5730        })
5731    }
5732
5733    fn with_arc_rwlock<Callback, R>(&self, _arc_rwlock: &Arc<RwLock<Root>>, _f: Callback) -> Option<R>
5734    where
5735        Callback: FnOnce(&Value) -> R,
5736    {
5737        // Arc<RwLock> read guard doesn't allow mutable access
5738        // This is a limitation - we'd need write() for mutable access
5739        None
5740    }
5741
5742    fn with_arc_rwlock_mut<Callback, R>(&self, arc_rwlock: &Arc<RwLock<Root>>, f: Callback) -> Option<R>
5743    where
5744        Callback: FnOnce(&mut Value) -> R,
5745    {
5746        arc_rwlock.write().ok().and_then(|mut guard| {
5747            self.get_mut(&mut *guard).map(|value| f(value))
5748        })
5749    }
5750}