| 1 | use std::ops::Range; |
| 2 | |
| 3 | const HIT_START: &str = "<c0>"; |
| 4 | const HIT_END: &str = "</c0>"; |
| 5 | const ELLIPSIS: &str = "<ddd/>"; |
| 6 | |
| 7 | #[derive(Debug, Clone, Default, PartialEq, Eq)] |
| 8 | pub struct HighlightedText { |
| 9 | pub text: String, |
| 10 | pub hits: Vec<Range<usize>>, |
| 11 | } |
| 12 | |
| 13 | pub fn split_highlights(summary: &str) -> HighlightedText { |
| 14 | let mut highlighted = HighlightedText::default(); |
| 15 | let mut rest = summary; |
| 16 | let mut hit_start: Option<usize> = None; |
| 17 | while !rest.is_empty() { |
| 18 | if let Some(after) = rest.strip_prefix(HIT_START) { |
| 19 | hit_start.get_or_insert(highlighted.text.len()); |
| 20 | rest = after; |
| 21 | } else if let Some(after) = rest.strip_prefix(HIT_END) { |
| 22 | if let Some(start) = hit_start |
| 23 | .take() |
| 24 | .filter(|start| *start < highlighted.text.len()) |
| 25 | { |
| 26 | highlighted.hits.push(start..highlighted.text.len()); |
| 27 | } |
| 28 | rest = after; |
| 29 | } else if let Some(after) = rest.strip_prefix(ELLIPSIS) { |
| 30 | highlighted.text.push_str("..."); |
| 31 | rest = after; |
| 32 | } else { |
| 33 | let next = rest.chars().next().unwrap_or_default(); |
| 34 | highlighted.text.push(next); |
| 35 | rest = &rest[next.len_utf8()..]; |
| 36 | } |
| 37 | } |
| 38 | highlighted |
| 39 | } |
| 40 | |
| 41 | #[cfg(test)] |
| 42 | mod tests { |
| 43 | use super::*; |
| 44 | |
| 45 | #[test] |
| 46 | fn hit_markers_become_byte_ranges_over_the_plain_text() { |
| 47 | let highlighted = split_highlights("Grüße an <c0>Christian</c0> und <c0>Anna</c0>"); |
| 48 | assert_eq!(highlighted.text, "Grüße an Christian und Anna"); |
| 49 | let words: Vec<&str> = highlighted |
| 50 | .hits |
| 51 | .iter() |
| 52 | .map(|hit| &highlighted.text[hit.clone()]) |
| 53 | .collect(); |
| 54 | assert_eq!(words, ["Christian", "Anna"]); |
| 55 | } |
| 56 | |
| 57 | #[test] |
| 58 | fn ellipsis_marker_and_unclosed_hit_are_tolerated() { |
| 59 | let highlighted = split_highlights("<ddd/>end of <c0>text"); |
| 60 | assert_eq!(highlighted.text, "...end of text"); |
| 61 | assert!(highlighted.hits.is_empty()); |
| 62 | } |
| 63 | } |