michis_collection_cursor 0.1.3

A cursor which wraps an indexable collection, providing a movable position which points to an index of the collection. Useful for things like history, undo-redo systems, or timelines.
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
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
#![no_std]

mod trait_impls_by_crate;

/// A `CollectionCursor` wraps an index-based collection, such as a `Vec<T>`, providing it with
/// a cursor that points to a spot in the collection.
///
/// One might compare this to `std::io::Cursor`, but intended for index-based collections rather
/// than I/O buffers. This makes it easier to implement systems that function by pointing to a spot
/// inside a collection of items; for example, undo-redo systems, timelines, or linear histories.
#[derive(Clone, Debug, Default, Hash, PartialEq, Eq, PartialOrd, Ord)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct CollectionCursor<Tape> {
	/// The underlying collection that the cursor will point into.
	inner: Tape,
	/// The cursor's current position atop `self.inner`. How this position is processed is dependant
	/// on the use-case, but generally this will point to the "beginning" of a cell - usually of the
	/// cell that we want to process next.
	///
	/// The cursor is constrained to `0 <= pos <= self.inner.len()`, except in cases where a user
	/// calls `self.get_mut()`, changes the length to be less than the pos, and forgets to clamp
	/// the pos back within the collection's bounds. However, such a thing is a logic error, and is
	/// on the user of the struct to avoid.
	pos: usize,
}

impl<Tape> CollectionCursor<Tape> {
	/// Creates a new `CollectionCursor` wrapping the provided collection.
	///
	/// The cursor's initial position will always be `0`.
	pub fn new(inner: Tape) -> Self {
		Self {
			inner,
			pos: Default::default(),
		}
	}

	/// Returns the current position of the cursor.
	///
	/// This can be assumed to uphold `0 <= cursor_position <= self.get_ref().len()`, where
	/// `cursor_position` is the value returned by this function.
	pub fn position(&self) -> usize {
		self.pos
	}

	/// Gets a reference to the underlying collection.
	pub fn get_ref(&self) -> &Tape {
		&self.inner
	}

	/// Gets a mutable reference to the underlying collection.
	///
	/// # Warning
	/// If the underlying collection's length is modified, you must ensure that
	/// `0 <= self.position() <= self.get_ref().len()` is upheld before the next attempt to
	/// read/write at the cursor. [`Self::clamp_to_last_item()`] and [`Self::clamp_to_end()`] may be
	/// useful in these cases.
	///
	/// Failure to do so is a logic error. The behavior resulting from such a logic error is not
	/// specified, but will generally result in panics, incorrect results, and other such unwanted
	/// behavior.
	pub fn get_mut(&mut self) -> &mut Tape {
		&mut self.inner
	}

	/// Consumes the `CollectionCursor`, returning the underlying collection.
	pub fn into_inner(self) -> Tape {
		self.inner
	}
}

impl<Tape: IndexableCollection> CollectionCursor<Tape> {
	/// Returns whether the cursor is at the end of the collection (one index past the last item in
	/// the collection).
	pub fn is_cursor_at_end(&self) -> bool {
		self.pos == self.inner.len()
	}

	/// Moves the cursor to a new index.
	///
	/// It is an error to seek to a position before `0` or after `self.get_ref().len()`. In these
	/// cases, `None` will be returned and the cursor will not be moved.
	///
	/// Otherwise, this will return `Some(new_pos)`, where `new_pos` is the new position of the
	/// cursor.
	// TODO: Change to something like `Result<usize, OutOfBoundsError>`
	pub fn seek(&mut self, pos: SeekFrom) -> Option<usize> {
		let collection_len = self.inner.len();

		let desired_position = match pos {
			SeekFrom::Start(p) => Some(p),
			SeekFrom::End(p) => collection_len.checked_add_signed(p),
			SeekFrom::Current(p) => self.pos.checked_add_signed(p),
		};

		desired_position
			.filter(|&pos| pos <= collection_len)
			.inspect(|&new_pos| self.pos = new_pos)
	}

