1use satteri_arena::{Arena, ArenaBuilder, StringRef};
34use satteri_ast::commands::{CommandError, JsNode};
35use satteri_ast::hast::HastNodeType;
36use satteri_ast::mdast::codec::*;
37use satteri_ast::mdast::MdastNodeType;
38use satteri_ast::rebuild::Patch;
39use satteri_ast::shared::{
40 encode_js_jsx_attrs, PROP_BOOL_FALSE, PROP_BOOL_TRUE, PROP_INT, PROP_NULL, PROP_SPACE_SEP,
41 PROP_STRING,
42};
43
44const CMD_REMOVE: u8 = 0x01;
46const CMD_INSERT_BEFORE: u8 = 0x05;
47const CMD_INSERT_AFTER: u8 = 0x06;
48const CMD_PREPEND_CHILD: u8 = 0x07;
49const CMD_APPEND_CHILD: u8 = 0x08;
50const CMD_WRAP: u8 = 0x09;
51const CMD_REPLACE: u8 = 0x0B;
52const CMD_SET_PROPERTY: u8 = 0x0C;
53
54const PAYLOAD_RAW_MARKDOWN: u8 = 0x10;
55const PAYLOAD_RAW_HTML: u8 = 0x11;
56const PAYLOAD_SERDE_JSON: u8 = 0x12;
57
58const FIELD_DEPTH: u16 = 0x0001;
60const FIELD_URL: u16 = 0x0010;
61const FIELD_TITLE: u16 = 0x0011;
62const FIELD_LANG: u16 = 0x0020;
63const FIELD_META: u16 = 0x0021;
64const FIELD_VALUE: u16 = 0x0022;
65const FIELD_ALT: u16 = 0x0030;
66const FIELD_ORDERED: u16 = 0x0040;
67const FIELD_START: u16 = 0x0041;
68const FIELD_SPREAD: u16 = 0x0042;
69const FIELD_CHECKED: u16 = 0x0050;
70const FIELD_IDENTIFIER: u16 = 0x0060;
71const FIELD_LABEL: u16 = 0x0061;
72const FIELD_REFERENCE_TYPE: u16 = 0x0062;
73const FIELD_NAME: u16 = 0x0070;
74
75struct BufReader<'a> {
76 data: &'a [u8],
77 pos: usize,
78}
79
80impl<'a> BufReader<'a> {
81 fn new(data: &'a [u8]) -> Self {
82 Self { data, pos: 0 }
83 }
84
85 fn remaining(&self) -> usize {
86 self.data.len() - self.pos
87 }
88
89 fn read_u8(&mut self) -> Result<u8, CommandError> {
90 if self.remaining() < 1 {
91 return Err(CommandError::UnexpectedEof);
92 }
93 let v = self.data[self.pos];
94 self.pos += 1;
95 Ok(v)
96 }
97
98 fn read_u32(&mut self) -> Result<u32, CommandError> {
99 if self.remaining() < 4 {
100 return Err(CommandError::UnexpectedEof);
101 }
102 let v = u32::from_le_bytes([
103 self.data[self.pos],
104 self.data[self.pos + 1],
105 self.data[self.pos + 2],
106 self.data[self.pos + 3],
107 ]);
108 self.pos += 4;
109 Ok(v)
110 }
111
112 fn read_bytes(&mut self, len: usize) -> Result<&'a [u8], CommandError> {
113 if self.remaining() < len {
114 return Err(CommandError::UnexpectedEof);
115 }
116 let slice = &self.data[self.pos..self.pos + len];
117 self.pos += len;
118 Ok(slice)
119 }
120
121 fn read_str(&mut self, len: usize) -> Result<&'a str, CommandError> {
122 let bytes = self.read_bytes(len)?;
123 std::str::from_utf8(bytes).map_err(|_| CommandError::InvalidUtf8)
124 }
125}
126
127fn resolve_mdast_field(node_type: u8, name: &str) -> Option<u16> {
129 match (node_type, name) {
130 (2, "depth") => Some(FIELD_DEPTH),
131 (15, "url") | (16, "url") | (9, "url") => Some(FIELD_URL),
132 (15, "title") | (16, "title") | (9, "title") => Some(FIELD_TITLE),
133 (8, "lang") => Some(FIELD_LANG),
134 (8, "meta") | (27, "meta") => Some(FIELD_META),
135 (10 | 13 | 7 | 25 | 26 | 28, "value")
136 | (8, "value")
137 | (27, "value")
138 | (102..=104, "value") => Some(FIELD_VALUE),
139 (16, "alt") => Some(FIELD_ALT),
140 (5, "ordered") => Some(FIELD_ORDERED),
141 (5, "start") => Some(FIELD_START),
142 (5 | 6, "spread") => Some(FIELD_SPREAD),
143 (6, "checked") => Some(FIELD_CHECKED),
144 (9 | 17 | 18 | 19 | 20, "identifier") => Some(FIELD_IDENTIFIER),
145 (9 | 17 | 18 | 19 | 20, "label") => Some(FIELD_LABEL),
146 (17 | 18 | 20, "referenceType") => Some(FIELD_REFERENCE_TYPE),
147 (100 | 101, "name") => Some(FIELD_NAME),
148 _ => None,
149 }
150}
151
152fn apply_set_property(
157 arena: &mut Arena,
158 node_id: u32,
159 prop_name: &str,
160 value_type: u8,
161 value_str: &str,
162) -> Result<(), CommandError> {
163 if prop_name == "data" {
170 if value_type == PROP_NULL {
171 arena.set_node_data(node_id, Vec::new());
172 } else {
173 arena.set_node_data(node_id, value_str.as_bytes().to_vec());
174 }
175 return Ok(());
176 }
177
178 if let Some(result) = apply_hast_set_property(arena, node_id, prop_name, value_type, value_str)
179 {
180 return result;
181 }
182
183 let node_type = arena.get_node(node_id).node_type;
185 let field_id =
186 resolve_mdast_field(node_type, prop_name).ok_or(CommandError::UnknownField(0))?;
187
188 match value_type {
189 PROP_STRING | PROP_SPACE_SEP => {
190 let sref = arena.alloc_string(value_str);
191 set_string_ref(arena, node_id, field_id, sref)
192 }
193 PROP_BOOL_TRUE => apply_mdast_bool(arena, node_id, node_type, field_id, true),
194 PROP_BOOL_FALSE => apply_mdast_bool(arena, node_id, node_type, field_id, false),
195 PROP_INT => {
196 let value: i64 = value_str.parse().unwrap_or(0);
197 apply_mdast_int(arena, node_id, node_type, field_id, value)
198 }
199 PROP_NULL => apply_mdast_null(arena, node_id, node_type, field_id),
200 _ => Err(CommandError::UnknownCommand(value_type)),
201 }
202}
203
204fn apply_mdast_int(
205 arena: &mut Arena,
206 node_id: u32,
207 node_type: u8,
208 field_id: u16,
209 value: i64,
210) -> Result<(), CommandError> {
211 let data_offset = arena.get_node(node_id).data_offset as usize;
212 let data_len = arena.get_node(node_id).data_len as usize;
213 match (node_type, field_id) {
214 (2, FIELD_DEPTH) => {
215 if data_len >= 1 {
216 arena.type_data[data_offset] = value as u8;
217 }
218 }
219 (5, FIELD_START) => {
220 if data_len >= 4 {
221 arena.type_data[data_offset..data_offset + 4]
222 .copy_from_slice(&(value as u32).to_ne_bytes());
223 }
224 }
225 (6, FIELD_CHECKED) => {
226 if data_len >= 1 {
227 arena.type_data[data_offset] = value as u8;
228 }
229 }
230 _ => return Err(CommandError::UnknownField(field_id)),
231 }
232 Ok(())
233}
234
235fn apply_mdast_bool(
236 arena: &mut Arena,
237 node_id: u32,
238 node_type: u8,
239 field_id: u16,
240 value: bool,
241) -> Result<(), CommandError> {
242 let data_offset = arena.get_node(node_id).data_offset as usize;
243 let data_len = arena.get_node(node_id).data_len as usize;
244 match (node_type, field_id) {
245 (5, FIELD_ORDERED) => {
246 if data_len >= 5 {
247 arena.type_data[data_offset + 4] = value as u8;
248 }
249 }
250 (5, FIELD_SPREAD) => {
251 if data_len >= 6 {
252 arena.type_data[data_offset + 5] = value as u8;
253 }
254 }
255 (6, FIELD_SPREAD) => {
256 if data_len >= 2 {
257 arena.type_data[data_offset + 1] = value as u8;
258 }
259 }
260 _ => return Err(CommandError::UnknownField(field_id)),
261 }
262 Ok(())
263}
264
265fn apply_mdast_null(
266 arena: &mut Arena,
267 node_id: u32,
268 node_type: u8,
269 field_id: u16,
270) -> Result<(), CommandError> {
271 match (node_type, field_id) {
272 (6, FIELD_CHECKED) => {
273 let data_offset = arena.get_node(node_id).data_offset as usize;
274 let data_len = arena.get_node(node_id).data_len as usize;
275 if data_len >= 1 {
276 arena.type_data[data_offset] = 2;
277 }
278 Ok(())
279 }
280 _ => set_string_ref(arena, node_id, field_id, StringRef::empty()),
281 }
282}
283
284fn set_string_ref(
285 arena: &mut Arena,
286 node_id: u32,
287 field_id: u16,
288 sref: StringRef,
289) -> Result<(), CommandError> {
290 let node = arena.get_node(node_id);
291 let node_type = node.node_type;
292 let data_offset = node.data_offset as usize;
293
294 let ref_offset = match (node_type, field_id) {
295 (10 | 13 | 7 | 25 | 26 | 28, FIELD_VALUE) => 0,
297 (15, FIELD_URL) => 0,
299 (15, FIELD_TITLE) => 8,
300 (16, FIELD_URL) => 0,
302 (16, FIELD_ALT) => 8,
303 (16, FIELD_TITLE) => 16,
304 (8, FIELD_LANG) => 0,
306 (8, FIELD_META) => 8,
307 (8, FIELD_VALUE) => 16,
308 (27, FIELD_META) => 0,
310 (27, FIELD_VALUE) => 8,
311 (9, FIELD_URL) => 0,
313 (9, FIELD_TITLE) => 8,
314 (9, FIELD_IDENTIFIER) => 16,
315 (9, FIELD_LABEL) => 24,
316 (17 | 18 | 20, FIELD_IDENTIFIER) => 0,
318 (17 | 18 | 20, FIELD_LABEL) => 8,
319 (19, FIELD_IDENTIFIER) => 0,
321 (19, FIELD_LABEL) => 8,
322 (100 | 101, FIELD_NAME) => 0,
324 (102..=104, FIELD_VALUE) => 0,
326 _ => return Err(CommandError::UnknownField(field_id)),
327 };
328
329 let abs_offset = data_offset + ref_offset;
330 let bytes_offset = sref.offset.to_ne_bytes();
331 let bytes_len = sref.len.to_ne_bytes();
332 arena.type_data[abs_offset..abs_offset + 4].copy_from_slice(&bytes_offset);
333 arena.type_data[abs_offset + 4..abs_offset + 8].copy_from_slice(&bytes_len);
334
335 Ok(())
336}
337
338fn parse_raw_markdown(markdown: &str, parse_markdown: &dyn Fn(&str) -> Arena) -> Arena {
339 parse_markdown(markdown)
340}
341
342fn escape_braces_in_html_text(html: &str) -> String {
350 let mut result = String::with_capacity(html.len());
351 let mut in_tag = false;
352 let mut in_quote: Option<char> = None;
353
354 for ch in html.chars() {
355 if in_tag {
356 match ch {
357 '"' | '\'' if in_quote == Some(ch) => {
358 in_quote = None;
359 result.push(ch);
360 }
361 '"' | '\'' if in_quote.is_none() => {
362 in_quote = Some(ch);
363 result.push(ch);
364 }
365 '>' if in_quote.is_none() => {
366 in_tag = false;
367 result.push(ch);
368 }
369 _ => result.push(ch),
370 }
371 } else {
372 match ch {
373 '<' => {
374 in_tag = true;
375 result.push(ch);
376 }
377 '{' => result.push_str("{'{'}"),
378 '}' => result.push_str("{'}'}"),
379 _ => result.push(ch),
380 }
381 }
382 }
383 result
384}
385
386fn js_node_to_arena(js_node: &JsNode) -> Result<(Arena, bool), CommandError> {
387 let mut builder = ArenaBuilder::new(String::new());
388 emit_js_node(js_node, &mut builder)?;
389 Ok((builder.finish(), js_node.keep_children))
390}
391
392fn emit_js_node(js_node: &JsNode, builder: &mut ArenaBuilder) -> Result<(), CommandError> {
393 if js_node.is_hast {
394 return emit_hast_js_node(js_node, builder);
395 }
396
397 let node_type = name_to_node_type(&js_node.node_type)?;
398 builder.open_node(node_type as u8);
399
400 let type_data = encode_js_node_data(js_node, node_type, builder);
401 if !type_data.is_empty() {
402 builder.set_data_current(&type_data);
403 }
404
405 write_js_node_data(js_node, builder)?;
406
407 if let Some(children) = &js_node.children {
408 for child in children {
409 emit_js_node(child, builder)?;
410 }
411 }
412
413 builder.close_node();
414 Ok(())
415}
416
417fn write_js_node_data(js_node: &JsNode, builder: &mut ArenaBuilder) -> Result<(), CommandError> {
418 let Some(data) = &js_node.data else {
419 return Ok(());
420 };
421 let id = builder.current_node_id();
422 let json = serde_json::to_vec(data).map_err(|e| CommandError::InvalidJson(e.to_string()))?;
423 builder.arena_mut().set_node_data(id, json);
424 Ok(())
425}
426
427fn encode_js_node_data(
428 js_node: &JsNode,
429 node_type: MdastNodeType,
430 builder: &mut ArenaBuilder,
431) -> Vec<u8> {
432 match node_type {
433 MdastNodeType::Heading => {
434 let depth = js_node.depth.unwrap_or(1);
435 encode_heading_data(depth)
436 }
437 MdastNodeType::Text
438 | MdastNodeType::InlineCode
439 | MdastNodeType::Html
440 | MdastNodeType::Yaml
441 | MdastNodeType::Toml
442 | MdastNodeType::InlineMath => {
443 let value = js_node.value.as_deref().unwrap_or("");
444 let sref = builder.alloc_string(value);
445 encode_string_ref_data(sref)
446 }
447 MdastNodeType::Code => {
448 let lang_ref = alloc_opt_str(builder, js_node.lang.as_deref());
449 let meta_ref = alloc_opt_str(builder, js_node.meta.as_deref());
450 let value_ref = alloc_opt_str(builder, js_node.value.as_deref());
451 encode_code_data(lang_ref, meta_ref, value_ref, b'`')
452 }
453 MdastNodeType::Math => {
454 let meta_ref = alloc_opt_str(builder, js_node.meta.as_deref());
455 let value_ref = alloc_opt_str(builder, js_node.value.as_deref());
456 encode_math_data(meta_ref, value_ref)
457 }
458 MdastNodeType::Link => {
459 let url_ref = alloc_opt_str(builder, js_node.url.as_deref());
460 let title_ref = alloc_opt_str(builder, js_node.title.as_deref());
461 encode_link_data(url_ref, title_ref)
462 }
463 MdastNodeType::Image => {
464 let url_ref = alloc_opt_str(builder, js_node.url.as_deref());
465 let alt_ref = alloc_opt_str(builder, js_node.alt.as_deref());
466 let title_ref = alloc_opt_str(builder, js_node.title.as_deref());
467 encode_image_data(url_ref, alt_ref, title_ref)
468 }
469 MdastNodeType::Definition => {
470 let url_ref = alloc_opt_str(builder, js_node.url.as_deref());
471 let title_ref = alloc_opt_str(builder, js_node.title.as_deref());
472 let id_ref = alloc_opt_str(builder, js_node.identifier.as_deref());
473 let label_ref = alloc_opt_str(builder, js_node.label.as_deref());
474 encode_definition_data(url_ref, title_ref, id_ref, label_ref)
475 }
476 MdastNodeType::List => {
477 let ordered = js_node.ordered.unwrap_or(false);
478 let start = js_node.start.unwrap_or(1);
479 let spread = js_node.spread.unwrap_or(false);
480 encode_list_data(ordered, start, spread)
481 }
482 MdastNodeType::ListItem => {
483 let checked = match js_node.checked {
484 Some(true) => 1u8,
485 Some(false) => 0u8,
486 None => 2u8, };
488 let spread = js_node.spread.unwrap_or(false);
489 encode_list_item_data(checked, spread)
490 }
491 MdastNodeType::LinkReference
492 | MdastNodeType::ImageReference
493 | MdastNodeType::FootnoteReference => {
494 let id_ref = alloc_opt_str(builder, js_node.identifier.as_deref());
495 let label_ref = alloc_opt_str(builder, js_node.label.as_deref());
496 let kind = match js_node.reference_type.as_deref() {
497 Some("collapsed") => 1u8,
498 Some("full") => 2u8,
499 _ => 0u8, };
501 encode_reference_data(id_ref, label_ref, kind)
502 }
503 MdastNodeType::FootnoteDefinition => {
504 let id_ref = alloc_opt_str(builder, js_node.identifier.as_deref());
505 let label_ref = alloc_opt_str(builder, js_node.label.as_deref());
506 encode_footnote_definition_data(id_ref, label_ref)
507 }
508 MdastNodeType::MdxJsxFlowElement | MdastNodeType::MdxJsxTextElement => {
509 let name_ref = alloc_opt_str(builder, js_node.name.as_deref());
510 let attr_tuples = encode_js_jsx_attrs(builder, js_node.attributes.as_deref());
511 encode_mdx_jsx_element_data(name_ref, &attr_tuples)
512 }
513 MdastNodeType::MdxFlowExpression
514 | MdastNodeType::MdxTextExpression
515 | MdastNodeType::MdxjsEsm => {
516 let value_ref = alloc_opt_str(builder, js_node.value.as_deref());
517 encode_expression_data(value_ref)
518 }
519 _ => Vec::new(),
521 }
522}
523
524fn alloc_opt_str(builder: &mut ArenaBuilder, s: Option<&str>) -> StringRef {
525 match s {
526 Some(v) if !v.is_empty() => builder.alloc_string(v),
527 _ => StringRef::empty(),
528 }
529}
530
531fn name_to_node_type(name: &str) -> Result<MdastNodeType, CommandError> {
532 match name {
533 "root" => Ok(MdastNodeType::Root),
534 "paragraph" => Ok(MdastNodeType::Paragraph),
535 "heading" => Ok(MdastNodeType::Heading),
536 "thematicBreak" => Ok(MdastNodeType::ThematicBreak),
537 "blockquote" => Ok(MdastNodeType::Blockquote),
538 "list" => Ok(MdastNodeType::List),
539 "listItem" => Ok(MdastNodeType::ListItem),
540 "html" => Ok(MdastNodeType::Html),
541 "code" => Ok(MdastNodeType::Code),
542 "definition" => Ok(MdastNodeType::Definition),
543 "text" => Ok(MdastNodeType::Text),
544 "emphasis" => Ok(MdastNodeType::Emphasis),
545 "strong" => Ok(MdastNodeType::Strong),
546 "inlineCode" => Ok(MdastNodeType::InlineCode),
547 "break" => Ok(MdastNodeType::Break),
548 "link" => Ok(MdastNodeType::Link),
549 "image" => Ok(MdastNodeType::Image),
550 "linkReference" => Ok(MdastNodeType::LinkReference),
551 "imageReference" => Ok(MdastNodeType::ImageReference),
552 "footnoteDefinition" => Ok(MdastNodeType::FootnoteDefinition),
553 "footnoteReference" => Ok(MdastNodeType::FootnoteReference),
554 "table" => Ok(MdastNodeType::Table),
555 "tableRow" => Ok(MdastNodeType::TableRow),
556 "tableCell" => Ok(MdastNodeType::TableCell),
557 "delete" => Ok(MdastNodeType::Delete),
558 "yaml" => Ok(MdastNodeType::Yaml),
559 "toml" => Ok(MdastNodeType::Toml),
560 "math" => Ok(MdastNodeType::Math),
561 "inlineMath" => Ok(MdastNodeType::InlineMath),
562 "mdxJsxFlowElement" => Ok(MdastNodeType::MdxJsxFlowElement),
563 "mdxJsxTextElement" => Ok(MdastNodeType::MdxJsxTextElement),
564 "mdxFlowExpression" => Ok(MdastNodeType::MdxFlowExpression),
565 "mdxTextExpression" => Ok(MdastNodeType::MdxTextExpression),
566 "mdxjsEsm" => Ok(MdastNodeType::MdxjsEsm),
567 other => Err(CommandError::UnknownNodeType(other.to_string())),
568 }
569}
570
571fn apply_hast_set_property(
579 arena: &mut Arena,
580 node_id: u32,
581 prop_name: &str,
582 value_type: u8,
583 value_str: &str,
584) -> Option<Result<(), CommandError>> {
585 let node_type = HastNodeType::from_u8(arena.get_node(node_id).node_type)?;
586
587 match node_type {
588 HastNodeType::Element => Some(apply_hast_element_property(
589 arena, node_id, prop_name, value_type, value_str,
590 )),
591
592 HastNodeType::Text
593 | HastNodeType::Comment
594 | HastNodeType::Raw
595 | HastNodeType::MdxFlowExpression
596 | HastNodeType::MdxTextExpression
597 | HastNodeType::MdxEsm
598 if prop_name == "value" =>
599 {
600 let sref = arena.alloc_string(value_str);
601 let data = arena.get_type_data(node_id);
602 if data.len() >= 8 {
603 let data_offset = arena.get_node(node_id).data_offset as usize;
604 arena.type_data[data_offset..data_offset + 4]
605 .copy_from_slice(&sref.offset.to_le_bytes());
606 arena.type_data[data_offset + 4..data_offset + 8]
607 .copy_from_slice(&sref.len.to_le_bytes());
608 Some(Ok(()))
609 } else {
610 Some(Err(CommandError::UnknownField(0)))
611 }
612 }
613
614 _ => None,
615 }
616}
617
618fn apply_hast_element_property(
620 arena: &mut Arena,
621 node_id: u32,
622 prop_name: &str,
623 value_type: u8,
624 value_str: &str,
625) -> Result<(), CommandError> {
626 let old_data = arena.get_type_data(node_id).to_vec();
627 if old_data.len() < 16 {
628 return Err(CommandError::UnexpectedEof);
629 }
630
631 let old_prop_count = u32::from_le_bytes(old_data[8..12].try_into().unwrap()) as usize;
632
633 let mut found_index: Option<usize> = None;
634 for i in 0..old_prop_count {
635 let base = 16 + i * 20;
636 let name_off = u32::from_le_bytes(old_data[base..base + 4].try_into().unwrap());
637 let name_len = u32::from_le_bytes(old_data[base + 4..base + 8].try_into().unwrap());
638 let existing_name = arena.get_str(StringRef::new(name_off, name_len));
639 if existing_name == prop_name {
640 found_index = Some(i);
641 break;
642 }
643 }
644
645 let name_ref = arena.alloc_string(prop_name);
646 let val_ref = if value_str.is_empty() {
647 StringRef::empty()
648 } else {
649 arena.alloc_string(value_str)
650 };
651
652 if let Some(idx) = found_index {
653 let mut new_data = old_data;
654 let base = 16 + idx * 20;
655 new_data[base..base + 4].copy_from_slice(&name_ref.offset.to_le_bytes());
656 new_data[base + 4..base + 8].copy_from_slice(&name_ref.len.to_le_bytes());
657 new_data[base + 8] = value_type;
658 new_data[base + 9..base + 12].copy_from_slice(&[0u8; 3]);
659 new_data[base + 12..base + 16].copy_from_slice(&val_ref.offset.to_le_bytes());
660 new_data[base + 16..base + 20].copy_from_slice(&val_ref.len.to_le_bytes());
661 arena.set_type_data(node_id, &new_data);
662 } else {
663 let new_prop_count = (old_prop_count + 1) as u32;
664 let mut new_data = Vec::with_capacity(16 + new_prop_count as usize * 20);
665 new_data.extend_from_slice(&old_data[0..8]);
666 new_data.extend_from_slice(&new_prop_count.to_le_bytes());
667 new_data.extend_from_slice(&0u32.to_le_bytes());
668 if old_prop_count > 0 {
669 new_data.extend_from_slice(&old_data[16..16 + old_prop_count * 20]);
670 }
671 new_data.extend_from_slice(&name_ref.offset.to_le_bytes());
672 new_data.extend_from_slice(&name_ref.len.to_le_bytes());
673 new_data.push(value_type);
674 new_data.extend_from_slice(&[0u8; 3]);
675 new_data.extend_from_slice(&val_ref.offset.to_le_bytes());
676 new_data.extend_from_slice(&val_ref.len.to_le_bytes());
677 arena.set_type_data(node_id, &new_data);
678 }
679
680 Ok(())
681}
682
683fn emit_hast_js_node(js_node: &JsNode, builder: &mut ArenaBuilder) -> Result<(), CommandError> {
685 let raw_type = name_to_hast_type(&js_node.node_type)
686 .ok_or_else(|| CommandError::UnknownNodeType(js_node.node_type.clone()))?;
687 builder.open_node_raw(raw_type as u8);
688
689 let type_data = encode_hast_js_node_data(js_node, raw_type, builder);
690 if !type_data.is_empty() {
691 builder.set_data_current(&type_data);
692 }
693
694 write_js_node_data(js_node, builder)?;
695
696 if let Some(children) = &js_node.children {
697 for child in children {
698 emit_hast_js_node(child, builder)?;
699 }
700 }
701
702 builder.close_node();
703 Ok(())
704}
705
706fn name_to_hast_type(name: &str) -> Option<HastNodeType> {
707 match name {
708 "root" => Some(HastNodeType::Root),
709 "element" => Some(HastNodeType::Element),
710 "text" => Some(HastNodeType::Text),
711 "comment" => Some(HastNodeType::Comment),
712 "doctype" => Some(HastNodeType::Doctype),
713 "raw" => Some(HastNodeType::Raw),
714 "mdxJsxFlowElement" => Some(HastNodeType::MdxJsxElement),
715 "mdxJsxTextElement" => Some(HastNodeType::MdxJsxTextElement),
716 "mdxFlowExpression" => Some(HastNodeType::MdxFlowExpression),
717 "mdxTextExpression" => Some(HastNodeType::MdxTextExpression),
718 "mdxjsEsm" => Some(HastNodeType::MdxEsm),
719 _ => None,
720 }
721}
722
723fn encode_hast_js_node_data(
724 js_node: &JsNode,
725 node_type: HastNodeType,
726 builder: &mut ArenaBuilder,
727) -> Vec<u8> {
728 match node_type {
729 HastNodeType::Element => {
730 let tag = js_node.tag_name.as_deref().unwrap_or("div");
731 let tag_ref = builder.alloc_string(tag);
732
733 let mut props: Vec<(StringRef, u8, StringRef)> = Vec::new();
734 if let Some(properties) = &js_node.properties {
735 for (key, value) in properties {
736 let name_ref = builder.alloc_string(key);
737 match value {
738 serde_json::Value::Bool(true) => {
739 props.push((name_ref, PROP_BOOL_TRUE, StringRef::empty()));
740 }
741 serde_json::Value::Bool(false) => {
742 props.push((name_ref, PROP_BOOL_FALSE, StringRef::empty()));
743 }
744 serde_json::Value::String(s) => {
745 let val_ref = builder.alloc_string(s);
746 props.push((name_ref, PROP_STRING, val_ref));
747 }
748 serde_json::Value::Number(n) => {
749 let val_ref = builder.alloc_string(&n.to_string());
750 props.push((name_ref, PROP_INT, val_ref));
751 }
752 serde_json::Value::Array(arr) => {
753 let joined: String = arr
754 .iter()
755 .filter_map(|v| v.as_str())
756 .collect::<Vec<_>>()
757 .join(" ");
758 let val_ref = builder.alloc_string(&joined);
759 props.push((name_ref, PROP_SPACE_SEP, val_ref));
760 }
761 _ => {}
762 }
763 }
764 }
765
766 let mut out = Vec::with_capacity(16 + props.len() * 20);
767 out.extend_from_slice(&tag_ref.offset.to_le_bytes());
768 out.extend_from_slice(&tag_ref.len.to_le_bytes());
769 out.extend_from_slice(&(props.len() as u32).to_le_bytes());
770 out.extend_from_slice(&0u32.to_le_bytes());
771 for (name_ref, kind, val_ref) in &props {
772 out.extend_from_slice(&name_ref.offset.to_le_bytes());
773 out.extend_from_slice(&name_ref.len.to_le_bytes());
774 out.push(*kind);
775 out.extend_from_slice(&[0u8; 3]);
776 out.extend_from_slice(&val_ref.offset.to_le_bytes());
777 out.extend_from_slice(&val_ref.len.to_le_bytes());
778 }
779 out
780 }
781
782 HastNodeType::Text | HastNodeType::Comment | HastNodeType::Raw => {
783 let value = js_node.value.as_deref().unwrap_or("");
784 let sref = builder.alloc_string(value);
785 let mut out = [0u8; 8];
786 out[0..4].copy_from_slice(&sref.offset.to_le_bytes());
787 out[4..8].copy_from_slice(&sref.len.to_le_bytes());
788 out.to_vec()
789 }
790
791 HastNodeType::MdxJsxElement | HastNodeType::MdxJsxTextElement => {
792 let name = js_node
793 .name
794 .as_deref()
795 .or(js_node.tag_name.as_deref())
796 .unwrap_or("");
797 let name_ref = builder.alloc_string(name);
798 let attr_tuples = encode_js_jsx_attrs(builder, js_node.attributes.as_deref());
799 encode_mdx_jsx_element_data(name_ref, &attr_tuples)
800 }
801
802 HastNodeType::MdxFlowExpression
803 | HastNodeType::MdxTextExpression
804 | HastNodeType::MdxEsm => {
805 let value = js_node.value.as_deref().unwrap_or("");
806 let sref = builder.alloc_string(value);
807 let mut out = [0u8; 8];
808 out[0..4].copy_from_slice(&sref.offset.to_le_bytes());
809 out[4..8].copy_from_slice(&sref.len.to_le_bytes());
810 out.to_vec()
811 }
812
813 _ => Vec::new(),
814 }
815}
816
817fn read_payload(
819 reader: &mut BufReader<'_>,
820 parse_markdown: &dyn Fn(&str) -> Arena,
821) -> Result<(Arena, bool), CommandError> {
822 let payload_type = reader.read_u8()?;
823 let len = reader.read_u32()? as usize;
824
825 match payload_type {
826 PAYLOAD_RAW_MARKDOWN => {
827 let md = reader.read_str(len)?;
828 Ok((parse_raw_markdown(md, parse_markdown), false))
829 }
830 PAYLOAD_RAW_HTML => {
831 let html = reader.read_str(len)?;
832 let escaped = escape_braces_in_html_text(html);
833 Ok((parse_raw_markdown(&escaped, parse_markdown), false))
834 }
835 PAYLOAD_SERDE_JSON => {
836 let json_str = reader.read_str(len)?;
837 let js_node: JsNode = serde_json::from_str(json_str)
838 .map_err(|e| CommandError::InvalidJson(e.to_string()))?;
839 js_node_to_arena(&js_node)
840 }
841 other => Err(CommandError::UnknownPayloadType(other)),
842 }
843}
844
845pub fn apply_commands(
851 mut arena: Arena,
852 command_buf: &[u8],
853 parse_markdown: &dyn Fn(&str) -> Arena,
854) -> Result<Arena, CommandError> {
855 if command_buf.is_empty() {
856 return Ok(arena);
857 }
858
859 let mut patches: Vec<Patch> = Vec::new();
860 let mut reader = BufReader::new(command_buf);
861
862 while reader.remaining() > 0 {
863 let cmd = reader.read_u8()?;
864
865 match cmd {
866 CMD_REMOVE => {
867 let node_id = reader.read_u32()?;
868 patches.push(Patch::Remove { node_id });
869 }
870
871 CMD_SET_PROPERTY => {
872 let node_id = reader.read_u32()?;
873 let value_type = reader.read_u8()?;
874 let name_len = reader.read_u32()? as usize;
875 let name = reader.read_str(name_len)?;
876 let value_len = reader.read_u32()? as usize;
877 let value = reader.read_str(value_len)?;
878 apply_set_property(&mut arena, node_id, name, value_type, value)?;
879 }
880
881 CMD_INSERT_BEFORE => {
882 let node_id = reader.read_u32()?;
883 let (new_tree, _) = read_payload(&mut reader, parse_markdown)?;
884 patches.push(Patch::InsertBefore { node_id, new_tree });
885 }
886
887 CMD_INSERT_AFTER => {
888 let node_id = reader.read_u32()?;
889 let (new_tree, _) = read_payload(&mut reader, parse_markdown)?;
890 patches.push(Patch::InsertAfter { node_id, new_tree });
891 }
892
893 CMD_PREPEND_CHILD => {
894 let node_id = reader.read_u32()?;
895 let (child_tree, _) = read_payload(&mut reader, parse_markdown)?;
896 patches.push(Patch::PrependChild {
897 node_id,
898 child_tree,
899 });
900 }
901
902 CMD_APPEND_CHILD => {
903 let node_id = reader.read_u32()?;
904 let (child_tree, _) = read_payload(&mut reader, parse_markdown)?;
905 patches.push(Patch::AppendChild {
906 node_id,
907 child_tree,
908 });
909 }
910
911 CMD_WRAP => {
912 let node_id = reader.read_u32()?;
913 let (parent_tree, _) = read_payload(&mut reader, parse_markdown)?;
914 patches.push(Patch::Wrap {
915 node_id,
916 parent_tree,
917 });
918 }
919
920 CMD_REPLACE => {
921 let node_id = reader.read_u32()?;
922 let (new_tree, keep_children) = read_payload(&mut reader, parse_markdown)?;
923 patches.push(Patch::Replace {
924 node_id,
925 new_tree,
926 keep_children,
927 });
928 }
929
930 other => return Err(CommandError::UnknownCommand(other)),
931 }
932 }
933
934 if patches.is_empty() {
935 Ok(arena)
936 } else {
937 satteri_ast::rebuild::rebuild(&arena, &patches)
938 }
939}
940
941#[cfg(test)]
942mod tests {
943 use super::*;
944 use satteri_ast::shared::PROP_INT;
945
946 fn test_parse_markdown(source: &str) -> Arena {
947 let mut b = ArenaBuilder::new(String::new());
948 b.open_node(MdastNodeType::Root as u8);
949 b.open_node(MdastNodeType::Paragraph as u8);
950 b.open_node(MdastNodeType::Text as u8);
951 let sref = b.alloc_string(source);
952 b.set_data_current(&satteri_arena::encode_string_ref_data(sref));
953 b.close_node();
954 b.close_node();
955 b.close_node();
956 b.finish()
957 }
958
959 fn push_u32(buf: &mut Vec<u8>, v: u32) {
960 buf.extend_from_slice(&v.to_le_bytes());
961 }
962
963 fn push_set_property(buf: &mut Vec<u8>, node_id: u32, value_type: u8, name: &str, value: &str) {
965 buf.push(CMD_SET_PROPERTY);
966 push_u32(buf, node_id);
967 buf.push(value_type);
968 push_u32(buf, name.len() as u32);
969 buf.extend_from_slice(name.as_bytes());
970 push_u32(buf, value.len() as u32);
971 buf.extend_from_slice(value.as_bytes());
972 }
973
974 fn build_hello_world() -> Arena {
975 use satteri_ast::mdast::codec::{encode_heading_data, encode_string_ref_data};
976
977 let source = "# Hello\n\nWorld".to_string();
978 let mut b = ArenaBuilder::new(source);
979
980 b.open_node(MdastNodeType::Root as u8);
981 b.set_position_current(0, 14, 1, 1, 2, 6);
982
983 b.open_node(MdastNodeType::Heading as u8);
984 b.set_position_current(0, 7, 1, 1, 1, 8);
985 b.set_data_current(&encode_heading_data(1));
986
987 b.open_node(MdastNodeType::Text as u8);
988 b.set_position_current(2, 7, 1, 3, 1, 8);
989 b.set_data_current(&encode_string_ref_data(StringRef::new(2, 5)));
990 b.close_node();
991
992 b.close_node();
993
994 b.open_node(MdastNodeType::Paragraph as u8);
995 b.set_position_current(9, 14, 2, 1, 2, 6);
996
997 b.open_node(MdastNodeType::Text as u8);
998 b.set_position_current(9, 14, 2, 1, 2, 6);
999 b.set_data_current(&encode_string_ref_data(StringRef::new(9, 5)));
1000 b.close_node();
1001
1002 b.close_node();
1003 b.close_node();
1004
1005 b.finish()
1006 }
1007
1008 #[test]
1009 fn empty_command_buffer() {
1010 let arena = build_hello_world();
1011 let result = apply_commands(arena.clone(), &[], &test_parse_markdown).unwrap();
1012 assert_eq!(result.len(), arena.len());
1013 }
1014
1015 #[test]
1016 fn remove_command() {
1017 let arena = build_hello_world();
1018 let heading_id = arena.get_children(0)[0];
1019 let mut buf = Vec::new();
1020 buf.push(CMD_REMOVE);
1021 push_u32(&mut buf, heading_id);
1022
1023 let result = apply_commands(arena.clone(), &buf, &test_parse_markdown).unwrap();
1024 assert_eq!(result.get_children(0).len(), 1);
1025 assert_eq!(
1026 result.get_node(result.get_children(0)[0]).node_type,
1027 MdastNodeType::Paragraph as u8
1028 );
1029 }
1030
1031 #[test]
1032 fn set_property_heading_depth() {
1033 let arena = build_hello_world();
1034 let heading_id = arena.get_children(0)[0];
1035
1036 let mut buf = Vec::new();
1037 push_set_property(&mut buf, heading_id, PROP_INT, "depth", "3");
1038
1039 let result = apply_commands(arena.clone(), &buf, &test_parse_markdown).unwrap();
1040 let heading_data = result.get_type_data(heading_id);
1041 let heading = decode_heading_data(heading_data);
1042 assert_eq!(heading.depth, 3);
1043 }
1044
1045 #[test]
1046 fn set_property_text_value() {
1047 let arena = build_hello_world();
1048 let heading_id = arena.get_children(0)[0];
1049 let text_id = arena.get_children(heading_id)[0];
1050
1051 let mut buf = Vec::new();
1052 push_set_property(&mut buf, text_id, PROP_STRING, "value", "Goodbye");
1053
1054 let result = apply_commands(arena.clone(), &buf, &test_parse_markdown).unwrap();
1055 let text_data = result.get_type_data(text_id);
1056 let sref = decode_string_ref_data(text_data);
1057 assert_eq!(result.get_str(sref), "Goodbye");
1058 }
1059
1060 #[test]
1061 fn replace_with_raw_markdown() {
1062 let arena = build_hello_world();
1063 let heading_id = arena.get_children(0)[0];
1064
1065 let raw_md = "## New Heading";
1066 let mut buf = Vec::new();
1067 buf.push(CMD_REPLACE);
1068 push_u32(&mut buf, heading_id);
1069 buf.push(PAYLOAD_RAW_MARKDOWN);
1070 push_u32(&mut buf, raw_md.len() as u32);
1071 buf.extend_from_slice(raw_md.as_bytes());
1072
1073 let result = apply_commands(arena.clone(), &buf, &test_parse_markdown).unwrap();
1074 let root_children = result.get_children(0);
1075 assert!(root_children.len() >= 2);
1076 }
1077
1078 #[test]
1079 fn replace_with_serde_json() {
1080 let arena = build_hello_world();
1081 let heading_id = arena.get_children(0)[0];
1082
1083 let json =
1084 r#"{"type":"heading","depth":2,"children":[{"type":"text","value":"Replaced"}]}"#;
1085 let mut buf = Vec::new();
1086 buf.push(CMD_REPLACE);
1087 push_u32(&mut buf, heading_id);
1088 buf.push(PAYLOAD_SERDE_JSON);
1089 push_u32(&mut buf, json.len() as u32);
1090 buf.extend_from_slice(json.as_bytes());
1091
1092 let result = apply_commands(arena.clone(), &buf, &test_parse_markdown).unwrap();
1093 let root_children = result.get_children(0);
1094 assert_eq!(root_children.len(), 2);
1095 let new_heading = root_children[0];
1096 assert_eq!(
1097 result.get_node(new_heading).node_type,
1098 MdastNodeType::Heading as u8
1099 );
1100 let heading_data = result.get_type_data(new_heading);
1101 assert_eq!(decode_heading_data(heading_data).depth, 2);
1102 }
1103
1104 #[test]
1105 fn multiple_commands() {
1106 let arena = build_hello_world();
1107 let heading_id = arena.get_children(0)[0];
1108 let text_id = arena.get_children(heading_id)[0];
1109
1110 let mut buf = Vec::new();
1111 push_set_property(&mut buf, heading_id, PROP_INT, "depth", "3");
1112 push_set_property(&mut buf, text_id, PROP_STRING, "value", "Hi");
1113
1114 let result = apply_commands(arena.clone(), &buf, &test_parse_markdown).unwrap();
1115
1116 let heading_data = result.get_type_data(heading_id);
1117 assert_eq!(decode_heading_data(heading_data).depth, 3);
1118
1119 let text_data = result.get_type_data(text_id);
1120 let sref = decode_string_ref_data(text_data);
1121 assert_eq!(result.get_str(sref), "Hi");
1122 }
1123
1124 #[test]
1125 fn set_property_null() {
1126 let arena = build_hello_world();
1127 let heading_id = arena.get_children(0)[0];
1128 let text_id = arena.get_children(heading_id)[0];
1129
1130 let mut buf = Vec::new();
1131 push_set_property(&mut buf, text_id, PROP_NULL, "value", "");
1132
1133 let result = apply_commands(arena.clone(), &buf, &test_parse_markdown).unwrap();
1134 let text_data = result.get_type_data(text_id);
1135 let sref = decode_string_ref_data(text_data);
1136 assert_eq!(sref.len, 0);
1137 }
1138
1139 #[test]
1140 fn js_node_to_arena_basic() {
1141 let js = JsNode {
1142 node_type: "heading".to_string(),
1143 children: Some(vec![JsNode {
1144 node_type: "text".to_string(),
1145 children: None,
1146 value: Some("Hello".to_string()),
1147 depth: None,
1148 url: None,
1149 title: None,
1150 alt: None,
1151 lang: None,
1152 meta: None,
1153 ordered: None,
1154 start: None,
1155 spread: None,
1156 checked: None,
1157 identifier: None,
1158 label: None,
1159 reference_type: None,
1160 name: None,
1161 attributes: None,
1162 tag_name: None,
1163 properties: None,
1164 is_hast: false,
1165 keep_children: false,
1166 data: None,
1167 }]),
1168 depth: Some(2),
1169 value: None,
1170 url: None,
1171 title: None,
1172 alt: None,
1173 lang: None,
1174 meta: None,
1175 ordered: None,
1176 start: None,
1177 spread: None,
1178 checked: None,
1179 identifier: None,
1180 label: None,
1181 reference_type: None,
1182 name: None,
1183 attributes: None,
1184 tag_name: None,
1185 properties: None,
1186 is_hast: false,
1187 keep_children: false,
1188 data: None,
1189 };
1190
1191 let (arena, _keep) = js_node_to_arena(&js).unwrap();
1192 assert_eq!(arena.len(), 2);
1193 assert_eq!(arena.get_node(0).node_type, MdastNodeType::Heading as u8);
1194 assert_eq!(arena.get_children(0).len(), 1);
1195 let text_id = arena.get_children(0)[0];
1196 assert_eq!(arena.get_node(text_id).node_type, MdastNodeType::Text as u8);
1197 }
1198
1199 #[test]
1200 fn escape_braces_in_html_text_basic() {
1201 assert_eq!(
1202 escape_braces_in_html_text("<span>{foo: 1}</span>"),
1203 "<span>{'{'}foo: 1{'}'}</span>"
1204 );
1205 }
1206
1207 #[test]
1208 fn escape_braces_preserves_attributes() {
1209 let result = escape_braces_in_html_text(r#"<span data-x="{a}">{b}</span>"#);
1210 assert!(
1211 result.contains(r#"data-x="{a}""#),
1212 "attribute braces preserved"
1213 );
1214 assert!(result.contains("{'{'}"), "text braces escaped");
1215 }
1216
1217 #[test]
1218 fn escape_braces_no_braces() {
1219 let html = r#"<pre class="shiki"><code><span style="color:red">hello</span></code></pre>"#;
1220 assert_eq!(escape_braces_in_html_text(html), html);
1221 }
1222
1223 #[test]
1224 fn escape_braces_shiki_output() {
1225 let html = r#"<pre class="shiki"><code><span style="color:#E1E4E8">const x = </span><span style="color:#B392F0">{</span><span style="color:#E1E4E8">foo: 1</span><span style="color:#B392F0">}</span></code></pre>"#;
1226 let escaped = escape_braces_in_html_text(html);
1227 assert!(
1228 !escaped.contains(">{<"),
1229 "bare braces in text should be escaped"
1230 );
1231 assert!(
1232 !escaped.contains(">}<"),
1233 "bare braces in text should be escaped"
1234 );
1235 assert!(escaped.contains(r#"class="shiki""#));
1236 assert!(escaped.contains(r#"style="color:#E1E4E8""#));
1237 }
1238
1239 #[test]
1240 fn hast_set_property_add_new() {
1241 let arena = build_hast_element(&[]);
1242 let element_id = arena.get_children(0)[0];
1243
1244 let mut buf = Vec::new();
1245 push_set_property(&mut buf, element_id, PROP_STRING, "class", "test");
1246
1247 let result = apply_commands(arena.clone(), &buf, &test_parse_markdown).unwrap();
1248 let data = result.get_type_data(element_id);
1249 let prop_count = u32::from_le_bytes(data[8..12].try_into().unwrap());
1250 assert_eq!(prop_count, 1);
1251 let name_ref = StringRef::new(
1252 u32::from_le_bytes(data[16..20].try_into().unwrap()),
1253 u32::from_le_bytes(data[20..24].try_into().unwrap()),
1254 );
1255 assert_eq!(result.get_str(name_ref), "class");
1256 let val_ref = StringRef::new(
1257 u32::from_le_bytes(data[28..32].try_into().unwrap()),
1258 u32::from_le_bytes(data[32..36].try_into().unwrap()),
1259 );
1260 assert_eq!(result.get_str(val_ref), "test");
1261 assert_eq!(data[24], PROP_STRING);
1262 }
1263
1264 #[test]
1265 fn hast_set_property_overwrite_existing() {
1266 let arena = build_hast_element(&[("class", PROP_STRING, "old")]);
1267 let element_id = arena.get_children(0)[0];
1268
1269 let mut buf = Vec::new();
1270 push_set_property(&mut buf, element_id, PROP_STRING, "class", "new-value");
1271
1272 let result = apply_commands(arena.clone(), &buf, &test_parse_markdown).unwrap();
1273 let data = result.get_type_data(element_id);
1274 let prop_count = u32::from_le_bytes(data[8..12].try_into().unwrap());
1275 assert_eq!(prop_count, 1);
1276 let val_ref = StringRef::new(
1277 u32::from_le_bytes(data[28..32].try_into().unwrap()),
1278 u32::from_le_bytes(data[32..36].try_into().unwrap()),
1279 );
1280 assert_eq!(result.get_str(val_ref), "new-value");
1281 }
1282
1283 #[test]
1284 fn hast_set_property_bool_true() {
1285 let arena = build_hast_element(&[]);
1286 let element_id = arena.get_children(0)[0];
1287
1288 let mut buf = Vec::new();
1289 push_set_property(&mut buf, element_id, PROP_BOOL_TRUE, "disabled", "");
1290
1291 let result = apply_commands(arena.clone(), &buf, &test_parse_markdown).unwrap();
1292 let data = result.get_type_data(element_id);
1293 let prop_count = u32::from_le_bytes(data[8..12].try_into().unwrap());
1294 assert_eq!(prop_count, 1);
1295 assert_eq!(data[24], PROP_BOOL_TRUE);
1296 }
1297
1298 #[test]
1299 fn hast_set_property_multiple_on_same_node() {
1300 let arena = build_hast_element(&[]);
1301 let element_id = arena.get_children(0)[0];
1302
1303 let mut buf = Vec::new();
1304 push_set_property(&mut buf, element_id, PROP_STRING, "class", "foo");
1305 push_set_property(&mut buf, element_id, PROP_STRING, "id", "bar");
1306
1307 let result = apply_commands(arena.clone(), &buf, &test_parse_markdown).unwrap();
1308 let data = result.get_type_data(element_id);
1309 let prop_count = u32::from_le_bytes(data[8..12].try_into().unwrap());
1310 assert_eq!(prop_count, 2);
1311 }
1312
1313 fn build_hast_element(props: &[(&str, u8, &str)]) -> Arena {
1315 use satteri_ast::hast::node::HastNodeType;
1316
1317 let mut b = ArenaBuilder::new(String::new());
1318 b.open_node_raw(HastNodeType::Root as u8);
1319 b.open_node_raw(HastNodeType::Element as u8);
1320 let tag_ref = b.alloc_string("div");
1321 let prop_tuples: Vec<(StringRef, u8, StringRef)> = props
1322 .iter()
1323 .map(|(name, kind, value)| {
1324 let n = b.alloc_string(name);
1325 let v = if value.is_empty() {
1326 StringRef::empty()
1327 } else {
1328 b.alloc_string(value)
1329 };
1330 (n, *kind, v)
1331 })
1332 .collect();
1333 let mut type_data = Vec::with_capacity(16 + prop_tuples.len() * 20);
1334 type_data.extend_from_slice(&tag_ref.offset.to_le_bytes());
1335 type_data.extend_from_slice(&tag_ref.len.to_le_bytes());
1336 type_data.extend_from_slice(&(prop_tuples.len() as u32).to_le_bytes());
1337 type_data.extend_from_slice(&0u32.to_le_bytes());
1338 for (n, kind, v) in &prop_tuples {
1339 type_data.extend_from_slice(&n.offset.to_le_bytes());
1340 type_data.extend_from_slice(&n.len.to_le_bytes());
1341 type_data.push(*kind);
1342 type_data.extend_from_slice(&[0u8; 3]);
1343 type_data.extend_from_slice(&v.offset.to_le_bytes());
1344 type_data.extend_from_slice(&v.len.to_le_bytes());
1345 }
1346 b.set_data_current(&type_data);
1347 b.close_node();
1348 b.close_node();
1349 b.finish()
1350 }
1351}