From ad7a1c54ce063192998a8fdff1042a7aa7277347 Mon Sep 17 00:00:00 2001 From: Zixuan Chen Date: Fri, 15 Jul 2022 20:32:35 +0800 Subject: [PATCH] refactor: better insert content trait --- crates/loro-core/src/op/insert_content.rs | 40 ++++++++++++++++++----- crates/rle/src/rle.rs | 2 +- 2 files changed, 33 insertions(+), 9 deletions(-) diff --git a/crates/loro-core/src/op/insert_content.rs b/crates/loro-core/src/op/insert_content.rs index 53916431..c139612d 100644 --- a/crates/loro-core/src/op/insert_content.rs +++ b/crates/loro-core/src/op/insert_content.rs @@ -4,32 +4,56 @@ use crate::id::ID; use rle::{HasLength, Mergable, Sliceable}; #[derive(PartialEq, Eq, Debug, Clone, Copy)] pub enum ContentTypeID { + Container, Text, Custom(u16), } -pub trait MergeableInsertContent { +pub trait MergeableContent { fn is_mergable_content(&self, other: &dyn InsertContent) -> bool; fn merge_content(&mut self, other: &dyn InsertContent); } -pub trait InsertContent: HasLength + std::fmt::Debug + Any + MergeableInsertContent { - fn id(&self) -> ContentTypeID; - fn slice(&self, from: usize, to: usize) -> Box; +pub trait SliceableContent { + fn slice_content(&self, from: usize, to: usize) -> Box; +} + +pub trait CloneContent { fn clone_content(&self) -> Box; } -impl MergeableInsertContent for T { +pub trait InsertContent: + HasLength + std::fmt::Debug + Any + MergeableContent + SliceableContent + CloneContent +{ + fn id(&self) -> ContentTypeID; +} + +impl SliceableContent for T { + fn slice_content(&self, from: usize, to: usize) -> Box { + Box::new(self.slice(from, to)) + } +} + +impl CloneContent for T { + fn clone_content(&self) -> Box { + Box::new(self.clone()) + } +} + +impl MergeableContent for T { fn is_mergable_content(&self, other: &dyn InsertContent) -> bool { if self.type_id() == other.type_id() { - self.is_mergable(unsafe { &*(other as *const dyn Any as *const T) }, &()) + self.is_mergable( + unsafe { &*(other as *const dyn InsertContent as *const T) }, + &(), + ) } else { false } } fn merge_content(&mut self, other: &dyn InsertContent) { - let other = unsafe { &*(other as *const dyn Any as *const T) }; + let other = unsafe { &*(other as *const dyn InsertContent as *const T) }; self.merge(other, &()); } } @@ -40,7 +64,7 @@ pub mod content { let t = TypeId::of::(); let concrete = content.type_id(); if t == concrete { - Some(unsafe { &*(content as *const dyn Any as *const T) }) + Some(unsafe { &*(content as *const dyn InsertContent as *const T) }) } else { None } diff --git a/crates/rle/src/rle.rs b/crates/rle/src/rle.rs index 885cf109..2cd25157 100644 --- a/crates/rle/src/rle.rs +++ b/crates/rle/src/rle.rs @@ -133,7 +133,7 @@ impl + HasLength, Cfg> RleVec { } pub fn slice_merged(&self, range: Range) -> &[T] { - todo!() + &self.vec[range] } }