| 1 | //! Bounded initial content, constructed by yrs rather than a second wire encoder. |
| 2 | use yrs::branch::{Branch, BranchPtr}; |
| 3 | use yrs::{ |
| 4 | Any, Doc, Map, MapRef, ReadTxn, Transact, XmlElementPrelim, XmlElementRef, XmlFragment, |
| 5 | XmlTextPrelim, |
| 6 | }; |
| 7 | |
| 8 | // Private ABI encoding: repeated [level:u8, utf8_length:u32 big endian, text]. |
| 9 | // Level 0 is a paragraph; 1..6 is a heading. Parse everything before mutation. |
| 10 | pub fn initialize(doc: &Doc, input: &[u8]) -> Result<(), &'static str> { |
| 11 | if doc.client_id() > u32::MAX as u64 { |
| 12 | return Err("client id limit"); |
| 13 | } |
| 14 | if input.len() > 128 * 1024 + 200 * 5 { |
| 15 | return Err("input limit"); |
| 16 | } |
| 17 | let mut rest = input; |
| 18 | let mut blocks = Vec::new(); |
| 19 | let mut total = 0; |
| 20 | while !rest.is_empty() { |
| 21 | if blocks.len() == 200 || rest.len() < 5 || rest[0] > 6 { |
| 22 | return Err("invalid block"); |
| 23 | } |
| 24 | let level = rest[0]; |
| 25 | let n = u32::from_be_bytes(rest[1..5].try_into().unwrap()) as usize; |
| 26 | rest = &rest[5..]; |
| 27 | if n > rest.len() { |
| 28 | return Err("invalid length"); |
| 29 | } |
| 30 | total += n; |
| 31 | if total > 128 * 1024 { |
| 32 | return Err("text limit"); |
| 33 | } |
| 34 | let text = std::str::from_utf8(&rest[..n]).map_err(|_| "invalid utf8")?; |
| 35 | blocks.push((level, text)); |
| 36 | rest = &rest[n..]; |
| 37 | } |
| 38 | if !doc.transact().state_vector().is_empty() { |
| 39 | return Err("document is not empty"); |
| 40 | } |
| 41 | let root = doc.get_or_insert_xml_fragment(crate::FRAGMENT_ROOT); |
| 42 | let mut txn = doc.transact_mut(); |
| 43 | for (level, text) in blocks { |
| 44 | let tag = if level == 0 { "paragraph" } else { "heading" }; |
| 45 | let node = root.push_back(&mut txn, XmlElementPrelim::empty(tag)); |
| 46 | if level > 0 { |
| 47 | // ProseMirror requires a NUMBER. yrs' XML convenience setter stores |
| 48 | // strings, so use the same branch attribute map with a typed value. |
| 49 | let branch = <XmlElementRef as AsRef<Branch>>::as_ref(&node); |
| 50 | MapRef::from(BranchPtr::from(branch)).insert( |
| 51 | &mut txn, |
| 52 | "level", |
| 53 | Any::Number(level as f64), |
| 54 | ); |
| 55 | } |
| 56 | if !text.is_empty() { |
| 57 | node.push_back(&mut txn, XmlTextPrelim::new(text)); |
| 58 | } |
| 59 | } |
| 60 | Ok(()) |
| 61 | } |
| 62 | |