oxide-mvu 0.4.2

A standalone MVU runtime for Rust with no_std support for embedded systems
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
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
//! The MVU runtime that orchestrates the event loop.

#[cfg(feature = "no_std")]
use alloc::boxed::Box;

use core::future::Future;

use async_channel::{bounded, Receiver};

use crate::{Effect, Event as EventTrait};
use crate::{Emitter, MvuLogic, Renderer};

/// Default event channel capacity.
///
/// This bounds the number of events that can be queued before `emit()` drops events.
/// Sized for embedded systems with limited heap. Increase this via
/// [`MvuRuntimeBuilder::capacity`] if your application generates high-frequency bursts of events.
pub const DEFAULT_EVENT_CAPACITY: usize = 32;

/// Builder for configuring and constructing an [`MvuRuntime`].
///
/// Created via [`MvuRuntime::builder`]. Allows customizing runtime parameters
/// like event buffer capacity before building the runtime.
///
/// # Example
///
/// ```rust,no_run
/// # use oxide_mvu::{Emitter, Effect, MvuLogic, MvuRuntime, Renderer};
/// # #[derive(Clone)] enum Event {}
/// # #[derive(Clone)] struct Model;
/// # struct Props;
/// # struct MyLogic;
/// # impl MvuLogic<Event, Model, Props> for MyLogic {
/// #     fn init(&self, model: Model) -> (Model, Effect<Event>) { (model, Effect::none()) }
/// #     fn update(&self, _: Event, model: &Model) -> (Model, Effect<Event>) { (model.clone(), Effect::none()) }
/// #     fn view(&self, _: &Model, _: &Emitter<Event>) -> Props { Props }
/// # }
/// # struct MyRenderer;
/// # impl Renderer<Props> for MyRenderer { fn render(&mut self, _: Props) {} }
/// // Use builder for custom configuration
/// let runtime = MvuRuntime::builder(Model, MyLogic, MyRenderer, |_| {})
///     .capacity(64)
///     .build();
/// ```
pub struct MvuRuntimeBuilder<Event, Model, Props, Logic, Render, Spawn>
where
    Event: EventTrait,
    Model: Clone,
    Logic: MvuLogic<Event, Model, Props>,
    Render: Renderer<Props>,
    Spawn: Spawner,
{
    init_model: Model,
    logic: Logic,
    renderer: Render,
    spawner: Spawn,
    capacity: usize,
    _event: core::marker::PhantomData<Event>,
    _props: core::marker::PhantomData<Props>,
}

impl<Event, Model, Props, Logic, Render, Spawn>
    MvuRuntimeBuilder<Event, Model, Props, Logic, Render, Spawn>
where
    Event: EventTrait,
    Model: Clone + 'static,
    Props: 'static,
    Logic: MvuLogic<Event, Model, Props>,
    Render: Renderer<Props>,
    Spawn: Spawner,
{
    /// Set the event buffer capacity.
    ///
    /// This bounds the number of events that can be queued before
    /// [`Emitter::try_emit`](crate::Emitter::try_emit) returns `false`.
    ///
    /// Defaults to [`DEFAULT_EVENT_CAPACITY`] (32).
    pub fn capacity(mut self, capacity: usize) -> Self {
        self.capacity = capacity;
        self
    }

    /// Build the runtime with the configured settings.
    pub fn build(self) -> MvuRuntime<Event, Model, Props, Logic, Render, Spawn> {
        let (event_sender, event_receiver) = bounded(self.capacity);
        let emitter = Emitter::new(event_sender);

        MvuRuntime {
            logic: self.logic,
            renderer: self.renderer,
            event_receiver,
            model: self.init_model,
            emitter,
            spawner: self.spawner,
            _props: core::marker::PhantomData,
        }
    }
}

use core::pin::Pin;

