Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions .changeset/from-frame-no-alloc.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
---
---

perf(relay): remove per-frame String allocation in MessageClass::from_frame (#1385)
28 changes: 15 additions & 13 deletions crates/nostream-relay/src/limits.rs
Original file line number Diff line number Diff line change
Expand Up @@ -101,27 +101,29 @@ impl MessageClass {
return Self::Other;
}

let mut word = String::new();
let mut word = [0u8; 8];
let mut len = 0;

loop {
match chars.next() {
Some('"') if !word.is_empty() => break,
Some(c) if word.len() < 8 && (c.is_ascii_alphabetic() || c == '-') => {
word.push(c.to_ascii_uppercase());
Some('"') if len > 0 => break,
Some(c) if len < word.len() && (c.is_ascii_alphabetic() || c == '-') => {
word[len] = c.to_ascii_uppercase() as u8;
len += 1;
}
_ => return Self::Other,
}
}

match word.as_str() {
"REQ" => Self::Req,
"EVENT" => Self::Event,
"COUNT" => Self::Count,
"CLOSE" => Self::Close,
"AUTH" => Self::Auth,
"NEG-OPEN" => Self::NegOpen,
"NEG-MSG" => Self::NegMsg,
"NEG-CLOSE" => Self::NegClose,
match &word[..len] {
b"REQ" => Self::Req,
b"EVENT" => Self::Event,
b"COUNT" => Self::Count,
b"CLOSE" => Self::Close,
b"AUTH" => Self::Auth,
b"NEG-OPEN" => Self::NegOpen,
b"NEG-MSG" => Self::NegMsg,
b"NEG-CLOSE" => Self::NegClose,
_ => Self::Other,
}
}
Expand Down
21 changes: 21 additions & 0 deletions crates/nostream-relay/tests/limits.rs
Original file line number Diff line number Diff line change
Expand Up @@ -764,6 +764,27 @@ fn a_mid_codepoint_cut_at_32_bytes_does_not_panic() {
assert_eq!(MessageClass::from_frame(&frame), MessageClass::Other);
}

#[test]
fn a_frame_whose_prefix_is_not_ascii_is_classified_without_panicking() {
for frame in [
r#"["é"]"#,
r#"["éREQ"]"#,
r#"["REQé"]"#,
"é[\"REQ\"]",
"[\u{00a0}é\"REQ\"]",
] {
assert_eq!(
MessageClass::from_frame(frame),
MessageClass::Other,
"frame {frame:?}"
);
}
assert_eq!(
MessageClass::from_frame("\u{00a0}[\"REQ\",\"café\"]"),
MessageClass::Req
);
}

/// Records every key the message level hands the store.
#[derive(Debug, Default)]
struct RecordingLimiter {
Expand Down
Loading