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
use std::{fmt, mem, ops};

use imbl::Vector;

use crate::vector::OneOrManyDiffs;

use super::{entry::EntryIndex, BroadcastMessage, ObservableVector, VectorDiff};

/// A transaction that allows making multiple updates to an `ObservableVector`
/// as an atomic unit.
///
/// For updates from the transaction to have affect, it has to be finalized with
/// [`.commit()`](Self::commit). If the transaction is dropped without that
/// method being called, the updates will be discarded.
pub struct ObservableVectorTransaction<'o, T: Clone> {
    // The observable vector being modified, only modified on commit.
    inner: &'o mut ObservableVector<T>,
    // A clone of the observable's values, what the methods operate on until commit.
    values: Vector<T>,
    // The batched updates, to be sent to subscribers on commit.
    batch: Vec<VectorDiff<T>>,
}

impl<'o, T: Clone + Send + Sync + 'static> ObservableVectorTransaction<'o, T> {
    pub(super) fn new(inner: &'o mut ObservableVector<T>) -> Self {
        let values = inner.values.clone();
        Self { inner, values, batch: Vec::new() }
    }

    /// Commit this transaction, persisting the changes and notifying
    /// subscribers.
    pub fn commit(mut self) {
        #[cfg(feature = "tracing")]
        tracing::debug!("commit");

        self.inner.values = mem::take(&mut self.values);

        if self.batch.is_empty() {
            #[cfg(feature = "tracing")]
            tracing::trace!(
                target: "eyeball_im::vector::broadcast",
                "Skipping broadcast of empty list of diffs"
            );
        } else {
            let diffs = OneOrManyDiffs::Many(mem::take(&mut self.batch));
            let msg = BroadcastMessage { diffs, state: self.inner.values.clone() };
            let _num_receivers = self.inner.sender.send(msg).unwrap_or(0);
            #[cfg(feature = "tracing")]
            tracing::debug!(
                target: "eyeball_im::vector::broadcast",
                "New observable value broadcast to {_num_receivers} receivers"
            );
        }
    }

    /// Roll back all changes made using this transaction so far.
    ///
    /// Same as dropping the transaction and starting a new one, semantically.
    pub fn rollback(&mut self) {
        #[cfg(feature = "tracing")]
        tracing::debug!("rollback (explicit)");

        self.values = self.inner.values.clone();
        self.batch.clear();
    }

    /// Append the given elements at the end of the `Vector` and notify
    /// subscribers.
    pub fn append(&mut self, values: Vector<T>) {
        #[cfg(feature = "tracing")]
        tracing::debug!(
            target: "eyeball_im::vector::transaction::update",
            "append(len = {})", values.len()
        );

        self.values.append(values.clone());
        self.add_to_batch(VectorDiff::Append { values });
    }

    /// Clear out all of the elements in this `Vector` and notify subscribers.
    pub fn clear(&mut self) {
        #[cfg(feature = "tracing")]
        tracing::debug!(target: "eyeball_im::vector::transaction::update", "clear");

        self.values.clear();
        self.batch.clear(); // All previous batched updates are irrelevant now
        self.add_to_batch(VectorDiff::Clear);
    }

    /// Add an element at the front of the list and notify subscribers.
    pub fn push_front(&mut self, value: T) {
        #[cfg(feature = "tracing")]
        tracing::debug!(target: "eyeball_im::vector::transaction::update", "push_front");

        self.values.push_front(value.clone());
        self.add_to_batch(VectorDiff::PushFront { value });
    }

    /// Add an element at the back of the list and notify subscribers.
    pub fn push_back(&mut self, value: T) {
        #[cfg(feature = "tracing")]
        tracing::debug!(target: "eyeball_im::vector::transaction::update", "push_back");

        self.values.push_back(value.clone());
        self.add_to_batch(VectorDiff::PushBack { value });
    }

    /// Remove the first element, notify subscribers and return the element.
    ///
    /// If there are no elements, subscribers will not be notified and this
    /// method will return `None`.
    pub fn pop_front(&mut self) -> Option<T> {
        let value = self.values.pop_front();
        if value.is_some() {
            #[cfg(feature = "tracing")]
            tracing::debug!(target: "eyeball_im::vector::transaction::update", "pop_front");

            self.add_to_batch(VectorDiff::PopFront);
        }
        value
    }

    /// Remove the last element, notify subscribers and return the element.
    ///
    /// If there are no elements, subscribers will not be notified and this
    /// method will return `None`.
    pub fn pop_back(&mut self) -> Option<T> {
        let value = self.values.pop_back();
        if value.is_some() {
            #[cfg(feature = "tracing")]
            tracing::debug!(target: "eyeball_im::vector::transaction::update", "pop_back");

            self.add_to_batch(VectorDiff::PopBack);
        }
        value
    }

    /// Insert an element at the given position and notify subscribers.
    ///
    /// # Panics
    ///
    /// Panics if `index > len`.
    #[track_caller]
    pub fn insert(&mut self, index: usize, value: T) {
        let len = self.values.len();
        if index <= len {
            #[cfg(feature = "tracing")]
            tracing::debug!(
                target: "eyeball_im::vector::transaction::update",
                "insert(index = {index})"
            );

            self.values.insert(index, value.clone());
            self.add_to_batch(VectorDiff::Insert { index, value });
        } else {
            panic!("index out of bounds: the length is {len} but the index is {index}");
        }
    }

    /// Replace the element at the given position, notify subscribers and return
    /// the previous element at that position.
    ///
    /// # Panics
    ///
    /// Panics if `index > len`.
    #[track_caller]
    pub fn set(&mut self, index: usize, value: T) -> T {
        let len = self.values.len();
        if index < len {
            #[cfg(feature = "tracing")]
            tracing::debug!(
                target: "eyeball_im::vector::transaction::update",
                "set(index = {index})"
            );

            let old_value = self.values.set(index, value.clone());
            self.add_to_batch(VectorDiff::Set { index, value });
            old_value
        } else {
            panic!("index out of bounds: the length is {len} but the index is {index}");
        }
    }

    /// Remove the element at the given position, notify subscribers and return
    /// the element.
    ///
    /// # Panics
    ///
    /// Panics if `index >= len`.
    #[track_caller]
    pub fn remove(&mut self, index: usize) -> T {
        let len = self.values.len();
        if index < len {
            #[cfg(feature = "tracing")]
            tracing::debug!(
                target: "eyeball_im::vector::transaction::update",
                "remove(index = {index})"
            );

            let value = self.values.remove(index);
            self.add_to_batch(VectorDiff::Remove { index });
            value
        } else {
            panic!("index out of bounds: the length is {len} but the index is {index}");
        }
    }

    /// Truncate the vector to `len` elements and notify subscribers.
    ///
    /// Does nothing if `len` is greater or equal to the vector's current
    /// length.
    pub fn truncate(&mut self, len: usize) {
        if len < self.len() {
            #[cfg(feature = "tracing")]
            tracing::debug!(target: "eyeball_im::vector::update", "truncate(len = {len})");

            self.values.truncate(len);
            self.add_to_batch(VectorDiff::Truncate { length: len });
        }
    }

    /// Gets an entry for the given index through which only the element at that
    /// index alone can be updated or removed.
    ///
    /// # Panics
    ///
    /// Panics if `index >= len`.
    #[track_caller]
    pub fn entry(&mut self, index: usize) -> ObservableVectorTransactionEntry<'_, 'o, T> {
        let len = self.values.len();
        if index < len {
            ObservableVectorTransactionEntry::new(self, index)
        } else {
            panic!("index out of bounds: the length is {len} but the index is {index}");
        }
    }

    /// Call the given closure for every element in this `ObservableVector`,
    /// with an entry struct that allows updating or removing that element.
    ///
    /// Iteration happens in order, i.e. starting at index `0`.
    pub fn for_each(&mut self, mut f: impl FnMut(ObservableVectorTransactionEntry<'_, 'o, T>)) {
        let mut entries = self.entries();
        while let Some(entry) = entries.next() {
            f(entry);
        }
    }

    /// Get an iterator over all the entries in this `ObservableVector`.
    ///
    /// This is a more flexible, but less convenient alternative to
    /// [`for_each`][Self::for_each]. If you don't need to use special control
    /// flow like `.await` or `break` when iterating, it's recommended to use
    /// that method instead.
    ///
    /// Because `std`'s `Iterator` trait does not allow iterator items to borrow
    /// from the iterator itself, the returned typed does not implement the
    /// `Iterator` trait and can thus not be used with a `for` loop. Instead,
    /// you have to call its `.next()` method directly, as in:
    ///
    /// ```rust
    /// # use eyeball_im::ObservableVector;
    /// # let mut ob = ObservableVector::<u8>::new();
    /// let mut entries = ob.entries();
    /// while let Some(entry) = entries.next() {
    ///     // use entry
    /// }
    /// ```
    pub fn entries(&mut self) -> ObservableVectorTransactionEntries<'_, 'o, T> {
        ObservableVectorTransactionEntries::new(self)
    }

    fn add_to_batch(&mut self, diff: VectorDiff<T>) {
        if self.inner.sender.receiver_count() != 0 {
            self.batch.push(diff);
        }
    }
}