/// A spawner trait for executing futures on an async runtime.
///
/// This abstraction allows you to use whatever concurrency model you want (tokio, async-std, embassy, etc.).
///
/// Function pointers and closures automatically implement this trait via the blanket implementation.
pub trait Spawner {
    /// Spawn a future on the async runtime.
    fn spawn(&self, future: Pin<Box<dyn Future<Output = ()> + Send>>);
}

/// Implement Spawner for any callable type that matches the signature.
///
/// This includes function pointers, closures, and function items.
impl<F> Spawner for F
where
    F: Fn(Pin<Box<dyn Future<Output = ()> + Send>>),
{
    fn spawn(&self, future: Pin<Box<dyn Future<Output = ()> + Send>>) {
        self(future)
    }
}

/// The MVU runtime that orchestrates the event loop.
///
/// This is the core of the framework. It:
/// 1. Initializes the Model and initial Effects via [`MvuLogic::init`]
/// 2. Processes events through [`MvuLogic::update`]
/// 3. Reduces the Model to Props via [`MvuLogic::view`]
/// 4. Delivers Props to the [`Renderer`] for rendering
///
/// The runtime creates a single [`Emitter`] that can send events from any thread.
/// Events are queued via a lock-free MPMC channel and processed on the thread where
/// [`MvuRuntime::run`] was called.
///
/// For testing with manual control, use `TestMvuRuntime` with `TestRenderer`
/// (both available with the `testing` feature).
///
/// See the [crate-level documentation](crate) for a complete example.
///
/// # Type Parameters
///
/// * `Event` - The event type for your application
/// * `Model` - The model/state type for your application
/// * `Props` - The props type produced by the view function
/// * `Logic` - The logic implementation type (implements [`MvuLogic`])
/// * `Render` - The renderer implementation type (implements [`Renderer`])
/// * `Spawn` - The spawner implementation type (implements [`Spawner`])
pub struct MvuRuntime<Event, Model, Props, Logic, Render, Spawn>
where
    Event: EventTrait,
    Model: Clone,
    Logic: MvuLogic<Event, Model, Props>,
    Render: Renderer<Props>,
    Spawn: Spawner,
{
    logic: Logic,
    renderer: Render,
    event_receiver: Receiver<Event>,
    model: Model,
    emitter: Emitter<Event>,
    spawner: Spawn,
    _props: core::marker::PhantomData<Props>,
}

impl<Event, Model, Props, Logic, Render, Spawn>
    MvuRuntime<Event, Model, Props, Logic, Render, Spawn>
