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
#![doc = include_str!("../README.md")]
#![no_std]

use core::ops::{Deref, DerefMut};
use core::borrow::{Borrow, BorrowMut};
use core::fmt::{Debug, Formatter};

/// Encapsulates a piece of state that can be modified and
/// we want all outside code to see the edit as a single
/// atomic change.
///
/// # Trait implementations
///
/// If trait use an immutable reference ([`AsRef<T>`], [`Deref<T>`], [`Borrow<T>`]...) give access to the current value
/// and mutable references ([`AsMut<T>`], [`DerefMut<T>`], [`BorrowMut<T>`]...) give access to the next value.
///
/// # Swapping
///
/// There are three ways to swap:
///
/// 1. [`DoubleBuffer::swap()`] - when swapping, the next value will have the previous current value.
/// 2. [`DoubleBuffer::swap_with_clone()`] - when swapping, the next value will keep same and will be cloned to the current value.
/// 3. [`DoubleBuffer::swap_with_default()`] - like [`DoubleBuffer::swap()`] but the next value will be set to the default value of the type.
///
/// Note that for the third way, the type must implement [`Default`].
///
/// You can read about the two ways [how the buffers are swapped](https://gameprogrammingpatterns.com/double-buffer.html#how-are-the-buffers-swapped)
/// in "Game Programming Patterns" by Robert Nystrom.
///
/// # Examples
///
/// The following example shows how the buffer is swapped with the three ways:
///
/// ```
/// # use double_buffer::DoubleBuffer;
/// let mut buffer: DoubleBuffer<[u8; 32]> = DoubleBuffer::default();
/// print!("{:?}", buffer); // DoubleBuffer { current: [0, ...], next: [0, ...] }
///
/// buffer[0] = 1;
/// print!("{:?}", buffer); // DoubleBuffer { current: [0, ...], next: [1, ...] }
///
/// buffer.swap();
/// print!("{:?}", buffer); // DoubleBuffer { current: [1, ...], next: [0, ...] }
///
/// buffer[0] = 2;
/// print!("{:?}", buffer); // DoubleBuffer { current: [1, ...], next: [2, ...] }
///
/// buffer.swap_with_clone();
/// print!("{:?}", buffer); // DoubleBuffer { current: [2, ...], next: [2, ...] }
///
/// buffer[0] = 3;
/// print!("{:?}", buffer); // DoubleBuffer { current: [2, ...], next: [3, ...] }
///
/// buffer.swap_with_default();
/// print!("{:?}", buffer); // DoubleBuffer { current: [3, ...], next: [0, ...] }
/// ```
pub struct DoubleBuffer<T> {
    current: T,
    next: T,
}

impl<T> DoubleBuffer<T> {
    #[inline]
    pub const fn new(current: T, next: T) -> Self {
        Self { current, next }
    }

    /// Swaps the current and next values,
    /// then writes will be over the previous current value.
    #[inline]
    pub fn swap(&mut self) {
        core::mem::swap(&mut self.current, &mut self.next);
    }
}

impl<T: Clone> DoubleBuffer<T> {
    /// Swaps buffers cloning the next value to the current value,
    /// then writes will continue over the same next value.
    #[inline]
    pub fn swap_with_clone(&mut self) {
        self.current = self.next.clone();
    }
}

impl<T: Default> DoubleBuffer<T> {
    /// Swaps buffers and sets the next value to the default value of the type,
    /// then writes will be over the default value.
    #[inline]
    pub fn swap_with_default(&mut self) {
        self.swap();
        self.next = T::default();
    }
}

impl<T: Debug> Debug for DoubleBuffer<T> {
    #[inline]
    fn fmt(&self, f: &mut Formatter<'_>) -> core::fmt::Result {
        f.debug_struct("DoubleBuffer")
            .field("current", &self.current)
            .field("next", &self.next)
            .finish()
    }
}

impl<T: Default> Default for DoubleBuffer<T> {
    #[inline]
    fn default() -> Self {
        Self::new(T::default(), T::default())
    }
}

impl<T> Deref for DoubleBuffer<T> {
    type Target = T;

    #[inline]
    fn deref(&self) -> &Self::Target {
        &self.current
    }
}

impl<T> DerefMut for DoubleBuffer<T> {
    #[inline]
    fn deref_mut(&mut self) -> &mut Self::Target {
        &mut self.next
    }
}

impl<T> Borrow<T> for DoubleBuffer<T> {
    #[inline]
    fn borrow(&self) -> &T {
        &self.current
    }
}

