zed 0.2.0

A minimal, Redux-like state management library for Rust with advanced features.
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
//! Error handling and edge case tests for the Zed crate
//! This module tests various error conditions and edge cases

use zed::*;

#[derive(Clone, Debug, PartialEq)]
struct TestState {
    value: i32,
    data: Vec<String>,
}

#[derive(Clone, Debug)]
enum TestAction {
    Increment,
    Decrement,
    AddData(String),
    ClearData,
}

#[cfg(test)]
mod error_handling_tests {
    use super::*;
    use std::sync::{Arc, Mutex};
    use std::thread;
    use std::time::Duration;

    #[test]
    fn test_store_with_panicking_reducer() {
        // Test that store can handle reducers that panic
        let store = configure_store(
            TestState {
                value: 0,
                data: vec![],
            },
            create_reducer(|state: &TestState, action: &TestAction| match action {
                TestAction::Increment => {
                    if state.value >= 10 {
                        panic!("Value too high!");
                    }
                    TestState {
                        value: state.value + 1,
                        data: state.data.clone(),
                    }
                }
                _ => state.clone(),
            }),
        );

        // Normal operations should work
        store.dispatch(TestAction::Increment);
        assert_eq!(store.get_state().value, 1);

        // Set value to 9
        for _ in 0..8 {
            store.dispatch(TestAction::Increment);
        }
        assert_eq!(store.get_state().value, 9);

        // This should panic, but we can't easily test panic behavior
        // in a unit test without special setup
        // store.dispatch(TestAction::Increment); // Would panic
    }

    #[test]
    fn test_concurrent_store_access_heavy_load() {
        let store = Arc::new(configure_store(
            TestState {
                value: 0,
                data: vec![],
            },
            create_reducer(|state: &TestState, action: &TestAction| match action {
                TestAction::Increment => TestState {
                    value: state.value + 1,
                    data: state.data.clone(),
                },
                TestAction::Decrement => TestState {
                    value: state.value - 1,
                    data: state.data.clone(),
                },
                TestAction::AddData(s) => {
                    let mut new_data = state.data.clone();
                    new_data.push(s.clone());
                    TestState {
                        value: state.value,
                        data: new_data,
                    }
                }
                TestAction::ClearData => TestState {
                    value: state.value,
                    data: vec![],
                },
            }),
        ));

        let num_threads = 50;
        let operations_per_thread = 100;
        let mut handles = vec![];

        for i in 0..num_threads {
            let store_clone = Arc::clone(&store);
            let handle = thread::spawn(move || {
                for j in 0..operations_per_thread {
                    match j % 4 {
                        0 => store_clone.dispatch(TestAction::Increment),
                        1 => store_clone.dispatch(TestAction::Decrement),
                        2 => {
                            store_clone.dispatch(TestAction::AddData(format!("thread_{i}_op_{j}")))
                        }
                        3 => store_clone.dispatch(TestAction::ClearData),
                        _ => unreachable!(),
                    }
                }
            });
            handles.push(handle);
        }

        for handle in handles {
            handle.join().unwrap();
        }

        // State should be consistent after all operations
        let final_state = store.get_state();
        println!(
            "Final state after heavy concurrent access: value={}, data_len={}",
            final_state.value,
            final_state.data.len()
        );

        // The exact values are non-deterministic due to concurrency,
        // but the state should be valid
        assert!(final_state.value >= -5000 && final_state.value <= 5000);
    }

    #[test]
    fn test_store_with_large_state() {
        // Test store with very large state
        let large_data: Vec<String> = (0..10000).map(|i| format!("item_{i}")).collect();

        let store = configure_store(
            TestState {
                value: 0,
                data: large_data,
            },
            create_reducer(|state: &TestState, action: &TestAction| match action {
                TestAction::Increment => TestState {
                    value: state.value + 1,
                    data: state.data.clone(),
                },
                TestAction::AddData(s) => {
                    let mut new_data = state.data.clone();
                    new_data.push(s.clone());
                    TestState {
                        value: state.value,
                        data: new_data,
                    }
                }
                _ => state.clone(),
            }),
        );

        let initial_len = store.get_state().data.len();
        assert_eq!(initial_len, 10000);

        store.dispatch(TestAction::Increment);
        assert_eq!(store.get_state().value, 1);
        assert_eq!(store.get_state().data.len(), 10000);

        store.dispatch(TestAction::AddData("new_item".to_string()));
        assert_eq!(store.get_state().data.len(), 10001);
    }

    #[test]
    fn test_reactive_system_with_many_reactions() {
        let mut system = ReactiveSystem::new(TestState {
            value: 0,
            data: vec![],
        });

        // Add many reactions to the same action
        for i in 0..1000 {
            system.on("increment".to_string(), move |state: &mut TestState| {
                state.value += i % 10; // Different increments
            });
        }

        system.trigger("increment".to_string());

        // The value should be the sum of all increments
        let expected_sum: i32 = (0..1000).map(|i| i % 10).sum();
        assert_eq!(system.current_state().value, expected_sum);
    }

    #[test]
    fn test_reactive_system_with_long_action_names() {
        let mut system = ReactiveSystem::new(TestState {
            value: 0,
            data: vec![],
        });

        let long_action_name = "a".repeat(10000);
        system.on(long_action_name.clone(), |state: &mut TestState| {
            state.value += 1;
        });

        system.trigger(long_action_name);
        assert_eq!(system.current_state().value, 1);
    }

