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
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
//! Events are a type of message which manipulate a resource.

use std::borrow::Cow;
use std::fmt::{self, Debug};

use den::{Difference, ExtendVec, Signature};

use crate::{log, utils, Deserialize, Duration, EventKind, Manager, Serialize, SystemTime, Uuid};

/// Creates a granular [`Difference`] between `base` and `target`.
///
/// If you [`Difference::apply`] this on `base`, you **should** get `target`.
#[allow(clippy::missing_panics_doc)]
pub fn diff(base: &[u8], target: &[u8]) -> Difference {
    let mut sig = Signature::new(256);
    sig.write(base);
    let sig = sig.finish();
    let rough_diff = sig.diff(target);
    #[allow(clippy::let_and_return)]
    let granular_diff = rough_diff
        .minify(8, base)
        .expect("The way we are using the function, this should never err.");
    granular_diff
}

/// A modification to a resource.
///
/// The resource must be initialised using [`Create`].
#[derive(PartialEq, Eq, Clone, Serialize, Deserialize)]
#[must_use]
pub struct Modify<S: ExtendVec + 'static = Vec<u8>> {
    pub(crate) resource: String,
    pub(crate) diff: Difference<S>,
}
impl Modify {
    /// Get the difference needed to get from `base` to `target`, as a modify event.
    pub fn new(resource: String, target: &[u8], base: &[u8]) -> Self {
        let diff = diff(base, target);

        Self { resource, diff }
    }
    /// Get the difference needed to get from `base` to `target`, as a modify event.
    ///
    /// This also verifies that the [`Modify::diff`] gives `target`.
    /// Using this over [`Self::new`] is only recommended when you have data that
    /// MUST be transmitted correctly.
    ///
    /// Most errors will however resolve once the client reconnects to the network or
    /// if a server, performs a hash check.
    ///
    /// This does not trigger an allocation.
    ///
    /// If the verification failed, we send the whole resource.
    pub fn new_with_verification(resource: String, target: &[u8], base: &[u8]) -> Self {
        let mut difference = diff(base, target);

        if !difference.verify(base, target) {
            difference = diff(b"", target);
            difference.set_original_data_len(base.len());
        }

        Self {
            resource,
            diff: difference,
        }
    }
}
impl<S: ExtendVec + 'static> Modify<S> {
    /// Get a reference to the sections of data this event modifies.
    pub fn diff(&self) -> &Difference<S> {
        &self.diff
    }
    /// Returns a reference to the target resource name.
    #[must_use]
    #[inline]
    pub fn resource(&self) -> &str {
        &self.resource
    }
    /// Set the inner `resource`.
    #[inline]
    pub(crate) fn set_resource(&mut self, resource: String) {
        self.resource = resource;
    }
}
impl<S: ExtendVec + AsRef<[u8]> + 'static> Debug for Modify<S> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "modify {:?} by ", self.resource())?;
        self.diff.fmt(f)?;
        Ok(())
    }
}
/// Deletion of a resource.
///
/// The resource must be initialised using [`Create`].
#[derive(PartialEq, Eq, Clone, Serialize, Deserialize)]
#[must_use]
pub struct Delete {
    resource: String,
    /// An optional successor to the [`Self::resource()`]
    successor: Option<String>,
}
impl Delete {
    /// Creates a new delete event.
    ///
    /// The successor, if present, directs all more recent modifications of the deleted resource
    /// ([`Self::resource`]) to another resource.
    /// This is useful for when a file is renamed.
    ///
    /// > Having a `MoveEvent` was experimented with, but ultimately failed.
    /// > Dig into the old git commits to see comments about it.
    pub fn new(resource: String, successor: Option<String>) -> Self {
        Self {
            resource,
            successor,
        }
    }

    /// Returns a reference to the target resource name.
    #[must_use]
    #[inline]
    pub fn resource(&self) -> &str {
        &self.resource
    }
    /// Returns a reference to the optional successor.
    #[must_use]
    #[inline]
    pub fn successor(&self) -> Option<&str> {
        self.successor.as_deref()
    }