	/// Clamps the cursor to the index of the last item, or `0` if no items exist. If the cursor is
	/// before or at that index, nothing will happen.
	pub fn clamp_to_last_item(&mut self) {
		// `usize`, by its nature, cannot be below `0`. Thus, we only need to know which is the
		// smaller value: the collection length, or the head position
		self.pos = self
			.pos
			.min(self.inner.len().saturating_sub(1));
	}

	/// Clamps the cursor to one index past the last item. If the cursor is before or at that index,
	/// nothing will happen.
	pub fn clamp_to_end(&mut self) {
		// `usize`, by its nature, cannot be below `0`. Thus, we only need to know which is the
		// smaller value: the collection length, or the head position
		self.pos = self.pos.min(self.inner.len());
	}

	/// Moves the cursor to the beginning of the collection.
	///
	/// This is a convenience method, equivalent to `self.seek(SeekFrom::Start(0))`.
	pub fn seek_to_start(&mut self) {
		self.pos = 0;
	}

	/// Moves the cursor backwards one item. Returning `true` if the move was successful, or `false`
	/// if we're already at the beginning of the collection.
	///
	/// This is a convenience method, equivalent to `self.seek(SeekFrom::Current(-1))`.
	pub fn seek_backward_one(&mut self) -> bool {
		self.seek_relative(-1).is_some()
	}

	/// Moves the cursor relative to the current position. The return value is the same as the one
	/// returned for [`Self::seek()`].
	///
	/// This is a convenience method, equivalent to `self.seek(SeekFrom::Current(offset))`.
	// TODO: Change to something like `Result<usize, OutOfBoundsError>`
	pub fn seek_relative(&mut self, offset: isize) -> Option<usize> {
		self.seek(SeekFrom::Current(offset))
	}

	/// Moves the cursor forwards one item, if an item exists. Returns `true` if the move was
	/// successful, and `false` if we're already at the end of the collection.
	///
	/// This is a convenience method, equivalent to `self.seek(SeekFrom::Current(1))`.
	pub fn seek_forward_one(&mut self) -> bool {
		self.seek_relative(1).is_some()
	}

	/// Moves the cursor to the index of the last item, or to `0` if no items exist.
	///
	/// This is a convenience method, equivalent to `self.seek(SeekFrom::End(-1))`.
	pub fn seek_to_last_item(&mut self) {
		self.pos = self.inner.len().saturating_sub(1);
	}

	/// Moves the cursor to one index past the last item.
	///
	/// This is a convenience method, equivalent to `self.seek(SeekFrom::End(0))`.
	pub fn seek_to_end(&mut self) {
		self.pos = self.inner.len();
	}

	/// Returns a reference to the element pointed at by the cursor.
	///
	/// Returns `None` if `self.position() >= self.get_ref().len()`.
	pub fn get_item_at_cursor(&self) -> Option<&Tape::Item> {
		self.inner.get_item(self.pos)
	}
}

impl<Tape: IndexableCollectionMut> CollectionCursor<Tape> {
	/// Returns a mutable reference to the element pointed at by the cursor.
	///
	/// Returns `None` if the cursor is out-of-bounds.
	pub fn get_item_at_cursor_mut(&mut self) -> Option<&mut Tape::Item> {
		self.inner.get_item_mut(self.pos)
	}

	/// Sets the slot at the cursor to `item`.
	///
	/// # Panics
	/// Panics if the insert operation panics. The circumstances for a panic are defined by the
	/// inner collection, but will usually occur if `self.position() >= self.get_ref().len()`.
	pub fn set_item_at_cursor(&mut self, item: Tape::Item) {
		self.inner.set_item(self.pos, item);
	}
}

impl<Tape: IndexableCollectionResizable> CollectionCursor<Tape> {
	/// Removes all elements within the inner collection, and returns the cursor to the index `0`.
	pub fn clear(&mut self) {
		self.inner.clear();
		self.pos = 0;
	}

