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
use regex::Regex;
use std::cell::RefCell;
use std::fmt::Display;
use std::rc::Rc;
static RE_OPEN_TAG: &str = r#"^\[(?P<tag>[^/\]]+?\S*?)((?:[ \t]+\S+?)?="?(?P<val>[^\]\n]*?))?"?\]"#;
static RE_CLOSE_TAG: &str = r#"^\[/(?P<tag>[^/\]]+?\S*?)\]"#;
#[derive(Debug, PartialEq, Eq)]
pub enum BBTag {
None,
Bold,
Italic,
Underline,
Strikethrough,
FontSize,
FontColor,
Center,
Left,
Right,
Quote,
Spoiler,
Link,
Image,
ListOrdered,
ListUnordered,
ListItem,
Code,
Preformatted,
Table,
TableHeading,
TableRow,
TableCell,
YouTube,
Unknown,
}
impl BBTag {
pub fn get_tag(tag: &str) -> BBTag {
let binding = tag.trim().to_lowercase();
let trim_tag = binding.as_str();
match trim_tag {
"b" => BBTag::Bold,
"i" => BBTag::Italic,
"u" => BBTag::Underline,
"s" => BBTag::Strikethrough,
"size" => BBTag::FontSize,
"color" => BBTag::FontColor,
"center" => BBTag::Center,
"left" => BBTag::Left,
"right" => BBTag::Right,
"quote" => BBTag::Quote,
"spoiler" => BBTag::Spoiler,
"url" => BBTag::Link,
"img" => BBTag::Image,
"ul" => BBTag::ListUnordered,
"list" => BBTag::ListUnordered,
"ol" => BBTag::ListOrdered,
"li" => BBTag::ListItem,
"*" => BBTag::ListItem,
"code" => BBTag::Code,
"pre" => BBTag::Preformatted,
"table" => BBTag::Table,
"tr" => BBTag::TableRow,
"th" => BBTag::TableHeading,
"td" => BBTag::TableCell,
"youtube" => BBTag::YouTube,
"" => BBTag::None,
&_ => BBTag::Unknown,
}
}
}
pub enum MatchType {
Open,
Close,
}
#[derive(Debug)]
pub struct BBNode {
pub text: String,
pub tag: BBTag,
pub value: Option<String>,
pub parent: Option<Rc<RefCell<BBNode>>>,
pub children: Vec<Rc<RefCell<BBNode>>>,
}
impl Default for BBNode {
fn default() -> Self {
Self {
text: "".to_string(),
tag: BBTag::None,
value: None,
parent: None,
children: vec![],
}
}
}
impl Display for BBNode {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let indent = usize::try_from(self.get_depth() * 2).unwrap();
writeln!(f, "{:indent$}Text : {}", "", self.text, indent = indent)?;
writeln!(f, "{:indent$}Tag : {:?}", "", self.tag, indent = indent)?;
writeln!(f, "{:indent$}Value : {:?}", "", self.value, indent = indent)?;
writeln!(
f,
"{:indent$}Parent: {}",
"",
self.parent.is_some(),
indent = indent
)?;
writeln!(f)?;
for child in self.children.iter() {
child.borrow().fmt(f)?;
}
Ok(())
}
}
impl BBNode {
pub fn new(text: &str, tag: BBTag) -> BBNode {
BBNode {
text: String::from(text),
tag,
value: None,
parent: None,
children: vec![],
}
}
fn get_depth(&self) -> i32 {
if self.parent.is_none() {
return 0;
}
return 1 + self.parent.as_ref().unwrap().borrow().get_depth();
}
}
#[allow(dead_code)]
pub struct BBCode {
open_matcher: Regex,
close_matcher: Regex,
}
impl Default for BBCode {
fn default() -> Self {
Self {
open_matcher: Regex::new(RE_OPEN_TAG).unwrap(),
close_matcher: Regex::new(RE_CLOSE_TAG).unwrap(),
}
}
}
impl BBCode {
#[allow(dead_code)]
pub fn parse(&self, input: &str) -> BBNode {
let mut slice = &input[0..];
let root = Rc::new(RefCell::new(BBNode::default()));
let mut curr_node = root.clone();
let mut closed_tag = false;
while !slice.is_empty() {
let captures = self.open_matcher.captures(slice);
if let Some(captures) = captures {
let tag = captures.name("tag").unwrap().as_str();
let bbtag = BBTag::get_tag(tag);
let node = Rc::new(RefCell::new(BBNode::new("", bbtag)));
if let Some(val) = captures.name("val") {
node.borrow_mut().value = Some(val.as_str().to_string());
}
node.borrow_mut().parent = Some(curr_node.clone());
curr_node.borrow_mut().children.push(node.clone());
curr_node = node.clone();
slice = &slice[captures.get(0).unwrap().as_str().len()..];
closed_tag = false;
continue;
} else if let Some(captures) = self.close_matcher.captures(slice) {
let tag = captures.name("tag").unwrap().as_str();
let bbtag = BBTag::get_tag(tag);
if bbtag == curr_node.borrow().tag {
let new_curr = curr_node.borrow().parent.clone().unwrap();
curr_node = new_curr.clone();
slice = &slice[captures.get(0).unwrap().as_str().len()..];
closed_tag = true;
continue;
}
}
if let Some(ch) = slice.chars().next() {
if closed_tag {
let node = Rc::new(RefCell::new(BBNode::new("", BBTag::None)));
node.borrow_mut().parent = Some(curr_node.clone());
curr_node.borrow_mut().children.push(node.clone());
curr_node = node.clone();
}
curr_node.borrow_mut().text.push(ch);
slice = &slice[ch.len_utf8()..];
closed_tag = false;
} else {
break;
}
}
root.take()
}
}
#[cfg(test)]
mod tests {
use super::*;
macro_rules! bbtest_all {
($($name:ident: $value:expr;)*) => {
$(
#[test]
fn $name() {
let open_re = Regex::new(RE_OPEN_TAG).unwrap();
let (input, expected_tag, expected_val) = $value;
let captures = open_re.captures(input);
if expected_tag.is_empty() && expected_val.is_empty() {
assert!(captures.is_none());
} else {
let captures = captures.unwrap();
let tag = captures.name("tag").unwrap().as_str();
assert_eq!(expected_tag, tag);
if expected_val.is_empty() {
let val = captures.name("val");
assert!(val.is_none());
} else {
let val = captures.name("val").unwrap().as_str();
assert_eq!(expected_val, val);
}
}
}
)*
}
}
#[test]
fn build_re() {
let _open_re = Regex::new(RE_OPEN_TAG).unwrap();
let _close_re = Regex::new(RE_CLOSE_TAG).unwrap();
}
#[test]
fn bbcode_default() {
let _bbcode = BBCode::default();
}
#[test]
fn parse() {
let parser = BBCode::default();
let result = parser.parse(r#"[i]oh no[/i] KR Patch for [B][SIZE="4"][URL="https://www.esoui.com/downloads/info1245-TamrielTradeCentre.html"][]Tamriel Trade Centre[/][/URL][/SIZE][/B] or something"#);
println!("{}", result);
}
bbtest_all! {
empty: ("hello", "", "");
bold: ("[b]hello[/b]", "b", "");
no_tag: ("[]hello[/]", "", "");
tag_and_val: ("[size=3]large[/size]", "size", "3");
tag_and_val_quote: (r#"[size="3"]large[/size]"#, "size", "3");
url: ("[url=https://www.com]some url[/url] ", "url", "https://www.com");
multi_tag: (r#"[SIZE="2"][COLOR=#e5e5e5][B]Team:[/COLOR][/B] "#, "SIZE", "2");
}
}