    /// Sets the inner `resource`.
    #[inline]
    pub(crate) fn set_resource(&mut self, resource: String) {
        self.resource = resource;
    }
    /// Returns the successor, if any.
    #[inline]
    pub(crate) fn take_successor(&mut self) -> Option<String> {
        self.successor.take()
    }
}
impl Debug for Delete {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "delete {:?}", self.resource())?;
        Ok(())
    }
}
/// The creation of a resource.
///
/// Creates an empty file. Overrides the file if it already exists.
#[derive(PartialEq, Eq, Clone, Serialize, Deserialize)]
#[must_use]
pub struct Create {
    resource: String,
}
impl Create {
    /// Signals `resource` should be created, or overridden if present.
    pub fn new(resource: String) -> Self {
        Self { resource }
    }

    /// Returns a reference to the target resource name.
    #[must_use]
    pub fn resource(&self) -> &str {
        &self.resource
    }
}
impl Debug for Create {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "create {:?}", self.resource())?;
        Ok(())
    }
}

macro_rules! event_kind_impl {
    ($type:ty, $enum_name:ident) => {
        impl From<$type> for Kind {
            fn from(event: $type) -> Self {
                Self::$enum_name(event)
            }
        }
        impl IntoEvent for $type {
            fn into_ev(self, manager: &Manager) -> Event {
                Event::new(self.into(), manager)
            }
        }
    };
}

/// Helper trait to convert from `*Event` structs to [`Event`].
///
/// Should not be implemented but used with [`Manager::process_event`].
#[allow(clippy::module_name_repetitions)] // We can't call it `Into`!
pub trait IntoEvent<S: ExtendVec + 'static = Vec<u8>> {
    /// Converts `self` into an [`Event`].
    fn into_ev(self, manager: &Manager) -> Event<S>;
}
impl IntoEvent for Event {
    fn into_ev(self, _manager: &Manager) -> Event {
        self
    }
}

impl<S: ExtendVec + 'static> From<Modify<S>> for Kind<S> {
    fn from(event: Modify<S>) -> Self {
        Self::Modify(event)
    }
}
impl<S: ExtendVec + 'static> IntoEvent<S> for Modify<S> {
    fn into_ev(self, manager: &Manager) -> Event<S> {
        Event::new(self.into(), manager)
    }
}
event_kind_impl!(Create, Create);
event_kind_impl!(Delete, Delete);

