snaplog 0.4.0

A library for easily recording changes to values
Documentation
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
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
//! A full [`Snaplog`] and it's associated types. A `Snaplog` is used to record snapshots of changes
//! to a value, such as successive edits to a file's contents.
//!
//! # Examples
//! ```
//! # use snaplog::{full::Snaplog, Select};
//! let mut snaplog: Snaplog<_> = vec![
//!     "content".to_string(),
//!     "new-content".to_string()
//! ].try_into()?;
//!
//! snaplog.record_change(|prev| format!("{prev}-change"));
//! snaplog.record("final-content".to_string());
//!
//! assert_eq!(snaplog[Select::Initial], "content");
//! assert_eq!(snaplog[Select::At(2)],   "new-content-change");
//! assert_eq!(snaplog[Select::Current], "final-content");
//!
//! snaplog.clear_history();
//!
//! assert_eq!(snaplog.history(), ["final-content"]);
//! assert_eq!(snaplog.has_changes(), false);
//! # Ok::<_, Box<dyn std::error::Error>>(())
//! ```

use crate::{EmptyHistoryError, Select, INVARIANT_UNWRAP};

use std::collections::TryReserveError;
use std::ops::{Bound, RangeBounds};

/// A struct for recording the history of changes done to a given `T` by storing a snapshot after
/// each change. The history of snapshots is stored in [`Vec`] in ascending order, that means the
/// first element is the initial element.
///
/// # Examples
/// ```
/// # use snaplog::{full::Snaplog, Select};
/// let mut snaplog: Snaplog<_> = vec![
///     "/path/to/file".to_string(),
///     "/path/to/file-backup".to_string(),
///     "/path/file-backup".to_string()
/// ].try_into()?;
///
/// assert_eq!(snaplog.has_changes(), true);
///
/// snaplog.record_change(|prev| format!("{prev}-copy"));
/// snaplog.record("/path/file".to_string());
///
/// assert_eq!(snaplog[Select::Initial], "/path/to/file");
/// assert_eq!(snaplog[Select::At(3)],   "/path/file-backup-copy");
/// assert_eq!(snaplog[Select::Current], "/path/file");
///
/// snaplog.clear_history();
///
/// assert_eq!(snaplog.history(), ["/path/file"]);
/// assert_eq!(snaplog.has_changes(), false);
/// # Ok::<_, Box<dyn std::error::Error>>(())
/// ```
#[derive(Debug)]
#[repr(transparent)]
pub struct Snaplog<T> {
    history: Vec<T>,
}

/// Various constructor functions.
impl<T> Snaplog<T> {
    /// Creates a new [`Snaplog`] from the given `initial` snapshot with no recorded changes.
    ///
    /// # Examples
    /// ```
    /// # use snaplog::full::Snaplog;
    /// let snaplog = Snaplog::new(0);
    ///
    /// assert_eq!(snaplog.initial(), snaplog.current());
    /// assert_eq!(snaplog.has_changes(), false);
    /// ```
    pub fn new(initial: T) -> Self {
        Self {
            history: vec![initial],
        }
    }

    /// Creates a new [`Snaplog`] for the given `history` backing vector.
    ///
    /// # Errors
    /// Returns an error if `history` was empty.
    ///
    /// # Examples
    /// ```
    /// # use snaplog::full::Snaplog;
    /// assert!(Snaplog::try_from_vec(vec![0]).is_ok());
    /// assert!(Snaplog::<()>::try_from_vec(vec![]).is_err());
    /// ```
    pub fn try_from_vec(history: Vec<T>) -> Result<Self, EmptyHistoryError> {
        if history.is_empty() {
            Err(EmptyHistoryError(()))
        } else {
            Ok(Self { history })
        }
    }

    /// Creates a new [`Snaplog`] for the given `history` backing vector.
    ///
    /// # Panics
    /// Panics if `history` was empty.
    ///
    ///
    /// # Examples
    /// ```
    /// # use snaplog::full::Snaplog;
    /// let snaplog = Snaplog::from_vec(vec![0]);
    /// ```
    ///
    /// This panics:
    /// ```should_panic
    /// # use snaplog::full::Snaplog;
    /// let snaplog: Snaplog<i32> = Snaplog::from_vec(vec![]);
    /// ```
    pub fn from_vec(history: Vec<T>) -> Self {
        match Self::try_from_vec(history) {
            Ok(this) => this,
            Err(_) => panic!("history must not be empty"),
        }
    }

