use crate::style::Style;
use std::ops::Range;
#[derive(Clone, Debug, PartialEq)]
pub struct StyledSegment {
pub range: Range<usize>,
pub style: Style,
pub priority: u8,
pub ref_id: Option<u16>,
pub line: Option<usize>,
}
impl StyledSegment {
#[must_use]
pub fn new(range: Range<usize>, style: Style) -> Self {
Self {
range,
style,
priority: 0,
ref_id: None,
line: None,
}
}
#[must_use]
pub fn with_priority(mut self, priority: u8) -> Self {
self.priority = priority;
self
}
#[must_use]
pub fn with_ref(mut self, ref_id: u16) -> Self {
self.ref_id = Some(ref_id);
self
}
#[must_use]
pub fn with_line(mut self, line: usize) -> Self {
self.line = Some(line);
self
}
#[must_use]
pub fn overlaps(&self, other: &Self) -> bool {
self.range.start < other.range.end && other.range.start < self.range.end
}
#[must_use]
pub fn contains(&self, pos: usize) -> bool {
self.range.contains(&pos)
}
#[must_use]
pub fn len(&self) -> usize {
self.range.end - self.range.start
}
#[must_use]
pub fn is_empty(&self) -> bool {
self.range.start >= self.range.end
}
}
#[derive(Clone, Debug)]
pub struct StyledChunk<'a> {
pub text: &'a str,
pub style: Style,
}
impl<'a> StyledChunk<'a> {
#[must_use]
pub fn new(text: &'a str, style: Style) -> Self {
Self { text, style }
}
#[must_use]
pub fn plain(text: &'a str) -> Self {
Self {
text,
style: Style::NONE,
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_segment_overlap() {
let a = StyledSegment::new(0..10, Style::NONE);
let b = StyledSegment::new(5..15, Style::NONE);
let c = StyledSegment::new(10..20, Style::NONE);
assert!(a.overlaps(&b));
assert!(b.overlaps(&a));
assert!(!a.overlaps(&c)); }
#[test]
fn test_segment_contains() {
let seg = StyledSegment::new(5..10, Style::NONE);
assert!(!seg.contains(4));
assert!(seg.contains(5));
assert!(seg.contains(9));
assert!(!seg.contains(10));
}
}