lagbuffer/
lib.rs

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
/// A trait representing an event that has an associated order key of type `OrderKey`.
///
/// Events modify the state, and the order in which they are applied is determined by the `OrderKey`.
///
/// # Type Parameters
/// - `OrderKey`: The type that determines the order of events, which must implement `Ord`.
pub trait Event<OrderKey: Ord> {
    /// Returns the order key of the event.
    fn get_order_key(&self) -> OrderKey;
}

/// A trait representing a state that can be modified by events.
///
/// The state must be clonable and can be updated based on the events it receives. Events
/// must have an associated order key of type `OrderKey` to determine their sequence.
///
/// # Type Parameters
/// - `OrderKey`: The type that determines the order of events, which must implement `Ord`.
pub trait State<OrderKey: Ord>: Clone {
    /// The type of event that modifies the state.
    type Event: Clone + Event<OrderKey>;

    /// Applies an event to the current state, modifying it accordingly.
    ///
    /// # Arguments
    /// - `event`: The event that will be applied to the state.
    fn apply(&mut self, event: &Self::Event);
}

/// A buffer system designed to handle out-of-order events and reconcile the state.
///
/// The `LagBuffer` is a generic structure that manages the application of events to a state,
/// ensuring that events are applied in the correct order even if they arrive out of sequence.
/// This is particularly useful in scenarios like networked applications or games, where events
/// may not arrive in the order they were generated due to latency or other network issues.
///
/// The buffer maintains two event buffers and their corresponding base states:
///
/// - **Active Buffer**: The primary buffer where events are stored and applied to the current state.
/// - **Secondary Buffer**: Used to assist in state reconstruction and prepare for buffer swaps.
///
/// The key features of `LagBuffer` include:
///
/// - **Event Ordering**: Ensures that events are applied in the correct order based on their `OrderKey`.
/// - **State Reconstruction**: Reconstructs the state efficiently when out-of-order events are received.
/// - **Buffer Swapping**: Manages memory usage by swapping buffers when they reach a certain capacity.
///
/// # Type Parameters
///
/// - `S`: The type of the state, which must implement the [`State`](trait.State.html) trait.
/// - `SIZE`: The maximum number of events each buffer can hold before triggering a swap.
/// - `OrderKey`: The type of the event's order key, which must implement [`Ord`](https://doc.rust-lang.org/std/cmp/trait.Ord.html). Defaults to `usize`.
///
/// # Fields
///
/// - `current_state`: The current state after applying all events from the active buffer.
/// - `active_buffer`: Index indicating which buffer is currently active (0 or 1).
/// - `buffer_bases`: An array holding the base states corresponding to each buffer.
/// - `buffers`: An array of two event buffers (`Vec<S::Event>`) used to store events.
///
/// # Examples
///
/// ```rust
/// use lagbuffer::{LagBuffer, State, Event}; // Replace `your_crate` with the actual crate name.
///
/// #[derive(Clone, Debug)]
/// struct MyState {
///     data: Vec<i32>,
/// }
///
/// impl MyState {
///     fn new() -> Self {
///         Self { data: Vec::new() }
///     }
/// }
///
/// impl State<usize> for MyState {
///     type Event = MyEvent;
///
///     fn apply(&mut self, event: &Self::Event) {
///         match event.action {
///             Action::Insert => self.data.push(event.value),
///             Action::Replace => {
///                 if let Some(pos) = self.data.iter().position(|&x| x == event.target) {
///                     self.data[pos] = event.value;
///                 }
///             }
///         }
///     }
/// }
///
/// #[derive(Clone)]
/// enum Action {
///     Insert,
///     Replace,
/// }
///
/// #[derive(Clone)]
/// struct MyEvent {
///     id: usize,
///     value: i32,
///     target: i32, // Used for replacing a specific element
///     action: Action,
/// }
///
/// impl Event<usize> for MyEvent {
///     fn get_order_key(&self) -> usize {
///         self.id
///     }
/// }
///
/// let initial_state = MyState::new();
/// let mut lag_buffer = LagBuffer::<MyState, 4>::new(initial_state);
///
/// // Create some events
/// let event1 = MyEvent {
///     id: 1,
///     value: 10,
///     target: 0,
///     action: Action::Insert,
/// };
/// let event3 = MyEvent {
///     id: 3,
///     value: 30,
///     target: 0,
///     action: Action::Insert,
/// };
/// let event2 = MyEvent {
///     id: 2,
///     value: 20,
///     target: 0,
///     action: Action::Insert,
/// }; // Out-of-order event
///
/// // Update the buffer with events, possibly out of order.
/// lag_buffer.update(event1);
/// lag_buffer.update(event3);
/// lag_buffer.update(event2);
///
/// // Access the current state.
/// let state = lag_buffer.state();
/// assert_eq!(state.data, vec![10, 20, 30]); // Should print [10, 20, 30]
/// ```
pub struct LagBuffer<S: State<OrderKey>, const SIZE: usize, OrderKey: Ord = usize> {
    current_state: S,
    active_buffer: usize,
    buffer_bases: [S; 2],
    buffers: [Vec<S::Event>; 2],
}