    /// Creates a new [`Snaplog`] from the given `history`. The elements are collected into a
    /// [`Vec`] the if you already have a vec at hand use [`from_vec`][Self::try_from_vec]. The
    /// first element is used as the initial element.
    ///
    /// # Errors
    /// Returns an error if `history` was empty.
    ///
    /// # Examples
    /// ```
    /// # use snaplog::full::Snaplog;
    /// assert!(Snaplog::try_from_history(0..=10).is_ok());
    /// assert!(Snaplog::<i32>::try_from_history(std::iter::empty()).is_err());
    /// ```
    pub fn try_from_history<I>(history: I) -> Result<Self, EmptyHistoryError>
    where
        I: IntoIterator<Item = T>,
    {
        Self::try_from_vec(history.into_iter().collect())
    }

    /// Creates a new [`Snaplog`] from the given `history`. The elements are collected into a
    /// [`Vec`] the if you already have a vec at hand use [`from_vec`][Self::from_vec]. The first
    /// element is used as the initial element.
    ///
    /// # Panics
    /// Panics if `history` was empty.
    ///
    /// # Examples
    /// ```
    /// # use snaplog::full::Snaplog;
    /// let snaplog = Snaplog::from_history(0..=10);
    /// ```
    ///
    /// This panics:
    /// ```should_panic
    /// # use snaplog::full::Snaplog;
    /// let snaplog: Snaplog<i32> = Snaplog::from_history(std::iter::empty());
    /// ```
    pub fn from_history<I>(history: I) -> Self
    where
        I: IntoIterator<Item = T>,
    {
        Self::from_vec(history.into_iter().collect())
    }
}

/// First class [`Snaplog`] members.
impl<T> Snaplog<T> {
    /// Records a snapshot in this [`Snaplog`].
    ///
    /// # Examples
    /// ```
    /// # use snaplog::full::Snaplog;
    /// let mut snaplog = Snaplog::new("a");
    ///
    /// snaplog.record("b");
    /// snaplog.record("c");
    /// assert_eq!(snaplog.history(), ["a", "b", "c"]);
    /// ```
    pub fn record(&mut self, snapshot: T) {
        self.history.push(snapshot);
    }

    /// Records multiple snapshots in this [`Snaplog`].
    ///
    /// # Examples
    /// ```
    /// # use snaplog::full::Snaplog;
    /// let mut snaplog = Snaplog::new("a");
    ///
    /// snaplog.record_all(["b", "c", "d"]);
    /// assert_eq!(snaplog.history(), ["a", "b", "c", "d"]);
    /// ```
    pub fn record_all<I>(&mut self, snapshots: I)
    where
        I: IntoIterator<Item = T>,
    {
        self.history.extend(snapshots);
    }

    /// Records a change to the current element in this [`Snaplog`].
    ///
    /// # Examples
    /// ```
    /// # use snaplog::full::Snaplog;
    /// let mut snaplog = Snaplog::new("a");
    ///
    /// snaplog.record_change(|prev| { assert_eq!(prev, &"a"); "b" });
    /// snaplog.record_change(|prev| { assert_eq!(prev, &"b"); "c" });
    /// assert_eq!(snaplog.history(), ["a", "b", "c"]);
    /// ```
    pub fn record_change<F>(&mut self, mut f: F)
    where
        F: FnMut(&T) -> T,
    {
        self.history.push(f(self.current()));
    }

    // TODO: keyword generics over try would be great here

    /// Tries to record a change to the current element in this [`Snaplog`].
    ///
    /// # Errors
    /// Returns the inner error if the closure failed.
    ///
    /// # Examples
    /// ```
    /// # use snaplog::full::Snaplog;
    /// let mut snaplog = Snaplog::new("a");
    ///
    /// snaplog.try_record_change(|prev| { assert_eq!(prev, &"a"); Ok("b") })?;
    /// snaplog.try_record_change(|prev| { assert_eq!(prev, &"b"); Ok("c") })?;
    /// assert_eq!(snaplog.try_record_change(|prev| Err(())), Err(()));
    /// assert_eq!(snaplog.history(), ["a", "b", "c"]);
    /// # Ok::<_, ()>(())
    /// ```
    pub fn try_record_change<F, E>(&mut self, mut f: F) -> Result<(), E>
    where
        F: FnMut(&T) -> Result<T, E>,
    {
        self.history.push(f(self.current())?);
        Ok(())
    }

