use serde::{Deserialize, Serialize};
use crate::{Position, Range};
#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum SelectionKind {
Caret,
LineWise,
BlockWise,
}
#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct Selection {
pub anchor: Position,
pub head: Position,
pub kind: SelectionKind,
}
impl Selection {
#[must_use]
pub const fn new(anchor: Position, head: Position, kind: SelectionKind) -> Self {
Self { anchor, head, kind }
}
#[must_use]
pub const fn caret_at(p: Position) -> Self {
Self {
anchor: p,
head: p,
kind: SelectionKind::Caret,
}
}
#[must_use]
pub fn is_collapsed(&self) -> bool {
self.anchor == self.head
}
#[must_use]
pub fn is_caret(&self) -> bool {
matches!(self.kind, SelectionKind::Caret) && self.is_collapsed()
}
#[must_use]
pub fn range(&self) -> Range {
Range::new(self.anchor, self.head)
}
#[must_use]
pub fn ordered_range(&self) -> Range {
self.range().ordered()
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn caret_at_origin_is_collapsed_and_caret() {
let s = Selection::caret_at(Position::ZERO);
assert!(s.is_collapsed());
assert!(s.is_caret());
}
#[test]
fn linewise_with_extent_is_not_caret() {
let s = Selection {
anchor: Position::ZERO,
head: Position::new(2, 0),
kind: SelectionKind::LineWise,
};
assert!(!s.is_collapsed());
assert!(!s.is_caret());
}
#[test]
fn caret_kind_with_extent_is_not_caret() {
let s = Selection {
anchor: Position::ZERO,
head: Position::new(0, 3),
kind: SelectionKind::Caret,
};
assert!(!s.is_collapsed());
assert!(!s.is_caret());
assert_eq!(s.ordered_range().start, Position::ZERO);
assert_eq!(s.ordered_range().end, Position::new(0, 3));
}
}