/// The kind of change of data.
#[derive(PartialEq, Eq, Clone, Serialize, Deserialize)]
#[must_use]
pub enum Kind<S: ExtendVec + 'static = Vec<u8>> {
    /// Modification.
    ///
    /// You need to make a [`Self::Create`] event before modifying the resource.
    /// If you don't do this, the modification MUST NOT be applied.
    Modify(Modify<S>),
    /// Creation.
    ///
    /// A new resource has been created. Before any other event can affect this resource,
    /// you'll have to initialise it with this event.
    Create(Create),
    /// Deletion.
    ///
    /// Can contain a [`Delete::successor`] to hint on where the file has been moved to. This
    /// enables subsequent [`Event`]s to be redirected to the successor.
    /// The redirections will stop when a new [`Self::Create`] event is triggered.
    Delete(Delete),
}
impl<S: ExtendVec + 'static> Kind<S> {
    /// Returns a reference to the target resource name.
    #[allow(clippy::inline_always)]
    #[inline(always)]
    #[must_use]
    pub fn resource(&self) -> &str {
        match &self {
            Kind::Modify(ev) => ev.resource(),
            Kind::Create(ev) => ev.resource(),
            Kind::Delete(ev) => ev.resource(),
        }
    }
}
impl<S: ExtendVec + AsRef<[u8]>> Debug for Kind<S> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Kind::Modify(m) => m.fmt(f),
            Kind::Create(c) => c.fmt(f),
            Kind::Delete(d) => d.fmt(f),
        }
    }
}
/// A change of data.
#[derive(PartialEq, Eq, Clone, Serialize, Deserialize)]
#[must_use]
pub struct Event<S: ExtendVec + 'static = Vec<u8>> {
    kind: Kind<S>,
    /// A [`Duration`] of time after UNIX_EPOCH.
    timestamp: Duration,
    /// A [`Duration`] of time after UNIX_EPOCH.
    ///
    /// This gives the receiver information about when to modify later events when this event
    /// arrives. If event 2 (stored in the log) has this set to before event 1's `timestamp`, we
    /// use [`utils::Offsets`] to modify event 2. If this is set to after event 1's `timestamp`, we
    /// do nothing.
    ///
    /// This provides some resistance against simultaneous changes (where the issuer doesn't yet
    /// know about the pier's new diff).
    latest_event: Duration,
    sender: Uuid,
}
impl<S: ExtendVec + 'static> Event<S> {
    /// Creates a new event from `kind`.
    ///
    /// Create an `Event` with the [`Self::timestamp`] set to the current time.
    pub fn new(kind: Kind<S>, sender: &Manager) -> Self {
        let latest_event = sender.event_log.latest_event(kind.resource());
        let latest_event =
            latest_event.map_or_else(|| Duration::ZERO, |ev| ev.event.timestamp_dur());
        Self {
            kind,
            timestamp: utils::systime_to_dur(utils::now()),
            latest_event,
            sender: sender.uuid(),
        }
    }
    /// Override [`Self::timestamp`] with `timestamp`.
    ///
    /// **NOTE**: Be very careful with this. `timestamp` MUST be within a second of real time,
    /// else you risk wrong results from the sync mechanism, forcing [`crate::MessageKind::HashCheck`].
    pub fn with_timestamp(mut self, timestamp: SystemTime) -> Self {
        self.timestamp = utils::systime_to_dur(timestamp);
        self
    }
    /// Returns a reference to the target resource name.
    #[allow(clippy::inline_always)]
    #[inline(always)]
    #[must_use]
    pub fn resource(&self) -> &str {
        self.inner().resource()
    }
    /// Returns a reference to the inner [`Kind`] where all the event data is stored.
    #[allow(clippy::inline_always)]
    #[inline(always)]
    pub fn inner(&self) -> &Kind<S> {
        &self.kind
    }
    /// Returns a mutable reference to the inner [`Kind`].
    #[inline]
    pub(crate) fn inner_mut(&mut self) -> &mut Kind<S> {
        &mut self.kind
    }
    pub(crate) fn timestamp_dur(&self) -> Duration {
        self.timestamp
    }
    /// Get the timestamp of this event.
    #[inline]
    #[must_use]
    pub fn timestamp(&self) -> SystemTime {
        utils::dur_to_systime(self.timestamp)
    }
    /// Returns the UUID of the sender of this event.
    #[inline]
    pub fn sender(&self) -> Uuid {
        self.sender
    }
    /// Get the [`Difference`], if [`Self::inner`] is [`Kind::Modify`].
    #[must_use]
    #[inline]
    pub fn diff(&self) -> Option<&Difference<S>> {
        match self.inner() {
            Kind::Modify(ev) => Some(ev.diff()),
            _ => None,
        }
    }
    /// Get the timestamp of the last event observed by the issuer of this event.
    #[inline]
    #[must_use]
    pub fn latest_event_timestamp(&self) -> SystemTime {
        utils::dur_to_systime(self.latest_event)
    }
}
impl<S: ExtendVec + AsRef<[u8]>> Debug for Event<S> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        self.inner().fmt(f)?;
        if f.alternate() {
            f.write_str(",\n")?;
        } else {
            f.write_str(", ")?;
        }
        write!(f, "timestamp: ")?;
        utils::fmt_dur(f, self.timestamp)?;
        if f.alternate() {
            f.write_str(",\n")?;
        } else {
            f.write_str(", ")?;
        }
        write!(f, "latest_event: ")?;
        utils::fmt_dur(f, self.latest_event)?;
        if f.alternate() {
            f.write_str(",\n")?;
        } else {
            f.write_str(", ")?;
        }
        write!(f, "sender: {}", self.sender)?;
        Ok(())
    }
}

