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