1use crate::parse::MAX_DEPTH;
2use crate::tree::{self, Comment, Decor, Entries, Entry, Item, Key, Member, Node, Object, Printer};
3use crate::{Error, Value};
4use std::borrow::Cow;
5use std::fmt::{self, Display, Write as _};
6use std::str::FromStr;
7
8#[derive(Debug, Clone, PartialEq)]
35pub struct Document {
36 outer: Decor,
40 root: Node,
41 source: String,
42}
43
44#[derive(Debug, Clone, Copy, PartialEq, Eq)]
48pub enum PathSegment<'a> {
49 Key(&'a str),
53 Index(usize),
57}
58
59impl<'a> From<&'a str> for PathSegment<'a> {
60 fn from(key: &'a str) -> Self {
61 Self::Key(key)
62 }
63}
64
65impl<'a> From<&'a String> for PathSegment<'a> {
66 fn from(key: &'a String) -> Self {
67 Self::Key(key)
68 }
69}
70
71impl From<usize> for PathSegment<'_> {
72 fn from(index: usize) -> Self {
73 Self::Index(index)
74 }
75}
76
77impl Display for PathSegment<'_> {
78 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
79 match self {
80 Self::Key(key) => crate::write::write_key(formatter, key),
81 Self::Index(index) => write!(formatter, "[{index}]"),
82 }
83 }
84}
85
86fn path_segments<'a>(
90 path: impl IntoIterator<Item = impl Into<PathSegment<'a>>>,
91) -> Result<Vec<PathSegment<'a>>, Error> {
92 let path: Vec<PathSegment<'a>> = path.into_iter().map(Into::into).collect();
93
94 if path.is_empty() {
95 return Err(Error::data(
96 "The path must be a non-empty array of keys and array indexes",
97 ));
98 }
99
100 Ok(path)
101}
102
103#[cold]
107fn path_error(path: &[PathSegment<'_>], index: usize, reason: &str) -> Error {
108 Error::data(format!(
109 "Cannot edit {}, because {} {reason}",
110 describe_path(path),
111 describe_parent(path, index)
112 ))
113}
114
115fn describe_path(path: &[PathSegment<'_>]) -> String {
119 let mut text = String::with_capacity(256);
120 let mut length = 0;
121
122 for (position, segment) in path.iter().enumerate() {
123 let start = text.len();
124 match segment {
125 PathSegment::Key(key) => {
126 if position > 0 {
127 text.push('.');
128 }
129
130 crate::parse::write_described_key(&mut text, key);
131 }
132 PathSegment::Index(index) => {
133 write!(text, "[{index}]").expect("writing to a String does not fail");
134 }
135 }
136 length += text[start..].encode_utf16().count();
137 if length > 200 {
138 break;
139 }
140 }
141
142 let needs_escape = |character: char| {
143 character.is_control()
144 || matches!(character, '\u{2028}' | '\u{2029}')
145 || is_format_character(character)
146 };
147 let shortened = crate::abbreviate(&text, 200);
148 let Some((start, _)) = shortened
149 .char_indices()
150 .find(|&(_, character)| needs_escape(character))
151 else {
152 return match shortened {
154 Cow::Owned(text) => text,
155 Cow::Borrowed(_) => text,
156 };
157 };
158 let mut description = String::with_capacity(shortened.len());
159 description.push_str(&shortened[..start]);
160
161 for character in shortened[start..].chars() {
162 if needs_escape(character) {
164 description.extend(character.escape_unicode());
165 } else {
166 description.push(character);
167 }
168 }
169
170 description
171}
172
173fn describe_parent(path: &[PathSegment<'_>], index: usize) -> String {
177 if index == 0 {
178 "the document".to_owned()
179 } else {
180 describe_path(&path[..index])
181 }
182}
183
184const fn is_format_character(character: char) -> bool {
188 matches!(
189 character,
190 '\u{AD}'
191 | '\u{600}'..='\u{605}'
192 | '\u{61C}'
193 | '\u{6DD}'
194 | '\u{70F}'
195 | '\u{890}'..='\u{891}'
196 | '\u{8E2}'
197 | '\u{180E}'
198 | '\u{200B}'..='\u{200F}'
199 | '\u{202A}'..='\u{202E}'
200 | '\u{2060}'..='\u{2064}'
201 | '\u{2066}'..='\u{206F}'
202 | '\u{FEFF}'
203 | '\u{FFF9}'..='\u{FFFB}'
204 | '\u{110BD}'
205 | '\u{110CD}'
206 | '\u{13430}'..='\u{1343F}'
207 | '\u{1BCA0}'..='\u{1BCA3}'
208 | '\u{1D173}'..='\u{1D17A}'
209 | '\u{E0001}'
210 | '\u{E0020}'..='\u{E007F}'
211 )
212}
213
214fn line_indentation(separator: &str, inherited: &str) -> String {
218 last_line_start(separator)
219 .map_or(inherited, |start| tree::indentation_of(&separator[start..]))
220 .to_owned()
221}
222
223fn comment_lines(leading: &str) -> &str {
227 last_line_start(leading).map_or("", |start| &leading[..start])
228}
229
230fn own_line(leading: &str) -> &str {
234 last_line_start(leading).map_or(leading, |start| &leading[start..])
235}
236
237fn last_line_start(decor: &str) -> Option<usize> {
241 tree::decor_parts(decor)
243 .filter(|(part, _)| *part == tree::DecorPart::LineFeed)
244 .last()
245 .map(|(_, range)| range.end)
246}
247
248#[cold]
252fn segment_error(node: &Node, path: &[PathSegment<'_>], offset: usize) -> Error {
253 let reason = match node {
254 Node::Object(_) => "is an object, so it needs a key, not an index",
255 Node::Array(_) => "is an array, so it needs an index, not a key",
256 Node::Scalar(_) => "is not an object or an array",
257 };
258
259 path_error(path, offset, reason)
260}
261
262fn step(node: &Node, segment: PathSegment<'_>) -> Option<usize> {
266 match (node, segment) {
267 (Node::Object(object), PathSegment::Key(key)) => object.position(key),
268 (Node::Array(array), PathSegment::Index(index)) if index < array.items().len() => {
269 Some(index)
270 }
271 _ => None,
272 }
273}
274
275impl Document {
276 fn printed_text(&self) -> String {
280 let mut printer = Printer::new(false);
281 printer.output.reserve(self.source.len());
282 printer.document(&self.outer, &self.root);
283 printer.output
284 }
285
286 #[must_use]
290 pub const fn root(&self) -> &Node {
291 &self.root
292 }
293
294 pub const fn root_mut(&mut self) -> &mut Node {
298 &mut self.root
299 }
300
301 #[must_use]
305 pub const fn outer_decor(&self) -> &Decor {
306 &self.outer
307 }
308
309 #[must_use]
324 pub fn get<'a>(
325 &self,
326 path: impl IntoIterator<Item = impl Into<PathSegment<'a>>>,
327 ) -> Option<&Node> {
328 let mut node = &self.root;
329
330 for segment in path {
331 let index = step(node, segment.into())?;
332
333 node = match node {
334 Node::Object(object) => object.members()[index].value(),
335 Node::Array(array) => array.items()[index].value(),
336 Node::Scalar(_) => unreachable!("a path does not step into a scalar"),
337 };
338 }
339
340 Some(node)
341 }
342
343 pub fn get_mut<'a>(
347 &mut self,
348 path: impl IntoIterator<Item = impl Into<PathSegment<'a>>>,
349 ) -> Option<&mut Node> {
350 let mut node = &mut self.root;
351
352 for segment in path {
353 let index = step(node, segment.into())?;
354
355 node = match node {
356 Node::Object(object) => object.members_mut()[index].value_mut(),
357 Node::Array(array) => array.items_mut()[index].value_mut(),
358 Node::Scalar(_) => unreachable!("a path does not step into a scalar"),
359 };
360 }
361
362 Some(node)
363 }
364
365 pub fn set<'a>(
384 &mut self,
385 path: impl IntoIterator<Item = impl Into<PathSegment<'a>>>,
386 value: impl Into<Value>,
387 ) -> Result<(), Error> {
388 let path = path_segments(path)?;
389
390 for segment in &path {
392 if let PathSegment::Key(key) = segment {
393 crate::write::check_representable(key, "key")?;
394 }
395 }
396
397 let value = tree::checked(value.into())?;
398 let before = self.root.clone();
399 let indentation = tree::indentation_of(own_line(&self.outer.leading));
401 let result = set_in(&mut self.root, &path, &path, value, indentation, false);
402
403 if let Err(error) = result.and_then(|()| {
405 crate::from_str::<serde_core::de::IgnoredAny>(&self.printed_text())
406 .map(|_| ())
407 .map_err(|error| Error::write(error.message()))
408 }) {
409 self.root = before;
410 return Err(error);
411 }
412
413 Ok(())
414 }
415
416 pub fn remove<'a>(
432 &mut self,
433 path: impl IntoIterator<Item = impl Into<PathSegment<'a>>>,
434 ) -> Result<bool, Error> {
435 let path = path_segments(path)?;
436
437 if let Node::Object(object) = &mut self.root
439 && !object.is_braced()
440 && let [member] = object.members()
441 && [PathSegment::Key(member.key().value())] == path.as_slice()
442 {
443 let mut member = object.members_mut().remove(0);
444 let mut decor = std::mem::take(member.decor_mut());
445 decor.trailing.push_str(object.closing_decor());
446 self.outer = decor;
447 self.root = Node::Object(Object::default());
448 return Ok(true);
449 }
450
451 remove_in(&mut self.root, &path, &path)
453 }
454
455 #[must_use]
461 pub fn comments(&self) -> Vec<Comment> {
462 let mut printer = Printer::new(true);
463 printer.output.reserve(self.source.len());
464
465 printer.document(&self.outer, &self.root);
466 printer.comments.unwrap_or_default()
467 }
468
469 #[must_use]
481 pub fn position(&self, offset: usize) -> crate::LineColumn {
482 crate::LineColumn::locate(&self.source, offset)
483 }
484
485 #[must_use]
500 pub fn format(&self) -> String {
501 tree::format::document(&self.outer, &self.root, self.source.len())
502 }
503
504 pub fn to_value(&self) -> Result<Value, Error> {
514 self.printed_text().parse()
515 }
516}
517
518fn stays_on_one_line(node: &Node) -> bool {
522 let has_content = |entry_count: usize, closing: &str| {
523 entry_count > 0 || !closing.trim_matches([' ', '\t']).is_empty()
524 };
525
526 let is_braced_with_content = match node {
527 Node::Object(object) => {
528 object.is_braced() && has_content(object.members().len(), object.closing_decor())
529 }
530 Node::Array(array) => has_content(array.items().len(), array.closing_decor()),
531 Node::Scalar(_) => false,
532 };
533
534 is_braced_with_content && node.is_on_one_line()
535}
536
537fn nest(path: &[PathSegment<'_>], start: usize, value: Value) -> Result<Value, Error> {
541 if let Some((position, index)) =
543 path.iter()
544 .enumerate()
545 .skip(start)
546 .rev()
547 .find_map(|(position, segment)| match segment {
548 PathSegment::Index(index) => Some((position, index)),
549 PathSegment::Key(_) => None,
550 }) {
551 return Err(path_error(
552 path,
553 position,
554 &format!("does not exist, so it has no index {index}"),
555 ));
556 }
557
558 if path.len() > MAX_DEPTH {
560 return Err(Error::write(format!(
561 "The document is nested more than {MAX_DEPTH} levels deep"
562 )));
563 }
564
565 Ok(path[start..]
566 .iter()
567 .rev()
568 .fold(value, |value, segment| match segment {
569 PathSegment::Key(key) => {
570 Value::Object(crate::Object::from([((*key).to_owned(), value)]))
571 }
572 PathSegment::Index(_) => unreachable!("an index is an error above"),
573 }))
574}
575
576fn set_in(
580 node: &mut Node,
581 path: &[PathSegment<'_>],
582 full_path: &[PathSegment<'_>],
583 value: Value,
584 indentation: &str,
585 is_inside_one_line: bool,
586) -> Result<(), Error> {
587 if path.is_empty() {
589 *node = Node::laid_out(value, (!is_inside_one_line).then_some(indentation));
590 return Ok(());
591 }
592
593 let is_one_line = is_inside_one_line || stays_on_one_line(node);
594 let offset = full_path.len() - path.len();
596
597 match (node, path[0]) {
598 (Node::Object(object), PathSegment::Key(key)) => set_in_object(
599 object,
600 key,
601 path,
602 full_path,
603 value,
604 indentation,
605 is_one_line,
606 ),
607 (Node::Array(array), PathSegment::Index(index)) => {
608 let count = array.items().len();
609
610 if index > count {
611 let owner = if offset == 0 {
612 "the document".to_owned()
613 } else {
614 format!("the array at {}", describe_path(&full_path[..offset]))
615 };
616 let items = if count == 1 {
617 "1 item".to_owned()
618 } else {
619 format!("{count} items")
620 };
621 return Err(Error::data(format!(
622 "Cannot edit {}, because {owner} has {items}. Add an item at index {count}",
623 describe_path(full_path)
624 )));
625 }
626
627 if index == count {
629 let value = nest(full_path, offset + 1, value)?;
630 let item = Item::new(Value::Null).expect("null can be written");
632 array
633 .entries_mut()
634 .append(item, value, indentation, is_one_line);
635 return Ok(());
636 }
637
638 let item_indentation = entry_indentation(array.items(), index, false, indentation);
639
640 set_in(
641 array.items_mut()[index].value_mut(),
642 &path[1..],
643 full_path,
644 value,
645 &item_indentation,
646 is_one_line,
647 )
648 }
649 (node, _) => Err(segment_error(node, full_path, offset)),
650 }
651}
652
653fn set_in_object(
657 object: &mut Object,
658 key: &str,
659 path: &[PathSegment<'_>],
660 full_path: &[PathSegment<'_>],
661 value: Value,
662 indentation: &str,
663 is_one_line: bool,
664) -> Result<(), Error> {
665 let offset = full_path.len() - path.len();
666
667 if let Some(index) = object.position(key) {
668 let member = &mut object.members_mut()[index];
669
670 if path.len() == 1
672 && matches!(member.value(), Node::Scalar(scalar) if scalar.is_block_string())
673 && member
674 .after_colon
675 .bytes()
676 .all(|byte| matches!(byte, b' ' | b'\t' | b'\n'))
677 {
678 member.after_colon = Cow::Borrowed(" ");
679 }
680
681 let entry_indentation =
683 entry_indentation(object.members(), index, !object.is_braced(), indentation);
684 let member_indentation =
685 line_indentation(&object.members()[index].after_colon, &entry_indentation);
686
687 return set_in(
688 object.members_mut()[index].value_mut(),
689 &path[1..],
690 full_path,
691 value,
692 &member_indentation,
693 is_one_line,
694 );
695 }
696
697 let value = nest(full_path, offset + 1, value)?;
698 let member = Member::new(Key::new(key), Value::Null)?;
700 object
701 .entries_mut()
702 .append(member, value, indentation, is_one_line);
703 Ok(())
704}
705
706fn entry_indentation<T: Entry>(
710 entries: &[T],
711 index: usize,
712 starts_line: bool,
713 indentation: &str,
714) -> String {
715 for position in (0..=index).rev() {
716 let previous_trailing = match position.checked_sub(1) {
717 Some(previous) => entries[previous].separator().decor.trailing.as_str(),
718 None if starts_line => "\n",
719 None => "",
720 };
721 let leading = &entries[position].separator().decor.leading;
722 let decor = if previous_trailing.is_empty() {
723 Cow::Borrowed(leading.as_str())
724 } else if leading.is_empty() {
725 Cow::Borrowed(previous_trailing)
726 } else {
727 Cow::Owned([previous_trailing, leading].concat())
728 };
729
730 if let Some(start) = last_line_start(&decor) {
731 return tree::indentation_of(&decor[start..]).to_owned();
732 }
733
734 if let Some(indentation) = position
736 .checked_sub(1)
737 .and_then(|previous| last_line_indentation(&entries[previous]))
738 {
739 return indentation;
740 }
741 }
742
743 indentation.to_owned()
744}
745
746fn last_line_indentation<T: Entry>(entry: &T) -> Option<String> {
750 if entry.is_on_one_line() {
751 return None;
752 }
753 let mut printer = Printer::new(true);
754 entry.print(&mut printer);
755 let text = printer.output;
756 let mut comments = printer.comments.unwrap_or_default().into_iter().rev();
758 let mut comment = comments.next();
759 let mut end = text.len();
760
761 let line_feed = loop {
762 let line_feed = text[..end].rfind('\n')?;
763
764 while comment
765 .as_ref()
766 .is_some_and(|comment| comment.span.start > line_feed)
767 {
768 comment = comments.next();
769 }
770
771 match &comment {
772 Some(comment) if comment.span.contains(&line_feed) => end = comment.span.start,
773 _ => break line_feed,
774 }
775 };
776
777 Some(tree::indentation_of(&text[line_feed + 1..]).to_owned())
778}
779
780fn end_line<T: Entry>(kept: &mut [T], moved: &mut String) {
784 match kept.last_mut() {
785 Some(last) => last.separator_mut().decor.trailing.push('\n'),
786 None => moved.push('\n'),
787 }
788}
789
790impl<T: Entry> Entries<'_, T> {
791 fn end_last_line(&mut self) {
795 let Some(last) = self.list.last_mut() else {
797 return;
798 };
799
800 if last.separator().decor.trailing.ends_with('\n') {
801 return;
802 }
803
804 if let Some(line_feed) = tree::first_line_end(self.closing) {
805 last.separator_mut()
806 .decor
807 .trailing
808 .push_str(&self.closing[..line_feed]);
809 self.closing.replace_range(..line_feed, "");
810 }
811 }
812
813 fn append(mut self, mut entry: T, value: Value, indentation: &str, is_one_line: bool) {
817 self.end_last_line();
818 let Self {
819 list: entries,
820 closing,
821 is_braced,
822 } = self;
823 let index = entries.len();
824 let (leading, trailing, has_comma, line) = match index.checked_sub(1) {
825 Some(previous) => {
826 let line = entry_indentation(entries, previous, !is_braced, indentation);
827 let separator = entries[previous].separator();
828 let decor = &separator.decor;
829
830 if is_braced && !decor.trailing.ends_with('\n') {
831 let line = last_line_indentation(&entries[previous]).unwrap_or(line);
833 let has_comma = separator.has_comma;
834
835 if !has_comma {
837 let owned = closing.trim_end_matches([' ', '\t']).len();
838 entries[previous]
839 .separator_mut()
840 .before_comma
841 .push_str(&closing[..owned]);
842 closing.replace_range(..owned, "");
843 }
844
845 (" ".to_owned(), String::new(), has_comma, line)
846 } else if decor.trailing.ends_with('\n') {
847 (line.clone(), "\n".to_owned(), false, line)
849 } else {
850 let trailing = &mut entries[previous].separator_mut().decor.trailing;
852
853 if !tree::ends_in_line_comment(trailing) {
854 trailing.truncate(trailing.trim_end_matches([' ', '\t']).len());
855 }
856
857 trailing.push('\n');
858 (line.clone(), String::new(), false, line)
859 }
860 }
861 None if !is_braced => (String::new(), "\n".to_owned(), false, String::new()),
863 None if is_one_line => {
865 let before = closing.trim_end_matches([' ', '\t']);
866 let leading = if before.is_empty() {
867 String::new()
868 } else {
869 [before, " "].concat()
870 };
871
872 closing.clear();
873 (leading, String::new(), false, indentation.to_owned())
874 }
875 None => {
876 let line = [indentation, "\t"].concat();
877
878 let leading = if tree::has_line_feed(closing)
880 && own_line(closing).trim_matches([' ', '\t']).is_empty()
881 {
882 [comment_lines(closing), &line].concat()
883 } else {
884 [closing.trim_end_matches([' ', '\t']), "\n", &line].concat()
885 };
886
887 *closing = indentation.to_owned();
888 (leading, "\n".to_owned(), false, line)
889 }
890 };
891
892 *entry.node_mut() = Node::laid_out(value, (!is_one_line).then_some(line.as_str()));
893 let separator = entry.separator_mut();
894 separator.decor = tree::Decor { leading, trailing };
895 separator.has_comma = has_comma;
896 entries.push(entry);
897
898 for position in index.saturating_sub(1)..=index {
900 if tree::shares_line_with_next(entries, position) {
901 entries[position].separator_mut().has_comma = true;
902 }
903 }
904 }
905}
906
907fn remove_in(
911 node: &mut Node,
912 path: &[PathSegment<'_>],
913 full_path: &[PathSegment<'_>],
914) -> Result<bool, Error> {
915 let offset = full_path.len() - path.len();
917
918 match (node, path[0]) {
920 (Node::Object(object), PathSegment::Key(key)) => {
921 let Some(index) = object.position(key) else {
923 return Ok(false);
924 };
925
926 if path.len() > 1 {
927 return remove_in(
928 object.members_mut()[index].value_mut(),
929 &path[1..],
930 full_path,
931 );
932 }
933
934 Ok(object.entries_mut().remove(index))
935 }
936 (Node::Array(array), PathSegment::Index(index)) => {
937 if index >= array.items().len() {
939 return Ok(false);
940 }
941
942 if path.len() > 1 {
943 return remove_in(array.items_mut()[index].value_mut(), &path[1..], full_path);
944 }
945
946 Ok(array.entries_mut().remove(index))
947 }
948 (node, _) => Err(segment_error(node, full_path, offset)),
949 }
950}
951
952impl<T: Entry> Entries<'_, T> {
953 fn remove(mut self, index: usize) -> bool {
957 self.end_last_line();
958 let Self {
959 list: entries,
960 closing,
961 is_braced,
962 } = self;
963 let entry = entries.remove(index);
965 let separator = entry.separator();
966 let decor = &separator.decor;
967 let leading_has_line_feed = tree::has_line_feed(&decor.leading);
968 let trailing_has_line_feed = tree::has_line_feed(&decor.trailing);
969 let (previous, following) = entries.split_at_mut(index);
970 let mut moved = comment_lines(&decor.leading).to_owned();
972 let removed_at = moved.len();
974 let mut indentation = Some(tree::indentation_of(own_line(&decor.leading)));
976 let starts_line = !is_braced
978 || previous
979 .last()
980 .is_some_and(|previous| tree::has_line_feed(&previous.separator().decor.trailing));
981 let ended_line = !starts_line && !leading_has_line_feed && trailing_has_line_feed;
983 let is_last_removed_without_comma = following.is_empty() && !separator.has_comma;
985 let is_comma_before_removed_spaced = previous
987 .last()
988 .is_some_and(|previous| previous.separator().decor.trailing.is_empty())
989 && !leading_has_line_feed;
990 let is_closing_owned = is_last_removed_without_comma && !trailing_has_line_feed;
992
993 if trailing_has_line_feed {
995 indentation = None;
996 }
997 if ended_line {
999 end_line(previous, &mut moved);
1000 indentation = None;
1001 }
1002
1003 if let Some(next) = following.first_mut() {
1004 let leading = &next.separator().decor.leading;
1005 let own = own_line(leading);
1006 let own = match indentation {
1008 Some(indentation) => [indentation, own.trim_start_matches([' ', '\t'])].concat(),
1009 None => own.to_owned(),
1010 };
1011 let leading = [moved.as_str(), comment_lines(leading), &own].concat();
1012 next.separator_mut().decor.leading = without_extra_blank_lines(
1013 &leading,
1014 removed_at,
1015 Surroundings::before_entry(previous.last(), is_braced),
1016 );
1017 } else {
1018 if is_closing_owned {
1020 closing.clear();
1021 }
1022 if let Some(indentation) = indentation
1024 && !tree::has_line_feed(closing)
1025 && !closing.trim_matches([' ', '\t']).is_empty()
1026 {
1027 *closing = [indentation, closing.trim_start_matches([' ', '\t'])].concat();
1028 }
1029 if !moved.is_empty() {
1030 moved.push_str(closing);
1031 *closing = without_extra_blank_lines(
1032 &moved,
1033 removed_at,
1034 Surroundings::before_closing(previous.last(), is_braced),
1035 );
1036 }
1037 }
1038
1039 if is_last_removed_without_comma
1040 && is_comma_before_removed_spaced
1041 && let Some(last) = entries.last_mut()
1042 {
1043 let separator = last.separator_mut();
1044 separator.has_comma = false;
1045
1046 if !separator.before_comma.is_empty() {
1048 let mut text = std::mem::take(&mut separator.before_comma);
1049 text.truncate(text.trim_end_matches([' ', '\t']).len());
1050 text.push_str(&separator.decor.trailing);
1051 let line_end = tree::first_line_end(&text).unwrap_or(0);
1053 separator.decor.trailing = text[..line_end].to_owned();
1054 closing.insert_str(0, &text[line_end..]);
1055 }
1056 }
1057
1058 if entries.is_empty() && closing.trim_matches([' ', '\t', '\n']).is_empty() {
1060 closing.clear();
1061 }
1062 true
1063 }
1064}
1065
1066#[derive(Clone, Copy)]
1070struct Surroundings {
1071 starts_line: bool,
1075 at_start: bool,
1079 at_end: bool,
1083}
1084
1085impl Surroundings {
1086 fn before_entry<T: Entry>(previous: Option<&T>, is_braced: bool) -> Self {
1090 Self {
1091 starts_line: previous.map_or(!is_braced, |previous| {
1092 tree::has_line_feed(&previous.separator().decor.trailing)
1093 }),
1094 at_start: previous.is_none(),
1095 at_end: false,
1096 }
1097 }
1098
1099 fn before_closing<T: Entry>(previous: Option<&T>, is_braced: bool) -> Self {
1103 Self {
1104 at_end: true,
1105 ..Self::before_entry(previous, is_braced)
1106 }
1107 }
1108}
1109
1110fn without_extra_blank_lines(decor: &str, removed_at: usize, surroundings: Surroundings) -> String {
1114 let Surroundings {
1115 starts_line,
1116 at_start,
1117 at_end,
1118 } = surroundings;
1119 let mut output = String::with_capacity(decor.len());
1120 let mut blank_run: Option<std::ops::Range<usize>> = None;
1122 let mut has_content = !at_start;
1123 let mut line_start = 0;
1124
1125 let end_run =
1126 |output: &mut String, run: std::ops::Range<usize>, is_at_start: bool, is_at_end: bool| {
1127 if removed_at < run.start || removed_at > run.end {
1129 output.push_str(&decor[run]);
1130 return;
1131 }
1132 let mut before = run.start..removed_at;
1133 let mut after = removed_at..run.end;
1134
1135 if !before.is_empty() && (!after.is_empty() || is_at_end) {
1137 before.end = decor[before.start..before.end - 1]
1138 .rfind('\n')
1139 .map_or(before.start, |index| before.start + index + 1);
1140 } else if !after.is_empty() && is_at_start {
1141 after.start = decor[after.clone()]
1142 .find('\n')
1143 .map_or(after.end, |index| after.start + index + 1);
1144 }
1145
1146 output.push_str(&decor[before]);
1147 output.push_str(&decor[after]);
1148 };
1149
1150 for (part, range) in tree::decor_parts(decor) {
1151 if part != tree::DecorPart::LineFeed {
1152 continue;
1153 }
1154
1155 let line = line_start..range.end;
1156 let is_empty = decor[line.clone()]
1157 .bytes()
1158 .all(|byte| matches!(byte, b' ' | b'\t' | b'\n'));
1159 let ends_earlier_line = line_start == 0 && !starts_line;
1161 line_start = range.end;
1162
1163 if is_empty && !ends_earlier_line {
1164 blank_run = Some(blank_run.map_or(line.clone(), |run| run.start..line.end));
1165 continue;
1166 }
1167
1168 if let Some(run) = blank_run.take() {
1169 end_run(&mut output, run, !has_content, false);
1170 }
1171
1172 has_content |= !is_empty && !ends_earlier_line;
1174 output.push_str(&decor[line]);
1175 }
1176
1177 let rest = &decor[line_start..];
1178
1179 if let Some(run) = blank_run {
1180 let is_at_end = at_end && rest.bytes().all(|byte| byte == b' ' || byte == b'\t');
1181 end_run(&mut output, run, !has_content, is_at_end);
1182 }
1183
1184 output.push_str(rest);
1185 output
1186}
1187
1188impl FromStr for Document {
1189 type Err = Error;
1190
1191 fn from_str(text: &str) -> Result<Self, Error> {
1195 let parts = tree::build(text, crate::parse::parse(text)?);
1196
1197 Ok(Self {
1198 outer: parts.outer,
1199 root: parts.root,
1200 source: text.to_owned(),
1201 })
1202 }
1203}
1204
1205impl Display for Document {
1209 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
1210 formatter.write_str(&self.printed_text())
1211 }
1212}