mirror of
https://github.com/storytold/craft-libs.git
synced 2026-11-29 17:55:45 +01:00
A document tree that keeps each container's children in an Arc<Vec<_>> and edits them with Arc::make_mut copies the whole child list on every edit while an undo snapshot still holds it. One edit on a layer of 100,000 objects copies 800 KB of handles. SharedVec<T> keeps elements in leaves of up to 64 under a counted B-tree with Arc blocks. get, set, get_mut, insert, remove, push and pop take O(log n) and copy only the blocks on their path; append, split_off, truncate, splice and retain rebuild the branches and keep every leaf they do not change. bytes_not_in and bytes_not_in_with count the blocks and element payloads one list holds and another does not, for undo-history limits. With the serde feature a list reads and writes as a plain sequence, the same bytes as a Vec. The examples/bench.rs example times edits beside a kept snapshot and iteration against Vec.
51 lines
1.6 KiB
Rust
51 lines
1.6 KiB
Rust
//! A list reads and writes as a plain sequence, the same as `Vec<T>`.
|
|
|
|
use std::fmt;
|
|
use std::marker::PhantomData;
|
|
use std::sync::Arc;
|
|
|
|
use serde::de::{SeqAccess, Visitor};
|
|
use serde::{Deserialize, Deserializer, Serialize, Serializer};
|
|
|
|
use crate::SharedVec;
|
|
use crate::node::{self, MAX};
|
|
|
|
impl<T: Serialize> Serialize for SharedVec<T> {
|
|
fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
|
|
serializer.collect_seq(self.iter())
|
|
}
|
|
}
|
|
|
|
impl<'de, T: Deserialize<'de> + Clone> Deserialize<'de> for SharedVec<T> {
|
|
fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
|
|
deserializer.deserialize_seq(SeqVisitor(PhantomData))
|
|
}
|
|
}
|
|
|
|
struct SeqVisitor<T>(PhantomData<T>);
|
|
|
|
impl<'de, T: Deserialize<'de> + Clone> Visitor<'de> for SeqVisitor<T> {
|
|
type Value = SharedVec<T>;
|
|
|
|
fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
|
f.write_str("a sequence")
|
|
}
|
|
|
|
fn visit_seq<A: SeqAccess<'de>>(self, mut seq: A) -> Result<SharedVec<T>, A::Error> {
|
|
// The length the input announces is not used for an allocation: the elements go into
|
|
// blocks as they arrive.
|
|
let mut leaves = Vec::new();
|
|
let mut leaf = Vec::with_capacity(MAX);
|
|
while let Some(value) = seq.next_element()? {
|
|
leaf.push(value);
|
|
if leaf.len() == MAX {
|
|
leaves.push(Arc::new(std::mem::replace(&mut leaf, Vec::with_capacity(MAX))));
|
|
}
|
|
}
|
|
if !leaf.is_empty() {
|
|
leaves.push(Arc::new(leaf));
|
|
}
|
|
Ok(SharedVec { root: node::build(leaves) })
|
|
}
|
|
}
|