Skip to content

Commit

Permalink
simplify
Browse files Browse the repository at this point in the history
  • Loading branch information
jjbayer committed Nov 8, 2024
1 parent 9a94fb5 commit b941be8
Showing 1 changed file with 40 additions and 21 deletions.
61 changes: 40 additions & 21 deletions relay-event-normalization/src/normalize/span/description/redis.rs
Original file line number Diff line number Diff line change
@@ -1,26 +1,25 @@
use std::cmp::Ordering;

/// Returns a redis command if it is a case-insensitive prefix of `seek`.
pub fn matching_redis_command(seek: &str) -> Option<&str> {
let seek = seek.as_bytes();
let index = REDIS_COMMANDS
.binary_search_by(|probe| {
let probe = probe.as_bytes();
// step 1 - compare prefixes
for (probe, seek) in probe.iter().zip(seek) {
match probe.to_ascii_lowercase().cmp(&seek.to_ascii_lowercase()) {
Ordering::Equal => continue,
neq => return neq,
};
}
// step 2 - compare length
match probe.len().cmp(&seek.len()) {
Ordering::Greater => Ordering::Greater,
_ => Ordering::Equal,
pub fn matching_redis_command(needle: &str) -> Option<&str> {
let mut longest_match = None;
for command in REDIS_COMMANDS {
if command.len() > longest_match.map_or(0, str::len) {
if is_ascii_prefix_lowercase(command, needle) {
// needle must be either the same length as command OR continue with a non-word
let next_needle_byte = needle.as_bytes().get(command.len()).unwrap_or(&b' ');
if next_needle_byte.is_ascii_whitespace() {
longest_match.replace(command);
}
}
})
.ok()?;
Some(REDIS_COMMANDS[index])
}
}
longest_match
}

fn is_ascii_prefix_lowercase(a: &str, b: &str) -> bool {
(a.len() <= b.len())
&& a.chars()
.zip(b.chars())
.all(|(a, b)| a.to_ascii_lowercase() == b.to_ascii_lowercase())
}

/// List of redis commands.
Expand Down Expand Up @@ -588,4 +587,24 @@ mod tests {
fn empty_needle() {
assert_eq!(matching_redis_command(""), None);
}

#[test]
fn ambiguous1() {
assert_eq!(matching_redis_command("ACL"), Some("ACL"));
}

#[test]
fn ambiguous2() {
assert_eq!(matching_redis_command("ACL CAT"), Some("ACL CAT"));
}

#[test]
fn non_word_boundary() {
assert_eq!(matching_redis_command("ACL cattington"), Some("ACL"));
}

#[test]
fn non_ascii() {
assert_eq!(matching_redis_command("ACL catø"), Some("ACL"));
}
}

0 comments on commit b941be8

Please sign in to comment.