	/// Inserts `item` at the cursor, shifting the following elements to the right by one index.
	///
	/// # Panics
	/// Panics if the insert operation panics. The circumstances for a panic are defined by the
	/// inner collection, but will usually occur if `self.position() > self.get_ref().len()`.
	pub fn insert_item_at_cursor(&mut self, item: Tape::Item) {
		self.inner.insert_item(self.pos, item);
	}

	/// If `self.position() == self.get_ref().len()`, then insert `item` at the cursor. Otherwise,
	/// set the slot at the cursor to `item`.
	///
	/// This is equivalent to [`Self::set_item_at_cursor`], except when
	/// `self.position() == self.get_ref().len()`, then it's equivalent to
	/// [`Self::insert_item_at_cursor`].
	///
	/// # Panics
	/// Panics if the set/insert operation panics. The circumstances for a panic are defined by the
	/// inner collection, but will usually occur if `self.position() > self.get_ref().len()`.
	pub fn set_or_insert_item_at_cursor(&mut self, item: Tape::Item) {
		if self.is_cursor_at_end() {
			self.insert_item_at_cursor(item);
		} else {
			self.set_item_at_cursor(item);
		}
	}

	/// Removes and returns the item at the cursor.
	///
	/// Returns `None` if `self.position() >= self.get_ref().len()`, or if the remove operation
	/// would normally panic.
	pub fn remove_item_at_cursor(&mut self) -> Option<Tape::Item> {
		// Note: We don't have to worry about moving the cursor. If the cursor is on the last item,
		// removing will put it one index past the end, which is still within the valid area for the
		// cursor to be. Meanwhile, if it's past the end, no item will be removed.
		self.inner.remove_item(self.pos)
	}
}

/// The various ways one can move the cursor of a [`CollectionCursor`].
#[derive(Clone, Copy, Debug, Hash, PartialEq, Eq, PartialOrd, Ord)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum SeekFrom {
	/// Moves the cursor to the provided index.
	///
	/// # Examples
	/// * `SeekFrom::Start(0)` will move the cursor to the first item
	/// * `SeekFrom::Start(5)` will move the cursor to the sixth item
	Start(usize),
	/// Moves the cursor to the cassette's length (as provided by [`IndexableCollection::len`]) plus
	/// the provided number of indices.
	///
	/// It is an error to seek before the first index, or more than one index past the last item.
	///
	/// # Examples
	/// * `SeekFrom::End(-1)` will move the cursor to the last item, if one exists
	/// * `SeekFrom::End(0)` will move the cursor to the index just after the last item
	End(isize),
	/// Moves the cursor to the current position (as provided by [`CollectionCursor::position`])
	/// plus the provided number of indices.
	///
	/// It is an error to seek before the first index, or more than one index past the last item.
	///
	/// # Examples
	/// * `SeekFrom::Current(-2)` will move the cursor back two indices
	/// * `SeekFrom::Current(0)` won't move anywhere
	/// * `SeekFrom::Current(5)` will move the cursor forward five indices
	Current(isize),
}

/// A trait for collections which are index-based, allowing the inner contents to be accessed.
#[allow(
	clippy::len_without_is_empty,
	reason = "While is_empty would normally be useful, we don't have a use for it here"
)]
pub trait IndexableCollection {
	/// The type of item this container contains.
	type Item;

	/// Gets the number of items this container currently contains.
	fn len(&self) -> usize;
	/// Gets a reference to the item at index `index`. Returns `None` if no item exists at `index`.
	fn get_item(&self, index: usize) -> Option<&Self::Item>;
}

/// A trait for `IndexableCollection`-implementing types which can also be mutated.
pub trait IndexableCollectionMut: IndexableCollection {
	/// Gets a mutable reference to the item at index `index`. Returns `None` if no item exists at
	/// `index`.
	fn get_item_mut(&mut self, index: usize) -> Option<&mut Self::Item>;
	/// Sets an item at a specific index.
	///
	/// This is allowed (and generally expected) to panic if `index >= self.len()`. However, if it
	/// doesn't, then ensure you are following the "rule of least surprise" - whether through
	/// documentation or otherwise.
	fn set_item(&mut self, index: usize, element: Self::Item);
}

