summaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authorcyqsimon <28627918+cyqsimon@users.noreply.github.com>2023-10-26 14:59:42 +0800
committerGitHub <noreply@github.com>2023-10-26 14:59:42 +0800
commit2c49b0fc12f37382fde48e616d381171e0321913 (patch)
treecb287c508e365946130d4863f4c6780b801d3c1d
parent34713f699bff998af6b6966ec9e0a28fb75b8586 (diff)
Use `once_cell::sync::Lazy` to make regex usage more ergonomic (#313)
-rw-r--r--src/os/lsof_utils.rs19
1 files changed, 9 insertions, 10 deletions
diff --git a/src/os/lsof_utils.rs b/src/os/lsof_utils.rs
index 166b9c9..ad441e7 100644
--- a/src/os/lsof_utils.rs
+++ b/src/os/lsof_utils.rs
@@ -1,5 +1,6 @@
-use std::{ffi::OsStr, net::IpAddr, process::Command, sync::OnceLock};
+use std::{ffi::OsStr, net::IpAddr, process::Command};
+use once_cell::sync::Lazy;
use regex::Regex;
use crate::{
@@ -18,9 +19,6 @@ pub struct RawConnection {
pub process_name: String,
}
-static CONNECTION_REGEX_ONCE: OnceLock<Regex> = OnceLock::new();
-static LISTEN_REGEX: OnceLock<Regex> = OnceLock::new();
-
fn get_null_addr(ip_type: &str) -> &str {
if ip_type.contains('4') {
"0.0.0.0"
@@ -31,10 +29,6 @@ fn get_null_addr(ip_type: &str) -> &str {
impl RawConnection {
pub fn new(raw_line: &str) -> Option<RawConnection> {
- let connection_regex = CONNECTION_REGEX_ONCE
- .get_or_init(|| Regex::new(r"\[?([^\s\]]*)\]?:(\d+)->\[?([^\s\]]*)\]?:(\d+)").unwrap());
- let listen_regex =
- LISTEN_REGEX.get_or_init(|| Regex::new(r"\[?([^\s\[\]]*)\]?:(.*)").unwrap());
// Example row
// com.apple 664 user 198u IPv4 0xeb179a6650592b8d 0t0 TCP 192.168.1.187:58535->1.2.3.4:443 (ESTABLISHED)
let columns: Vec<&str> = raw_line.split_ascii_whitespace().collect();
@@ -59,8 +53,13 @@ impl RawConnection {
let connection_str = columns[8];
// "(LISTEN)" or "(ESTABLISHED)", this column may or may not be present
// let connection_state = columns[9];
+
+ static CONNECTION_REGEX: Lazy<Regex> =
+ Lazy::new(|| Regex::new(r"\[?([^\s\]]*)\]?:(\d+)->\[?([^\s\]]*)\]?:(\d+)").unwrap());
+ static LISTEN_REGEX: Lazy<Regex> =
+ Lazy::new(|| Regex::new(r"\[?([^\s\[\]]*)\]?:(.*)").unwrap());
// If this socket is in a "connected" state
- if let Some(caps) = connection_regex.captures(connection_str) {
+ if let Some(caps) = CONNECTION_REGEX.captures(connection_str) {
// Example
// 192.168.1.187:64230->0.1.2.3:5228
// *:*
@@ -78,7 +77,7 @@ impl RawConnection {
process_name,
};
Some(connection)
- } else if let Some(caps) = listen_regex.captures(connection_str) {
+ } else if let Some(caps) = LISTEN_REGEX.captures(connection_str) {
let local_ip = if caps.get(1).unwrap().as_str() == "*" {
get_null_addr(ip_type)
} else {