rust-elm 0.9.0

Elm Architecture for Rust: composable reducers, pure effects, async runtime.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
//! Lock-backed bindings with keypath projection (SwiftUI `Binding` dynamic-member style).
//!
//! Reads and writes go through the store's shared mutex — no full-state clone.
//! Project a field with [`StateBinding::project`] / [`ProjectedBinding::project`].
//!
//! When a keypath cannot focus (e.g. `None` in an `Option` field), [`ProjectedBinding::with`]
//! and [`ProjectedBinding::with_mut`] return [`None`] instead of panicking.

use std::marker::PhantomData;
use std::sync::Arc;

use key_paths_core::RefKpTrait;
use parking_lot::{Mutex, RwLock};

use crate::runtime::state_access::{StateRead, StateWrite};

/// Read/write access to store state without cloning `S`.
#[derive(Clone)]
pub struct StateBinding<S: 'static> {
    state: Arc<Mutex<S>>,
}

impl<S: 'static> StateBinding<S> {
    pub(crate) fn new(state: Arc<Mutex<S>>) -> Self {
        Self { state }
    }

    /// Borrow the root state under the lock.
    pub fn with<R>(&self, f: impl FnOnce(&S) -> R) -> R {
        f(&*self.state.lock())
    }

    /// Mutably borrow the root state under the lock.
    pub fn with_mut<R>(&self, f: impl FnOnce(&mut S) -> R) -> R {
        f(&mut *self.state.lock())
    }

    /// Project a property via keypath — reads/writes go to the original binding's state.
    pub fn project<V, SK>(&self, kp: SK) -> ProjectedBinding<S, V, SK>
    where
        SK: RefKpTrait<S, V>,
    {
        ProjectedBinding {
            state: Arc::clone(&self.state),
            kp,
            _marker: PhantomData,
        }
    }
}

/// A field projected from a [`StateBinding`] through a keypath.
pub struct ProjectedBinding<Root: 'static, Focus: 'static, SK> {
    state: Arc<Mutex<Root>>,
    kp: SK,
    _marker: PhantomData<Focus>,
}

impl<Root, Focus, SK> Clone for ProjectedBinding<Root, Focus, SK>
where
    Root: 'static,
    Focus: 'static,
    SK: RefKpTrait<Root, Focus> + Clone,
{
    fn clone(&self) -> Self {
        Self {
            state: Arc::clone(&self.state),
            kp: self.kp.clone(),
            _marker: PhantomData,
        }
    }
}

impl<Root, Focus, SK> ProjectedBinding<Root, Focus, SK>
where
    Root: 'static,
    Focus: 'static,
    SK: RefKpTrait<Root, Focus>,
{
    /// Borrow the focused value under the root lock, or [`None`] if the keypath misses.
    pub fn with<R>(&self, f: impl FnOnce(&Focus) -> R) -> Option<R> {
        let guard = self.state.lock();
        let focused = self.kp.focus(&*guard)?;
        Some(f(focused))
    }

    /// Mutably borrow the focused value under the root lock, or [`None`] if the keypath misses.
    pub fn with_mut<R>(&self, f: impl FnOnce(&mut Focus) -> R) -> Option<R> {
        let mut guard = self.state.lock();
        let focused = self.kp.focus_mut(&mut *guard)?;
        Some(f(focused))
    }

    /// Chain another keypath segment (consumes `self`; parent keypath must be [`Clone`]).
    pub fn project<V, SubSK>(self, sub_kp: SubSK) -> ComposedBinding<Root, Focus, V, SK, SubSK>
    where
        SubSK: RefKpTrait<Focus, V>,
        SK: Clone,
    {
        ComposedBinding {
            state: self.state,
            parent_kp: self.kp,
            sub_kp,
            _marker: PhantomData,
        }
    }
}

/// Two-segment keypath projection from root state.
pub struct ComposedBinding<Root: 'static, Mid: 'static, Focus: 'static, ParentKP, SubKP> {
    state: Arc<Mutex<Root>>,
    parent_kp: ParentKP,
    sub_kp: SubKP,
    _marker: PhantomData<(Mid, Focus)>,
}

impl<Root, Mid, Focus, ParentKP, SubKP> ComposedBinding<Root, Mid, Focus, ParentKP, SubKP>
where
    Root: 'static,
    Mid: 'static,
    Focus: 'static,
    ParentKP: RefKpTrait<Root, Mid>,
    SubKP: RefKpTrait<Mid, Focus>,
{
    /// Borrow through parent then child keypath; [`None`] if either segment misses.
    pub fn with<R>(&self, f: impl FnOnce(&Focus) -> R) -> Option<R> {
        let guard = self.state.lock();
        let mid = self.parent_kp.focus(&*guard)?;
        let focused = self.sub_kp.focus(mid)?;
        Some(f(focused))
    }

    /// Mutably borrow through parent then child keypath; [`None`] if either segment misses.
    pub fn with_mut<R>(&self, f: impl FnOnce(&mut Focus) -> R) -> Option<R> {
        let mut guard = self.state.lock();
        let mid = self.parent_kp.focus_mut(&mut *guard)?;
        let focused = self.sub_kp.focus_mut(mid)?;
        Some(f(focused))
    }
}

