1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961
#![doc = include_str!("../README.md")]
use std::{borrow::Cow, error::Error, fmt::Display};
use tree_iterators_rs::prelude::{OwnedTreeNode, TreeNode};
use whitespacesv::{ColumnAlignment, WSVError, WSVWriter};
/// Equivalent to [parse](https://docs.rs/simpleml/latest/simpleml/fn.parse.html),
/// but returns Strings instead of Cows for better ease of use.
pub fn parse_owned(source_text: &str) -> Result<TreeNode<SMLElement<String>>, ParseError> {
let borrowed = parse(source_text)?;
Ok(to_owned(borrowed))
}
fn to_owned(tree: TreeNode<SMLElement<Cow<'_, str>>>) -> TreeNode<SMLElement<String>> {
let children = match tree.children {
None => None,
Some(children) => {
let mut new_children = Vec::with_capacity(children.len());
for child in children {
new_children.push(to_owned(child));
}
Some(new_children)
}
};
TreeNode {
value: tree.value.to_owned(),
children,
}
}
/// Parses the Simple Markup Language text into a tree of SMLElements.
/// For details about how to use TreeNode, see [tree_iterators_rs](https://crates.io/crates/tree_iterators_rs)
/// and the documentation related to that crate.
pub fn parse(source_text: &str) -> Result<TreeNode<SMLElement<Cow<'_, str>>>, ParseError> {
let wsv_result = whitespacesv::parse(source_text);
let wsv = match wsv_result {
Err(err) => return Err(ParseError::WSV(err)),
Ok(wsv) => wsv,
};
let end_keyword = match wsv.iter().rev().find(|line| !line.is_empty()) {
None => {
return Err(ParseError::SML(SMLError {
err_type: SMLErrorType::EndKeywordNotDetected,
line_num: wsv.len(),
}))
}
Some(last_line) => match last_line.get(0).unwrap() {
None => None,
Some(val) => Some(val.to_lowercase()),
},
};
let mut lines_iter = wsv.into_iter().enumerate();
let root_element_name;
loop {
let first_line = lines_iter.next();
match first_line {
None => panic!("Found an empty file, but this should've returned an SMLError::EndKeywordNotDetected"),
Some((line_num, mut first_line)) => {
if first_line.is_empty() { continue; }
if first_line.len() > 1 { return Err(ParseError::SML(SMLError {
err_type: SMLErrorType::InvalidRootElementStart,
line_num,
})) }
match std::mem::take(first_line.get_mut(0).unwrap()) {
None => return Err(ParseError::SML(SMLError {
err_type: SMLErrorType::NullValueAsElementName,
line_num,
})),
Some(root) => {
root_element_name = root;
break;
}
}
}
}
}
let root = TreeNode {
value: SMLElement {
name: root_element_name,
attributes: Vec::with_capacity(0),
},
children: None,
};
let mut nodes_being_built = vec![root];
let mut result = None;
for (line_num, mut line) in lines_iter {
if line.is_empty() {
continue;
}
if line.len() == 1 {
let val;
let val_lowercase;
match line.get_mut(0) {
None => {
if end_keyword.is_some() {
return Err(ParseError::SML(SMLError {
err_type: SMLErrorType::NullValueAsElementName,
line_num,
}));
}
val = None;
val_lowercase = None;
}
Some(inner_val) => match inner_val {
None => {
val = None;
val_lowercase = None;
}
Some(innermost_val) => {
val_lowercase = Some(innermost_val.to_lowercase());
val = Some(std::mem::take(innermost_val));
}
},
};
if val_lowercase == end_keyword {
match nodes_being_built.pop() {
None => {
return Err(ParseError::SML(SMLError {
err_type: SMLErrorType::OnlyOneRootElementAllowed,
line_num,
}))
}
Some(top) => {
let nodes_being_built_len = nodes_being_built.len();
if nodes_being_built_len == 0 {
if result.is_some() {
return Err(ParseError::SML(SMLError {
err_type: SMLErrorType::OnlyOneRootElementAllowed,
line_num,
}));
} else {
result = Some(top);
continue;
}
}
let new_top = nodes_being_built
.get_mut(nodes_being_built_len - 1)
.unwrap();
match &mut new_top.children {
None => new_top.children = Some(vec![top]),
Some(children) => children.push(top),
}
}
}
} else {
nodes_being_built.push(TreeNode {
value: SMLElement {
name: val.expect("BUG: Null element names are prohibited."),
attributes: Vec::with_capacity(0),
},
children: None,
});
}
} else {
let mut values = line.into_iter();
let name = match values.next().unwrap() {
None => {
return Err(ParseError::SML(SMLError {
err_type: SMLErrorType::NullValueAsAttributeName,
line_num,
}))
}
Some(val) => val,
};
let attr_values = values.collect::<Vec<_>>();
let nodes_being_built_len = nodes_being_built.len();
if nodes_being_built_len == 0 {
return Err(ParseError::SML(SMLError {
err_type: SMLErrorType::OnlyOneRootElementAllowed,
line_num,
}));
}
let current = nodes_being_built
.get_mut(nodes_being_built_len - 1)
.unwrap();
current.value.attributes.push(SMLAttribute {
name,
values: attr_values,
});
}
}
match result {
None => Err(ParseError::SML(SMLError {
err_type: SMLErrorType::RootNotClosed,
line_num: 0,
})),
Some(result) => {
Ok(result)
}
}
}
pub struct SMLWriter<StrAsRef>
where
StrAsRef: AsRef<str> + From<&'static str> + ToString,
{
indent_str: String,
end_keyword: Option<String>,
column_alignment: ColumnAlignment,
values: TreeNode<SMLElement<StrAsRef>>,
}
impl<StrAsRef> SMLWriter<StrAsRef>
where
StrAsRef: AsRef<str> + From<&'static str> + ToString,
{
pub fn new(values: TreeNode<SMLElement<StrAsRef>>) -> Self {
Self {
values,
indent_str: " ".to_string(), // default to 4 spaces
end_keyword: None, // Use minified as the default
column_alignment: ColumnAlignment::default(),
}
}
/// Sets the indentation string to be used in the output.
/// If the passed in str contains any non-whitespace characters,
/// this call will fail and return None.
pub fn indent_with(mut self, str: &str) -> Option<Self> {
if str.chars().any(|ch| !Self::is_whitespace(ch)) {
return None;
}
self.indent_str = str.to_string();
return Some(self);
}
/// Sets the end keyword to be used in the output.
/// If the passed in string is the empty string "",
/// '-' will be used instead.
pub fn with_end_keyword(mut self, str: Option<&str>) -> Self {
match str {
None | Some("") => {
self.end_keyword = None;
return self;
}
Some(str) => {
debug_assert!(!str.is_empty());
let needs_quotes = str
.chars()
.any(|ch| ch == '"' || ch == '#' || ch == '\n' || Self::is_whitespace(ch))
|| str == "-";
if !needs_quotes {
self.end_keyword = Some(str.to_string());
} else {
let mut result = String::new();
result.push('"');
for ch in str.chars() {
match ch {
'"' => result.push_str("\"\""),
'\n' => result.push_str("\"/\""),
ch => result.push(ch),
}
}
result.push('"');
self.end_keyword = Some(result);
}
return self;
}
}
}
/// Sets the column alignment of the attributes' generated WSV.
/// The element alignment will be unaffected, but all attributes
/// and their values will be aligned this way.
pub fn align_columns(mut self, alignment: ColumnAlignment) -> Self {
self.column_alignment = alignment;
return self;
}
/// Writes the values in this SMLWriter out to a String. This operation
/// can fail if any of the values would result in an SML attribute or
/// element where the name is the same as the "End" keyword. If that
/// happens, you as the caller will receive an Err() variant of Result.
pub fn to_string(self) -> Result<String, SMLWriterError> {
let mut result = String::new();
Self::to_string_helper(
self.values,
0,
&self.column_alignment,
&self.indent_str,
self.end_keyword.as_ref(),
&mut result,
)?;
return Ok(result);
}
fn to_string_helper(
value: TreeNode<SMLElement<StrAsRef>>,
depth: usize,
alignment: &ColumnAlignment,
indent_str: &str,
end_keyword: Option<&String>,
buf: &mut String,
) -> Result<(), SMLWriterError> {
let (value, children) = value.get_value_and_children();
if let Some(end_keyword) = end_keyword {
if value.name.as_ref() == end_keyword {
return Err(SMLWriterError::ElementHasEndKeywordName);
}
}
for _ in 0..depth {
buf.push_str(indent_str);
}
buf.push_str(value.name.as_ref());
if !value.attributes.is_empty() {
buf.push('\n');
for _ in 0..depth + 1 {
buf.push_str(indent_str);
}
}
if let Some(end_keyword) = end_keyword {
for attribute in value.attributes.iter() {
if attribute.name.as_ref() == end_keyword {
return Err(SMLWriterError::AttributeHasEndKeywordName);
}
}
}
let values_for_writer = value
.attributes
.into_iter()
.map(|attr| std::iter::once(Some(attr.name)).chain(attr.values.into_iter()));
match alignment {
ColumnAlignment::Packed => {
for ch in WSVWriter::new(values_for_writer) {
buf.push(ch);
if ch == '\n' {
for _ in 0..depth + 1 {
buf.push_str(indent_str);
}
}
}
}
ColumnAlignment::Left | ColumnAlignment::Right => {
for ch in WSVWriter::new(values_for_writer)
.align_columns(match alignment {
ColumnAlignment::Left => ColumnAlignment::Left,
ColumnAlignment::Right => ColumnAlignment::Right,
ColumnAlignment::Packed => {
panic!("BUG: ColumnAlignment::Packed shouldn't go down this path")
}
})
.to_string()
.chars()
{
buf.push(ch);
if ch == '\n' {
for _ in 0..depth + 1 {
buf.push_str(indent_str);
}
}
}
}
}
for child in children.into_iter().flat_map(|opt| opt) {
buf.push('\n');
Self::to_string_helper(child, depth + 1, alignment, indent_str, end_keyword, buf)?;
}
buf.push('\n');
for _ in 0..depth {
buf.push_str(indent_str);
}
match end_keyword {
None => buf.push('-'),
Some(end) => buf.push_str(end),
}
return Ok(());
}
const fn is_whitespace(ch: char) -> bool {
match ch {
'\u{0009}' | '\u{000B}' | '\u{000C}' | '\u{000D}' | '\u{0020}' | '\u{0085}'
| '\u{00A0}' | '\u{1680}' | '\u{2000}' | '\u{2001}' | '\u{2002}' | '\u{2003}'
| '\u{2004}' | '\u{2005}' | '\u{2006}' | '\u{2007}' | '\u{2008}' | '\u{2009}'
| '\u{200A}' | '\u{2028}' | '\u{2029}' | '\u{202F}' | '\u{205F}' | '\u{3000}' => {
return true;
}
_ => return false,
}
}
}
#[derive(Debug, Clone, Copy)]
pub enum SMLWriterError {
ElementHasEndKeywordName,
AttributeHasEndKeywordName,
}
impl Error for SMLWriterError {}
impl Display for SMLWriterError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
SMLWriterError::AttributeHasEndKeywordName => {
write!(f, "Attribute Has End Keyword Name")?
}
SMLWriterError::ElementHasEndKeywordName => write!(f, "Element Has End Keyword Name")?,
}
Ok(())
}
}
#[derive(Debug, Clone)]
pub enum ParseError {
WSV(WSVError),
SML(SMLError),
}
impl Error for ParseError {}
impl Display for ParseError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
ParseError::SML(err) => err.fmt(f)?,
ParseError::WSV(err) => err.fmt(f)?,
}
Ok(())
}
}
#[derive(Debug, Clone)]
pub struct SMLError {
err_type: SMLErrorType,
line_num: usize,
}
impl SMLError {
pub fn err_type(&self) -> SMLErrorType {
self.err_type
}
pub fn line_num(&self) -> usize {
self.line_num
}
}
impl Error for SMLError {}
impl Display for SMLError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let mut result = String::new();
result.push_str("(line: ");
result.push_str(&self.line_num().to_string());
result.push_str(") ");
match self.err_type() {
SMLErrorType::EndKeywordNotDetected => {
result.push_str("End Keyword Not Detected");
}
SMLErrorType::InvalidRootElementStart => {
result.push_str("Invalid Root Element Start");
}
SMLErrorType::NullValueAsAttributeName => {
result.push_str("Null Value as Attribute Name");
}
SMLErrorType::NullValueAsElementName => {
result.push_str("Null Value as Element Name");
}
SMLErrorType::OnlyOneRootElementAllowed => {
result.push_str("Only One Root Element Allowed");
}
SMLErrorType::RootNotClosed => {
result.push_str("Root Not Closed");
}
}
write!(f, "{}", result)?;
Ok(())
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum SMLErrorType {
/// This error can happen for 2 reasons:
/// 1. the file was empty or only contained comments
/// 2. the file is invalid SML.
EndKeywordNotDetected,
InvalidRootElementStart,
NullValueAsElementName,
NullValueAsAttributeName,
RootNotClosed,
OnlyOneRootElementAllowed,
}
#[derive(Debug)]
pub struct SMLElement<StrAsRef>
where
StrAsRef: AsRef<str>,
{
pub name: StrAsRef,
pub attributes: Vec<SMLAttribute<StrAsRef>>,
}
impl SMLElement<Cow<'_, str>> {
fn to_owned(self) -> SMLElement<String> {
let mut attributes = Vec::with_capacity(self.attributes.len());
for attr in self.attributes {
attributes.push(attr.to_owned());
}
SMLElement {
name: match self.name {
Cow::Borrowed(str) => str.to_string(),
Cow::Owned(string) => string,
},
attributes,
}
}
}
#[derive(Debug)]
pub struct SMLAttribute<StrAsRef>
where
StrAsRef: AsRef<str>,
{
pub name: StrAsRef,
pub values: Vec<Option<StrAsRef>>,
}
impl SMLAttribute<Cow<'_, str>> {
fn to_owned(self) -> SMLAttribute<String> {
let mut values = Vec::with_capacity(self.values.len());
for value in self.values {
let new_value = match value {
None => None,
Some(cow) => match cow {
Cow::Borrowed(str) => Some(str.to_string()),
Cow::Owned(string) => Some(string),
},
};
values.push(new_value);
}
SMLAttribute {
name: match self.name {
Cow::Borrowed(str) => str.to_string(),
Cow::Owned(string) => string,
},
values,
}
}
}
#[cfg(test)]
mod tests {
use tree_iterators_rs::prelude::OwnedTreeNode;
use crate::{SMLAttribute, SMLElement, SMLWriter};
#[test]
fn reads_example_correctly() {
let result = super::parse(include_str!("../example.txt")).unwrap();
for (i, element) in result.dfs_preorder().enumerate() {
match i {
0 => {
assert_eq!("Configuration", &element.name);
assert_eq!(0, element.attributes.len());
}
1 => {
assert_eq!("Video", &element.name);
assert_eq!(3, element.attributes.len());
for (j, attribute) in element.attributes.into_iter().enumerate() {
match j {
0 => {
assert_eq!("Resolution", attribute.name);
assert_eq!(2, attribute.values.len());
assert_eq!(
"1280",
attribute
.values
.get(0)
.as_ref()
.unwrap()
.as_ref()
.unwrap()
.as_ref()
);
assert_eq!(
"720",
attribute
.values
.get(1)
.as_ref()
.unwrap()
.as_ref()
.unwrap()
.as_ref()
);
}
1 => {
assert_eq!("RefreshRate", attribute.name);
assert_eq!(1, attribute.values.len());
assert_eq!(
"60",
attribute
.values
.get(0)
.as_ref()
.unwrap()
.as_ref()
.unwrap()
.as_ref()
);
}
2 => {
assert_eq!("Fullscreen", attribute.name);
assert_eq!(1, attribute.values.len());
assert_eq!(
"true",
attribute
.values
.get(0)
.as_ref()
.unwrap()
.as_ref()
.unwrap()
.as_ref()
);
}
_ => panic!("Should only have 3 attributes"),
}
}
}
2 => {
assert_eq!("Audio", &element.name);
assert_eq!(2, element.attributes.len());
for (j, attribute) in element.attributes.into_iter().enumerate() {
match j {
0 => {
assert_eq!("Volume", attribute.name);
assert_eq!(1, attribute.values.len());
assert_eq!(
"100",
attribute
.values
.get(0)
.as_ref()
.unwrap()
.as_ref()
.unwrap()
.as_ref()
);
}
1 => {
assert_eq!("Music", attribute.name);
assert_eq!(1, attribute.values.len());
assert_eq!(
"80",
attribute
.values
.get(0)
.as_ref()
.unwrap()
.as_ref()
.unwrap()
.as_ref()
);
}
_ => panic!("Should only have 2 values under audio"),
}
}
}
3 => {
assert_eq!("Player", element.name);
assert_eq!(1, element.attributes.len());
let attr = element.attributes.get(0).unwrap();
assert_eq!("Name", attr.name);
assert_eq!(1, attr.values.len());
assert_eq!(
"Hero 123",
attr.values
.get(0)
.as_ref()
.unwrap()
.as_ref()
.unwrap()
.as_ref()
);
}
_ => panic!("Should only have 4 sub-elements"),
}
}
}
#[test]
fn reads_example_correctly_owned() {
let result = super::parse_owned(include_str!("../example.txt")).unwrap();
for (i, element) in result.dfs_preorder().enumerate() {
match i {
0 => {
assert_eq!("Configuration", &element.name);
assert_eq!(0, element.attributes.len());
}
1 => {
assert_eq!("Video", &element.name);
assert_eq!(3, element.attributes.len());
for (j, attribute) in element.attributes.into_iter().enumerate() {
match j {
0 => {
assert_eq!("Resolution", attribute.name);
assert_eq!(2, attribute.values.len());
assert_eq!(
"1280",
attribute.values.get(0).as_ref().unwrap().as_ref().unwrap()
);
assert_eq!(
"720",
attribute.values.get(1).as_ref().unwrap().as_ref().unwrap()
);
}
1 => {
assert_eq!("RefreshRate", attribute.name);
assert_eq!(1, attribute.values.len());
assert_eq!(
"60",
attribute.values.get(0).as_ref().unwrap().as_ref().unwrap()
);
}
2 => {
assert_eq!("Fullscreen", attribute.name);
assert_eq!(1, attribute.values.len());
assert_eq!(
"true",
attribute.values.get(0).as_ref().unwrap().as_ref().unwrap()
);
}
_ => panic!("Should only have 3 attributes"),
}
}
}
2 => {
assert_eq!("Audio", &element.name);
assert_eq!(2, element.attributes.len());
for (j, attribute) in element.attributes.into_iter().enumerate() {
match j {
0 => {
assert_eq!("Volume", attribute.name);
assert_eq!(1, attribute.values.len());
assert_eq!(
"100",
attribute.values.get(0).as_ref().unwrap().as_ref().unwrap()
);
}
1 => {
assert_eq!("Music", attribute.name);
assert_eq!(1, attribute.values.len());
assert_eq!(
"80",
attribute.values.get(0).as_ref().unwrap().as_ref().unwrap()
);
}
_ => panic!("Should only have 2 values under audio"),
}
}
}
3 => {
assert_eq!("Player", element.name);
assert_eq!(1, element.attributes.len());
let attr = element.attributes.get(0).unwrap();
assert_eq!("Name", attr.name);
assert_eq!(1, attr.values.len());
assert_eq!(
"Hero 123",
attr.values.get(0).as_ref().unwrap().as_ref().unwrap()
);
}
_ => panic!("Should only have 4 sub-elements"),
}
}
}
#[test]
fn test_write() {
let input = include_str!("../example.txt");
println!(
"{}",
super::SMLWriter::new(super::parse(input).unwrap())
.align_columns(whitespacesv::ColumnAlignment::Right)
.indent_with(" ")
.unwrap()
.to_string()
.unwrap()
);
}
#[test]
fn readme_example() {
use tree_iterators_rs::prelude::*;
// Build up our value set
let my_sml_values = TreeNode {
value: SMLElement {
name: "Configuration",
attributes: Vec::with_capacity(0),
},
children: Some(vec![
TreeNode {
value: SMLElement {
name: "Video",
attributes: vec![
SMLAttribute {
name: "Resolution",
values: vec![Some("1280"), Some("720")],
},
SMLAttribute {
name: "RefreshRate",
values: vec![Some("60")],
},
SMLAttribute {
name: "Fullscreen",
values: vec![Some("true")],
},
],
},
children: None,
},
TreeNode {
value: SMLElement {
name: "Audio",
attributes: vec![
SMLAttribute {
name: "Volume",
values: vec![Some("100")],
},
SMLAttribute {
name: "Music",
values: vec![Some("80")],
},
],
},
children: None,
},
TreeNode {
value: SMLElement {
name: "Player",
attributes: vec![SMLAttribute {
name: "Name",
values: vec![Some("Hero 123")],
}],
},
children: None,
},
]),
};
// actually write the values
let str = SMLWriter::new(my_sml_values)
// Setting up a custom end keyword
.with_end_keyword(Some("my_custom_end_keyword"))
// Using 8 spaces as the indent string. The default is 4 spaces.
.indent_with(" ")
.unwrap()
// Align the WSV tables to the right.
.align_columns(whitespacesv::ColumnAlignment::Right)
.to_string()
.unwrap();
/// Result:
/// Configuration
/// Video
/// Resolution 1280 720
/// RefreshRate 60
/// Fullscreen true
/// my_custom_end_keyword
/// Audio
/// Volume 100
/// Music 80
/// my_custom_end_keyword
/// Player
/// Name "Hero 123"
/// my_custom_end_keyword
/// my_custom_end_keyword
println!("{}", str);
}
#[test]
fn parses_input_with_strange_end_keyword() {
let input = r#"
Configuration
Video
Resolution 1280 720
RefreshRate 60
Fullscreen true
"End with spaces"
Audio
Volume 100
Music 80
"End with spaces"
Player
Name "Hero 123"
"End with spaces"
"End with spaces""#;
println!("{:?}", super::parse(input).unwrap());
}
#[test]
fn parses_input_with_strange_end_keyword_owned() {
let input = r#"
Configuration
Video
Resolution 1280 720
RefreshRate 60
Fullscreen true
"End with spaces"
Audio
Volume 100
Music 80
"End with spaces"
Player
Name "Hero 123"
"End with spaces"
"End with spaces""#;
println!("{:?}", super::parse_owned(input).unwrap());
}
#[test]
fn parses_input_with_null_end_keyword() {
let input = r#"
Configuration
Video
Resolution 1280 720
RefreshRate 60
Fullscreen true
-
Audio
Volume 100
Music 80
-
Player
Name "Hero 123"
-
-"#;
println!("{:?}", super::parse(input).unwrap());
}
#[test]
fn doesnt_crash_bad_input() {
let str = r#"Value1
Configuration 2 0 2
Otherval 1
InnerEl
-"#;
super::parse(str).ok();
}
}