/// A trait for `IndexableCollectionMut`-implementing types which can also be resized.
pub trait IndexableCollectionResizable: IndexableCollectionMut {
	/// Inserts an item at a specific index, moving the item at the index and all items after it
	/// one index forward.
	///
	/// This is allowed (and generally expected) to panic if `index > self.len()`. However, if it
	/// doesn't, then ensure you are following the "rule of least surprise" - whether through
	/// documentation or otherwise.
	fn insert_item(&mut self, index: usize, element: Self::Item);
	/// Removes the item at index `index` from the container, and returns the item, or `None` if no
	/// item exists at index `index`.
	///
	/// You must ensure that removing at an index past the end of the collection does not panic. If
	/// the normal `remove()` method of a collection would panic given an invalid index, your
	/// implementation must check and return `None` in those instances.
	fn remove_item(&mut self, index: usize) -> Option<Self::Item>;
	/// Clears the container's contents.
	fn clear(&mut self);
}

#[cfg(test)]
mod collection_cursor_tests {
	extern crate alloc;

	use super::*;
	use alloc::vec::Vec;

	type TestCollection = CollectionCursor<TestVec>;

	// We wrap a `Vec<i32>` into a test collection, so that we always have impls for the various traits,
	// regardless of the feature set.
	#[derive(Clone, Debug, Default, Hash, PartialEq, Eq, PartialOrd, Ord)]
	struct TestVec {
		inner: Vec<i32>,
	}

	impl IndexableCollection for TestVec {
		type Item = i32;

		fn len(&self) -> usize {
			self.inner.len()
		}

		fn get_item(&self, index: usize) -> Option<&Self::Item> {
			self.inner.get(index)
		}
	}

	impl IndexableCollectionMut for TestVec {
		fn get_item_mut(&mut self, index: usize) -> Option<&mut Self::Item> {
			self.inner.get_mut(index)
		}

		fn set_item(&mut self, index: usize, element: Self::Item) {
			self.inner[index] = element;
		}
	}

	impl IndexableCollectionResizable for TestVec {
		fn insert_item(&mut self, index: usize, element: Self::Item) {
			self.inner.insert(index, element);
		}

		fn remove_item(&mut self, index: usize) -> Option<Self::Item> {
			(index < self.inner.len()).then(|| self.inner.remove(index))
		}

		fn clear(&mut self) {
			self.inner.clear();
		}
	}

	fn test_vec() -> TestVec {
		let res = TestVec {
			inner: Vec::from([0, 1, 2, 3, 4, 5, 9, 8, 7, 6]),
		};

		// Ensure that the length is a known value.
		// IF YOU CHANGE THIS, ENSURE TESTS ARE CHANGED TO MATCH.
		assert_eq!(res.inner.len(), 10);

		res
	}

	fn test_collection() -> TestCollection {
		let res = CollectionCursor {
			inner: self::test_vec(),
			pos: Default::default(),
		};

		// Ensure that the cursor position is a known value.
		// IF YOU CHANGE THIS, ENSURE TESTS ARE CHANGED TO MATCH.
		assert_eq!(res.pos, Default::default());

		res
	}

	#[test]
	fn new() {
		let new_collection = CollectionCursor::new(self::test_vec());
		let test_collection = self::test_collection();

		assert_eq!(new_collection, test_collection);
	}

	#[test]
	fn position() {
		let mut collection = self::test_collection();
		assert_eq!(collection.position(), 0);

		collection.pos = 5;
		assert_eq!(collection.position(), 5);

		collection.pos = usize::MAX;
		assert_eq!(collection.position(), usize::MAX);
	}

	#[test]
	fn get_ref() {
		let collection = self::test_collection();
		assert_eq!(collection.get_ref(), &self::test_vec());
	}

