1use fancy_regex::Regex as FancyRegex;
23use regex::Regex;
24use std::collections::HashMap;
25use std::sync::LazyLock;
26use std::sync::{Arc, Mutex};
27
28#[derive(Debug)]
30pub struct RegexCache {
31 cache: HashMap<String, Arc<Regex>>,
32 fancy_cache: HashMap<String, Arc<FancyRegex>>,
33 usage_stats: HashMap<String, u64>,
34}
35
36impl Default for RegexCache {
37 fn default() -> Self {
38 Self::new()
39 }
40}
41
42impl RegexCache {
43 pub fn new() -> Self {
44 Self {
45 cache: HashMap::new(),
46 fancy_cache: HashMap::new(),
47 usage_stats: HashMap::new(),
48 }
49 }
50
51 pub fn get_regex(&mut self, pattern: &str) -> Result<Arc<Regex>, regex::Error> {
53 if let Some(regex) = self.cache.get(pattern) {
54 *self.usage_stats.entry(pattern.to_string()).or_insert(0) += 1;
55 return Ok(regex.clone());
56 }
57
58 let regex = Arc::new(Regex::new(pattern)?);
59 self.cache.insert(pattern.to_string(), regex.clone());
60 *self.usage_stats.entry(pattern.to_string()).or_insert(0) += 1;
61 Ok(regex)
62 }
63
64 pub fn get_fancy_regex(&mut self, pattern: &str) -> Result<Arc<FancyRegex>, Box<fancy_regex::Error>> {
66 if let Some(regex) = self.fancy_cache.get(pattern) {
67 *self.usage_stats.entry(pattern.to_string()).or_insert(0) += 1;
68 return Ok(regex.clone());
69 }
70
71 match FancyRegex::new(pattern) {
72 Ok(regex) => {
73 let arc_regex = Arc::new(regex);
74 self.fancy_cache.insert(pattern.to_string(), arc_regex.clone());
75 *self.usage_stats.entry(pattern.to_string()).or_insert(0) += 1;
76 Ok(arc_regex)
77 }
78 Err(e) => Err(Box::new(e)),
79 }
80 }
81
82 pub fn get_stats(&self) -> HashMap<String, u64> {
84 self.usage_stats.clone()
85 }
86
87 pub fn clear(&mut self) {
89 self.cache.clear();
90 self.fancy_cache.clear();
91 self.usage_stats.clear();
92 }
93}
94
95static GLOBAL_REGEX_CACHE: LazyLock<Arc<Mutex<RegexCache>>> = LazyLock::new(|| Arc::new(Mutex::new(RegexCache::new())));
97
98pub fn get_cached_regex(pattern: &str) -> Result<Arc<Regex>, regex::Error> {
104 let mut cache = GLOBAL_REGEX_CACHE.lock().unwrap_or_else(|poisoned| {
105 let mut guard = poisoned.into_inner();
107 guard.clear();
108 guard
109 });
110 cache.get_regex(pattern)
111}
112
113pub fn get_cached_fancy_regex(pattern: &str) -> Result<Arc<FancyRegex>, Box<fancy_regex::Error>> {
119 let mut cache = GLOBAL_REGEX_CACHE.lock().unwrap_or_else(|poisoned| {
120 let mut guard = poisoned.into_inner();
122 guard.clear();
123 guard
124 });
125 cache.get_fancy_regex(pattern)
126}
127
128pub fn get_cache_stats() -> HashMap<String, u64> {
132 match GLOBAL_REGEX_CACHE.lock() {
133 Ok(cache) => cache.get_stats(),
134 Err(_) => HashMap::new(),
135 }
136}
137
138#[macro_export]
156macro_rules! regex_lazy {
157 ($pattern:expr) => {{
158 static REGEX: LazyLock<regex::Regex> = LazyLock::new(|| regex::Regex::new($pattern).unwrap());
159 &*REGEX
160 }};
161}
162
163#[macro_export]
170macro_rules! regex_cached {
171 ($pattern:expr) => {{ $crate::utils::regex_cache::get_cached_regex($pattern).expect("Failed to compile regex") }};
172}
173
174#[macro_export]
181macro_rules! fancy_regex_cached {
182 ($pattern:expr) => {{ $crate::utils::regex_cache::get_cached_fancy_regex($pattern).expect("Failed to compile fancy regex") }};
183}
184
185pub use crate::regex_lazy;
187
188pub const URL_STANDARD_STR: &str = concat!(
222 r#"(?:https?|ftps?|ftp)://"#, r#"(?:"#,
224 r#"\[[0-9a-fA-F:%.\-a-zA-Z]+\]"#, r#"|"#,
226 r#"[^\s<>\[\]()\\'\"`/]+"#, r#")"#,
228 r#"(?::\d+)?"#, r#"(?:/[^\s<>\[\]\\'\"`]*)?"#, r#"(?:\?[^\s<>\[\]\\'\"`]*)?"#, r#"(?:#[^\s<>\[\]\\'\"`]*)?"#, );
233
234pub const URL_WWW_STR: &str = concat!(
239 r#"www\.(?:[a-zA-Z0-9][-a-zA-Z0-9]*\.)+[a-zA-Z]{2,}"#, r#"(?:/[^\s<>\[\]\\'\"`]*)?"#, );
242
243pub const URL_IPV6_STR: &str = concat!(
248 r#"(?:https?|ftps?|ftp)://"#,
249 r#"\[[0-9a-fA-F:%.\-a-zA-Z]+\]"#, r#"(?::\d+)?"#, r#"(?:/[^\s<>\[\]\\'\"`]*)?"#, r#"(?:\?[^\s<>\[\]\\'\"`]*)?"#, r#"(?:#[^\s<>\[\]\\'\"`]*)?"#, );
255
256pub const URL_QUICK_CHECK_STR: &str = r#"(?:https?|ftps?|ftp)://|@|www\."#;
261
262pub const URL_SIMPLE_STR: &str = r#"(?:https?|ftps?|ftp)://[^\s<>]+[^\s<>.,]"#;
268
269pub static URL_STANDARD_REGEX: LazyLock<Regex> = LazyLock::new(|| Regex::new(URL_STANDARD_STR).unwrap());
274
275pub static URL_WWW_REGEX: LazyLock<Regex> = LazyLock::new(|| Regex::new(URL_WWW_STR).unwrap());
278
279pub static URL_IPV6_REGEX: LazyLock<Regex> = LazyLock::new(|| Regex::new(URL_IPV6_STR).unwrap());
282
283pub static URL_QUICK_CHECK_REGEX: LazyLock<Regex> = LazyLock::new(|| Regex::new(URL_QUICK_CHECK_STR).unwrap());
286
287pub static URL_SIMPLE_REGEX: LazyLock<Regex> = LazyLock::new(|| Regex::new(URL_SIMPLE_STR).unwrap());
290
291pub static URL_PATTERN: LazyLock<Regex> = LazyLock::new(|| URL_SIMPLE_REGEX.clone());
293
294pub static ATX_HEADING_REGEX: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"^(\s*)(#{1,6})(\s+|$)").unwrap());
296pub static CLOSED_ATX_HEADING_REGEX: LazyLock<Regex> =
297 LazyLock::new(|| Regex::new(r"^(\s*)(#{1,6})(\s+)(.*)(\s+)(#+)(\s*)$").unwrap());
298pub static SETEXT_HEADING_REGEX: LazyLock<Regex> =
299 LazyLock::new(|| Regex::new(r"^(\s*)[^\s]+.*\n(\s*)(=+|-+)\s*$").unwrap());
300pub static TRAILING_PUNCTUATION_REGEX: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"[.,:);!?]$").unwrap());
301
302pub static ATX_HEADING_WITH_CAPTURE: LazyLock<Regex> =
304 LazyLock::new(|| Regex::new(r"^(#{1,6})\s+(.+?)(?:\s+#*\s*)?$").unwrap());
305pub static SETEXT_HEADING_WITH_CAPTURE: LazyLock<FancyRegex> =
306 LazyLock::new(|| FancyRegex::new(r"^([^\n]+)\n([=\-])\2+\s*$").unwrap());
307
308pub static UNORDERED_LIST_MARKER_REGEX: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"^(\s*)([*+-])(\s+)").unwrap());
310pub static ORDERED_LIST_MARKER_REGEX: LazyLock<Regex> =
311 LazyLock::new(|| Regex::new(r"^(\s*)(\d+)([.)])(\s+)").unwrap());
312pub static LIST_MARKER_ANY_REGEX: LazyLock<Regex> =
313 LazyLock::new(|| Regex::new(r"^(\s*)(?:([*+-])|(\d+)[.)])(\s+)").unwrap());
314
315pub static FENCED_CODE_BLOCK_START_REGEX: LazyLock<Regex> =
317 LazyLock::new(|| Regex::new(r"^(\s*)(```|~~~)(.*)$").unwrap());
318pub static FENCED_CODE_BLOCK_END_REGEX: LazyLock<Regex> =
319 LazyLock::new(|| Regex::new(r"^(\s*)(```|~~~)(\s*)$").unwrap());
320pub static INDENTED_CODE_BLOCK_REGEX: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"^(\s{4,})(.*)$").unwrap());
321pub static CODE_FENCE_REGEX: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"^(`{3,}|~{3,})").unwrap());
322
323pub static EMPHASIS_REGEX: LazyLock<FancyRegex> =
325 LazyLock::new(|| FancyRegex::new(r"(\s|^)(\*{1,2}|_{1,2})(?=\S)(.+?)(?<=\S)(\2)(\s|$)").unwrap());
326pub static SPACE_IN_EMPHASIS_REGEX: LazyLock<FancyRegex> =
327 LazyLock::new(|| FancyRegex::new(r"(\*|_)(\s+)(.+?)(\s+)(\1)").unwrap());
328
329pub static ASTERISK_EMPHASIS: LazyLock<Regex> =
333 LazyLock::new(|| Regex::new(r"(?:^|[^*])\*(\s+[^*]+\s*|\s*[^*]+\s+)\*(?:[^*]|$)").unwrap());
334pub static UNDERSCORE_EMPHASIS: LazyLock<Regex> =
335 LazyLock::new(|| Regex::new(r"(?:^|[^_])_(\s+[^_]+\s*|\s*[^_]+\s+)_(?:[^_]|$)").unwrap());
336pub static DOUBLE_UNDERSCORE_EMPHASIS: LazyLock<Regex> =
337 LazyLock::new(|| Regex::new(r"(?:^|[^_])__(\s+[^_]+\s*|\s*[^_]+\s+)__(?:[^_]|$)").unwrap());
338pub static DOUBLE_ASTERISK_EMPHASIS: LazyLock<FancyRegex> =
339 LazyLock::new(|| FancyRegex::new(r"\*\*\s+([^*]+?)\s+\*\*").unwrap());
340pub static DOUBLE_ASTERISK_SPACE_START: LazyLock<FancyRegex> =
341 LazyLock::new(|| FancyRegex::new(r"\*\*\s+([^*]+?)\*\*").unwrap());
342pub static DOUBLE_ASTERISK_SPACE_END: LazyLock<FancyRegex> =
343 LazyLock::new(|| FancyRegex::new(r"\*\*([^*]+?)\s+\*\*").unwrap());
344
345pub static FENCED_CODE_BLOCK_START: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"^(\s*)```(?:[^`\r\n]*)$").unwrap());
347pub static FENCED_CODE_BLOCK_END: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"^(\s*)```\s*$").unwrap());
348pub static ALTERNATE_FENCED_CODE_BLOCK_START: LazyLock<Regex> =
349 LazyLock::new(|| Regex::new(r"^(\s*)~~~(?:[^~\r\n]*)$").unwrap());
350pub static ALTERNATE_FENCED_CODE_BLOCK_END: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"^(\s*)~~~\s*$").unwrap());
351pub static INDENTED_CODE_BLOCK_PATTERN: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"^(\s{4,})").unwrap());
352
353pub static HTML_TAG_REGEX: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"<([a-zA-Z][^>]*)>").unwrap());
355pub static HTML_SELF_CLOSING_TAG_REGEX: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"<([a-zA-Z][^>]*/)>").unwrap());
356pub static HTML_TAG_FINDER: LazyLock<Regex> = LazyLock::new(|| Regex::new("(?i)</?[a-zA-Z][^>]*>").unwrap());
357pub static HTML_OPENING_TAG_FINDER: LazyLock<Regex> = LazyLock::new(|| Regex::new("(?i)<[a-zA-Z][^>]*>").unwrap());
358pub static HTML_TAG_QUICK_CHECK: LazyLock<Regex> = LazyLock::new(|| Regex::new("(?i)</?[a-zA-Z]").unwrap());
359
360pub static LINK_REFERENCE_DEFINITION_REGEX: LazyLock<Regex> =
362 LazyLock::new(|| Regex::new(r"^\s*\[([^\]]+)\]:\s+(.+)$").unwrap());
363pub static INLINE_LINK_REGEX: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"\[([^\]]+)\]\(([^)]+)\)").unwrap());
364pub static LINK_TEXT_REGEX: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"\[([^\]]*)\]").unwrap());
365pub static LINK_REGEX: LazyLock<FancyRegex> =
366 LazyLock::new(|| FancyRegex::new(r"(?<!\\)\[([^\]]*)\]\(([^)#]*)#([^)]+)\)").unwrap());
367pub static EXTERNAL_URL_REGEX: LazyLock<FancyRegex> =
368 LazyLock::new(|| FancyRegex::new(r"^(https?://|ftp://|www\.|[^/]+\.[a-z]{2,})").unwrap());
369
370pub static IMAGE_REGEX: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"!\[([^\]]*)\]\(([^)]+)\)").unwrap());
372
373pub static TRAILING_WHITESPACE_REGEX: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"\s+$").unwrap());
375pub static MULTIPLE_BLANK_LINES_REGEX: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"\n{3,}").unwrap());
376
377pub static FRONT_MATTER_REGEX: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"^---\n.*?\n---\n").unwrap());
379
380pub static INLINE_CODE_REGEX: LazyLock<FancyRegex> = LazyLock::new(|| FancyRegex::new(r"`[^`]+`").unwrap());
382pub static BOLD_ASTERISK_REGEX: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"\*\*(.+?)\*\*").unwrap());
383pub static BOLD_UNDERSCORE_REGEX: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"__(.+?)__").unwrap());
384pub static ITALIC_ASTERISK_REGEX: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"\*([^*]+?)\*").unwrap());
385pub static ITALIC_UNDERSCORE_REGEX: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"_([^_]+?)_").unwrap());
386pub static LINK_TEXT_FULL_REGEX: LazyLock<FancyRegex> =
387 LazyLock::new(|| FancyRegex::new(r"\[([^\]]*)\]\([^)]*\)").unwrap());
388pub static STRIKETHROUGH_REGEX: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"~~(.+?)~~").unwrap());
389pub static MULTIPLE_HYPHENS: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"-{2,}").unwrap());
390pub static TOC_SECTION_START: LazyLock<Regex> =
391 LazyLock::new(|| Regex::new(r"^#+\s*(?:Table of Contents|Contents|TOC)\s*$").unwrap());
392
393pub static BLOCKQUOTE_PREFIX_RE: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"^(\s*>+\s*)").unwrap());
395
396pub static IMAGE_REF_PATTERN: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"^!\[.*?\]\[.*?\]$").unwrap());
398pub static LINK_REF_PATTERN: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"^\[.*?\]:\s*https?://\S+$").unwrap());
399pub static URL_IN_TEXT: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"https?://\S+").unwrap());
407pub static SENTENCE_END: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"[.!?]\s+[A-Z]").unwrap());
408pub static ABBREVIATION: LazyLock<Regex> = LazyLock::new(|| {
409 Regex::new(r"\b(?:Mr|Mrs|Ms|Dr|Prof|Sr|Jr|vs|etc|i\.e|e\.g|Inc|Corp|Ltd|Co|St|Ave|Blvd|Rd|Ph\.D|M\.D|B\.A|M\.A|Ph\.D|U\.S|U\.K|U\.N|N\.Y|L\.A|D\.C)\.\s+[A-Z]").unwrap()
410});
411pub static DECIMAL_NUMBER: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"\d+\.\s*\d+").unwrap());
412pub static LIST_ITEM: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"^\s*\d+\.\s+").unwrap());
413pub static REFERENCE_LINK: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"\[([^\]]*)\]\[([^\]]*)\]").unwrap());
414
415pub static EMAIL_PATTERN: LazyLock<Regex> =
417 LazyLock::new(|| Regex::new(r"[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}").unwrap());
418
419pub static REF_LINK_REGEX: LazyLock<FancyRegex> =
423 LazyLock::new(|| FancyRegex::new(r"(?<!\\)\[((?:[^\[\]\\]|\\.|\[[^\]]*\])*)\]\[([^\]]*)\]").unwrap());
424
425pub static SHORTCUT_REF_REGEX: LazyLock<FancyRegex> =
430 LazyLock::new(|| FancyRegex::new(r"(?<![\\)\]])\[((?:[^\[\]\\]|\\.|\[[^\]]*\])*)\](?!\s*[\[\(])").unwrap());
431
432pub static INLINE_LINK_FANCY_REGEX: LazyLock<FancyRegex> =
434 LazyLock::new(|| FancyRegex::new(r"(?<!\\)\[([^\]]+)\]\(([^)]+)\)").unwrap());
435
436pub static INLINE_IMAGE_FANCY_REGEX: LazyLock<FancyRegex> =
438 LazyLock::new(|| FancyRegex::new(r"!\[([^\]]*)\]\(([^)]+)\)").unwrap());
439
440pub static LINKED_IMAGE_INLINE_INLINE: LazyLock<FancyRegex> =
448 LazyLock::new(|| FancyRegex::new(r"\[!\[([^\]]*)\]\(([^)]+)\)\]\(([^)]+)\)").unwrap());
449
450pub static LINKED_IMAGE_REF_INLINE: LazyLock<FancyRegex> =
452 LazyLock::new(|| FancyRegex::new(r"\[!\[([^\]]*)\]\[([^\]]*)\]\]\(([^)]+)\)").unwrap());
453
454pub static LINKED_IMAGE_INLINE_REF: LazyLock<FancyRegex> =
456 LazyLock::new(|| FancyRegex::new(r"\[!\[([^\]]*)\]\(([^)]+)\)\]\[([^\]]*)\]").unwrap());
457
458pub static LINKED_IMAGE_REF_REF: LazyLock<FancyRegex> =
460 LazyLock::new(|| FancyRegex::new(r"\[!\[([^\]]*)\]\[([^\]]*)\]\]\[([^\]]*)\]").unwrap());
461
462pub static REF_IMAGE_REGEX: LazyLock<FancyRegex> =
464 LazyLock::new(|| FancyRegex::new(r"!\[((?:[^\[\]\\]|\\.|\[[^\]]*\])*)\]\[([^\]]*)\]").unwrap());
465
466pub static FOOTNOTE_REF_REGEX: LazyLock<FancyRegex> = LazyLock::new(|| FancyRegex::new(r"\[\^([^\]]+)\]").unwrap());
468
469pub static STRIKETHROUGH_FANCY_REGEX: LazyLock<FancyRegex> = LazyLock::new(|| FancyRegex::new(r"~~([^~]+)~~").unwrap());
471
472pub static WIKI_LINK_REGEX: LazyLock<FancyRegex> = LazyLock::new(|| FancyRegex::new(r"\[\[([^\]]+)\]\]").unwrap());
474
475pub static INLINE_MATH_REGEX: LazyLock<FancyRegex> =
477 LazyLock::new(|| FancyRegex::new(r"(?<!\$)\$(?!\$)([^\$]+)\$(?!\$)").unwrap());
478pub static DISPLAY_MATH_REGEX: LazyLock<FancyRegex> = LazyLock::new(|| FancyRegex::new(r"\$\$([^\$]+)\$\$").unwrap());
479
480pub static EMOJI_SHORTCODE_REGEX: LazyLock<FancyRegex> =
482 LazyLock::new(|| FancyRegex::new(r":([a-zA-Z0-9_+-]+):").unwrap());
483
484pub static HTML_TAG_PATTERN: LazyLock<FancyRegex> =
486 LazyLock::new(|| FancyRegex::new(r"</?[a-zA-Z][^>]*>|<[a-zA-Z][^>]*/\s*>").unwrap());
487
488pub static HTML_ENTITY_REGEX: LazyLock<FancyRegex> =
490 LazyLock::new(|| FancyRegex::new(r"&[a-zA-Z][a-zA-Z0-9]*;|&#\d+;|&#x[0-9a-fA-F]+;").unwrap());
491
492pub static HUGO_SHORTCODE_REGEX: LazyLock<FancyRegex> =
496 LazyLock::new(|| FancyRegex::new(r"\{\{[<%][\s\S]*?[%>]\}\}").unwrap());
497
498pub static HTML_COMMENT_START: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"<!--").unwrap());
501pub static HTML_COMMENT_END: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"-->").unwrap());
502pub static HTML_COMMENT_PATTERN: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"<!--[\s\S]*?-->").unwrap());
503
504pub static HTML_HEADING_PATTERN: LazyLock<FancyRegex> =
506 LazyLock::new(|| FancyRegex::new(r"^\s*<h([1-6])(?:\s[^>]*)?>.*</h\1>\s*$").unwrap());
507
508pub static HEADING_CHECK: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"(?m)^(?:\s*)#").unwrap());
510
511pub static HR_DASH: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"^\-{3,}\s*$").unwrap());
513pub static HR_ASTERISK: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"^\*{3,}\s*$").unwrap());
514pub static HR_UNDERSCORE: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"^_{3,}\s*$").unwrap());
515pub static HR_SPACED_DASH: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"^(\-\s+){2,}\-\s*$").unwrap());
516pub static HR_SPACED_ASTERISK: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"^(\*\s+){2,}\*\s*$").unwrap());
517pub static HR_SPACED_UNDERSCORE: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"^(_\s+){2,}_\s*$").unwrap());
518
519pub fn has_heading_markers(content: &str) -> bool {
522 content.contains('#')
523}
524
525pub fn has_list_markers(content: &str) -> bool {
527 content.contains('*')
528 || content.contains('-')
529 || content.contains('+')
530 || (content.contains('.') && content.contains(|c: char| c.is_ascii_digit()))
531}
532
533pub fn has_code_block_markers(content: &str) -> bool {
535 content.contains("```") || content.contains("~~~") || content.contains("\n ")
536 }
538
539pub fn has_emphasis_markers(content: &str) -> bool {
541 content.contains('*') || content.contains('_')
542}
543
544pub fn has_html_tags(content: &str) -> bool {
546 content.contains('<') && (content.contains('>') || content.contains("/>"))
547}
548
549pub fn has_link_markers(content: &str) -> bool {
551 (content.contains('[') && content.contains(']'))
552 || content.contains("http://")
553 || content.contains("https://")
554 || content.contains("ftp://")
555}
556
557pub fn has_image_markers(content: &str) -> bool {
559 content.contains("![")
560}
561
562pub fn contains_url(content: &str) -> bool {
565 if !content.contains("://") {
567 return false;
568 }
569
570 let chars: Vec<char> = content.chars().collect();
571 let mut i = 0;
572
573 while i < chars.len() {
574 if i + 2 < chars.len()
576 && ((chars[i] == 'h' && chars[i + 1] == 't' && chars[i + 2] == 't')
577 || (chars[i] == 'f' && chars[i + 1] == 't' && chars[i + 2] == 'p'))
578 {
579 let mut j = i;
581 while j + 2 < chars.len() {
582 if chars[j] == ':' && chars[j + 1] == '/' && chars[j + 2] == '/' {
583 return true;
584 }
585 j += 1;
586
587 if j > i + 10 {
589 break;
590 }
591 }
592 }
593 i += 1;
594 }
595
596 false
597}
598
599pub fn escape_regex(s: &str) -> String {
601 let mut result = String::with_capacity(s.len() * 2);
602
603 for c in s.chars() {
604 if matches!(
606 c,
607 '.' | '+' | '*' | '?' | '^' | '$' | '(' | ')' | '[' | ']' | '{' | '}' | '|' | '\\'
608 ) {
609 result.push('\\');
610 }
611 result.push(c);
612 }
613
614 result
615}
616
617#[cfg(test)]
618mod tests {
619 use super::*;
620
621 #[test]
622 fn test_regex_cache_new() {
623 let cache = RegexCache::new();
624 assert!(cache.cache.is_empty());
625 assert!(cache.fancy_cache.is_empty());
626 assert!(cache.usage_stats.is_empty());
627 }
628
629 #[test]
630 fn test_regex_cache_default() {
631 let cache = RegexCache::default();
632 assert!(cache.cache.is_empty());
633 assert!(cache.fancy_cache.is_empty());
634 assert!(cache.usage_stats.is_empty());
635 }
636
637 #[test]
638 fn test_get_regex_compilation() {
639 let mut cache = RegexCache::new();
640
641 let regex1 = cache.get_regex(r"\d+").unwrap();
643 assert_eq!(cache.cache.len(), 1);
644 assert_eq!(cache.usage_stats.get(r"\d+"), Some(&1));
645
646 let regex2 = cache.get_regex(r"\d+").unwrap();
648 assert_eq!(cache.cache.len(), 1);
649 assert_eq!(cache.usage_stats.get(r"\d+"), Some(&2));
650
651 assert!(Arc::ptr_eq(®ex1, ®ex2));
653 }
654
655 #[test]
656 fn test_get_regex_invalid_pattern() {
657 let mut cache = RegexCache::new();
658 let result = cache.get_regex(r"[unterminated");
659 assert!(result.is_err());
660 assert!(cache.cache.is_empty());
661 }
662
663 #[test]
664 fn test_get_fancy_regex_compilation() {
665 let mut cache = RegexCache::new();
666
667 let regex1 = cache.get_fancy_regex(r"(?<=foo)bar").unwrap();
669 assert_eq!(cache.fancy_cache.len(), 1);
670 assert_eq!(cache.usage_stats.get(r"(?<=foo)bar"), Some(&1));
671
672 let regex2 = cache.get_fancy_regex(r"(?<=foo)bar").unwrap();
674 assert_eq!(cache.fancy_cache.len(), 1);
675 assert_eq!(cache.usage_stats.get(r"(?<=foo)bar"), Some(&2));
676
677 assert!(Arc::ptr_eq(®ex1, ®ex2));
679 }
680
681 #[test]
682 fn test_get_fancy_regex_invalid_pattern() {
683 let mut cache = RegexCache::new();
684 let result = cache.get_fancy_regex(r"(?<=invalid");
685 assert!(result.is_err());
686 assert!(cache.fancy_cache.is_empty());
687 }
688
689 #[test]
690 fn test_get_stats() {
691 let mut cache = RegexCache::new();
692
693 let _ = cache.get_regex(r"\d+").unwrap();
695 let _ = cache.get_regex(r"\d+").unwrap();
696 let _ = cache.get_regex(r"\w+").unwrap();
697 let _ = cache.get_fancy_regex(r"(?<=foo)bar").unwrap();
698
699 let stats = cache.get_stats();
700 assert_eq!(stats.get(r"\d+"), Some(&2));
701 assert_eq!(stats.get(r"\w+"), Some(&1));
702 assert_eq!(stats.get(r"(?<=foo)bar"), Some(&1));
703 }
704
705 #[test]
706 fn test_clear_cache() {
707 let mut cache = RegexCache::new();
708
709 let _ = cache.get_regex(r"\d+").unwrap();
711 let _ = cache.get_fancy_regex(r"(?<=foo)bar").unwrap();
712
713 assert!(!cache.cache.is_empty());
714 assert!(!cache.fancy_cache.is_empty());
715 assert!(!cache.usage_stats.is_empty());
716
717 cache.clear();
719
720 assert!(cache.cache.is_empty());
721 assert!(cache.fancy_cache.is_empty());
722 assert!(cache.usage_stats.is_empty());
723 }
724
725 #[test]
726 fn test_global_cache_functions() {
727 let regex1 = get_cached_regex(r"\d{3}").unwrap();
729 let regex2 = get_cached_regex(r"\d{3}").unwrap();
730 assert!(Arc::ptr_eq(®ex1, ®ex2));
731
732 let fancy1 = get_cached_fancy_regex(r"(?<=test)ing").unwrap();
734 let fancy2 = get_cached_fancy_regex(r"(?<=test)ing").unwrap();
735 assert!(Arc::ptr_eq(&fancy1, &fancy2));
736
737 let stats = get_cache_stats();
739 assert!(stats.contains_key(r"\d{3}"));
740 assert!(stats.contains_key(r"(?<=test)ing"));
741 }
742
743 #[test]
744 fn test_regex_lazy_macro() {
745 let re = regex_lazy!(r"^test.*end$");
746 assert!(re.is_match("test something end"));
747 assert!(!re.is_match("test something"));
748
749 let re2 = regex_lazy!(r"^start.*finish$");
753 assert!(re2.is_match("start and finish"));
754 assert!(!re2.is_match("start without end"));
755 }
756
757 #[test]
758 fn test_has_heading_markers() {
759 assert!(has_heading_markers("# Heading"));
760 assert!(has_heading_markers("Text with # symbol"));
761 assert!(!has_heading_markers("Text without heading marker"));
762 }
763
764 #[test]
765 fn test_has_list_markers() {
766 assert!(has_list_markers("* Item"));
767 assert!(has_list_markers("- Item"));
768 assert!(has_list_markers("+ Item"));
769 assert!(has_list_markers("1. Item"));
770 assert!(!has_list_markers("Text without list markers"));
771 }
772
773 #[test]
774 fn test_has_code_block_markers() {
775 assert!(has_code_block_markers("```code```"));
776 assert!(has_code_block_markers("~~~code~~~"));
777 assert!(has_code_block_markers("Text\n indented code"));
778 assert!(!has_code_block_markers("Text without code blocks"));
779 }
780
781 #[test]
782 fn test_has_emphasis_markers() {
783 assert!(has_emphasis_markers("*emphasis*"));
784 assert!(has_emphasis_markers("_emphasis_"));
785 assert!(has_emphasis_markers("**bold**"));
786 assert!(has_emphasis_markers("__bold__"));
787 assert!(!has_emphasis_markers("no emphasis"));
788 }
789
790 #[test]
791 fn test_has_html_tags() {
792 assert!(has_html_tags("<div>content</div>"));
793 assert!(has_html_tags("<br/>"));
794 assert!(has_html_tags("<img src='test.jpg'>"));
795 assert!(!has_html_tags("no html tags"));
796 assert!(!has_html_tags("less than < but no tag"));
797 }
798
799 #[test]
800 fn test_has_link_markers() {
801 assert!(has_link_markers("[text](url)"));
802 assert!(has_link_markers("[reference][1]"));
803 assert!(has_link_markers("http://example.com"));
804 assert!(has_link_markers("https://example.com"));
805 assert!(has_link_markers("ftp://example.com"));
806 assert!(!has_link_markers("no links here"));
807 }
808
809 #[test]
810 fn test_has_image_markers() {
811 assert!(has_image_markers(""));
812 assert!(has_image_markers(""));
813 assert!(!has_image_markers("[link](url)"));
814 assert!(!has_image_markers("no images"));
815 }
816
817 #[test]
818 fn test_contains_url() {
819 assert!(contains_url("http://example.com"));
820 assert!(contains_url("Text with https://example.com link"));
821 assert!(contains_url("ftp://example.com"));
822 assert!(!contains_url("Text without URL"));
823 assert!(!contains_url("http not followed by ://"));
824
825 assert!(!contains_url("http"));
827 assert!(!contains_url("https"));
828 assert!(!contains_url("://"));
829 assert!(contains_url("Visit http://site.com now"));
830 assert!(contains_url("See https://secure.site.com/path"));
831 }
832
833 #[test]
834 fn test_contains_url_performance() {
835 let long_text = "a".repeat(10000);
837 assert!(!contains_url(&long_text));
838
839 let text_with_url = format!("{long_text}https://example.com");
841 assert!(contains_url(&text_with_url));
842 }
843
844 #[test]
845 fn test_escape_regex() {
846 assert_eq!(escape_regex("a.b"), "a\\.b");
847 assert_eq!(escape_regex("a+b*c"), "a\\+b\\*c");
848 assert_eq!(escape_regex("(test)"), "\\(test\\)");
849 assert_eq!(escape_regex("[a-z]"), "\\[a-z\\]");
850 assert_eq!(escape_regex("normal text"), "normal text");
851
852 assert_eq!(escape_regex(".$^{[(|)*+?\\"), "\\.\\$\\^\\{\\[\\(\\|\\)\\*\\+\\?\\\\");
854
855 assert_eq!(escape_regex(""), "");
857
858 assert_eq!(escape_regex("test.com/path?query=1"), "test\\.com/path\\?query=1");
860 }
861
862 #[test]
863 fn test_static_regex_patterns() {
864 assert!(URL_SIMPLE_REGEX.is_match("https://example.com"));
866 assert!(URL_SIMPLE_REGEX.is_match("http://test.org/path"));
867 assert!(URL_SIMPLE_REGEX.is_match("ftp://files.com"));
868 assert!(!URL_SIMPLE_REGEX.is_match("not a url"));
869
870 assert!(ATX_HEADING_REGEX.is_match("# Heading"));
872 assert!(ATX_HEADING_REGEX.is_match(" ## Indented"));
873 assert!(ATX_HEADING_REGEX.is_match("### "));
874 assert!(!ATX_HEADING_REGEX.is_match("Not a heading"));
875
876 assert!(UNORDERED_LIST_MARKER_REGEX.is_match("* Item"));
878 assert!(UNORDERED_LIST_MARKER_REGEX.is_match("- Item"));
879 assert!(UNORDERED_LIST_MARKER_REGEX.is_match("+ Item"));
880 assert!(ORDERED_LIST_MARKER_REGEX.is_match("1. Item"));
881 assert!(ORDERED_LIST_MARKER_REGEX.is_match("99. Item"));
882
883 assert!(FENCED_CODE_BLOCK_START_REGEX.is_match("```"));
885 assert!(FENCED_CODE_BLOCK_START_REGEX.is_match("```rust"));
886 assert!(FENCED_CODE_BLOCK_START_REGEX.is_match("~~~"));
887 assert!(FENCED_CODE_BLOCK_END_REGEX.is_match("```"));
888 assert!(FENCED_CODE_BLOCK_END_REGEX.is_match("~~~"));
889
890 assert!(BOLD_ASTERISK_REGEX.is_match("**bold**"));
892 assert!(BOLD_UNDERSCORE_REGEX.is_match("__bold__"));
893 assert!(ITALIC_ASTERISK_REGEX.is_match("*italic*"));
894 assert!(ITALIC_UNDERSCORE_REGEX.is_match("_italic_"));
895
896 assert!(HTML_TAG_REGEX.is_match("<div>"));
898 assert!(HTML_TAG_REGEX.is_match("<span class='test'>"));
899 assert!(HTML_SELF_CLOSING_TAG_REGEX.is_match("<br/>"));
900 assert!(HTML_SELF_CLOSING_TAG_REGEX.is_match("<img src='test'/>"));
901
902 assert!(TRAILING_WHITESPACE_REGEX.is_match("line with spaces "));
904 assert!(TRAILING_WHITESPACE_REGEX.is_match("tabs\t\t"));
905 assert!(MULTIPLE_BLANK_LINES_REGEX.is_match("\n\n\n"));
906 assert!(MULTIPLE_BLANK_LINES_REGEX.is_match("\n\n\n\n"));
907
908 assert!(BLOCKQUOTE_PREFIX_RE.is_match("> Quote"));
910 assert!(BLOCKQUOTE_PREFIX_RE.is_match(" > Indented quote"));
911 assert!(BLOCKQUOTE_PREFIX_RE.is_match(">> Nested"));
912 }
913
914 #[test]
915 fn test_thread_safety() {
916 use std::thread;
917
918 let handles: Vec<_> = (0..10)
919 .map(|i| {
920 thread::spawn(move || {
921 let pattern = format!(r"\d{{{i}}}");
922 let regex = get_cached_regex(&pattern).unwrap();
923 assert!(regex.is_match(&"1".repeat(i)));
924 })
925 })
926 .collect();
927
928 for handle in handles {
929 handle.join().unwrap();
930 }
931 }
932
933 #[test]
938 fn test_url_standard_basic() {
939 assert!(URL_STANDARD_REGEX.is_match("https://example.com"));
941 assert!(URL_STANDARD_REGEX.is_match("http://example.com"));
942 assert!(URL_STANDARD_REGEX.is_match("https://example.com/"));
943 assert!(URL_STANDARD_REGEX.is_match("https://example.com/path"));
944 assert!(URL_STANDARD_REGEX.is_match("ftp://files.example.com"));
945 assert!(URL_STANDARD_REGEX.is_match("ftps://secure.example.com"));
946
947 assert!(!URL_STANDARD_REGEX.is_match("not a url"));
949 assert!(!URL_STANDARD_REGEX.is_match("example.com"));
950 assert!(!URL_STANDARD_REGEX.is_match("www.example.com"));
951 }
952
953 #[test]
954 fn test_url_standard_with_path() {
955 assert!(URL_STANDARD_REGEX.is_match("https://example.com/path/to/page"));
956 assert!(URL_STANDARD_REGEX.is_match("https://example.com/path/to/page.html"));
957 assert!(URL_STANDARD_REGEX.is_match("https://example.com/path/to/page/"));
958 }
959
960 #[test]
961 fn test_url_standard_with_query() {
962 assert!(URL_STANDARD_REGEX.is_match("https://example.com?query=value"));
963 assert!(URL_STANDARD_REGEX.is_match("https://example.com/path?query=value"));
964 assert!(URL_STANDARD_REGEX.is_match("https://example.com/path?a=1&b=2"));
965 }
966
967 #[test]
968 fn test_url_standard_with_fragment() {
969 assert!(URL_STANDARD_REGEX.is_match("https://example.com#section"));
970 assert!(URL_STANDARD_REGEX.is_match("https://example.com/path#section"));
971 assert!(URL_STANDARD_REGEX.is_match("https://example.com/path?query=value#section"));
972 }
973
974 #[test]
975 fn test_url_standard_with_port() {
976 assert!(URL_STANDARD_REGEX.is_match("https://example.com:8080"));
977 assert!(URL_STANDARD_REGEX.is_match("https://example.com:443/path"));
978 assert!(URL_STANDARD_REGEX.is_match("http://localhost:3000"));
979 assert!(URL_STANDARD_REGEX.is_match("https://192.168.1.1:8080/path"));
980 }
981
982 #[test]
983 fn test_url_standard_wikipedia_style_parentheses() {
984 let url = "https://en.wikipedia.org/wiki/Rust_(programming_language)";
986 assert!(URL_STANDARD_REGEX.is_match(url));
987
988 let cap = URL_STANDARD_REGEX.find(url).unwrap();
990 assert_eq!(cap.as_str(), url);
991
992 let url2 = "https://example.com/path_(foo)_(bar)";
994 let cap2 = URL_STANDARD_REGEX.find(url2).unwrap();
995 assert_eq!(cap2.as_str(), url2);
996 }
997
998 #[test]
999 fn test_url_standard_ipv6() {
1000 assert!(URL_STANDARD_REGEX.is_match("https://[::1]/path"));
1002 assert!(URL_STANDARD_REGEX.is_match("https://[2001:db8::1]:8080/path"));
1003 assert!(URL_STANDARD_REGEX.is_match("http://[fe80::1%eth0]/"));
1004 }
1005
1006 #[test]
1007 fn test_url_www_basic() {
1008 assert!(URL_WWW_REGEX.is_match("www.example.com"));
1010 assert!(URL_WWW_REGEX.is_match("www.example.co.uk"));
1011 assert!(URL_WWW_REGEX.is_match("www.sub.example.com"));
1012
1013 assert!(!URL_WWW_REGEX.is_match("example.com"));
1015
1016 assert!(URL_WWW_REGEX.is_match("https://www.example.com"));
1020 }
1021
1022 #[test]
1023 fn test_url_www_with_path() {
1024 assert!(URL_WWW_REGEX.is_match("www.example.com/path"));
1025 assert!(URL_WWW_REGEX.is_match("www.example.com/path/to/page"));
1026 assert!(URL_WWW_REGEX.is_match("www.example.com/path_(with_parens)"));
1027 }
1028
1029 #[test]
1030 fn test_url_ipv6_basic() {
1031 assert!(URL_IPV6_REGEX.is_match("https://[::1]/"));
1033 assert!(URL_IPV6_REGEX.is_match("http://[2001:db8::1]/path"));
1034 assert!(URL_IPV6_REGEX.is_match("https://[fe80::1]:8080/path"));
1035 assert!(URL_IPV6_REGEX.is_match("ftp://[::ffff:192.168.1.1]/file"));
1036 }
1037
1038 #[test]
1039 fn test_url_ipv6_with_zone_id() {
1040 assert!(URL_IPV6_REGEX.is_match("https://[fe80::1%eth0]/path"));
1042 assert!(URL_IPV6_REGEX.is_match("http://[fe80::1%25eth0]:8080/"));
1043 }
1044
1045 #[test]
1046 fn test_url_simple_detection() {
1047 assert!(URL_SIMPLE_REGEX.is_match("https://example.com"));
1049 assert!(URL_SIMPLE_REGEX.is_match("http://test.org/path"));
1050 assert!(URL_SIMPLE_REGEX.is_match("ftp://files.com/file.zip"));
1051 assert!(!URL_SIMPLE_REGEX.is_match("not a url"));
1052 }
1053
1054 #[test]
1055 fn test_url_quick_check() {
1056 assert!(URL_QUICK_CHECK_REGEX.is_match("https://example.com"));
1058 assert!(URL_QUICK_CHECK_REGEX.is_match("http://example.com"));
1059 assert!(URL_QUICK_CHECK_REGEX.is_match("ftp://files.com"));
1060 assert!(URL_QUICK_CHECK_REGEX.is_match("www.example.com"));
1061 assert!(URL_QUICK_CHECK_REGEX.is_match("user@example.com"));
1062 assert!(!URL_QUICK_CHECK_REGEX.is_match("just plain text"));
1063 }
1064
1065 #[test]
1066 fn test_url_edge_cases() {
1067 let url = "https://example.com/path";
1069 assert!(URL_STANDARD_REGEX.is_match(url));
1070
1071 let text = "Check https://example.com, it's great!";
1074 let cap = URL_STANDARD_REGEX.find(text).unwrap();
1075 assert!(cap.as_str().ends_with(','));
1077
1078 let text2 = "See <https://example.com> for more";
1080 assert!(URL_STANDARD_REGEX.is_match(text2));
1081
1082 let cap2 = URL_STANDARD_REGEX.find(text2).unwrap();
1084 assert!(!cap2.as_str().contains('>'));
1085 }
1086
1087 #[test]
1088 fn test_url_with_complex_paths() {
1089 let urls = [
1091 "https://github.com/owner/repo/blob/main/src/file.rs#L123",
1092 "https://docs.example.com/api/v2/endpoint?format=json&page=1",
1093 "https://cdn.example.com/assets/images/logo.png?v=2023",
1094 "https://search.example.com/results?q=test+query&filter=all",
1095 ];
1096
1097 for url in urls {
1098 assert!(URL_STANDARD_REGEX.is_match(url), "Should match: {url}");
1099 }
1100 }
1101
1102 #[test]
1103 fn test_url_pattern_strings_are_valid() {
1104 assert!(URL_STANDARD_REGEX.is_match("https://example.com"));
1106 assert!(URL_WWW_REGEX.is_match("www.example.com"));
1107 assert!(URL_IPV6_REGEX.is_match("https://[::1]/"));
1108 assert!(URL_QUICK_CHECK_REGEX.is_match("https://example.com"));
1109 assert!(URL_SIMPLE_REGEX.is_match("https://example.com"));
1110 }
1111}