From 89a5ee4a8a9359bd82a154c16057c9f40ffec122 Mon Sep 17 00:00:00 2001 From: appflowy Date: Thu, 8 Sep 2022 17:47:53 +0800 Subject: [PATCH] fix: potential crash while calling apply_insert if the path is empty --- shared-lib/lib-ot/src/core/document/document.rs | 13 +++++++------ shared-lib/lib-ot/src/core/document/position.rs | 6 ++++++ 2 files changed, 13 insertions(+), 6 deletions(-) diff --git a/shared-lib/lib-ot/src/core/document/document.rs b/shared-lib/lib-ot/src/core/document/document.rs index 95508237a4..a20457a656 100644 --- a/shared-lib/lib-ot/src/core/document/document.rs +++ b/shared-lib/lib-ot/src/core/document/document.rs @@ -121,14 +121,15 @@ impl DocumentTree { } fn apply_insert(&mut self, path: &Path, nodes: &[NodeSubTree]) -> Result<(), OTError> { + debug_assert!(!path.is_empty()); + if path.is_empty() { + return Err(OTErrorCode::PathIsEmpty.into()); + } - - let parent_path = &path.0[0..(path.0.len() - 1)]; - let last_index = path.0[path.0.len() - 1]; - - + let (parent_path, last_path) = path.split_at(path.0.len() - 1); + let last_index = *last_path.first().unwrap(); let parent_node = self - .node_at_path(&Path(parent_path.to_vec())) + .node_at_path(parent_path) .ok_or_else(|| ErrorBuilder::new(OTErrorCode::PathNotFound).build())?; self.insert_child_at_index(parent_node, last_index, nodes) diff --git a/shared-lib/lib-ot/src/core/document/position.rs b/shared-lib/lib-ot/src/core/document/position.rs index 697bde8177..e45c2556d6 100644 --- a/shared-lib/lib-ot/src/core/document/position.rs +++ b/shared-lib/lib-ot/src/core/document/position.rs @@ -39,6 +39,12 @@ impl From<&Vec> for Path { } } +impl From<&[usize]> for Path { + fn from(values: &[usize]) -> Self { + Path(values.to_vec()) + } +} + impl Path { // delta is default to be 1