    // NOTE: this may be superseded by an impl using a single Generator that takes the current arg
    // and yields the next, but it would have to be some kind of generator that can give a goos size
    // estimation which in turn would hurt the ergonomics
    //
    // this impl:
    // pub fn record_changes_all<G>(&mut self, generator: G)
    //     where for<'t> G: Generator<&'t T, Yield = T, Return = ()>
    //
    // came with live time problems when I tested it out and using it with generator syntax eg.:
    // let snapshot = Snapshot::new("initial".to_string());
    // snapshot.record_changes_all(|prev| yield format!("{prev}-edit"));
    //
    // the current impl is the closest thing to an ergonomic size hint generator

    /// Records multiple successive changes to the current element in this [`Snaplog`].
    ///
    /// # Examples
    /// ```
    /// # use snaplog::full::Snaplog;
    /// let mut snaplog = Snaplog::new("a");
    ///
    /// snaplog.record_changes_all(&mut ["b", "c", "d"], |change, _| *change);
    /// assert_eq!(snaplog.history(), ["a", "b", "c", "d"]);
    /// ```
    pub fn record_changes_all<F, M>(&mut self, mutations: &mut [M], mut f: F)
    where
        F: FnMut(&mut M, &T) -> T,
    {
        self.history.reserve(mutations.len());

        for mutation in mutations {
            self.history.push(f(mutation, self.current()));
        }
    }

    /// Returns whether or not there are any changes recorded in this [`Snaplog`].
    ///
    /// # Examples
    /// ```
    /// # use snaplog::full::Snaplog;
    /// let mut snaplog = Snaplog::new("a");
    ///
    /// assert_eq!(snaplog.has_changes(), false);
    /// snaplog.record("b");
    /// snaplog.record("c");
    /// assert_eq!(snaplog.has_changes(), true);
    /// ```
    pub fn has_changes(&self) -> bool {
        self.history.len() > 1
    }

    /// Returns the initial element.
    ///
    /// # Examples
    /// ```
    /// # use snaplog::full::Snaplog;
    /// let mut snaplog = Snaplog::new("a");
    ///
    /// snaplog.record("b");
    /// snaplog.record("c");
    /// assert_eq!(snaplog.initial(), &"a");
    /// ```
    pub fn initial(&self) -> &T {
        self.history.first().expect(INVARIANT_UNWRAP)
    }

    /// Returns the element at the given [`Select`].
    ///
    /// # Examples
    /// ```
    /// # use snaplog::{full::Snaplog, Select};
    /// let mut snaplog = Snaplog::new("a");
    ///
    /// snaplog.record("b");
    /// snaplog.record("c");
    /// assert_eq!(snaplog.snapshot_at(Select::At(1)), &"b");
    /// ```
    pub fn snapshot_at(&self, select: Select) -> &T {
        select.index_into(&self.history)
    }

    /// Returns the current element, that is the last recorded change or the initial element if
    /// there are no none.
    ///
    /// # Examples
    /// ```
    /// # use snaplog::full::Snaplog;
    /// let mut snaplog = Snaplog::new("a");
    ///
    /// snaplog.record("b");
    /// snaplog.record("c");
    /// assert_eq!(snaplog.current(), &"c");
    /// ```
    pub fn current(&self) -> &T {
        self.history.last().expect(INVARIANT_UNWRAP)
    }

    /// Returns the initial element.
    ///
    /// # Examples
    /// ```
    /// # use snaplog::full::Snaplog;
    /// let mut snaplog = Snaplog::new("a");
    ///
    /// snaplog.record("b");
    /// snaplog.record("c");
    /// assert_eq!(snaplog.initial_mut(), &mut "a");
    /// ```
    pub fn initial_mut(&mut self) -> &mut T {
        self.history.first_mut().expect(INVARIANT_UNWRAP)
    }

    /// Returns the element at the given [`Select`].
    ///
    /// # Examples
    /// ```
    /// # use snaplog::{full::Snaplog, Select};
    /// let mut snaplog = Snaplog::new("a");
    ///
    /// snaplog.record("b");
    /// snaplog.record("c");
    /// assert_eq!(snaplog.snapshot_at_mut(Select::At(1)), &mut "b");
    /// ```
    pub fn snapshot_at_mut(&mut self, select: Select) -> &mut T {
        select.index_into_mut(&mut self.history)
    }

