Skip to content

Commit 4ec78de

Browse files
authored
Reduce parsing allocations (#18)
* Use Cow for node text to avoid allocations when possible * Avoid allocations for tag names * Avoid allocations for parameters when not necessary * Fix new clippy lints
1 parent e83c214 commit 4ec78de

File tree

4 files changed

+54
-42
lines changed

4 files changed

+54
-42
lines changed

src/bbcode/mod.rs

Lines changed: 23 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,14 @@
1-
use std::{collections::HashMap, fmt::Display, sync::Arc};
1+
use std::{borrow::Cow, collections::HashMap, fmt::Display, sync::Arc};
22

33
pub mod parser;
44

55
#[derive(Debug, Clone, PartialEq, Eq)]
6-
pub enum BbcodeNode {
7-
Tag(BbcodeTag),
8-
Text(String),
6+
pub enum BbcodeNode<'a> {
7+
Tag(BbcodeTag<'a>),
8+
Text(Cow<'a, str>),
99
}
1010

11-
impl Display for BbcodeNode {
11+
impl Display for BbcodeNode<'_> {
1212
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1313
match self {
1414
BbcodeNode::Tag(node) => node.fmt(f),
@@ -18,25 +18,25 @@ impl Display for BbcodeNode {
1818
}
1919

2020
#[derive(Debug, Clone, PartialEq, Eq)]
21-
pub struct BbcodeTag {
21+
pub struct BbcodeTag<'a> {
2222
/// The name of the tag, e.g. `tag` for `[tag]something[/tag]`.
23-
name: String,
23+
name: &'a str,
2424

2525
/// A simple parameter for the tag, e.g. `value` for `[tag=value]something[/tag]`.
26-
simple_param: Option<String>,
26+
simple_param: Option<Cow<'a, str>>,
2727

2828
/// Complex parameters, e.g. the map `value1` -> `xxx`, `value2` -> `yyy` for `[tag value1=”xxx” value2=”yyy”]something[/tag]`.
29-
complex_params: HashMap<String, String>,
29+
complex_params: HashMap<&'a str, Cow<'a, str>>,
3030

3131
/// The child nodes (or text) contained inside this node.
32-
children: Vec<Arc<BbcodeNode>>,
32+
children: Vec<Arc<BbcodeNode<'a>>>,
3333
}
3434

35-
impl BbcodeTag {
35+
impl<'a> BbcodeTag<'a> {
3636
/// Create a new, empty tag.
37-
pub fn new<S: Into<String>>(name: S) -> Self {
37+
pub fn new(name: &'a str) -> Self {
3838
Self {
39-
name: name.into(),
39+
name,
4040
simple_param: None,
4141
complex_params: HashMap::new(),
4242
children: Vec::new(),
@@ -45,55 +45,56 @@ impl BbcodeTag {
4545

4646
/// Add a simple parameter to the tag.
4747
#[cfg(test)]
48-
pub fn with_simple_param<P: Into<String>>(mut self, tag_param: P) -> Self {
48+
pub fn with_simple_param<P: Into<Cow<'a, str>>>(mut self, tag_param: P) -> Self {
4949
self.simple_param = Some(tag_param.into());
5050
self
5151
}
5252

5353
/// Add a simple parameter to the tag.
54-
pub fn add_simple_param<P: Into<String>>(&mut self, tag_param: P) -> &mut Self {
54+
pub fn add_simple_param<P: Into<Cow<'a, str>>>(&mut self, tag_param: P) -> &mut Self {
5555
self.simple_param = Some(tag_param.into());
5656
self
5757
}
5858

5959
/// Add a key/value parameter.
6060
#[cfg(test)]
61-
pub fn with_param<K: Into<String>, V: Into<String>>(mut self, key: K, value: V) -> Self {
61+
pub fn with_param<K: Into<&'a str>, V: Into<Cow<'a, str>>>(mut self, key: K, value: V) -> Self {
6262
self.complex_params.insert(key.into(), value.into());
6363
self
6464
}
6565

6666
/// Add a nested tag inside this one.
6767
#[cfg(test)]
68-
pub fn with_tag(mut self, tag: BbcodeTag) -> Self {
68+
pub fn with_tag(mut self, tag: BbcodeTag<'a>) -> Self {
6969
self.children.push(Arc::new(BbcodeNode::Tag(tag)));
7070
self
7171
}
7272

7373
/// Add text inside of the node.
7474
#[cfg(test)]
7575
pub fn with_text<T: Into<String>>(mut self, text: T) -> Self {
76-
self.children.push(Arc::new(BbcodeNode::Text(text.into())));
76+
self.children
77+
.push(Arc::new(BbcodeNode::Text(Cow::Owned(text.into()))));
7778
self
7879
}
7980

8081
/// The name of this tag.
8182
pub fn name(&self) -> &str {
82-
&self.name
83+
self.name
8384
}
8485

8586
/// The child nodes of this tag.
86-
pub fn children(&self) -> &Vec<Arc<BbcodeNode>> {
87+
pub fn children(&self) -> &Vec<Arc<BbcodeNode<'a>>> {
8788
&self.children
8889
}
8990

9091
/// If it exists, the simple tag parameter of this tag.
91-
pub fn simple_param(&self) -> &Option<String> {
92+
pub fn simple_param(&self) -> &Option<Cow<'a, str>> {
9293
&self.simple_param
9394
}
9495
}
9596

96-
impl Display for BbcodeTag {
97+
impl Display for BbcodeTag<'_> {
9798
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
9899
fn fmt_param(param: &str) -> String {
99100
if param.contains(' ') {

src/bbcode/parser.rs

Lines changed: 28 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
use std::sync::Arc;
1+
use std::{borrow::Cow, sync::Arc};
22

33
use nom::{
44
branch::alt,
@@ -25,28 +25,30 @@ pub fn parse_bbcode(input: &str) -> IResult<&str, Vec<Arc<BbcodeNode>>> {
2525

2626
fn parse_bbcode_internal<'a, E: ParseError<&'a str>>(
2727
input: &'a str,
28-
) -> IResult<&'a str, Vec<Arc<BbcodeNode>>, E> {
28+
) -> IResult<&'a str, Vec<Arc<BbcodeNode<'a>>>, E> {
2929
many0(map(parse_node, |element| element.into()))(input)
3030
}
3131

32-
fn parse_node<'a, E: ParseError<&'a str>>(input: &'a str) -> IResult<&'a str, BbcodeNode, E> {
32+
fn parse_node<'a, E: ParseError<&'a str>>(input: &'a str) -> IResult<&'a str, BbcodeNode<'a>, E> {
3333
alt((
3434
map(parse_text, BbcodeNode::Text),
3535
map(parse_tag, BbcodeNode::Tag),
3636
))(input)
3737
}
3838

39-
fn parse_tag<'a, E: ParseError<&'a str>>(input: &'a str) -> IResult<&'a str, BbcodeTag, E> {
39+
fn parse_tag<'a, E: ParseError<&'a str>>(input: &'a str) -> IResult<&'a str, BbcodeTag<'a>, E> {
4040
let (input, mut tag) = parse_opening_tag(input)?;
4141
let (input, children) = parse_bbcode_internal(input)?;
42-
let (input, _) = parse_closing_tag(input, &tag.name)?;
42+
let (input, _) = parse_closing_tag(input, tag.name)?;
4343

4444
tag.children = children;
4545

4646
Ok((input, tag))
4747
}
4848

49-
fn parse_opening_tag<'a, E: ParseError<&'a str>>(input: &'a str) -> IResult<&'a str, BbcodeTag, E> {
49+
fn parse_opening_tag<'a, E: ParseError<&'a str>>(
50+
input: &'a str,
51+
) -> IResult<&'a str, BbcodeTag<'a>, E> {
5052
let (mut input, mut tag) = map(preceded(char('['), alpha1), BbcodeTag::new)(input)?;
5153

5254
if let Ok((new_input, simple_param)) = preceded(char('='), parse_param::<E>)(input) {
@@ -69,19 +71,21 @@ fn parse_closing_tag<'a, E: ParseError<&'a str>>(
6971
)(input)
7072
}
7173

72-
fn parse_text<'a, E: ParseError<&'a str>>(input: &'a str) -> IResult<&'a str, String, E> {
74+
fn parse_text<'a, E: ParseError<&'a str>>(input: &'a str) -> IResult<&'a str, Cow<'a, str>, E> {
7375
parse_inner_string("[]\\").parse(input)
7476
}
7577

76-
fn parse_param<'a, E: ParseError<&'a str>>(input: &'a str) -> IResult<&'a str, String, E> {
78+
fn parse_param<'a, E: ParseError<&'a str>>(input: &'a str) -> IResult<&'a str, Cow<'a, str>, E> {
7779
alt((
7880
parse_quoted_string,
79-
map(parse_literal("\"\\[]"), |literal| literal.to_string()),
81+
map(parse_literal("\"\\[]"), Cow::Borrowed),
8082
))
8183
.parse(input)
8284
}
8385

84-
fn parse_quoted_string<'a, E: ParseError<&'a str>>(input: &'a str) -> IResult<&'a str, String, E> {
86+
fn parse_quoted_string<'a, E: ParseError<&'a str>>(
87+
input: &'a str,
88+
) -> IResult<&'a str, Cow<'a, str>, E> {
8589
delimited(
8690
char('"'),
8791
map(opt(parse_inner_string("\"\\")), |string| {
@@ -94,17 +98,25 @@ fn parse_quoted_string<'a, E: ParseError<&'a str>>(input: &'a str) -> IResult<&'
9498

9599
fn parse_inner_string<'a, E: ParseError<&'a str>>(
96100
exclude: &'a str,
97-
) -> impl Parser<&'a str, String, E> {
101+
) -> impl Parser<&'a str, Cow<'a, str>, E> {
98102
move |input| {
99103
fold_many1(
100104
parse_fragment(exclude),
101-
String::new,
102-
|mut string, fragment| {
105+
Cow::<'a, str>::default,
106+
|mut cow, fragment| {
103107
match fragment {
104-
StringFragment::Literal(s) => string.push_str(s),
105-
StringFragment::EscapedChar(c) => string.push(c),
108+
StringFragment::Literal(s) => {
109+
if cow.is_empty() {
110+
cow = Cow::Borrowed(s);
111+
} else {
112+
cow.to_mut().push_str(s);
113+
}
114+
}
115+
StringFragment::EscapedChar(c) => {
116+
cow.to_mut().push(c);
117+
}
106118
}
107-
string
119+
cow
108120
},
109121
)
110122
.parse(input)

src/bevy/bbcode.rs

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,6 @@ use super::color::BbCodeColor;
66

77
#[derive(Debug, Clone, Component, Default)]
88
#[require(Text, BbcodeSettings)]
9-
109
pub struct Bbcode {
1110
/// The bbcode-formatted text.
1211
pub content: String,

src/bevy/conversion.rs

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -48,7 +48,7 @@ impl BbcodeContext {
4848
}
4949
} else {
5050
Self {
51-
color: color.clone().into(),
51+
color: color.to_string().into(),
5252
..self.clone()
5353
}
5454
}
@@ -60,7 +60,7 @@ impl BbcodeContext {
6060
"m" | "marker" => {
6161
if let Some(marker) = tag.simple_param() {
6262
let mut markers = self.markers.clone();
63-
markers.push(marker.clone());
63+
markers.push(marker.to_string());
6464

6565
Self {
6666
markers,
@@ -74,7 +74,7 @@ impl BbcodeContext {
7474
"font" => {
7575
if let Some(font_family) = tag.simple_param() {
7676
Self {
77-
font_family: font_family.clone(),
77+
font_family: font_family.to_string(),
7878
..self.clone()
7979
}
8080
} else {

0 commit comments

Comments
 (0)