where
    Event: EventTrait,
    Model: Clone + 'static,
    Props: 'static,
    Logic: MvuLogic<Event, Model, Props>,
    Render: Renderer<Props>,
    Spawn: Spawner,
{
    /// Create a builder for configuring the runtime.
    ///
    /// Use this when you need to customize runtime parameters like event buffer capacity.
    ///
    /// # Arguments
    ///
    /// * `init_model` - The initial state
    /// * `logic` - Application logic implementing MvuLogic
    /// * `renderer` - Platform rendering implementation for rendering Props
    /// * `spawner` - Spawner to execute async effects on your chosen runtime
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// # use oxide_mvu::{Emitter, Effect, MvuLogic, MvuRuntime, Renderer};
    /// # #[derive(Clone)] enum Event {}
    /// # #[derive(Clone)] struct Model;
    /// # struct Props;
    /// # struct MyLogic;
    /// # impl MvuLogic<Event, Model, Props> for MyLogic {
    /// #     fn init(&self, model: Model) -> (Model, Effect<Event>) { (model, Effect::none()) }
    /// #     fn update(&self, _: Event, model: &Model) -> (Model, Effect<Event>) { (model.clone(), Effect::none()) }
    /// #     fn view(&self, _: &Model, _: &Emitter<Event>) -> Props { Props }
    /// # }
    /// # struct MyRenderer;
    /// # impl Renderer<Props> for MyRenderer { fn render(&mut self, _: Props) {} }
    /// // For memory-constrained embedded systems
    /// let runtime = MvuRuntime::builder(Model, MyLogic, MyRenderer, |_| {})
    ///     .capacity(8)
    ///     .build();
    /// ```
    pub fn builder(
        init_model: Model,
        logic: Logic,
        renderer: Render,
        spawner: Spawn,
    ) -> MvuRuntimeBuilder<Event, Model, Props, Logic, Render, Spawn> {
        MvuRuntimeBuilder {
            init_model,
            logic,
            renderer,
            spawner,
            capacity: DEFAULT_EVENT_CAPACITY,
            _event: core::marker::PhantomData,
            _props: core::marker::PhantomData,
        }
    }

    /// Initialize the runtime and run the event processing loop.
    ///
    /// - Uses the MvuLogic::init function to create and enqueue initial side effects.
    /// - Reduces the initial Model provided at construction to Props via MvuLogic::view.
    /// - Renders the initial Props.
    /// - Processes events from the channel in a loop.
    ///
    /// This is an async function that runs the event loop. You can spawn it on your
    /// chosen runtime using the spawner, or await it directly.
    ///
    /// Events can be emitted from any thread via the Emitter, but are always processed
    /// sequentially on the thread where this future is awaited/polled.
    pub async fn run(mut self) {
        let (init_model, init_effect) = self.logic.init(self.model.clone());

        let initial_props = {
            let emitter = &self.emitter;
            self.logic.view(&init_model, emitter)
        };

        self.renderer.render(initial_props);

        // Execute initial effect by spawning it
        Self::spawn_effect(&self.spawner, &self.emitter, init_effect);

        // Event processing loop
        while let Ok(event) = self.event_receiver.recv().await {
            self.step(event);
        }
    }

    fn step(&mut self, event: Event) {
        // Update model with event
        let (new_model, effect) = self.logic.update(event, &self.model);

        // Reduce to props and render
        let props = self.logic.view(&new_model, &self.emitter);
        self.renderer.render(props);

        // Update model
        self.model = new_model;

        // Execute the effect
        Self::spawn_effect(&self.spawner, &self.emitter, effect);
    }

    pub fn spawn_effect(spawner: &Spawn, emitter: &Emitter<Event>, effect: Effect<Event>) {
        match effect {
            Effect::None => {}
            Effect::Just(event) => {
                let emitter = emitter.clone();
                spawner.spawn(Box::pin(async move { emitter.emit(event).await }));
            }
            Effect::Async(boxed_future) => spawner.spawn(boxed_future.call_box(emitter)),
            Effect::Batch(effects) => {
                for effect in effects {
                    Self::spawn_effect(spawner, emitter, effect);
                }
            }
        }
    }
}

#[cfg(any(test, feature = "testing"))]
/// Test spawner function that executes futures synchronously.
///
/// This blocks on the future immediately rather than spawning it on an async runtime.
pub fn test_spawner_fn(fut: Pin<Box<dyn Future<Output = ()> + Send>>) {
    // Execute the future synchronously for deterministic testing
    futures::executor::block_on(fut);
}

#[cfg(any(test, feature = "testing"))]
/// Creates a test spawner that executes futures synchronously.
///
/// This is useful for testing - it blocks on the future immediately rather
/// than spawning it on an async runtime. Use this with [`TestMvuRuntime`]
/// or [`MvuRuntime`] in test scenarios.
///
/// Returns a function pointer that can be passed directly to runtime constructors
/// without heap allocation.
pub fn create_test_spawner() -> fn(Pin<Box<dyn Future<Output = ()> + Send>>) {
    test_spawner_fn
}

