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
use crate::std_shapes::shapes::ShapeKind;
use crate::std_shapes::shapes::*;
pub fn print_record(rec: &RecordDef, indent: usize) {
match rec {
RecordDef::Text(label, port) => {
println!("\"{}\"", label);
if let Option::Some(port) = port {
println!("\"{}\"", port);
}
}
RecordDef::Array(arr) => {
print!("{}", " ".repeat(indent));
println!("[");
for elem in arr {
print_record(elem, indent + 1);
}
print!("{}", " ".repeat(indent));
println!("]");
}
}
}
struct RecordParser {
input: Vec<char>,
pos: usize,
}
struct RecordParserFrame {
label: String,
arr: Vec<RecordDef>,
}
impl RecordParserFrame {
pub fn new() -> Self {
Self {
label: String::new(),
arr: Vec::new(),
}
}
fn split_label_to_text_and_port(str: &str) -> (String, Option<String>) {
let str = str.trim();
if str.starts_with('<') {
if let Option::Some(idx) = str.find('>') {
let port = &str[1..idx];
return (
str[idx + 1..].trim().to_string(),
Option::Some(port.to_string()),
);
}
}
(str.to_string(), Option::None)
}
pub fn finalize_label(&mut self) {
if !self.label.trim().is_empty() {
let ret = Self::split_label_to_text_and_port(&self.label);
let text = RecordDef::Text(ret.0, ret.1);
self.arr.push(text);
self.label.clear();
}
}
pub fn finalize_record(&mut self) -> RecordDef {
self.finalize_label();
match self.arr.len() {
0 => RecordDef::Text(String::from(""), Option::None),
_ => RecordDef::Array(self.arr.clone()),
}
}
}
impl RecordParser {
pub fn new(input: &str) -> Self {
Self {
input: input.chars().collect(),
pos: 0,
}
}
pub fn parse(&mut self) -> RecordDef {
let mut frame = RecordParserFrame::new();
loop {
let ch = self.input[self.pos];
match ch {
'{' => {
self.pos += 1;
frame.finalize_label();
let ret = self.parse();
frame.arr.push(ret);
}
'|' => {
self.pos += 1;
frame.finalize_label();
}
'}' => {
self.pos += 1;
frame.finalize_label();
return frame.finalize_record();
}
_ => {
self.pos += 1;
frame.label.push(ch);
}
}
if self.pos == self.input.len() {
return frame.finalize_record();
}
}
}
}
pub fn parse_record_string(label: &str) -> RecordDef {
RecordParser::new(label).parse()
}
pub fn record_builder(label: &str) -> ShapeKind {
let res = parse_record_string(label);
ShapeKind::Record(res)
}