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