impl<S: State<OrderKey>, const SIZE: usize, OrderKey: Ord> LagBuffer<S, SIZE, OrderKey> {
    /// Creates a new `LagBuffer` with the given initial state.
    ///
    /// # Arguments
    ///
    /// - `initial_state`: The initial state from which the buffer will start.
    ///
    /// # Returns
    ///
    /// A new `LagBuffer` instance initialized with the provided state.
    pub fn new(initial_state: S) -> Self {
        Self {
            buffers: [Vec::with_capacity(SIZE), Vec::with_capacity(SIZE)],
            active_buffer: 0,
            buffer_bases: [initial_state.clone(), initial_state.clone()],
            current_state: initial_state,
        }
    }

    /// Updates the buffer with a new event.
    ///
    /// This method handles the incoming event by determining whether it is in order or out of order
    /// based on its `OrderKey`. It ensures that the events are applied to the state in the correct
    /// order, reconstructing the state if necessary.
    ///
    /// # Behavior
    ///
    /// - **In-Order Event**:
    ///   - The event's `OrderKey` is greater than or equal to the last event's key in the active buffer.
    ///   - The event is applied directly to the `current_state`.
    ///   - The event is added to the active buffer.
    ///   - If the active buffer's length exceeds half of `SIZE`, the event is also added to the secondary buffer.
    ///
    /// - **Out-of-Order Event**:
    ///   - The event's `OrderKey` is less than the last event's key in the active buffer.
    ///   - The event is inserted into the active buffer at the correct position to maintain order.
    ///   - The `current_state` is reconstructed by cloning the base state of the active buffer and
    ///     reapplying all events from the active buffer.
    ///   - If the active buffer's length exceeds half of `SIZE` and the secondary buffer is not empty,
    ///     the event is also inserted into the secondary buffer at the correct position.
    ///
    /// - **Buffer Swap**:
    ///   - Occurs after the event is processed.
    ///   - If the active buffer's length exceeds `SIZE`, a buffer swap is triggered:
    ///     - The `current_state` is saved as the new base state for the active buffer.
    ///     - The active buffer is cleared.
    ///     - The active and secondary buffers swap roles.
    ///
    /// # Arguments
    ///
    /// - `event`: The event to be applied or buffered.
    pub fn update(&mut self, event: S::Event) {
        let active_buffer = self.active_buffer;
        let secondary_buffer = 1 - active_buffer;

        // Determine if the event is in order
        let in_order = match self.buffers[active_buffer].last() {
            Some(last_event) => last_event.get_order_key() <= event.get_order_key(),
            None => true,
        };

        if in_order {
            // In-order event: apply directly and add to active buffer
            self.current_state.apply(&event);
            self.buffers[active_buffer].push(event.clone());

            // If buffer is more than half full, start populating the secondary buffer
            if self.buffers[active_buffer].len() > (SIZE / 2) {
                self.buffers[secondary_buffer].push(event);
            }
        } else {
            // Out-of-order event: insert into active buffer and reconstruct state
            let insert_position = self.buffers[active_buffer]
                .binary_search_by_key(&event.get_order_key(), S::Event::get_order_key)
                .unwrap_or_else(|e| e);

            self.buffers[active_buffer].insert(insert_position, event.clone());

            // Reconstruct current state from buffer base and events
            self.current_state = self.buffer_bases[active_buffer].clone();
            for buffered_event in &self.buffers[active_buffer] {
                self.current_state.apply(buffered_event);
            }

            // Update secondary buffer if necessary
            if self.buffers[active_buffer].len() > (SIZE / 2)
                && !self.buffers[secondary_buffer].is_empty()
            {
                let insert_position = self.buffers[secondary_buffer]
                    .binary_search_by_key(&event.get_order_key(), S::Event::get_order_key)
                    .unwrap_or_else(|e| e);

                self.buffers[secondary_buffer].insert(insert_position, event);
            }
        }

        // Check if buffer swap is needed
        if self.buffers[active_buffer].len() > SIZE {
            // Save current state as new buffer base
            self.buffer_bases[active_buffer] = self.current_state.clone();
            // Clear the active buffer
            self.buffers[active_buffer].clear();
            // Swap active and secondary buffers
            self.active_buffer = secondary_buffer;
        }
    }

    /// Returns a reference to the current state.
    ///
    /// # Returns
    ///
    /// A reference to the current state after applying all events.
    pub fn state(&self) -> &S {
        &self.current_state
    }

    #[cfg(test)]
    pub fn get_active_buffer_len(&self) -> usize {
        self.buffers[self.active_buffer].len()
    }

