//! Bounded initial content, constructed by yrs rather than a second wire encoder. use yrs::branch::{Branch, BranchPtr}; use yrs::{ Any, Doc, Map, MapRef, ReadTxn, Transact, XmlElementPrelim, XmlElementRef, XmlFragment, XmlTextPrelim, }; // Private ABI encoding: repeated [level:u8, utf8_length:u32 big endian, text]. // Level 0 is a paragraph; 1..6 is a heading. Parse everything before mutation. pub fn initialize(doc: &Doc, input: &[u8]) -> Result<(), &'static str> { if doc.client_id() > u32::MAX as u64 { return Err("client id limit"); } if input.len() > 128 * 1024 + 200 * 5 { return Err("input limit"); } let mut rest = input; let mut blocks = Vec::new(); let mut total = 0; while !rest.is_empty() { if blocks.len() == 200 || rest.len() < 5 || rest[0] > 6 { return Err("invalid block"); } let level = rest[0]; let n = u32::from_be_bytes(rest[1..5].try_into().unwrap()) as usize; rest = &rest[5..]; if n > rest.len() { return Err("invalid length"); } total += n; if total > 128 * 1024 { return Err("text limit"); } let text = std::str::from_utf8(&rest[..n]).map_err(|_| "invalid utf8")?; blocks.push((level, text)); rest = &rest[n..]; } if !doc.transact().state_vector().is_empty() { return Err("document is not empty"); } let root = doc.get_or_insert_xml_fragment(crate::FRAGMENT_ROOT); let mut txn = doc.transact_mut(); for (level, text) in blocks { let tag = if level == 0 { "paragraph" } else { "heading" }; let node = root.push_back(&mut txn, XmlElementPrelim::empty(tag)); if level > 0 { // ProseMirror requires a NUMBER. yrs' XML convenience setter stores // strings, so use the same branch attribute map with a typed value. let branch = >::as_ref(&node); MapRef::from(BranchPtr::from(branch)).insert( &mut txn, "level", Any::Number(level as f64), ); } if !text.is_empty() { node.push_back(&mut txn, XmlTextPrelim::new(text)); } } Ok(()) }