    /// Returns the current element, that is the last recorded change or the initial element if
    /// there are no none.
    ///
    /// # Examples
    /// ```
    /// # use snaplog::full::Snaplog;
    /// let mut snaplog = Snaplog::new("a");
    ///
    /// snaplog.record("b");
    /// snaplog.record("c");
    /// assert_eq!(snaplog.current_mut(), &mut "c");
    /// ```
    pub fn current_mut(&mut self) -> &mut T {
        self.history.last_mut().expect(INVARIANT_UNWRAP)
    }

    /// Clones the element at the given [`Select`].
    ///
    /// # Examples
    /// ```
    /// # use snaplog::{full::Snaplog, Select};
    /// let mut snaplog = Snaplog::new("a");
    ///
    /// snaplog.record("b");
    /// snaplog.record("c");
    /// assert_eq!(snaplog.clone_snapshot_at(Select::At(1)), "b");
    /// ```
    pub fn clone_snapshot_at(&self, select: Select) -> T
    where
        T: Clone,
    {
        select.index_into(&self.history).clone()
    }

    /// Returns the full history recorded in this [`Snaplog`], including the initial element.
    ///
    /// # Examples
    /// ```
    /// # use snaplog::full::Snaplog;
    /// let mut snaplog = Snaplog::new("a");
    ///
    /// snaplog.record("b");
    /// snaplog.record("c");
    /// assert_eq!(snaplog.history(), ["a", "b", "c"]);
    /// ```
    pub fn history(&self) -> &[T] {
        self.history.as_slice()
    }

    /// Returns a mutable reference to the underlying `history`.
    ///
    /// # Examples
    /// ```
    /// # use snaplog::full::Snaplog;
    /// let mut snaplog = Snaplog::try_from_history(0..=10)?;
    /// let history = snaplog.history_mut();
    ///
    /// history[0] = 10;
    /// assert_eq!(snaplog.history(), [10, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]);
    /// # Ok::<_, Box<dyn std::error::Error>>(())
    /// ```
    pub fn history_mut(&mut self) -> &mut [T] {
        self.history.as_mut_slice()
    }

    /// Drains the history in the specified range, a left open range is interpreted as starting
    /// behind the initial element, elements that are not yielded from the [`Iterator`] are dropped.
    ///
    /// # Panics
    /// Panics if the lower range bound is inclusive `0`.
    /// Panics if the lower or upper bound are out of range.
    ///
    /// # Examples
    /// ```
    /// # use snaplog::full::Snaplog;
    /// let mut snaplog = Snaplog::try_from_history(0..=10)?;
    ///
    /// snaplog.drain(2..=8);
    /// assert_eq!(snaplog.history(), [0, 1, 9, 10]);
    /// # Ok::<_, Box<dyn std::error::Error>>(())
    /// ```
    /// The unbounded range is reinterpreted as starting at `1`:
    /// ```
    /// # use snaplog::full::Snaplog;
    /// # let mut snaplog = Snaplog::try_from_history(0..=10)?;
    /// snaplog.drain(..);
    /// assert_eq!(snaplog.history(), [0]);
    /// # Ok::<_, Box<dyn std::error::Error>>(())
    /// ```
    /// The only invalid lower bound is `0`:
    /// ```should_panic
    /// # use snaplog::full::Snaplog;
    /// # let mut snaplog = Snaplog::try_from_history(0..=10)?;
    /// snaplog.drain(0..);
    /// # Ok::<_, Box<dyn std::error::Error>>(())
    /// ```
    pub fn drain<R>(&mut self, range: R) -> impl Iterator<Item = T> + '_
    where
        R: RangeBounds<usize>,
    {
        let start_bound = match range.start_bound() {
            Bound::Included(&idx) if idx == 0 => panic!("cannot drain initial element"),
            Bound::Included(&idx) => Bound::Included(idx),
            Bound::Excluded(&idx) => Bound::Excluded(idx),
            Bound::Unbounded => Bound::Excluded(0),
        };

        self.history
            .drain((start_bound, range.end_bound().cloned()))
    }

