From bf84433d5bf1fec7f04f9f896290cab94d149b7e Mon Sep 17 00:00:00 2001 From: Dane Johnson Date: Wed, 12 Oct 2022 11:30:08 -0500 Subject: [PATCH] Use lazy_static! to avoid expensive regex compiles in loop --- Cargo.lock | 7 +++++++ Cargo.toml | 3 ++- src/message.rs | 7 +++++-- 3 files changed, 14 insertions(+), 3 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index ca0e287..a3c984e 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -224,6 +224,7 @@ name = "hexland-server" version = "0.1.0" dependencies = [ "futures", + "lazy_static", "rand", "regex", "sha2", @@ -264,6 +265,12 @@ version = "1.0.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6c8af84674fe1f223a982c933a0ee1086ac4d4052aa0fb8060c12c6ad838e754" +[[package]] +name = "lazy_static" +version = "1.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e2abad23fbc42b3700f2f279844dc832adb2b2eb069b2df918f455c4e18cc646" + [[package]] name = "libc" version = "0.2.133" diff --git a/Cargo.toml b/Cargo.toml index 0e2a5ef..945af69 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -11,4 +11,5 @@ rand = "0.8.5" regex = "1.6.0" tokio = { version = "1.21.2", features = ["full"] } tokio-tungstenite = "0.17.2" -futures = "0.3.24" \ No newline at end of file +futures = "0.3.24" +lazy_static = "1.4.0" \ No newline at end of file diff --git a/src/message.rs b/src/message.rs index 1b0a38d..5824baf 100644 --- a/src/message.rs +++ b/src/message.rs @@ -6,6 +6,7 @@ use tokio_tungstenite::{ tungstenite::Message as WsMessage, }; use futures::{StreamExt, SinkExt}; +use lazy_static::lazy_static; #[derive(PartialEq, Debug)] pub struct Message { @@ -25,8 +26,10 @@ pub enum Error { impl Message { pub fn parse(text: String) -> Result { - let re = regex::Regex::new(r"^([A-Z_]+):\s*(.*)").unwrap(); - match re.captures(text.as_str()) { + lazy_static! { + static ref RE: regex::Regex = regex::Regex::new(r"^([A-Z_]+):\s*(.*)").unwrap(); + } + match RE.captures(text.as_str()) { Some(captures) => { if captures.len() < 3 { Err(Error::BadParse)