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

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 two ways to swap:
///
/// 1. [`DoubleBuffer::swap()`] - when swapping, the next value will have the previous current value.
/// 2. [`DoubleBuffer::swap_cloning()`] - when swapping, the next value will keep same and will be cloned to the current value.
///
/// 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
///
/// ```
/// use double_buffer::DoubleBuffer;
///
/// let mut buffer: DoubleBuffer<u32> = DoubleBuffer::default();
/// *buffer = 1;
///
/// assert_eq!(buffer, 0);
/// buffer.swap();
/// assert_eq!(buffer, 1);
/// ```
pub struct DoubleBuffer<T> {
    current: T,
    next: T,
}

impl<T> DoubleBuffer<T> {
    #[inline]
    pub 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) {
        std::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_cloning(&mut self) {
        self.current = self.next.clone();
    }
}

impl<T: Debug> Debug for DoubleBuffer<T> {
    #[inline]
    fn fmt(&self, f: &mut Formatter<'_>) -> std::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<std::cmp::Ordering> {
        self.current.partial_cmp(other)
    }
}

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

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

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

    #[test]
    fn test_debug_format() {
        let buffer: DoubleBuffer<u32> = DoubleBuffer::default();
        assert_eq!(format!("{:?}", buffer), "DoubleBuffer { current: 0, next: 0 }");
    }

    #[test]
    fn test_modify_and_swap() {
        let mut buffer: DoubleBuffer<u32> = DoubleBuffer::default();
        *buffer = 1;

        assert_eq!(buffer, 0);

        buffer.swap();

        assert_eq!(buffer, 1);

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

    #[test]
    fn test_modify_and_swap_cloning() {
        let mut buffer: DoubleBuffer<u32> = DoubleBuffer::default();
        *buffer = 1;

        assert_eq!(buffer, 0);
        assert_ne!(buffer, 1);

        buffer.swap_cloning();

        assert_eq!(buffer, 1);
        assert_ne!(buffer, 0);

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

    #[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]);

        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;

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

        assert_eq!(buffer, [0, 0, 0]);

        buffer.swap();

        assert_eq!(buffer, [1, 3, 1]);
    }
}