    /// Wipe the recorded history, keeping only the current element as the new initial element.
    ///
    /// # Examples
    /// ```
    /// # use snaplog::full::Snaplog;
    /// let mut snaplog = Snaplog::new("a");
    ///
    /// snaplog.record("b");
    /// snaplog.record("c");
    /// snaplog.clear_history();
    /// assert_eq!(snaplog.initial(), &"c");
    /// assert_eq!(snaplog.has_changes(), false);
    /// ```
    pub fn clear_history(&mut self) {
        self.history.drain(..self.history.len() - 1);
    }

    /// Wipe the recorded changes, keeping only the initial element.
    ///
    /// # Examples
    /// ```
    /// # use snaplog::full::Snaplog;
    /// let mut snaplog = Snaplog::new("a");
    ///
    /// snaplog.record("b");
    /// snaplog.record("c");
    /// snaplog.reset();
    /// assert_eq!(snaplog.initial(), &"a");
    /// assert_eq!(snaplog.has_changes(), false);
    /// ```
    pub fn reset(&mut self) {
        self.history.drain(1..);
    }

    /// Reserve space for `n` additional elements.
    ///
    /// # Examples
    /// ```
    /// # use snaplog::full::Snaplog;
    /// let mut snaplog = Snaplog::new("a");
    /// snaplog.reserve(10);
    /// ```
    pub fn reserve(&mut self, n: usize) {
        self.history.reserve(n);
    }

    /// Reserve space for `n` additional elements.
    ///
    /// # Errors
    /// Returns an error if [`Vec::try_reserve`] failed.
    ///
    /// # Examples
    /// ```
    /// # use snaplog::full::Snaplog;
    /// let mut snaplog = Snaplog::new("a");
    /// snaplog.try_reserve(10)?;
    /// # Ok::<_, Box<dyn std::error::Error>>(())
    /// ```
    pub fn try_reserve(&mut self, n: usize) -> Result<(), TryReserveError> {
        self.history.try_reserve(n)
    }

    /// Returns an iterator over references of the whole underling history.
    ///
    /// # Examples
    /// ```
    /// # use snaplog::full::Snaplog;
    /// let mut snaplog = Snaplog::try_from_history(0..=10)?;
    ///
    /// let mut copy = vec![];
    /// for &snapshot in snaplog.iter() {
    ///     copy.push(snapshot);
    /// }
    ///
    /// assert_eq!(copy, [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]);
    /// # Ok::<_, Box<dyn std::error::Error>>(())
    /// ```
    pub fn iter(&self) -> Iter<'_, T> {
        self.history.iter()
    }

    /// Returns an iterator over mutable references of the whole underling history.
    ///
    /// # Examples
    /// ```
    /// # use snaplog::full::Snaplog;
    /// let mut snaplog = Snaplog::try_from_history(0..=10)?;
    ///
    /// for snapshot in snaplog.iter_mut().filter(|&&mut n| n % 2 == 0) {
    ///     *snapshot = 2;
    /// }
    ///
    /// assert_eq!(snaplog.history(), [2, 1, 2, 3, 2, 5, 2, 7, 2, 9, 2]);
    /// # Ok::<_, Box<dyn std::error::Error>>(())
    /// ```
    pub fn iter_mut(&mut self) -> IterMut<'_, T> {
        self.history.iter_mut()
    }

    /// Unwrap the [`Snaplog`] into it's initial snapshot.
    ///
    /// # Examples
    /// ```
    /// # use snaplog::full::Snaplog;
    /// let mut snaplog = Snaplog::new("a");
    ///
    /// snaplog.record("b");
    /// snaplog.record("c");
    /// assert_eq!(snaplog.into_initial(), "a");
    /// ```
    pub fn into_initial(mut self) -> T {
        self.history.swap_remove(0)
    }

    /// Unwrap the [`Snaplog`] into it's current snapshot.
    ///
    /// # Examples
    /// ```
    /// # use snaplog::full::Snaplog;
    /// let mut snaplog = Snaplog::new("a");
    ///
    /// snaplog.record("b");
    /// snaplog.record("c");
    /// assert_eq!(snaplog.into_current(), "c");
    /// ```
    pub fn into_current(mut self) -> T {
        self.history.pop().expect(INVARIANT_UNWRAP)
    }

    /// Unwrap the [`Snaplog`] into it's current snapshot.
    ///
    /// # Examples
    /// ```
    /// # use snaplog::{full::Snaplog, Select};
    /// let mut snaplog = Snaplog::new("a");
    ///
    /// snaplog.record("b");
    /// snaplog.record("c");
    /// assert_eq!(snaplog.into_snapshot_at(Select::At(1)), "b");
    /// ```
    pub fn into_snapshot_at(mut self, select: Select) -> T {
        select.index_into_remove(&mut self.history)
    }

    /// Unwrap the [`Snaplog`] into it's history.
    ///
    /// # Examples
    /// ```
    /// # use snaplog::full::Snaplog;
    /// let mut snaplog = Snaplog::new("a");
    ///
    /// snaplog.record("b");
    /// snaplog.record("c");
    /// assert_eq!(snaplog.into_inner(), ["a", "b", "c"]);
    /// ```
    pub fn into_inner(self) -> Vec<T> {
        self.history
    }
}