impl<T> fmt::Debug for ObservableVectorTransaction<'_, T>
where
    T: Clone + fmt::Debug,
{
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("ObservableVectorWriteGuard")
            .field("values", &self.values)
            .finish_non_exhaustive()
    }
}

// Note: No DerefMut because all mutating must go through inherent methods that
// notify subscribers
impl<T: Clone> ops::Deref for ObservableVectorTransaction<'_, T> {
    type Target = Vector<T>;

    fn deref(&self) -> &Self::Target {
        &self.values
    }
}

impl<T: Clone> Drop for ObservableVectorTransaction<'_, T> {
    fn drop(&mut self) {
        #[cfg(feature = "tracing")]
        if !self.batch.is_empty() {
            tracing::debug!("rollback (drop)");
        }
    }
}

/// A handle to a single value in an [`ObservableVector`], obtained from a
/// transaction.
pub struct ObservableVectorTransactionEntry<'a, 'o, T: Clone> {
    inner: &'a mut ObservableVectorTransaction<'o, T>,
    index: EntryIndex<'a>,
}

impl<'a, 'o, T> ObservableVectorTransactionEntry<'a, 'o, T>
where
    T: Clone + Send + Sync + 'static,
{
    pub(super) fn new(inner: &'a mut ObservableVectorTransaction<'o, T>, index: usize) -> Self {
        Self { inner, index: EntryIndex::Owned(index) }
    }

    fn new_borrowed(
        inner: &'a mut ObservableVectorTransaction<'o, T>,
        index: &'a mut usize,
    ) -> Self {
        Self { inner, index: EntryIndex::Borrowed(index) }
    }

    /// Get the index of the element this `ObservableVectorEntry` refers to.
    pub fn index(this: &Self) -> usize {
        this.index.value()
    }

    /// Replace the given element, notify subscribers and return the previous
    /// element.
    pub fn set(this: &mut Self, value: T) -> T {
        this.inner.set(this.index.value(), value)
    }

    /// Remove the given element, notify subscribers and return the element.
    pub fn remove(mut this: Self) -> T {
        this.inner.remove(this.index.make_owned())
    }
}

