From 5514f0a1428f5dd9f4c0e06b8c17e03389f7b2b4 Mon Sep 17 00:00:00 2001 From: Riccardo Mazzarini Date: Sun, 12 Nov 2023 18:44:26 +0100 Subject: [PATCH] fzf-v2: fix bug in `matches` --- src/algos/fzf/v2.rs | 38 +++++++++++++++++--------------------- tests/fzf_v2.rs | 16 +++++++++++++++- 2 files changed, 32 insertions(+), 22 deletions(-) diff --git a/src/algos/fzf/v2.rs b/src/algos/fzf/v2.rs index 24849e1..bda7654 100644 --- a/src/algos/fzf/v2.rs +++ b/src/algos/fzf/v2.rs @@ -250,14 +250,10 @@ fn matches<'idx>( let mut last_matched_idx = MatchedIdx::default(); - let mut byte_offset; - - let mut matched_char; - loop { let query_char = pattern.char(query_char_idx); - (byte_offset, matched_char) = utils::find_first( + let (byte_offset, matched_char) = utils::find_first( query_char, candidate, is_candidate_ascii, @@ -283,30 +279,30 @@ fn matches<'idx>( candidate.get_unchecked(byte_offset + matched_char_byte_len..) }; + last_matched_idx += + MatchedIdx { byte_offset: matched_char_byte_len, char_offset: 1 }; + if query_char_idx + 1 < pattern.char_len() { - last_matched_idx += MatchedIdx { - byte_offset: matched_char_byte_len, - char_offset: 1, - }; query_char_idx += 1; } else { break; } } - (byte_offset, matched_char) = utils::find_last( - pattern.char(query_char_idx), - candidate, - is_candidate_ascii, - is_case_sensitive, - char_eq, - ) - .unwrap_or((0, matched_char)); + let last_char_offset_inclusive = last_matched_idx.byte_offset + + if let Some((byte_offset, matched_char)) = utils::find_last( + pattern.char(query_char_idx), + candidate, + is_candidate_ascii, + is_case_sensitive, + char_eq, + ) { + byte_offset + matched_char.len_utf8() + } else { + 0 + }; - Some(( - matched_idxs, - last_matched_idx.byte_offset + byte_offset + matched_char.len_utf8(), - )) + Some((matched_idxs, last_char_offset_inclusive)) } /// TODO: docs diff --git a/tests/fzf_v2.rs b/tests/fzf_v2.rs index 08dcc5e..95e00d4 100644 --- a/tests/fzf_v2.rs +++ b/tests/fzf_v2.rs @@ -262,7 +262,7 @@ fn fzf_v2_score_3() { let mach = fzf.distance(parser.parse("\0\0"), "\0#B\0\u{364}\0\0").unwrap(); - assert_eq!(mach.matched_ranges().sorted(), [3..4, 6..7]); + assert_eq!(mach.matched_ranges().sorted(), [6..8]); } #[test] @@ -278,3 +278,17 @@ fn fzf_v2_score_4() { assert_eq!(mach.matched_ranges(), [1..2, 7..9]); } + +#[test] +fn fzf_v2_score_5() { + let mut fzf = FzfV2::new() + .with_case_sensitivity(CaseSensitivity::Insensitive) + .with_matched_ranges(true) + .with_normalization(true); + + let mut parser = FzfParser::new(); + + let mach = fzf.distance(parser.parse("E"), "\u{364}E").unwrap(); + + assert_eq!(mach.matched_ranges(), [0..2]); +}