Skip to content

Commit b7791d0

Browse files
committed
Add a fast path returning Cow::Borrowed for ASCII-only prepping
For already normalized JIDs, this reduces the parsing time by -69.6% to -98.5% depending on the length of the JID, and only increases it for other JIDs by +5.8% which is quite acceptable in that uncommon case.
1 parent bf7e494 commit b7791d0

File tree

1 file changed

+25
-1
lines changed

1 file changed

+25
-1
lines changed

src/lib.rs

Lines changed: 25 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -45,7 +45,8 @@ impl std::error::Error for Error {}
4545
pub fn saslprep(s: &str) -> Result<Cow<'_, str>, Error> {
4646
// fast path for ascii text
4747
if s.chars()
48-
.all(|c| c.is_ascii() && !tables::ascii_control_character(c)) {
48+
.all(|c| c.is_ascii() && !tables::ascii_control_character(c))
49+
{
4950
return Ok(Cow::Borrowed(s));
5051
}
5152

@@ -123,6 +124,13 @@ fn is_prohibited_bidirectional_text(s: &str) -> bool {
123124
///
124125
/// [RFC 3491]: https://tools.ietf.org/html/rfc3491
125126
pub fn nameprep(s: &str) -> Result<Cow<'_, str>, Error> {
127+
// fast path for ascii text
128+
if s.chars()
129+
.all(|c| c.is_ascii_lowercase() && !tables::ascii_control_character(c))
130+
{
131+
return Ok(Cow::Borrowed(s));
132+
}
133+
126134
// 3. Mapping
127135
let mapped = s.chars()
128136
.filter(|&c| !tables::commonly_mapped_to_nothing(c))
@@ -171,6 +179,15 @@ pub fn nameprep(s: &str) -> Result<Cow<'_, str>, Error> {
171179
///
172180
/// [RFC 3920, Appendix A]: https://tools.ietf.org/html/rfc3920#appendix-A
173181
pub fn nodeprep(s: &str) -> Result<Cow<'_, str>, Error> {
182+
// fast path for ascii text
183+
if s.chars().all(|c| {
184+
c.is_ascii_lowercase()
185+
&& !tables::ascii_control_character(c)
186+
&& !prohibited_node_character(c)
187+
}) {
188+
return Ok(Cow::Borrowed(s));
189+
}
190+
174191
// A.3. Mapping
175192
let mapped = s.chars()
176193
.filter(|&c| !tables::commonly_mapped_to_nothing(c))
@@ -229,6 +246,13 @@ fn prohibited_node_character(c: char) -> bool {
229246
///
230247
/// [RFC 3920, Appendix B]: https://tools.ietf.org/html/rfc3920#appendix-B
231248
pub fn resourceprep(s: &str) -> Result<Cow<'_, str>, Error> {
249+
// fast path for ascii text
250+
if s.chars()
251+
.all(|c| c.is_ascii() && !tables::ascii_control_character(c))
252+
{
253+
return Ok(Cow::Borrowed(s));
254+
}
255+
232256
// B.3. Mapping
233257
let mapped = s.chars()
234258
.filter(|&c| !tables::commonly_mapped_to_nothing(c))

0 commit comments

Comments
 (0)