    #[cfg(test)]
    pub fn get_secondary_buffer_len(&self) -> usize {
        let secondary_buffer = if self.active_buffer == 1 { 0 } else { 1 };
        self.buffers[secondary_buffer].len()
    }
}

// Testing section.

#[cfg(test)]
mod tests {
    use super::*;
    // Example State and Event implementation for testing.

    #[derive(Clone, Debug, PartialEq)]
    struct MyState {
        pub data: Vec<i32>,
    }

    impl MyState {
        pub fn new() -> Self {
            Self { data: Vec::new() }
        }
    }

    impl State<usize> for MyState {
        type Event = MyEvent;

        fn apply(&mut self, event: &Self::Event) {
            match event.action {
                Action::Insert => self.data.push(event.value),
                Action::Replace => {
                    if let Some(pos) = self.data.iter().position(|&x| x == event.target) {
                        self.data[pos] = event.value;
                    }
                }
            }
        }
    }

    #[derive(Clone)]
    enum Action {
        Insert,
        Replace,
    }

    #[derive(Clone)]
    struct MyEvent {
        id: usize,
        value: i32,
        target: i32, // Used for replacing a specific element
        action: Action,
    }

    impl Event<usize> for MyEvent {
        fn get_order_key(&self) -> usize {
            self.id
        }
    }

    #[test]
    fn test_event_application_in_order() {
        let mut buffer = LagBuffer::<MyState, 4>::new(MyState::new());

        // Apply 4 insert events in order.
        buffer.update(MyEvent {
            id: 1,
            value: 10,
            target: 0,
            action: Action::Insert,
        });
        buffer.update(MyEvent {
            id: 2,
            value: 20,
            target: 0,
            action: Action::Insert,
        });
        buffer.update(MyEvent {
            id: 3,
            value: 30,
            target: 0,
            action: Action::Insert,
        });
        buffer.update(MyEvent {
            id: 4,
            value: 40,
            target: 0,
            action: Action::Insert,
        });
        buffer.update(MyEvent {
            id: 5,
            value: 50,
            target: 0,
            action: Action::Insert,
        });

        // Verify that the current state is as expected (order matters here).
        assert_eq!(buffer.state().data, vec![10, 20, 30, 40, 50]);

        // Verify that a buffer swap happened and secondary buffer is cleared.
        assert_eq!(buffer.get_secondary_buffer_len(), 0);
    }

    #[test]
    fn test_event_application_out_of_order() {
        let mut buffer = LagBuffer::<MyState, 4>::new(MyState::new());

        // Apply some insert events.
        buffer.update(MyEvent {
            id: 1,
            value: 10,
            target: 0,
            action: Action::Insert,
        });
        buffer.update(MyEvent {
            id: 3,
            value: 30,
            target: 0,
            action: Action::Insert,
        });
        buffer.update(MyEvent {
            id: 2,
            value: 20,
            target: 0,
            action: Action::Insert,
        }); // Out-of-order event.

        // The state should reflect that the event with id=2 was applied in the correct order.
        assert_eq!(buffer.state().data, vec![10, 20, 30]);
    }

    #[test]
    fn test_buffer_has_half_after_swap() {
        let mut buffer = LagBuffer::<MyState, 4>::new(MyState::new());

        // Apply 5 events to trigger buffer swap.
        buffer.update(MyEvent {
            id: 1,
            value: 10,
            target: 0,
            action: Action::Insert,
        });
        buffer.update(MyEvent {
            id: 2,
            value: 20,
            target: 0,
            action: Action::Insert,
        });
        buffer.update(MyEvent {
            id: 3,
            value: 30,
            target: 0,
            action: Action::Insert,
        });
        buffer.update(MyEvent {
            id: 4,
            value: 40,
            target: 0,
            action: Action::Insert,
        });
        buffer.update(MyEvent {
            id: 5,
            value: 50,
            target: 0,
            action: Action::Insert,
        });

        // After buffer swap, one more than half of the events should be in the active buffer.
        assert_eq!(buffer.get_active_buffer_len(), 3);
    }

    #[test]
    fn test_replace_action() {
        let mut buffer = LagBuffer::<MyState, 4>::new(MyState::new());

        // Apply insert events.
        buffer.update(MyEvent {
            id: 1,
            value: 10,
            target: 0,
            action: Action::Insert,
        });
        buffer.update(MyEvent {
            id: 2,
            value: 20,
            target: 0,
            action: Action::Insert,
        });
        buffer.update(MyEvent {
            id: 3,
            value: 30,
            target: 0,
            action: Action::Insert,
        });

        // Apply a replace event.
        buffer.update(MyEvent {
            id: 4,
            value: 99,
            target: 20,
            action: Action::Replace,
        });

        // Verify that the replace action was correctly applied.
        assert_eq!(buffer.state().data, vec![10, 99, 30]);
    }
}