    #[test]
    fn test_capsule_with_expensive_cache_operations() {
        #[derive(Clone)]
        struct ExpensiveCache<T: Clone> {
            value: Option<T>,
            access_count: Arc<Mutex<u32>>,
        }

        impl<T: Clone> ExpensiveCache<T> {
            fn new() -> Self {
                Self {
                    value: None,
                    access_count: Arc::new(Mutex::new(0)),
                }
            }
        }

        impl<T: Clone> Cache<T> for ExpensiveCache<T> {
            fn get(&self) -> Option<T> {
                // Simulate expensive operation
                thread::sleep(Duration::from_millis(1));
                *self.access_count.lock().unwrap() += 1;
                self.value.clone()
            }

            fn set(&mut self, value: T) {
                // Simulate expensive operation
                thread::sleep(Duration::from_millis(1));
                *self.access_count.lock().unwrap() += 1;
                self.value = Some(value);
            }
        }

        let mut capsule = Capsule::new(TestState {
            value: 0,
            data: vec![],
        })
        .with_cache(ExpensiveCache::new())
        .with_logic(|state: &mut TestState, action: TestAction| match action {
            TestAction::Increment => state.value += 1,
            TestAction::AddData(s) => state.data.push(s),
            _ => {}
        });

        // Operations should work despite expensive cache
        capsule.dispatch(TestAction::Increment);
        assert_eq!(capsule.get_state().value, 1);

        capsule.dispatch(TestAction::AddData("test".to_string()));
        assert_eq!(capsule.get_state().data.len(), 1);
    }

    #[test]
    fn test_state_mesh_with_many_connections() {
        let mut main_node = StateNode::new(
            "main".to_string(),
            TestState {
                value: 0,
                data: vec![],
            },
        );

        // Create many connected nodes
        for i in 0..100 {
            let node = StateNode::new(
                format!("node_{i}"),
                TestState {
                    value: i,
                    data: vec![format!("data_{}", i)],
                },
            );
            main_node.connect(node);
        }

        // Update main node state
        main_node.state.value = 999;
        main_node.propagate_update();

        // All connected nodes should have been updated
        for (id, node) in &main_node.connections {
            assert_eq!(node.state.value, 999, "Node {id} was not updated");
        }
    }

    #[test]
    fn test_timeline_with_many_states() {
        let mut timeline = StateManager::new(
            TestState {
                value: 0,
                data: vec![],
            },
            |state: &TestState, action: &dyn std::any::Any| {
                if let Some(test_action) = action.downcast_ref::<TestAction>() {
                    match test_action {
                        TestAction::Increment => TestState {
                            value: state.value + 1,
                            data: state.data.clone(),
                        },
                        TestAction::AddData(s) => {
                            let mut new_data = state.data.clone();
                            new_data.push(s.clone());
                            TestState {
                                value: state.value,
                                data: new_data,
                            }
                        }
                        _ => state.clone(),
                    }
                } else {
                    state.clone()
                }
            },
        );

        // Create a long history
        for i in 0..1000 {
            timeline.dispatch(TestAction::Increment);
            if i % 10 == 0 {
                timeline.dispatch(TestAction::AddData(format!("checkpoint_{i}")));
            }
        }

        assert_eq!(timeline.current_state().value, 1000);
        assert_eq!(timeline.current_state().data.len(), 100);
        assert_eq!(timeline.history_len(), 1101); // 1000 increments + 100 data additions + 1 initial

        // Test rewinding through large history
        timeline.rewind(500);
        assert_eq!(timeline.current_position(), 600);

        timeline.rewind(1000); // Should clamp to 0
        assert_eq!(timeline.current_position(), 0);
        assert_eq!(timeline.current_state().value, 0);
    }

    #[test]
    fn test_state_node_circular_references() {
        let mut node1 = StateNode::new(
            "node1".to_string(),
            TestState {
                value: 1,
                data: vec![],
            },
        );

        let mut node2 = StateNode::new(
            "node2".to_string(),
            TestState {
                value: 2,
                data: vec![],
            },
        );

        let node3 = StateNode::new(
            "node3".to_string(),
            TestState {
                value: 3,
                data: vec![],
            },
        );

        // Create circular-like connections
        node1.connect(node2.clone());
        node2.connect(node3.clone());
        node1.connect(node3);

        // Update node1 and propagate
        node1.state.value = 999;
        node1.propagate_update();

        // Check that updates propagated correctly
        assert_eq!(node1.connections.get("node2").unwrap().state.value, 999);
        assert_eq!(node1.connections.get("node3").unwrap().state.value, 999);
    }

    #[test]
    fn test_empty_state_operations() {
        // Test with empty/minimal state
        let store = configure_store(
            TestState {
                value: 0,
                data: vec![],
            },
            create_reducer(|state: &TestState, _action: &TestAction| {
                state.clone() // No-op reducer
            }),
        );

        // Should work with no-op reducer
        store.dispatch(TestAction::Increment);
        assert_eq!(store.get_state().value, 0);

        let mut reactive = ReactiveSystem::new(TestState {
            value: 0,
            data: vec![],
        });

        // Should work with no reactions
        reactive.trigger("nonexistent".to_string());
        assert_eq!(reactive.current_state().value, 0);
    }
}