	#[test]
	fn get_mut() {
		let mut collection = self::test_collection();
		assert_eq!(collection.get_mut(), &mut self::test_vec());
	}

	#[test]
	fn into_inner() {
		let collection = self::test_collection();
		assert_eq!(collection.into_inner(), self::test_vec());
	}

	#[test]
	fn is_cursor_at_end() {
		let mut collection = self::test_collection();

		assert!(
			!collection.is_cursor_at_end(),
			"should return false when not at end"
		);

		collection.pos = collection.inner.len();
		assert!(
			collection.is_cursor_at_end(),
			"should return true when at end"
		);
	}

	#[test]
	fn seek() {
		fn inner(
			collection: &mut TestCollection,
			seek_from: SeekFrom,
			expected_result: Option<usize>,
			expected_pos: usize,
			error_message: &'static str,
		) {
			let new_pos = collection.seek(seek_from);
			assert_eq!(new_pos, expected_result, "{error_message}");
			assert_eq!(
				collection.pos, expected_pos,
				"the seek did not place the cursor at the expected position"
			);
		}

		let mut collection = self::test_collection();

		// Seeking to within valid bounds should return the `Some(the new position)` and move the
		// cursor
		inner(
			&mut collection,
			SeekFrom::Start(3),
			Some(3),
			3,
			"`Start(x)` should move the cursor within the bounds of the collection",
		);
		inner(
			&mut collection,
			SeekFrom::Start(0),
			Some(0),
			0,
			"`Start(0)` should move the cursor to the start of the collection",
		);

		inner(
			&mut collection,
			SeekFrom::Current(0),
			Some(0),
			0,
			"`Current(0) shouldn't move the cursor",
		);
		inner(
			&mut collection,
			SeekFrom::Current(7),
			Some(7),
			7,
			"`Current(x)` should move the cursor forward within the bounds of the collection",
		);
		inner(
			&mut collection,
			SeekFrom::Current(-2),
			Some(5),
			5,
			"`Current(-x) should move the cursor backwards within the bounds of the collection",
		);
		inner(
			&mut collection,
			SeekFrom::Current(-5),
			Some(0),
			0,
			"`Current(-current_pos) should move the cursor to the start of the collection",
		);

		// TODO: De-hardcode the expected results
		inner(
			&mut collection,
			SeekFrom::End(0),
			Some(10),
			10,
			"`End(0)` should move the cursor to one past the end of the collection",
		);
		inner(
			&mut collection,
			SeekFrom::End(-1),
			Some(9),
			9,
			"`End(-1)` should move the cursor to the end of the collection",
		);
		inner(
			&mut collection,
			SeekFrom::End(-5),
			Some(5),
			5,
			"`End(-x)` should move the cursor within the bounds of the collection",
		);
		inner(
			&mut collection,
			SeekFrom::End(-10),
			Some(0),
			0,
			"`End(-len)` should move the cursor to the start of the collection",
		);

		// Seek to a known position. We reuse the testing function to ensure we're actually there,
		// just in case the test data has been messed with improperly.
		inner(
			&mut collection,
			SeekFrom::Start(7),
			Some(7),
			7,
			"this shouldn't fail",
		);

		// Seeking outside valid bounds should return `None` and *not* move the cursor
		inner(
			&mut collection,
			SeekFrom::Start(usize::MAX),
			None,
			7,
			"`Start(x)` shouldn't move if doing so would put it past one index past the end of the collection",
		);

		inner(
			&mut collection,
			SeekFrom::Current(-isize::MAX),
			None,
			7,
			"`Current(-X)` shouldn't move if doing so would put it past the start of the collection",
		);
		inner(
			&mut collection,
			SeekFrom::Current(isize::MAX),
			None,
			7,
			"`Current(x)` shouldn't move if doing so would put it past the end of the collection",
		);

		inner(
			&mut collection,
			SeekFrom::End(1),
			None,
			7,
			"`End(1)` shouldn't move if doing so would put it past the end of the collection",
		);
		inner(
			&mut collection,
			SeekFrom::End(-isize::MAX),
			None,
			7,
			"`End(-x)` shouldn't move if doing so would put it past the start of the collection",
		);
		inner(
			&mut collection,
			SeekFrom::End(isize::MAX),
			None,
			7,
			"`End(x)` shouldn't move if doing so would put it past the end of the collection",
		);
	}

