swiftide_core/
util.rs

1//! Utility functions for Swiftide
2
3/// Safely truncates a string to a maximum number of characters.
4///
5/// Respects utf8 character boundaries.
6pub fn safe_truncate_utf8(s: impl AsRef<str>, max_chars: usize) -> String {
7    s.as_ref().chars().take(max_chars).collect()
8}
9
10/// Debug print a long string by truncating to n characters
11///
12/// Enabled with the `truncate-debug` feature flag, which is enabled by default.
13///
14/// If debugging large outputs is needed, set `swiftide_core` to `no-default-features`
15///
16/// # Example
17///
18/// ```ignore
19/// # use swiftide_core::util::debug_long_utf8;
20/// let s = debug_long_utf8("🦀".repeat(10), 3);
21///
22/// assert_eq!(s, "🦀🦀🦀 (10)");
23/// ```
24pub fn debug_long_utf8(s: impl AsRef<str>, max_chars: usize) -> String {
25    if cfg!(feature = "truncate-debug") {
26        let trunc = safe_truncate_utf8(&s, max_chars);
27
28        format!("{} ({})", trunc, s.as_ref().chars().count())
29    } else {
30        s.as_ref().into()
31    }
32}
33
34#[cfg(test)]
35mod tests {
36    use super::*;
37
38    #[test]
39    fn test_safe_truncate_str_with_utf8_char_boundary() {
40        let s = "🦀".repeat(101);
41
42        // Single char
43        assert_eq!(safe_truncate_utf8(&s, 100).chars().count(), 100);
44
45        // With invalid char boundary
46        let s = "Jürgen".repeat(100);
47        assert_eq!(safe_truncate_utf8(&s, 100).chars().count(), 100);
48    }
49}