Skip to main content

java_diff_utils_rs/text/
string_utils.rs

1//! Utility functions for text manipulation and wrapping.
2
3// 1. Standalone public functions
4pub fn html_entities(str_input: &str) -> String {
5    str_input.replace('<', "&lt;").replace('>', "&gt;")
6}
7
8/// Expands tab characters into 4 spaces and HTML-escapes the result,
9/// matching java-diff-utils' `StringUtils.normalize`.
10pub fn normalize(str_input: &str) -> String {
11    html_entities(&str_input.replace('\t', "    "))
12}
13
14use unicode_segmentation::UnicodeSegmentation;
15
16/// Wraps text to column_width, joining wrapped segments with `<br/>` tags.
17/// A column_width of 0 leaves the line untouched (no wrapping is possible).
18pub fn wrap_text(line: &str, column_width: usize) -> String {
19    if column_width == 0 {
20        return line.to_string();
21    }
22
23    let graphemes: Vec<&str> = line.graphemes(true).collect();
24    if graphemes.len() <= column_width {
25        return line.to_string();
26    }
27
28    let mut result = String::new();
29    for (i, &g) in graphemes.iter().enumerate() {
30        if i > 0 && i % column_width == 0 {
31            result.push_str("<br/>");
32        }
33        result.push_str(g);
34    }
35
36    result
37}
38
39pub fn wrap_text_list(list: &[String], column_width: usize) -> Vec<String> {
40    list.iter().map(|s| wrap_text(s, column_width)).collect()
41}
42
43// 2. Struct wrapper mapping to the standalone functions
44pub struct StringUtils;
45
46impl StringUtils {
47    pub fn html_entities(str_input: &str) -> String {
48        html_entities(str_input)
49    }
50
51    pub fn normalize(str_input: &str) -> String {
52        normalize(str_input)
53    }
54
55    /// Unlike the free `wrap_text` function, this associated method matches
56    /// java-diff-utils' `StringUtils.wrapText(String, int)`, which requires a
57    /// positive column width and panics otherwise.
58    pub fn wrap_text(line: &str, column_width: usize) -> String {
59        if column_width == 0 {
60            panic!("column width must be positive");
61        }
62        wrap_text(line, column_width)
63    }
64
65    pub fn wrap_text_list(list: &[String], column_width: usize) -> Vec<String> {
66        wrap_text_list(list, column_width)
67    }
68}