// ── RwLock-backed bindings (concurrent readers) ─────────────────────────────

/// Read-only binding over [`RwLock`] state — many concurrent readers.
#[derive(Clone)]
pub struct ReadStateBinding<S: 'static> {
    state: Arc<RwLock<S>>,
}

impl<S: 'static> ReadStateBinding<S> {
    pub(crate) fn new(state: Arc<RwLock<S>>) -> Self {
        Self { state }
    }

    pub fn with_read<R>(&self, f: impl FnOnce(&S) -> R) -> R {
        self.state.with_read(f)
    }

    pub fn project<V, SK>(&self, kp: SK) -> ReadProjectedBinding<S, V, SK>
    where
        SK: RefKpTrait<S, V>,
    {
        ReadProjectedBinding {
            state: Arc::clone(&self.state),
            kp,
            _marker: PhantomData,
        }
    }
}

/// Read/write binding over [`RwLock`] state — writes take exclusive lock.
#[derive(Clone)]
pub struct RwStateBinding<S: 'static> {
    state: Arc<RwLock<S>>,
}

impl<S: 'static> RwStateBinding<S> {
    pub(crate) fn new(state: Arc<RwLock<S>>) -> Self {
        Self { state }
    }

    pub fn with_read<R>(&self, f: impl FnOnce(&S) -> R) -> R {
        self.state.with_read(f)
    }

    pub fn with_write<R>(&self, f: impl FnOnce(&mut S) -> R) -> R {
        self.state.with_write(f)
    }

    pub fn read_store(&self) -> ReadStateBinding<S> {
        ReadStateBinding::new(Arc::clone(&self.state))
    }

    pub fn project<V, SK>(&self, kp: SK) -> RwProjectedBinding<S, V, SK>
    where
        SK: RefKpTrait<S, V>,
    {
        RwProjectedBinding {
            state: Arc::clone(&self.state),
            kp,
            _marker: PhantomData,
        }
    }
}

/// Read-only projected field from [`ReadStateBinding`].
pub struct ReadProjectedBinding<Root: 'static, Focus: 'static, SK> {
    state: Arc<RwLock<Root>>,
    kp: SK,
    _marker: PhantomData<Focus>,
}

impl<Root, Focus, SK> Clone for ReadProjectedBinding<Root, Focus, SK>
where
    Root: 'static,
    Focus: 'static,
    SK: RefKpTrait<Root, Focus> + Clone,
{
    fn clone(&self) -> Self {
        Self {
            state: Arc::clone(&self.state),
            kp: self.kp.clone(),
            _marker: PhantomData,
        }
    }
}

impl<Root, Focus, SK> ReadProjectedBinding<Root, Focus, SK>
where
    Root: 'static,
    Focus: 'static,
    SK: RefKpTrait<Root, Focus>,
{
    pub fn with_read<R>(&self, f: impl FnOnce(&Focus) -> R) -> Option<R> {
        let guard = self.state.read();
        let focused = self.kp.focus(&*guard)?;
        Some(f(focused))
    }
}

/// Projected field from [`RwStateBinding`].
pub struct RwProjectedBinding<Root: 'static, Focus: 'static, SK> {
    state: Arc<RwLock<Root>>,
    kp: SK,
    _marker: PhantomData<Focus>,
}

impl<Root, Focus, SK> Clone for RwProjectedBinding<Root, Focus, SK>
where
    Root: 'static,
    Focus: 'static,
    SK: RefKpTrait<Root, Focus> + Clone,
{
    fn clone(&self) -> Self {
        Self {
            state: Arc::clone(&self.state),
            kp: self.kp.clone(),
            _marker: PhantomData,
        }
    }
}

impl<Root, Focus, SK> RwProjectedBinding<Root, Focus, SK>
where
    Root: 'static,
    Focus: 'static,
    SK: RefKpTrait<Root, Focus>,
{
    pub fn with_read<R>(&self, f: impl FnOnce(&Focus) -> R) -> Option<R> {
        let guard = self.state.read();
        let focused = self.kp.focus(&*guard)?;
        Some(f(focused))
    }

    pub fn with_write<R>(&self, f: impl FnOnce(&mut Focus) -> R) -> Option<R> {
        let mut guard = self.state.write();
        let focused = self.kp.focus_mut(&mut *guard)?;
        Some(f(focused))
    }
}

// ── ArcSwap snapshot bindings (`arc-swap` feature) ──────────────────────────

/// Lock-free read binding over [`ArcSwap`](arc_swap::ArcSwap) state snapshots.
#[cfg(feature = "arc-swap")]
#[derive(Clone)]
pub struct SnapshotStateBinding<S: 'static> {
    state: Arc<arc_swap::ArcSwap<S>>,
}