impl<T> fmt::Debug for ObservableVectorTransactionEntry<'_, '_, T>
where
    T: Clone + fmt::Debug,
{
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let index = self.index.value();
        f.debug_struct("ObservableVectorEntry")
            .field("item", &self.inner[index])
            .field("index", &index)
            .finish()
    }
}

impl<T: Clone> ops::Deref for ObservableVectorTransactionEntry<'_, '_, T> {
    type Target = T;

    fn deref(&self) -> &Self::Target {
        &self.inner[self.index.value()]
    }
}

impl<T: Clone> Drop for ObservableVectorTransactionEntry<'_, '_, T> {
    fn drop(&mut self) {
        // If there is an association with an externally-stored index, that
        // index must be incremented on drop. This allows an external iterator
        // that produces ObservableVectorEntry items to advance conditionally.
        //
        // There are two cases this branch is not hit:
        //
        // - make_owned was previously called (used for removing the item and resuming
        //   iteration with the same index)
        // - the ObservableVectorEntry was created with ObservableVector::entry, i.e.
        //   it's not used for iteration at all
        if let EntryIndex::Borrowed(idx) = &mut self.index {
            **idx += 1;
        }
    }
}

/// An "iterator"¹ that yields entries into an [`ObservableVector`], obtained
/// from a transaction.
///
/// ¹ conceptually, though it does not implement `std::iterator::Iterator`
#[derive(Debug)]
pub struct ObservableVectorTransactionEntries<'a, 'o, T: Clone> {
    inner: &'a mut ObservableVectorTransaction<'o, T>,
    index: usize,
}

impl<'a, 'o, T> ObservableVectorTransactionEntries<'a, 'o, T>
where
    T: Clone + Send + Sync + 'static,
{
    pub(super) fn new(inner: &'a mut ObservableVectorTransaction<'o, T>) -> Self {
        Self { inner, index: 0 }
    }

    /// Advance this iterator, yielding an `ObservableVectorEntry` for the next
    /// item in the vector, or `None` if all items have been visited.
    #[allow(clippy::should_implement_trait)]
    pub fn next(&mut self) -> Option<ObservableVectorTransactionEntry<'_, 'o, T>> {
        if self.index < self.inner.len() {
            Some(ObservableVectorTransactionEntry::new_borrowed(self.inner, &mut self.index))
        } else {
            None
        }
    }
}