	fn __clamp_to(
		clamp_method: fn(&mut TestCollection),
		first_test_expected_pos: usize,
		first_test_error_message: &'static str,
	) {
		let mut collection = self::test_collection();

		collection.pos = usize::MAX;
		clamp_method(&mut collection);
		assert_eq!(
			collection.pos, first_test_expected_pos,
			"{}",
			first_test_error_message
		);

		collection.pos = 2;
		clamp_method(&mut collection);
		assert_eq!(
			collection.pos, 2,
			"shouldn't move the cursor when already within the bounds of the collection"
		);

		collection = CollectionCursor::new(TestVec::default());

		collection.pos = 0;
		clamp_method(&mut collection);
		assert_eq!(
			collection.pos, 0,
			"should keep the cursor at index `0` when given an empty collection"
		);

		collection.pos = usize::MAX;
		clamp_method(&mut collection);
		assert_eq!(
			collection.pos, 0,
			"should keep the cursor at index `0` when given an empty collection"
		);
	}

	#[test]
	fn clamp_to_last_item() {
		let collection_len = self::test_collection().inner.len();

		__clamp_to(
			CollectionCursor::clamp_to_last_item,
			collection_len - 1,
			"should move the cursor to the last item of the collection",
		);
	}

	#[test]
	fn clamp_to_end() {
		let collection_len = self::test_collection().inner.len();

		__clamp_to(
			CollectionCursor::clamp_to_end,
			collection_len,
			"should move the cursor to the one index past the last item of the collection",
		);
	}

	#[test]
	fn seek_backward_one() {
		fn inner(
			collection: &mut TestCollection,
			should_succeed: bool,
			expected_new_pos: usize,
			error_message: &'static str,
		) {
			let seek_success = collection.seek_backward_one();
			assert_eq!(seek_success, should_succeed, "{error_message}");
			assert_eq!(
				collection.pos, expected_new_pos,
				"cursor was not moved to the expected position"
			);
		}

		let mut collection = self::test_collection();

		inner(
			&mut collection,
			false,
			0,
			"shouldn't seek past the beginning of the collection",
		);

		collection.pos = 5;
		inner(
			&mut collection,
			true,
			4,
			"should seek backward if within the bounds of the collection",
		);

		collection.pos = usize::MAX;
		inner(
			&mut collection,
			false,
			usize::MAX,
			"shouldn't seek if outside the bounds of the collection",
		);
	}

	#[test]
	fn seek_relative() {
		fn inner(
			collection: &mut TestCollection,
			offset: isize,
			expected_result: Option<usize>,
			expected_pos: usize,
			error_message: &'static str,
		) {
			let seek_res = collection.seek_relative(offset);
			assert_eq!(seek_res, expected_result, "{error_message}");
			assert_eq!(
				collection.pos, expected_pos,
				"the relative seek did not position the cursor as expected"
			);
		}

		let mut collection = self::test_collection();

		inner(&mut collection, 0, Some(0), 0, "shouldn't move at all");

		collection.pos = 5;
		inner(
			&mut collection,
			-2,
			Some(3),
			3,
			"should move when within the bounds of the collection",
		);
		inner(
			&mut collection,
			2,
			Some(5),
			5,
			"should move when within the bounds of the collection",
		);

		inner(&mut collection, 0, Some(5), 5, "shouldn't move at all");

		collection.pos = 5;
		inner(
			&mut collection,
			isize::MAX,
			None,
			5,
			"shouldn't move past the end of the collection",
		);
		inner(
			&mut collection,
			-isize::MAX,
			None,
			5,
			"shouldn't move before the beginning of the collection",
		);

		collection.pos = usize::MAX;
		inner(
			&mut collection,
			5,
			None,
			usize::MAX,
			"shouldn't move when outside the bounds of the collection",
		);
		inner(
			&mut collection,
			-5,
			None,
			usize::MAX,
			"shouldn't move when outside the bounds of the collection",
		);
	}