impl<T> BorrowMut<T> for DoubleBuffer<T> {
    #[inline]
    fn borrow_mut(&mut self) -> &mut T {
        &mut self.next
    }
}

impl<T> AsRef<T> for DoubleBuffer<T> {
    #[inline]
    fn as_ref(&self) -> &T {
        &self.current
    }
}

impl<T> AsMut<T> for DoubleBuffer<T> {
    #[inline]
    fn as_mut(&mut self) -> &mut T {
        &mut self.next
    }
}

impl<T: PartialEq> PartialEq<T> for DoubleBuffer<T> {
    #[inline]
    fn eq(&self, other: &T) -> bool {
        self.current.eq(other)
    }
}

impl<T: PartialEq> PartialEq for DoubleBuffer<T> {
    #[inline]
    fn eq(&self, other: &Self) -> bool {
        self.current.eq(&other.current)
    }
}

impl<T: Eq> Eq for DoubleBuffer<T> {}

impl<T: PartialOrd> PartialOrd<T> for DoubleBuffer<T> {
    #[inline]
    fn partial_cmp(&self, other: &T) -> Option<core::cmp::Ordering> {
        self.current.partial_cmp(other)
    }
}

impl<T: PartialOrd> PartialOrd for DoubleBuffer<T> {
    #[inline]
    fn partial_cmp(&self, other: &Self) -> Option<core::cmp::Ordering> {
        self.current.partial_cmp(&other.current)
    }
}

impl<T: Ord> Ord for DoubleBuffer<T> {
    #[inline]
    fn cmp(&self, other: &Self) -> core::cmp::Ordering {
        self.current.cmp(&other.current)
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_access_and_modify() {
        let mut buffer: DoubleBuffer<u32> = DoubleBuffer::new(1, 2);
        assert_eq!(buffer, 1);

        *buffer = 3;
        assert_eq!(buffer, 1);

        buffer.swap();
        assert_eq!(buffer, 3);
    }

    #[test]
    fn test_swap() {
        let mut buffer: DoubleBuffer<u32> = DoubleBuffer::new(1, 2);
        assert_eq!(buffer.current, 1);
        assert_eq!(buffer.next, 2);

        buffer.swap();
        assert_eq!(buffer.current, 2);
        assert_eq!(buffer.next, 1);
    }

    #[test]
    fn test_swap_with_clone() {
        let mut buffer: DoubleBuffer<u32> = DoubleBuffer::new(1, 2);
        assert_eq!(buffer.current, 1);
        assert_eq!(buffer.next, 2);

        buffer.swap_with_clone();
        assert_eq!(buffer.current, 2);
        assert_eq!(buffer.next, 2);
    }

    #[test]
    fn test_swap_with_default() {
        let mut buffer: DoubleBuffer<u32> = DoubleBuffer::new(1, 2);
        assert_eq!(buffer.current, 1);
        assert_eq!(buffer.next, 2);

        buffer.swap_with_default();
        assert_eq!(buffer.current, 2);
        assert_eq!(buffer.next, 0);
    }

    #[test]
    fn test_greater_and_less_than() {
        let mut buffer: DoubleBuffer<i32> = DoubleBuffer::default();
        *buffer = 1;
        assert!(buffer > -1);
        assert!(buffer < 1);

        buffer.swap();
        assert!(buffer > 0);
        assert!(buffer < 2);
    }

    #[test]
    fn test_modify_bytes_array() {
        let mut buffer: DoubleBuffer<[u8; 3]> = DoubleBuffer::default();
        buffer[1] = 2;
        assert_eq!(buffer[1], 0);
        assert_eq!(buffer, [0, 0, 0]);

        assert_eq!(buffer.current, [0, 0, 0]);
        assert_eq!(buffer.next, [0, 2, 0]);

        buffer.swap();
        assert_eq!(buffer[1], 2);
        assert_eq!(buffer, [0, 2, 0]);

        assert_eq!(buffer.current, [0, 2, 0]);
        assert_eq!(buffer.next, [0, 0, 0]);
    }

    #[test]
    fn test_for_iter_mut_bytes_array() {
        let mut buffer: DoubleBuffer<[u8; 3]> = DoubleBuffer::default();
        buffer[1] = 2;

        assert_eq!(buffer.current, [0, 0, 0]);
        assert_eq!(buffer.next, [0, 2, 0]);

        for byte in buffer.iter_mut() {
            *byte += 1;
        }

        assert_eq!(buffer.current, [0, 0, 0]);
        assert_eq!(buffer.next, [1, 3, 1]);
    }
}