From 0b9b54f82d5be56279d7fdfa7d7ff543a7faf64e Mon Sep 17 00:00:00 2001 From: Zixuan Chen Date: Fri, 2 Dec 2022 14:08:37 +0800 Subject: [PATCH] perf: speed up insert & del --- .../loro-core/src/container/text/unicode.rs | 34 +++++++++++++++---- 1 file changed, 27 insertions(+), 7 deletions(-) diff --git a/crates/loro-core/src/container/text/unicode.rs b/crates/loro-core/src/container/text/unicode.rs index 0d352836..2e033aed 100644 --- a/crates/loro-core/src/container/text/unicode.rs +++ b/crates/loro-core/src/container/text/unicode.rs @@ -11,7 +11,7 @@ use rle::{ use super::string_pool::PoolString; #[derive(Debug, Clone, Copy)] -pub(super) struct UnicodeTreeTrait; +pub(super) struct UnicodeTreeTrait; #[derive(Debug, Default, Clone, Copy, PartialEq, Eq)] pub struct TextLength { @@ -25,19 +25,37 @@ impl Add for TextLength { fn add(self, rhs: Self) -> Self::Output { TextLength { utf8: self.utf8 + rhs.utf8, - utf16: self.utf16.and_then(|x| rhs.utf16.map(|y| x + y)), + utf16: if let (Some(a), Some(b)) = (self.utf16, rhs.utf16) { + Some(a + b) + } else { + None + }, } } } impl Sum for TextLength { fn sum>(iter: I) -> Self { - iter.reduce(|a, b| a + b).unwrap_or_default() + let mut u8 = 0; + let mut u16 = Some(0); + for item in iter { + u8 += item.utf8; + if let (Some(a), Some(b)) = (u16, item.utf16) { + u16 = Some(a + b); + } else { + u16 = None; + } + } + + Self { + utf8: u8, + utf16: u16, + } } } -impl RleTreeTrait for UnicodeTreeTrait { - const MAX_CHILDREN_NUM: usize = SIZE as usize; +impl RleTreeTrait for UnicodeTreeTrait { + const MAX_CHILDREN_NUM: usize = SIZE; type Int = usize; @@ -118,7 +136,8 @@ impl RleTreeTrait for UnicodeTreeTrait { } } -pub(super) fn find_pos_internal( +#[inline(always)] +pub(super) fn find_pos_internal( node: &rle::rle_tree::node::InternalNode<'_, PoolString, UnicodeTreeTrait>, mut index: usize, f: &F, @@ -157,7 +176,8 @@ where FindPosResult::new(node.children().len() - 1, last_cache, Position::End) } -pub(super) fn find_pos_leaf( +#[inline(always)] +pub(super) fn find_pos_leaf( node: &rle::rle_tree::node::LeafNode<'_, PoolString, UnicodeTreeTrait>, mut index: usize, f: &F,