diff --git a/crates/loro-internal/src/handler.rs b/crates/loro-internal/src/handler.rs index 55969bb1..3912fad2 100644 --- a/crates/loro-internal/src/handler.rs +++ b/crates/loro-internal/src/handler.rs @@ -3615,7 +3615,14 @@ impl MapHandler { pub fn len(&self) -> usize { match &self.inner { MaybeDetached::Detached(m) => m.try_lock().unwrap().value.len(), - MaybeDetached::Attached(a) => a.with_state(|state| state.as_map_state().unwrap().len()), + MaybeDetached::Attached(a) => a.with_state(|state| { + state + .as_map_state() + .unwrap() + .iter() + .filter(|&(_, v)| v.value.is_some()) + .count() + }), } } diff --git a/crates/loro/tests/loro_rust_test.rs b/crates/loro/tests/loro_rust_test.rs index 2d0d1e0e..a8706b8e 100644 --- a/crates/loro/tests/loro_rust_test.rs +++ b/crates/loro/tests/loro_rust_test.rs @@ -854,3 +854,20 @@ fn awareness() { ); assert_eq!(b.get_all_states().get(&2).map(|x| x.state.clone()), None); } + +#[test] +// https://github.com/loro-dev/loro/issues/397 +fn len_and_is_empty_inconsistency() { + let doc = LoroDoc::new(); + let map = doc.get_map("map"); + println!("{:#?}", map); + assert!(map.is_empty()); + map.insert("leaf", 42i64).unwrap(); + println!("{:#?}", map.get("leaf")); + + assert_eq!(map.len(), 1); + map.delete("leaf").unwrap(); + println!("{:#?}", map.get("leaf")); + assert_eq!(map.len(), 0); + assert!(map.is_empty()); +}