Applies a per-file cap to search results, keeping the top `max_total` results but allowing at most `max_per_file` from any single file. Results must already be sorted by score (descending). Excess results from over-represented files are moved to a spillover list and appended at the end if there's room.
(
candidates: Vec<SearchResult>,
max_total: usize,
max_per_file: usize,
)
| 888 | /// over-represented files are moved to a spillover list and appended at the |
| 889 | /// end if there's room. |
| 890 | fn apply_per_file_cap( |
| 891 | candidates: Vec<SearchResult>, |
| 892 | max_total: usize, |
| 893 | max_per_file: usize, |
| 894 | ) -> Vec<Node> { |
| 895 | let mut file_counts: HashMap<String, usize> = HashMap::new(); |
| 896 | let mut accepted: Vec<Node> = Vec::new(); |
| 897 | let mut spillover: Vec<Node> = Vec::new(); |
| 898 | |
| 899 | for sr in candidates { |
| 900 | let count = file_counts.entry(sr.node.file_path.clone()).or_insert(0); |
| 901 | if *count < max_per_file { |
| 902 | *count += 1; |
| 903 | accepted.push(sr.node); |
| 904 | } else { |
| 905 | spillover.push(sr.node); |
| 906 | } |
| 907 | if accepted.len() >= max_total { |
| 908 | break; |
| 909 | } |
| 910 | } |
| 911 | |
| 912 | // Fill remaining slots from spillover |
| 913 | for node in spillover { |
| 914 | if accepted.len() >= max_total { |
| 915 | break; |
| 916 | } |
| 917 | accepted.push(node); |
| 918 | } |
| 919 | |
| 920 | accepted |
| 921 | } |
| 922 | |
| 923 | #[cfg(test)] |
| 924 | #[allow(clippy::unwrap_used, clippy::expect_used, clippy::float_cmp)] |