	#[test]
	fn seek_forward_one() {
		fn inner(
			collection: &mut TestCollection,
			should_succeed: bool,
			expected_new_pos: usize,
			error_message: &'static str,
		) {
			let seek_success = collection.seek_forward_one();
			assert_eq!(seek_success, should_succeed, "{error_message}");
			assert_eq!(
				collection.pos, expected_new_pos,
				"cursor was not moved to the expected position"
			);
		}

		let mut collection = self::test_collection();

		inner(
			&mut collection,
			true,
			1,
			"should seek forward when an item is available",
		);

		collection.pos = 5;
		inner(
			&mut collection,
			true,
			6,
			"should seek forward when an item is available",
		);

		let collection_len = collection.inner.len();

		collection.pos = collection_len - 1;
		inner(
			&mut collection,
			true,
			collection_len,
			"should seek one past the end of the bounds of the collection",
		);

		collection.pos = collection_len;
		inner(
			&mut collection,
			false,
			collection_len,
			"shouldn't seek past one index past the end of the bounds of the collection",
		);

		collection.pos = usize::MAX;
		inner(
			&mut collection,
			false,
			usize::MAX,
			"shouldn't seek at all past `len()` of the collection",
		);
	}

	fn __seek_to(
		seek_method: fn(&mut TestCollection),
		initial_pos: usize,
		expected_new_pos: usize,
	) {
		let mut collection = self::test_collection();
		collection.pos = initial_pos;
		seek_method(&mut collection);
		assert_eq!(
			collection.pos, expected_new_pos,
			"should seek to the expected position"
		);
	}

	#[test]
	fn seek_to_start() {
		// seek_to_start should ALWAYS succeed
		__seek_to(CollectionCursor::seek_to_start, 5, 0);
		__seek_to(CollectionCursor::seek_to_start, usize::MAX, 0);
	}

	#[test]
	fn seek_to_last_item() {
		let expected_pos = self::test_vec().len() - 1;
		__seek_to(CollectionCursor::seek_to_last_item, 5, expected_pos);
		__seek_to(
			CollectionCursor::seek_to_last_item,
			usize::MAX,
			expected_pos,
		);
	}

	#[test]
	fn seek_to_end() {
		// seek_to_end should ALWAYS succeed
		let expected_pos = self::test_collection().inner.len();
		__seek_to(CollectionCursor::seek_to_end, 5, expected_pos);
		__seek_to(CollectionCursor::seek_to_end, usize::MAX, expected_pos);
	}

	#[test]
	fn get_item_at_cursor() {
		let test_vec = self::test_vec();
		let mut collection = self::test_collection();

		// We deliberately request one item past the end, to test if that's also the same
		for i in 0..=(test_vec.len()) {
			collection.pos = i;
			let test_vec_get = test_vec.inner.get(i);
			let collection_get = collection.get_item_at_cursor();

			assert_eq!(
				test_vec_get, collection_get,
				"should get the same item from the same index (index = `{i}`)"
			);
		}
	}

	#[test]
	fn clear() {
		let mut test_vec = self::test_vec();
		let mut collection = self::test_collection();

		test_vec.clear();
		collection.clear();

		assert_eq!(collection.inner, test_vec);
	}

	#[test]
	fn get_item_at_cursor_mut() {
		let mut test_vec = self::test_vec();
		let mut collection = self::test_collection();

		// We deliberately request one item past the end, to test if that's also the same
		for i in 0..=(test_vec.len()) {
			collection.pos = i;
			let test_vec_get = test_vec.inner.get_mut(i);
			let collection_get = collection.get_item_at_cursor_mut();

			assert_eq!(
				test_vec_get, collection_get,
				"should get the same item from the same index (index = `{i}`)"
			);
		}
	}