/// Unsafe implementations.
impl<T> Snaplog<T> {
    /// Creates a new [`Snaplog`] for the given `history` backing vector.
    ///
    /// # Safety
    /// The caller must ensure that the [`Vec`] contains at least one element.
    ///
    /// # Examples
    /// ```
    /// # use snaplog::full::Snaplog;
    /// // this is fine
    /// let snaplog = unsafe { Snaplog::from_vec_unchecked(vec![0]) };
    ///
    /// // this will later fail
    /// let snaplog: Snaplog<i32> = unsafe { Snaplog::from_vec_unchecked(vec![]) };
    /// ```
    pub unsafe fn from_vec_unchecked(history: Vec<T>) -> Self {
        Self { history }
    }

    /// Creates a new [`Snaplog`] for the given `history` backing vector.
    ///
    /// # Safety
    /// The caller must ensure that the `iter` contains at least one element.
    ///
    /// # Examples
    /// ```
    /// # use snaplog::full::Snaplog;
    /// // this is fine
    /// let snaplog = unsafe { Snaplog::from_history_unchecked(0..=10) };
    ///
    /// // this will later fail
    /// let snaplog: Snaplog<i32> = unsafe { Snaplog::from_history_unchecked(std::iter::empty()) };
    /// ```
    pub unsafe fn from_history_unchecked<I>(history: I) -> Self
    where
        I: IntoIterator<Item = T>,
    {
        // SAFETY: invariants must be upheld by the caller
        unsafe { Self::from_vec_unchecked(history.into_iter().collect()) }
    }

    /// Returns a mutable reference to the underlying [`Vec`]. The first element of this vector is
    /// the initial element and is always set.
    ///
    /// # Safety
    /// The caller must ensure that the [`Vec`] retains at least one element after mutation, this
    /// element serves as the initial element.
    ///
    /// # Examples
    /// ```
    /// # use snaplog::full::Snaplog;
    /// let mut snaplog = Snaplog::try_from_history(0..=10)?;
    ///
    /// // SAFETY: no elements are removed
    /// let inner = unsafe { snaplog.history_mut_vec() };
    /// inner[5] = 100;
    /// inner[6] = 200;
    /// inner.drain(1..=3);
    /// inner.push(300);
    ///
    /// assert_eq!(snaplog.history(), [0, 4, 100, 200, 7, 8, 9, 10, 300]);
    /// # Ok::<_, Box<dyn std::error::Error>>(())
    /// ```
    pub unsafe fn history_mut_vec(&mut self) -> &mut Vec<T> {
        &mut self.history
    }
}

// first class traits
impl<T: PartialEq> PartialEq for Snaplog<T> {
    fn eq(&self, other: &Self) -> bool {
        // it is assumed that inequality is more common than equality
        //
        // 'trickle through' snaps (changes are not completely overwritten)
        //
        // eg.: if two snaplogs only differed in the number they appended to a file name on
        // snapshot[1] but are other wise the same:
        //
        // [0] "/a/rather/long/file/path"   // move file up
        // [1] "/a/rather/long/path"        // rename append _x where x differs on each snaplog
        // [2] "/a/rather/long/path_x"      // move file up
        // [3] "/a/rather/path_x"           // move file up
        // [4] "/a/path_x"                  // move file up
        // [5] "/path_x"
        //
        // the change for snapshot[1] is still noticeable at snapshot[5], so not all snapshots need
        // to be compared to check for inequality
        if self.initial() == other.initial() && self.history.len() == other.history.len() {
            // if they hav the same length they must both have changes if one has
            if self.has_changes() {
                (self.history.last() == other.history.last())
                    && (self.history[1..self.history.len() - 1]
                        == other.history[1..other.history.len() - 1])
            } else {
                true // no changes and initials are equal
            }
        } else {
            false // non equal initials or changelog length
        }
    }
}

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