#[cfg(feature = "arc-swap")]
impl<S: 'static> SnapshotStateBinding<S> {
    pub(crate) fn new(state: Arc<arc_swap::ArcSwap<S>>) -> Self {
        Self { state }
    }

    pub fn with_snapshot<R>(&self, f: impl FnOnce(&S) -> R) -> R {
        f(&*self.state.load_full())
    }

    pub fn load(&self) -> Arc<S>
    where
        S: Clone,
    {
        self.state.load_full()
    }

    pub fn project<V, SK>(&self, kp: SK) -> SnapshotProjectedBinding<S, V, SK>
    where
        SK: RefKpTrait<S, V>,
    {
        SnapshotProjectedBinding {
            state: Arc::clone(&self.state),
            kp,
            _marker: PhantomData,
        }
    }
}

/// Projected field from [`SnapshotStateBinding`].
#[cfg(feature = "arc-swap")]
pub struct SnapshotProjectedBinding<Root: 'static, Focus: 'static, SK> {
    state: Arc<arc_swap::ArcSwap<Root>>,
    kp: SK,
    _marker: PhantomData<Focus>,
}

#[cfg(feature = "arc-swap")]
impl<Root, Focus, SK> Clone for SnapshotProjectedBinding<Root, Focus, SK>
where
    Root: 'static,
    Focus: 'static,
    SK: RefKpTrait<Root, Focus> + Clone,
{
    fn clone(&self) -> Self {
        Self {
            state: Arc::clone(&self.state),
            kp: self.kp.clone(),
            _marker: PhantomData,
        }
    }
}

#[cfg(feature = "arc-swap")]
impl<Root, Focus, SK> SnapshotProjectedBinding<Root, Focus, SK>
where
    Root: 'static,
    Focus: 'static,
    SK: RefKpTrait<Root, Focus>,
{
    pub fn with_snapshot<R>(&self, f: impl FnOnce(&Focus) -> R) -> Option<R> {
        let snapshot = self.state.load_full();
        let focused = self.kp.focus(&*snapshot)?;
        Some(f(focused))
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use key_paths_derive::{FieldDiff, Kp};
    use rust_key_paths::Kp as KpPath;

    #[derive(Debug, Kp, Clone, Hash, FieldDiff, PartialEq)]
    struct Episode {
        current_position: i32,
        is_favorite: bool,
    }

    fn position_kp() -> KpPath<
        Episode,
        i32,
        &'static Episode,
        &'static i32,
        &'static mut Episode,
        &'static mut i32,
        for<'b> fn(&'b Episode) -> Option<&'b i32>,
        for<'b> fn(&'b mut Episode) -> Option<&'b mut i32>,
    > {
        fn get(e: &Episode) -> Option<&i32> {
            Some(&e.current_position)
        }
        fn get_mut(e: &mut Episode) -> Option<&mut i32> {
            Some(&mut e.current_position)
        }
        KpPath::new(get, get_mut)
    }

    fn favorite_kp() -> KpPath<
        Episode,
        bool,
        &'static Episode,
        &'static bool,
        &'static mut Episode,
        &'static mut bool,
        for<'b> fn(&'b Episode) -> Option<&'b bool>,
        for<'b> fn(&'b mut Episode) -> Option<&'b mut bool>,
    > {
        fn get(e: &Episode) -> Option<&bool> {
            Some(&e.is_favorite)
        }
        fn get_mut(e: &mut Episode) -> Option<&mut bool> {
            Some(&mut e.is_favorite)
        }
        KpPath::new(get, get_mut)
    }

    #[test]
    fn binding_projects_fields_without_cloning_root() {
        let state = Arc::new(Mutex::new(Episode {
            current_position: 1,
            is_favorite: false,
        }));
        let binding = StateBinding::new(state);

        let position = binding.project(position_kp());
        assert_eq!(position.with(|p| *p), Some(1));

        position.with_mut(|p| *p = 2);
        assert_eq!(binding.with(|e| e.current_position), 2);

        let favorite = binding.project(favorite_kp());
        favorite.with_mut(|f| *f = true);
        assert!(binding.with(|e| e.is_favorite));
    }

    #[test]
    fn projected_binding_returns_none_when_keypath_misses() {
        #[derive(Kp, Clone, Hash, FieldDiff, PartialEq, Debug)]
        struct Root {
            child: Option<Episode>,
        }

        fn child_kp() -> KpPath<
            Root,
            Episode,
            &'static Root,
            &'static Episode,
            &'static mut Root,
            &'static mut Episode,
            for<'b> fn(&'b Root) -> Option<&'b Episode>,
            for<'b> fn(&'b mut Root) -> Option<&'b mut Episode>,
        > {
            fn get(r: &Root) -> Option<&Episode> {
                r.child.as_ref()
            }
            fn get_mut(r: &mut Root) -> Option<&mut Episode> {
                r.child.as_mut()
            }
            KpPath::new(get, get_mut)
        }

        let binding = StateBinding::new(Arc::new(Mutex::new(Root { child: None })));
        let child = binding.project(child_kp());
        assert!(child.with(|_| ()).is_none());
        assert!(child.with_mut(|_| ()).is_none());
    }
}