#[cfg(any(test, feature = "testing"))]
/// Test runtime driver for manual event processing control.
///
/// Only available with the `testing` feature or during tests.
///
/// Returned by [`TestMvuRuntime::run`]. Provides methods to manually
/// emit events and process the event queue for precise control in tests.
///
/// See [`TestMvuRuntime`] for usage.
pub struct TestMvuDriver<Event, Model, Props, Logic, Render, Spawn>
where
    Event: EventTrait,
    Model: Clone + 'static,
    Props: 'static,
    Logic: MvuLogic<Event, Model, Props>,
    Render: Renderer<Props>,
    Spawn: Spawner,
{
    _runtime: TestMvuRuntime<Event, Model, Props, Logic, Render, Spawn>,
}

#[cfg(any(test, feature = "testing"))]
impl<Event, Model, Props, Logic, Render, Spawn>
    TestMvuDriver<Event, Model, Props, Logic, Render, Spawn>
where
    Event: EventTrait,
    Model: Clone + 'static,
    Props: 'static,
    Logic: MvuLogic<Event, Model, Props>,
    Render: Renderer<Props>,
    Spawn: Spawner,
{
    /// Process all queued events.
    ///
    /// This processes events until the queue is empty. Call this after emitting
    /// events to drive the event loop in tests.
    pub fn process_events(&mut self) {
        self._runtime.process_queued_events();
    }
}

#[cfg(any(test, feature = "testing"))]
/// Test runtime for MVU with manual event processing control.
///
/// Only available with the `testing` feature or during tests.
///
/// Unlike [`MvuRuntime`], this runtime does not automatically
/// process events when they are emitted. Instead, tests must manually call
/// [`TestMvuDriver::process_events`] on the returned driver
/// to process the event queue.
///
/// This provides precise control over event timing in tests.
///
/// ```rust
/// use oxide_mvu::{Emitter, Effect, Renderer, MvuLogic, TestMvuRuntime};
/// # #[derive(Clone)]
/// # enum Event { Increment }
/// # #[derive(Clone)]
/// # struct Model { count: i32 }
/// # struct Props { count: i32, on_click: Box<dyn Fn()> }
/// # struct MyApp;
/// # impl MvuLogic<Event, Model, Props> for MyApp {
/// #     fn init(&self, model: Model) -> (Model, Effect<Event>) { (model, Effect::none()) }
/// #     fn update(&self, event: Event, model: &Model) -> (Model, Effect<Event>) {
/// #         (Model { count: model.count + 1 }, Effect::none())
/// #     }
/// #     fn view(&self, model: &Model, emitter: &Emitter<Event>) -> Props {
/// #         let e = emitter.clone();
/// #         Props { count: model.count, on_click: Box::new(move || { e.try_emit(Event::Increment); }) }
/// #     }
/// # }
/// # struct TestRenderer;
/// # impl Renderer<Props> for TestRenderer { fn render(&mut self, _props: Props) {} }
/// use oxide_mvu::create_test_spawner;
///
/// let runtime = TestMvuRuntime::builder(
///     Model { count: 0 },
///     MyApp,
///     TestRenderer,
///     create_test_spawner()
/// ).build();
/// let mut driver = runtime.run();
/// driver.process_events(); // Manually process events
/// ```
pub struct TestMvuRuntime<Event, Model, Props, Logic, Render, Spawn>
where
    Event: EventTrait,
    Model: Clone + 'static,
    Props: 'static,
    Logic: MvuLogic<Event, Model, Props>,
    Render: Renderer<Props>,
    Spawn: Spawner,
{
    runtime: MvuRuntime<Event, Model, Props, Logic, Render, Spawn>,
}

#[cfg(any(test, feature = "testing"))]
/// Builder for configuring and constructing a [`TestMvuRuntime`].
///
/// Created via [`TestMvuRuntime::builder`]. Allows customizing runtime parameters
/// like event buffer capacity before building the test runtime.
pub struct TestMvuRuntimeBuilder<Event, Model, Props, Logic, Render, Spawn>
where
    Event: EventTrait,
    Model: Clone + 'static,
    Props: 'static,
    Logic: MvuLogic<Event, Model, Props>,
    Render: Renderer<Props>,
    Spawn: Spawner,
{
    init_model: Model,
    logic: Logic,
    renderer: Render,
    spawner: Spawn,
    capacity: usize,
    _event: core::marker::PhantomData<Event>,
    _props: core::marker::PhantomData<Props>,
}