impl<T: Clone> Clone for Snaplog<T> {
    fn clone(&self) -> Self {
        Self {
            history: self.history.clone(),
        }
    }

    fn clone_from(&mut self, source: &Self) {
        self.history.clone_from(&source.history)
    }
}

impl<T> std::ops::Index<Select> for Snaplog<T> {
    type Output = T;

    fn index(&self, index: Select) -> &Self::Output {
        self.snapshot_at(index)
    }
}

impl<T> std::ops::IndexMut<Select> for Snaplog<T> {
    fn index_mut(&mut self, index: Select) -> &mut Self::Output {
        self.snapshot_at_mut(index)
    }
}

// iter
impl<T> std::iter::Extend<T> for Snaplog<T> {
    fn extend<I: IntoIterator<Item = T>>(&mut self, iter: I) {
        self.history.extend(iter);
    }
}

// TODO: try_from_itertor, this is likely blocked by `try_trait_v2`
// impl<T> std::iter::FromIterator<T> for Snaplog<T> {
//     fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> Self {
//         // Self::try_from_history(iter)
//         unimplemented!("is not infallible")
//     }
// }

/// A type alias for [`std::vec::IntoIter`].
///
/// # Examples
/// ```
/// # use snaplog::full::Snaplog;
/// let snaplog = Snaplog::new(());
///
/// for snapshot in snaplog.into_iter() {
///     let s: () = snapshot;
/// }
///
/// let snaplog = Snaplog::new(());
///
/// for snapshot in snaplog {
///     let s: () = snapshot;
/// }
/// ```
pub type IntoIter<T> = std::vec::IntoIter<T>;

impl<T> IntoIterator for Snaplog<T> {
    type Item = T;
    type IntoIter = IntoIter<T>;

    fn into_iter(self) -> Self::IntoIter {
        self.history.into_iter()
    }
}

/// A type alias for [`std::slice::Iter`].
///
/// # Examples
/// ```
/// # use snaplog::full::Snaplog;
/// let snaplog = Snaplog::new(());
///
/// for snapshot in snaplog.iter() {
///     let s: &() = snapshot;
/// }
///
/// for snapshot in &snaplog {
///     let s: &() = snapshot;
/// }
/// ```
pub type Iter<'cl, T> = std::slice::Iter<'cl, T>;

impl<'cl, T> IntoIterator for &'cl Snaplog<T> {
    type Item = &'cl T;
    type IntoIter = Iter<'cl, T>;

    fn into_iter(self) -> Self::IntoIter {
        self.iter()
    }
}

/// A type alias for [`std::slice::IterMut`].
///
/// # Examples
/// ```
/// # use snaplog::full::Snaplog;
/// let mut snaplog = Snaplog::new(());
///
/// for snapshot in snaplog.iter_mut() {
///     let s: &mut () = snapshot;
/// }
///
/// for snapshot in &mut snaplog {
///     let s: &mut () = snapshot;
/// }
/// ```
pub type IterMut<'cl, T> = std::slice::IterMut<'cl, T>;

impl<'cl, T> IntoIterator for &'cl mut Snaplog<T> {
    type Item = &'cl mut T;
    type IntoIter = IterMut<'cl, T>;

    fn into_iter(self) -> Self::IntoIter {
        self.iter_mut()
    }
}

// conversions
impl<T> From<T> for Snaplog<T> {
    fn from(initial: T) -> Self {
        Self::new(initial)
    }
}

impl<T> From<Snaplog<T>> for Vec<T> {
    fn from(snaplog: Snaplog<T>) -> Self {
        snaplog.into_inner()
    }
}

impl<T> TryFrom<Vec<T>> for Snaplog<T> {
    type Error = EmptyHistoryError;

    fn try_from(value: Vec<T>) -> Result<Self, Self::Error> {
        Self::try_from_vec(value)
    }
}