/// Error during [`Unwinder`] operations.
#[derive(Debug)]
pub enum UnwindError {
    /// The resource has previously been destroyed.
    ///
    /// The returned byte array contains the unchanged data passed to the function.
    ResourceDestroyed(Vec<u8>),
    /// An error during an application of a section.
    ///
    /// The rewound resource is also returned, if you want to use it.
    /// The diffs which erred aren't applied.
    Apply(den::ApplyError, Vec<u8>),
}
impl UnwindError {
    /// Get the data of this error.
    #[must_use]
    pub fn into_data(self) -> Vec<u8> {
        match self {
            UnwindError::Apply(_, vec) | UnwindError::ResourceDestroyed(vec) => vec,
        }
    }
    /// Get the data from [`Self::Apply`] or return `resource_destroyed_err`.
    #[allow(clippy::missing_errors_doc)]
    pub fn ignore_apply_err<E>(self, resource_destroyed_err: E) -> Result<Vec<u8>, E> {
        match self {
            UnwindError::ResourceDestroyed(_) => Err(resource_destroyed_err),
            UnwindError::Apply(_, vec) => Ok(vec),
        }
    }
}

/// Unwinds the stack of stored events to get the local data to a previous state.
///
/// Has nothing to do with unwinding of the program's stack in a [`panic!`].
#[derive(Debug, Clone)]
pub struct Unwinder<'a> {
    /// Ordered from last (temporally).
    events: &'a [log::ReceivedEvent],
    unwound_events: Vec<&'a Difference>,
    // these are allocated once to optimize allocations
    buffer: Vec<u8>,
    manager: Option<&'a Manager>,
}
impl<'a> Unwinder<'a> {
    /// If you supply [`None`] to `manager` and this leaks to the user, and they call
    /// [`Self::last_change_to_resource`]
    pub(crate) fn new(events: &'a [log::ReceivedEvent], manager: Option<&'a Manager>) -> Self {
        Self {
            events,
            unwound_events: vec![],
            buffer: vec![],
            manager,
        }
    }
    /// Returns `true` if `modern_resource_name` is valid and hasn't been recreated since the start
    /// of the event log we're tracking.
    pub(crate) fn check_name(&self, modern_resource_name: &str) -> bool {
        for log_event in self.events {
            if log_event.event.resource() == modern_resource_name {
                match &log_event.event.inner() {
                    EventKind::Delete(_) | EventKind::Create(_) => {
                        return false;
                    }
                    // Do nothing; the file is just modified.
                    EventKind::Modify(_) => {}
                }
            }
        }
        true
    }
    /// Get an iterator over the [`Difference`]s to `modern_resource_name`.
    ///
    /// Returns [`None`] if `modern_resource_name` was destroyed/created
    /// during the events we're tracking.
    #[must_use]
    pub fn sections<'b>(
        &'b self,
        modern_resource_name: &'b str,
    ) -> Option<impl Iterator<Item = &Difference> + 'b> {
        if !self.check_name(modern_resource_name) {
            return None;
        }

        let iter = self.events.iter().rev().filter_map(move |received_ev| {
            if received_ev.event.resource() != modern_resource_name {
                return None;
            }
            match received_ev.event.inner() {
                EventKind::Modify(ev) => Some(ev.diff()),
                EventKind::Delete(_) | EventKind::Create(_) => unreachable!(
                    "Unexpected delete or create event in unwinding of event log.\
                    Please report this bug."
                ),
            }
        });
        Some(iter)
    }
    /// Get an iterator over the events stored in this unwinder.
    /// The first item is the oldest one. The last is the most recent.
    ///
    /// Useful it you want to get resources affected since a timestamp:
    ///
    /// ```
    /// # use agde::*;
    /// use std::time::{Duration, SystemTime};
    /// let manager = Manager::new(false, 0, Duration::from_secs(60), 512);
    ///
    /// let unwinder = manager.unwinder_to(SystemTime::now() - Duration::from_secs(2));
    /// for event in unwinder.events() {
    ///     println!("Resource {} changed in some way.", event.resource());
    /// }
    /// ```
    pub fn events(&self) -> impl Iterator<Item = &Event> + DoubleEndedIterator + '_ {
        self.events.iter().map(|received_ev| &received_ev.event)
    }
    /// Reverts the `resource` with `modern_resource_name` to the bottom of the internal list.
    ///
    /// # Panics
    ///
    /// If you called this before and didn't call [`Self::unwind`], this panics.
    ///
    /// # Errors
    ///
    /// Returns [`UnwindError::ResourceDestroyed`] if `modern_resource_name` has been re-created or
    /// destroyed during the timeline of this unwinder.
    pub fn unwind(
        &mut self,
        resource: impl Into<Vec<u8>>,
        modern_resource_name: &str,
    ) -> Result<Vec<u8>, UnwindError> {
        assert_eq!(
            self.unwound_events.len(),
            0,
            "The rewinding stack must be empty!"
        );

        if !self.check_name(modern_resource_name) {
            return Err(UnwindError::ResourceDestroyed(resource.into()));
        }

        let mut error = None;

        let mut resource = resource.into();
        // these are allocated once to optimize allocations
        let mut other = std::mem::take(&mut self.buffer);

        // On move events, only change resource.
        // On delete messages, panic. A bug.
        // ↑ should be contracted by the creator.
        for received_ev in self.events.iter().rev() {
            if received_ev.event.resource() != modern_resource_name {
                continue;
            }
            match received_ev.event.inner() {
                EventKind::Modify(ev) => {
                    let diff = ev.diff();

                    // `TODO`: don't hardcode fill_byte.
                    let ok = ev.diff().in_bounds(&resource);

                    if ok {
                        ev.diff()
                            .revert(&resource, &mut other, b' ')
                            .expect("we made sure the references were in bounds");

                        std::mem::swap(&mut resource, &mut other);
                        other.clear();
                        self.unwound_events.push(diff);
                    } else {
                        error = Some(den::ApplyError::RefOutOfBounds);
                    }
                }
                EventKind::Delete(_) | EventKind::Create(_) => unreachable!(
                    "Unexpected delete or create event in unwinding of event log.\
                    Please report this bug."
                ),
            }
        }
        self.buffer = other;

        if let Some(err) = error {
            Err(UnwindError::Apply(err, resource))
        } else {
            Ok(resource)
        }
    }
    /// Rewinds the `resource` back up.
    ///
    /// # Errors
    ///
    /// Passes errors from [`Difference::apply`].
    #[allow(clippy::missing_panics_doc)]
    pub fn rewind(
        &mut self,
        resource: impl Into<Vec<u8>>,
    ) -> Result<Vec<u8>, (den::ApplyError, Vec<u8>)> {
        let mut vec = resource.into();
        let mut other = vec![];
        let mut error = None;
        // Unwind the stack, redoing all the events.
        while let Some(diff) = self.unwound_events.pop() {
            if diff.in_bounds(&vec) {
                if diff.apply_overlaps(vec.len()) {
                    diff.apply(&vec, &mut other)
                        .expect("we made sure the references were in bounds");
                    std::mem::swap(&mut vec, &mut other);
                    other.clear();
                } else {
                    diff.apply_in_place(&mut vec)
                        .expect("we made sure the references were in bounds");
                }
            } else {
                error = Some(den::ApplyError::RefOutOfBounds);
            }
        }
        match error {
            Some(e) => Err((e, vec)),
            None => Ok(vec),
        }
    }

    /// Clears all unwound events. Makes [`Self::rewind`] useless if called after [`Self::unwind`].
    pub(crate) fn clear_unwound(&mut self) {
        self.unwound_events.clear();
    }

    /// See [`Manager::last_change_to_resource`].
    #[must_use]
    #[allow(clippy::missing_panics_doc)] // this is guaranteed by the contracts in `Self::new`
    pub fn last_change_to_resource(&self, resource: &str) -> SystemTime {
        self.manager.unwrap().last_change_to_resource(resource)
    }
}

