halo/
string_builder.rs

1//! 高效的字符串拼接工具(对齐 go-sqlbuilder 的 stringBuilder 行为)。
2
3#[derive(Debug, Default, Clone)]
4pub(crate) struct StringBuilder {
5    buf: String,
6}
7
8impl StringBuilder {
9    pub(crate) fn new() -> Self {
10        Self { buf: String::new() }
11    }
12
13    /// 写入 `s`;如果不是首次写入,会先写入一个空格。
14    #[allow(dead_code)]
15    pub(crate) fn write_leading(&mut self, s: &str) {
16        if !self.buf.is_empty() {
17            self.buf.push(' ');
18        }
19        self.buf.push_str(s);
20    }
21
22    pub(crate) fn write_str(&mut self, s: &str) {
23        self.buf.push_str(s);
24    }
25
26    pub(crate) fn write_char(&mut self, c: char) {
27        self.buf.push(c);
28    }
29
30    #[allow(dead_code)]
31    pub(crate) fn write_strings(&mut self, items: &[String], sep: &str) {
32        let mut first_added = false;
33        for s in items {
34            if s.is_empty() {
35                continue;
36            }
37            if first_added {
38                self.buf.push_str(sep);
39            }
40            self.buf.push_str(s);
41            first_added = true;
42        }
43    }
44
45    #[allow(dead_code)]
46    pub(crate) fn write_strings_str(&mut self, items: &[&str], sep: &str) {
47        let mut first_added = false;
48        for &s in items {
49            if s.is_empty() {
50                continue;
51            }
52            if first_added {
53                self.buf.push_str(sep);
54            }
55            self.buf.push_str(s);
56            first_added = true;
57        }
58    }
59
60    #[allow(dead_code)]
61    pub(crate) fn grow(&mut self, n: usize) {
62        self.buf.reserve(n);
63    }
64
65    #[allow(dead_code)]
66    pub(crate) fn reset(&mut self) {
67        self.buf.clear();
68    }
69
70    pub(crate) fn into_string(self) -> String {
71        self.buf
72    }
73}
74
75#[allow(dead_code)]
76pub(crate) fn filter_empty_strings(mut ss: Vec<String>) -> Vec<String> {
77    ss.retain(|s| !s.is_empty());
78    ss
79}