#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct Selection {
index: usize,
count: usize,
}
impl Selection {
#[must_use]
pub const fn new(count: usize) -> Self {
Self { index: 0, count }
}
#[must_use]
pub const fn index(&self) -> usize {
self.index
}
#[must_use]
pub const fn count(&self) -> usize {
self.count
}
#[must_use]
pub const fn is_empty(&self) -> bool {
self.count == 0
}
pub const fn down(&mut self) {
if self.count == 0 {
return;
}
self.index = (self.index + 1) % self.count;
}
pub const fn up(&mut self) {
if self.count == 0 {
return;
}
self.index = if self.index == 0 {
self.count - 1
} else {
self.index - 1
};
}
pub const fn down_by(&mut self, n: usize) {
if self.count == 0 {
return;
}
self.index = (self.index + n) % self.count;
}
pub const fn up_by(&mut self, n: usize) {
if self.count == 0 {
return;
}
self.index = self.index.wrapping_sub(n) % self.count;
}
pub const fn first(&mut self) {
self.index = 0;
}
pub const fn last(&mut self) {
if self.count == 0 {
return;
}
self.index = self.count - 1;
}
pub const fn set(&mut self, index: usize) {
if self.count == 0 {
return;
}
self.index = if index >= self.count {
self.count - 1
} else {
index
};
}
pub const fn clamp_to(&mut self, new_count: usize) {
self.count = new_count;
if new_count == 0 {
self.index = 0;
} else if self.index >= new_count {
self.index = new_count - 1;
}
}
pub const fn reset(&mut self) {
self.index = 0;
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn wraps_down_at_bottom() {
let mut s = Selection::new(3);
s.down();
s.down();
s.down();
assert_eq!(s.index(), 0);
}
#[test]
fn wraps_up_at_top() {
let mut s = Selection::new(3);
s.up();
assert_eq!(s.index(), 2);
}
#[test]
fn empty_list_is_no_op() {
let mut s = Selection::new(0);
s.down();
s.up();
s.first();
s.last();
assert_eq!(s.index(), 0);
assert!(s.is_empty());
}
#[test]
fn clamp_shrinks_below_cursor() {
let mut s = Selection::new(5);
s.last(); s.clamp_to(2); assert_eq!(s.index(), 1);
}
#[test]
fn clamp_grows_keeps_cursor() {
let mut s = Selection::new(3);
s.down(); s.clamp_to(10);
assert_eq!(s.index(), 1);
}
#[test]
fn down_by_wraps() {
let mut s = Selection::new(5);
s.down_by(7); assert_eq!(s.index(), 2);
}
#[test]
fn up_by_wraps() {
let mut s = Selection::new(5);
s.down_by(2); s.up_by(7); let expected = 2_usize.wrapping_sub(7) % 5;
assert_eq!(s.index(), expected);
}
}