#[derive(Debug)]
/// An error when [rewinding](Rewinder::rewind).
pub enum RewindError {
    /// An error occurred when applying a diff.
    ///
    /// The rewound resource is also returned, if you want to use it.
    /// The diffs which erred aren't applied.
    Apply(den::ApplyError, Vec<u8>),
    /// The resource has been destroyed since last commit. Throw away your changes.
    ///
    /// The inner byte array is the `data` supposed to be rewound.
    ResourceDestroyed(Vec<u8>),
}
impl RewindError {
    /// Returns the recovered data.
    #[must_use]
    pub fn into_data(self) -> Vec<u8> {
        match self {
            RewindError::Apply(_e, vec) => vec,
            RewindError::ResourceDestroyed(vec) => vec,
        }
    }
}

/// Struct to apply all the diffs from a specified timestamp to a resource.
///
/// See [`Manager::rewind_from_last_commit`] for more info.
#[derive(Debug, Clone)]
pub struct Rewinder<'a> {
    /// Ordered from last (temporally).
    events: &'a [log::ReceivedEvent],
    buf: Vec<u8>,
    manager: &'a Manager,
}
impl<'a> Rewinder<'a> {
    pub(crate) fn new(slice: &'a [log::ReceivedEvent], manager: &'a Manager) -> Self {
        Self {
            events: slice,
            buf: Vec::new(),
            manager,
        }
    }
    /// Rewinds the `resource` back up to the most recent version.
    /// `diff_modification` can be used to change the diff just before it's applied.
    ///
    /// # Errors
    ///
    /// Passes errors from [`Difference::apply`].
    #[allow(clippy::missing_panics_doc)]
    pub fn rewind_with_modify_diff(
        &mut self,
        resource: &str,
        data: impl Into<Vec<u8>>,
        mut diff_modification: impl FnMut(&Difference) -> Cow<'_, Difference>,
    ) -> Result<Vec<u8>, RewindError> {
        let mut vec = data.into();
        let mut other = std::mem::take(&mut self.buf);

        let mut error = None;

        // if event started ev from beginning, don't apply the
        let breaking_idx = self
            .events
            .iter()
            .rposition(|ev| ev.event.resource() == resource && ev.event.diff().is_none());

        if breaking_idx.is_some() {
            return Err(RewindError::ResourceDestroyed(vec));
        }

        // Apply all events.
        for received_event in self.events {
            if received_event.event.resource() != resource {
                continue;
            }
            let diff = if let Some(diff) = received_event.event.diff() {
                diff
            } else {
                continue;
            };
            let diff = diff_modification(diff);
            if diff.in_bounds(&vec) {
                if diff.apply_overlaps_adaptive_end(vec.len()) {
                    diff.apply_adaptive_end(&vec, &mut other)
                        .expect("we made sure the references were in bounds");
                    std::mem::swap(&mut vec, &mut other);

                    other.clear();
                } else {
                    diff.apply_in_place_adaptive_end(&mut vec)
                        .expect("we made sure the references were in bounds");
                }
            } else {
                error = Some(den::ApplyError::RefOutOfBounds);
            }
        }
        self.buf = other;

        if let Some(err) = error {
            Err(RewindError::Apply(err, vec))
        } else {
            Ok(vec)
        }
    }
    /// Rewinds the `resource` back up to the most recent version.
    ///
    /// # Errors
    ///
    /// Passes errors from [`Difference::apply`].
    pub fn rewind(
        &mut self,
        resource: &str,
        data: impl Into<Vec<u8>>,
    ) -> Result<Vec<u8>, RewindError> {
        self.rewind_with_modify_diff(resource, data, |d| Cow::Borrowed(d))
    }

    /// Get an iterator over the events stored in this rewinder.
    /// The first item is the oldest one. The last is the most recent.
    pub fn events(&self) -> impl Iterator<Item = &Event> + DoubleEndedIterator + '_ {
        self.events.iter().map(|received_ev| &received_ev.event)
    }

    /// See [`Manager::last_change_to_resource`].
    #[must_use]
    pub fn last_change_to_resource(&self, resource: &str) -> SystemTime {
        self.manager.last_change_to_resource(resource)
    }
}