rumdl_lib/utils/
mod.rs

1//!
2//! Shared utilities for rumdl, including document structure analysis, code block handling, regex helpers, and string extensions.
3//! Provides reusable traits and functions for rule implementations and core linter logic.
4
5pub mod anchor_styles;
6pub mod code_block_utils;
7// DocumentStructure has been merged into LintContext
8// pub mod document_structure;
9pub mod early_returns;
10pub mod element_cache;
11pub mod emphasis_utils;
12pub mod fix_utils;
13pub mod header_id_utils;
14pub mod jinja_utils;
15pub mod kramdown_utils;
16pub mod line_ending;
17pub mod markdown_elements;
18pub mod mkdocs_admonitions;
19pub mod mkdocs_common;
20pub mod mkdocs_critic;
21pub mod mkdocs_footnotes;
22pub mod mkdocs_patterns;
23pub mod mkdocs_snippets;
24pub mod mkdocs_tabs;
25pub mod mkdocs_test_utils;
26pub mod mkdocstrings_refs;
27pub mod range_utils;
28pub mod regex_cache;
29pub mod skip_context;
30pub mod string_interner;
31pub mod table_utils;
32pub mod text_reflow;
33pub mod utf8_offsets;
34
35pub use code_block_utils::CodeBlockUtils;
36// pub use document_structure::DocumentStructure;
37pub use line_ending::{
38    LineEnding, detect_line_ending, detect_line_ending_enum, ensure_consistent_line_endings, get_line_ending_str,
39    normalize_line_ending,
40};
41pub use markdown_elements::{ElementQuality, ElementType, MarkdownElement, MarkdownElements};
42pub use range_utils::LineIndex;
43
44/// Check if a line is a definition list item (Extended Markdown)
45///
46/// Definition lists use the pattern:
47/// ```text
48/// Term
49/// : Definition
50/// ```
51///
52/// Supported by: PHP Markdown Extra, Kramdown, Pandoc, Hugo, and others
53pub fn is_definition_list_item(line: &str) -> bool {
54    let trimmed = line.trim_start();
55    trimmed.starts_with(": ")
56        || (trimmed.starts_with(':') && trimmed.len() > 1 && trimmed.chars().nth(1).is_some_and(|c| c.is_whitespace()))
57}
58
59/// Trait for string-related extensions
60pub trait StrExt {
61    /// Replace trailing spaces with a specified replacement string
62    fn replace_trailing_spaces(&self, replacement: &str) -> String;
63
64    /// Check if the string has trailing whitespace
65    fn has_trailing_spaces(&self) -> bool;
66
67    /// Count the number of trailing spaces in the string
68    fn trailing_spaces(&self) -> usize;
69}
70
71impl StrExt for str {
72    fn replace_trailing_spaces(&self, replacement: &str) -> String {
73        // Custom implementation to handle both newlines and tabs specially
74
75        // Check if string ends with newline
76        let (content, ends_with_newline) = if let Some(stripped) = self.strip_suffix('\n') {
77            (stripped, true)
78        } else {
79            (self, false)
80        };
81
82        // Find where the trailing spaces begin
83        let mut non_space_len = content.len();
84        for c in content.chars().rev() {
85            if c == ' ' {
86                non_space_len -= 1;
87            } else {
88                break;
89            }
90        }
91
92        // Build the final string
93        let mut result =
94            String::with_capacity(non_space_len + replacement.len() + if ends_with_newline { 1 } else { 0 });
95        result.push_str(&content[..non_space_len]);
96        result.push_str(replacement);
97        if ends_with_newline {
98            result.push('\n');
99        }
100
101        result
102    }
103
104    fn has_trailing_spaces(&self) -> bool {
105        self.trailing_spaces() > 0
106    }
107
108    fn trailing_spaces(&self) -> usize {
109        // Custom implementation to handle both newlines and tabs specially
110
111        // Prepare the string without newline if it ends with one
112        let content = self.strip_suffix('\n').unwrap_or(self);
113
114        // Count only trailing spaces at the end, not tabs
115        let mut space_count = 0;
116        for c in content.chars().rev() {
117            if c == ' ' {
118                space_count += 1;
119            } else {
120                break;
121            }
122        }
123
124        space_count
125    }
126}
127
128use std::collections::hash_map::DefaultHasher;
129use std::hash::{Hash, Hasher};
130
131/// Fast hash function for string content
132///
133/// This utility function provides a quick way to generate a hash from string content
134/// for use in caching mechanisms. It uses Rust's built-in DefaultHasher.
135///
136/// # Arguments
137///
138/// * `content` - The string content to hash
139///
140/// # Returns
141///
142/// A 64-bit hash value derived from the content
143pub fn fast_hash(content: &str) -> u64 {
144    let mut hasher = DefaultHasher::new();
145    content.hash(&mut hasher);
146    hasher.finish()
147}
148
149#[cfg(test)]
150mod tests {
151    use super::*;
152
153    #[test]
154    fn test_detect_line_ending_pure_lf() {
155        // Test content with only LF line endings
156        let content = "First line\nSecond line\nThird line\n";
157        assert_eq!(detect_line_ending(content), "\n");
158    }
159
160    #[test]
161    fn test_detect_line_ending_pure_crlf() {
162        // Test content with only CRLF line endings
163        let content = "First line\r\nSecond line\r\nThird line\r\n";
164        assert_eq!(detect_line_ending(content), "\r\n");
165    }
166
167    #[test]
168    fn test_detect_line_ending_mixed_more_lf() {
169        // Test content with mixed line endings where LF is more common
170        let content = "First line\nSecond line\r\nThird line\nFourth line\n";
171        assert_eq!(detect_line_ending(content), "\n");
172    }
173
174    #[test]
175    fn test_detect_line_ending_mixed_more_crlf() {
176        // Test content with mixed line endings where CRLF is more common
177        let content = "First line\r\nSecond line\r\nThird line\nFourth line\r\n";
178        assert_eq!(detect_line_ending(content), "\r\n");
179    }
180
181    #[test]
182    fn test_detect_line_ending_empty_string() {
183        // Test empty string - should default to LF
184        let content = "";
185        assert_eq!(detect_line_ending(content), "\n");
186    }
187
188    #[test]
189    fn test_detect_line_ending_single_line_no_ending() {
190        // Test single line without any line endings - should default to LF
191        let content = "This is a single line with no line ending";
192        assert_eq!(detect_line_ending(content), "\n");
193    }
194
195    #[test]
196    fn test_detect_line_ending_equal_lf_and_crlf() {
197        // Test edge case with equal number of CRLF and LF
198        // Since LF count is calculated as total '\n' minus CRLF count,
199        // and the algorithm uses > (not >=), it should default to LF
200        let content = "Line 1\r\nLine 2\nLine 3\r\nLine 4\n";
201        assert_eq!(detect_line_ending(content), "\n");
202    }
203
204    #[test]
205    fn test_detect_line_ending_single_lf() {
206        // Test with just a single LF
207        let content = "Line 1\n";
208        assert_eq!(detect_line_ending(content), "\n");
209    }
210
211    #[test]
212    fn test_detect_line_ending_single_crlf() {
213        // Test with just a single CRLF
214        let content = "Line 1\r\n";
215        assert_eq!(detect_line_ending(content), "\r\n");
216    }
217
218    #[test]
219    fn test_detect_line_ending_embedded_cr() {
220        // Test with CR characters that are not part of CRLF
221        // These should not affect the count
222        let content = "Line 1\rLine 2\nLine 3\r\nLine 4\n";
223        // This has 1 CRLF and 2 LF (after subtracting the CRLF)
224        assert_eq!(detect_line_ending(content), "\n");
225    }
226}