loro/crates/rle/src/rle_trait.rs

87 lines
2.3 KiB
Rust
Raw Normal View History

2022-10-24 03:51:36 +00:00
use std::fmt::Debug;
2022-08-05 12:04:49 +00:00
2022-10-24 03:51:36 +00:00
use num::{traits::AsPrimitive, FromPrimitive, Integer};
2022-08-05 10:47:51 +00:00
2022-07-26 18:24:25 +00:00
pub trait Mergable<Cfg = ()> {
fn is_mergable(&self, _other: &Self, _conf: &Cfg) -> bool
where
Self: Sized,
{
false
}
fn merge(&mut self, _other: &Self, _conf: &Cfg)
where
Self: Sized,
{
unreachable!()
}
}
2022-10-22 15:01:55 +00:00
/// NOTE: [Sliceable] implementation should be coherent with [Mergable]:
///
/// - For all k, a.slice(0,k).merge(a.slice(k, a.len())) == a
2022-07-26 18:24:25 +00:00
pub trait Sliceable {
fn slice(&self, from: usize, to: usize) -> Self;
}
#[derive(Debug, Clone, Copy)]
pub struct Slice<'a, T> {
pub value: &'a T,
pub start: usize,
pub end: usize,
}
impl<T: Sliceable> Slice<'_, T> {
pub fn into_inner(&self) -> T {
self.value.slice(self.start, self.end)
}
}
2022-10-12 03:31:07 +00:00
#[allow(clippy::len_without_is_empty)]
2022-07-26 18:24:25 +00:00
pub trait HasLength {
2022-10-24 06:48:08 +00:00
/// It is the length of the content, i.e. the length when no [Mergable::merge] ever happen.
///
/// However, when the content is deleted, [HasLength::content_len] is expected to be zero in some [crate::RleTree] use cases
fn content_len(&self) -> usize;
/// It is the length of the atom element underneath, i.e. the length when no [Mergable::merge] ever happen.
///
/// It is the same as [HasLength::atom_len] in the most of the cases.
/// However, oppose to [HasLength::atom_len], when the content is deleted, [HasLength::content_len] should not change
fn atom_len(&self) -> usize {
self.content_len()
}
2022-07-26 18:24:25 +00:00
}
2022-10-11 08:50:22 +00:00
pub trait Rle<Cfg = ()>: HasLength + Sliceable + Mergable<Cfg> + Debug + Clone {}
2022-07-26 18:24:25 +00:00
2022-10-12 17:24:47 +00:00
pub trait ZeroElement {
fn zero_element() -> Self;
}
impl<T: Default> ZeroElement for T {
fn zero_element() -> Self {
Default::default()
}
}
2022-10-11 08:50:22 +00:00
impl<T: HasLength + Sliceable + Mergable<Cfg> + Debug + Clone, Cfg> Rle<Cfg> for T {}
2022-08-05 12:04:49 +00:00
2022-10-24 03:51:36 +00:00
pub trait HasIndex: HasLength {
type Int: GlobalIndex;
fn get_start_index(&self) -> Self::Int;
2022-08-05 12:04:49 +00:00
2022-10-24 03:51:36 +00:00
#[inline]
fn get_end_index(&self) -> Self::Int {
2022-10-24 09:17:27 +00:00
self.get_start_index() + Self::Int::from_usize(self.atom_len()).unwrap()
2022-08-05 12:04:49 +00:00
}
}
2022-10-24 03:51:36 +00:00
pub trait GlobalIndex:
Debug + Integer + Copy + Default + FromPrimitive + AsPrimitive<usize>
{
2022-08-05 12:04:49 +00:00
}
2022-10-18 13:54:32 +00:00
2022-10-24 03:51:36 +00:00
impl<T: Debug + Integer + Copy + Default + FromPrimitive + AsPrimitive<usize>> GlobalIndex for T {}