	#[test]
	fn set_item_at_cursor() {
		let mut test_vec = self::test_vec();
		let mut collection = self::test_collection();

		const AT_POS: usize = 5;
		const TO_VALUE: i32 = 52345;

		test_vec.inner[AT_POS] = TO_VALUE;
		collection.pos = AT_POS;
		collection.set_item_at_cursor(TO_VALUE);

		assert_eq!(
			collection.inner.inner.get(AT_POS),
			Some(&TO_VALUE),
			"should modify the inner collection to have the correct value at the head"
		);
		assert_eq!(collection.inner, test_vec, "should set only one value");
	}

	#[test]
	fn insert_item_at_cursor() {
		let mut test_vec = self::test_vec();
		let mut collection = self::test_collection();

		const AT_POS: usize = 5;
		const TO_VALUE: i32 = 52345;

		test_vec.inner.insert(AT_POS, TO_VALUE);
		collection.pos = AT_POS;
		collection.insert_item_at_cursor(TO_VALUE);

		assert_eq!(
			collection.inner.inner.get(AT_POS),
			Some(&TO_VALUE),
			"should modify the inner collection to have the correct value at the head"
		);
		assert_eq!(collection.inner, test_vec, "should insert only one value");
	}

	#[test]
	fn set_or_insert_item_at_cursor() {
		fn should_set(
			collection: &mut TestCollection,
			test_vec: &mut TestVec,
			at_pos: usize,
			to_value: i32,
		) {
			test_vec.inner[at_pos] = to_value;
			collection.pos = at_pos;
			collection.set_or_insert_item_at_cursor(to_value);

			assert_eq!(
				collection.inner.inner.get(at_pos),
				Some(&to_value),
				"should modify the inner collection to have the correct value at the head"
			);
			assert_eq!(
				collection.inner, *test_vec,
				"should set the value at the cursor's position, when the cursor is not at the end"
			);
		}

		fn should_insert(
			collection: &mut TestCollection,
			test_vec: &mut TestVec,
			at_pos: usize,
			to_value: i32,
		) {
			test_vec.inner.insert(at_pos, to_value);
			collection.pos = at_pos;
			collection.set_or_insert_item_at_cursor(to_value);

			assert_eq!(
				collection.inner.inner.get(at_pos),
				Some(&to_value),
				"should modify the inner collection to have the correct value at the head"
			);
			assert_eq!(
				collection.inner, *test_vec,
				"should insert the value at the end, when the cursor is at the end"
			);
		}

		let mut collection = self::test_collection();
		let mut test_vec = self::test_vec();

		should_set(&mut collection, &mut test_vec, 5, 52345);
		should_insert(&mut collection, &mut test_vec, 10, 67241);

		// We perform the tests again but in reverse order, to ensure that
		// `set_or_insert_item_at_cursor` is actually doing its job, and not just faking it.

		should_insert(&mut collection, &mut test_vec, 11, 34512);
		should_set(&mut collection, &mut test_vec, 7, 51263);
	}

	#[test]
	fn remove_item_at_cursor() {
		const AT_POS: usize = 5;

		let mut test_vec = self::test_vec();
		let mut collection = self::test_collection();

		let test_vec_res = test_vec.inner.remove(5);
		collection.pos = AT_POS;
		let collection_res = collection.remove_item_at_cursor();
		assert_eq!(
			collection_res,
			Some(test_vec_res),
			"should return the right value"
		);
		assert_eq!(collection.inner, test_vec, "should remove only one value");

		// Additionally, test that this does NOT panic when out-of-bounds
		collection.pos = collection.inner.len() * 2;
		let collection_res = collection.remove_item_at_cursor();
		assert_eq!(
			collection_res, None,
			"should return `None` if the head was out-of-bounds"
		);
	}
}