#[cfg(any(test, feature = "testing"))]
impl<Event, Model, Props, Logic, Render, Spawn>
    TestMvuRuntimeBuilder<Event, Model, Props, Logic, Render, Spawn>
where
    Event: EventTrait,
    Model: Clone + 'static,
    Props: 'static,
    Logic: MvuLogic<Event, Model, Props>,
    Render: Renderer<Props>,
    Spawn: Spawner,
{
    /// Set the event buffer capacity.
    ///
    /// This bounds the number of events that can be queued before
    /// [`Emitter::try_emit`] returns `false`.
    ///
    /// Defaults to [`DEFAULT_EVENT_CAPACITY`].
    pub fn capacity(mut self, capacity: usize) -> Self {
        self.capacity = capacity;
        self
    }

    /// Build the test runtime with the configured settings.
    pub fn build(self) -> TestMvuRuntime<Event, Model, Props, Logic, Render, Spawn> {
        let (event_sender, event_receiver) = bounded(self.capacity);

        TestMvuRuntime {
            runtime: MvuRuntime {
                logic: self.logic,
                renderer: self.renderer,
                event_receiver,
                model: self.init_model,
                emitter: Emitter::new(event_sender),
                spawner: self.spawner,
                _props: core::marker::PhantomData,
            },
        }
    }
}

#[cfg(any(test, feature = "testing"))]
impl<Event, Model, Props, Logic, Render, Spawn>
    TestMvuRuntime<Event, Model, Props, Logic, Render, Spawn>
where
    Event: EventTrait,
    Model: Clone + 'static,
    Props: 'static,
    Logic: MvuLogic<Event, Model, Props>,
    Render: Renderer<Props>,
    Spawn: Spawner,
{
    /// Create a builder for configuring the test runtime.
    ///
    /// # Arguments
    ///
    /// * `init_model` - The initial state
    /// * `logic` - Application logic implementing MvuLogic
    /// * `renderer` - Platform rendering implementation for rendering Props
    /// * `spawner` - Spawner to execute async effects on your chosen runtime
    pub fn builder(
        init_model: Model,
        logic: Logic,
        renderer: Render,
        spawner: Spawn,
    ) -> TestMvuRuntimeBuilder<Event, Model, Props, Logic, Render, Spawn> {
        TestMvuRuntimeBuilder {
            init_model,
            logic,
            renderer,
            spawner,
            capacity: DEFAULT_EVENT_CAPACITY,
            _event: core::marker::PhantomData,
            _props: core::marker::PhantomData,
        }
    }

    /// Initializes the runtime and returns a driver for manual event processing.
    ///
    /// This processes initial effects and renders the initial state, then returns
    /// a [`TestMvuDriver`] that provides manual control over event processing.
    pub fn run(mut self) -> TestMvuDriver<Event, Model, Props, Logic, Render, Spawn> {
        let (init_model, init_effect) = self.runtime.logic.init(self.runtime.model.clone());

        let initial_props = { self.runtime.logic.view(&init_model, &self.runtime.emitter) };

        self.runtime.renderer.render(initial_props);

        // Execute initial effect by spawning it
        MvuRuntime::<Event, Model, Props, Logic, Render, Spawn>::spawn_effect(
            &self.runtime.spawner,
            &self.runtime.emitter,
            init_effect,
        );

        TestMvuDriver { _runtime: self }
    }

    /// Process all queued events (for testing).
    ///
    /// This is exposed for TestMvuRuntime to manually drive event processing.
    fn process_queued_events(&mut self) {
        while let Ok(event) = self.runtime.event_receiver.try_recv() {
            self.runtime.step(event);
        }
    }
}