fix: when computing the len of the map, do not count elements that are None (#402)

This commit is contained in:
Yang Si 2024-07-14 16:40:46 +08:00 committed by GitHub
parent cc5ca7d296
commit ce88b326dd
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
2 changed files with 25 additions and 1 deletions

View file

@ -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()
}),
}
}

View file

@ -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());
}