aboutsummaryrefslogtreecommitdiff
path: root/alacritty/src/string.rs
blob: b8c47d3bd4d231feacb2a8a09dd6fc3b997023e0 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
use std::cmp::Ordering;
use std::iter::Skip;
use std::str::Chars;

use unicode_width::UnicodeWidthChar;

/// The action performed by [`StrShortener`].
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum TextAction {
    /// Yield a spacer.
    Spacer,
    /// Terminate state reached.
    Terminate,
    /// Yield a shortener.
    Shortener,
    /// Yield a character.
    Char,
}

/// The direction which we should shorten.
#[derive(Clone, Copy, PartialEq, Eq)]
pub enum ShortenDirection {
    /// Shorten to the start of the string.
    Left,

    /// Shorten to the end of the string.
    Right,
}

/// Iterator that yield shortened version of the text.
pub struct StrShortener<'a> {
    chars: Skip<Chars<'a>>,
    accumulated_len: usize,
    max_width: usize,
    direction: ShortenDirection,
    shortener: Option<char>,
    text_action: TextAction,
}

impl<'a> StrShortener<'a> {
    pub fn new(
        text: &'a str,
        max_width: usize,
        direction: ShortenDirection,
        mut shortener: Option<char>,
    ) -> Self {
        if text.is_empty() {
            // If we don't have any text don't produce a shortener for it.
            let _ = shortener.take();
        }

        if direction == ShortenDirection::Right {
            return Self {
                #[allow(clippy::iter_skip_zero)]
                chars: text.chars().skip(0),
                accumulated_len: 0,
                text_action: TextAction::Char,
                max_width,
                direction,
                shortener,
            };
        }

        let mut offset = 0;
        let mut current_len = 0;

        let mut iter = text.chars().rev().enumerate();

        while let Some((idx, ch)) = iter.next() {
            let ch_width = ch.width().unwrap_or(1);
            current_len += ch_width;

            match current_len.cmp(&max_width) {
                // We can only be here if we've faced wide character or we've already
                // handled equality situation. Anyway, break.
                Ordering::Greater => break,
                Ordering::Equal => {
                    if shortener.is_some() && iter.clone().next().is_some() {
                        // We have one more character after, shortener will accumulate for
                        // the `current_len`.
                        break;
                    } else {
                        // The match is exact, consume shortener.
                        let _ = shortener.take();
                    }
                },
                Ordering::Less => (),
            }

            offset = idx + 1;
        }

        // Consume the iterator to count the number of characters in it.
        let num_chars = iter.last().map_or(offset, |(idx, _)| idx + 1);
        let skip_chars = num_chars - offset;

        let text_action = if current_len < max_width || shortener.is_none() {
            TextAction::Char
        } else {
            TextAction::Shortener
        };

        let chars = text.chars().skip(skip_chars);

        Self { chars, accumulated_len: 0, text_action, max_width, direction, shortener }
    }
}

impl Iterator for StrShortener<'_> {
    type Item = char;

    fn next(&mut self) -> Option<Self::Item> {
        match self.text_action {
            TextAction::Spacer => {
                self.text_action = TextAction::Char;
                Some(' ')
            },
            TextAction::Terminate => {
                // We've reached the termination state.
                None
            },
            TextAction::Shortener => {
                // When we shorten from the left we yield the shortener first and process the rest.
                self.text_action = if self.direction == ShortenDirection::Left {
                    TextAction::Char
                } else {
                    TextAction::Terminate
                };

                // Consume the shortener to avoid yielding it later when shortening left.
                self.shortener.take()
            },
            TextAction::Char => {
                let ch = self.chars.next()?;
                let ch_width = ch.width().unwrap_or(1);

                // Advance width.
                self.accumulated_len += ch_width;

                if self.accumulated_len > self.max_width {
                    self.text_action = TextAction::Terminate;
                    return self.shortener;
                } else if self.accumulated_len == self.max_width && self.shortener.is_some() {
                    // Check if we have a next char.
                    let has_next = self.chars.clone().next().is_some();

                    // We should terminate after that.
                    self.text_action = TextAction::Terminate;

                    return has_next.then(|| self.shortener.unwrap()).or(Some(ch));
                }

                // Add a spacer for wide character.
                if ch_width == 2 {
                    self.text_action = TextAction::Spacer;
                }

                Some(ch)
            },
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn into_shortened_with_shortener() {
        let s = "Hello";
        let len = s.chars().count();
        assert_eq!(
            "",
            StrShortener::new("", 1, ShortenDirection::Left, Some('.')).collect::<String>()
        );

        assert_eq!(
            ".",
            StrShortener::new(s, 1, ShortenDirection::Right, Some('.')).collect::<String>()
        );

        assert_eq!(
            ".",
            StrShortener::new(s, 1, ShortenDirection::Left, Some('.')).collect::<String>()
        );

        assert_eq!(
            "H.",
            StrShortener::new(s, 2, ShortenDirection::Right, Some('.')).collect::<String>()
        );

        assert_eq!(
            ".o",
            StrShortener::new(s, 2, ShortenDirection::Left, Some('.')).collect::<String>()
        );

        assert_eq!(
            s,
            &StrShortener::new(s, len * 2, ShortenDirection::Right, Some('.')).collect::<String>()
        );

        assert_eq!(
            s,
            &StrShortener::new(s, len * 2, ShortenDirection::Left, Some('.')).collect::<String>()
        );

        let s = "ちはP";
        let len = 2 + 2 + 1;
        assert_eq!(
            ".",
            &StrShortener::new(s, 1, ShortenDirection::Right, Some('.')).collect::<String>()
        );

        assert_eq!(
            &".",
            &StrShortener::new(s, 1, ShortenDirection::Left, Some('.')).collect::<String>()
        );

        assert_eq!(
            ".",
            &StrShortener::new(s, 2, ShortenDirection::Right, Some('.')).collect::<String>()
        );

        assert_eq!(
            ".P",
            &StrShortener::new(s, 2, ShortenDirection::Left, Some('.')).collect::<String>()
        );

        assert_eq!(
            "ち .",
            &StrShortener::new(s, 3, ShortenDirection::Right, Some('.')).collect::<String>()
        );

        assert_eq!(
            ".P",
            &StrShortener::new(s, 3, ShortenDirection::Left, Some('.')).collect::<String>()
        );

        assert_eq!(
            "ち は P",
            &StrShortener::new(s, len * 2, ShortenDirection::Left, Some('.')).collect::<String>()
        );

        assert_eq!(
            "ち は P",
            &StrShortener::new(s, len * 2, ShortenDirection::Right, Some('.')).collect::<String>()
        );
    }

    #[test]
    fn into_shortened_without_shortener() {
        let s = "Hello";
        assert_eq!("", StrShortener::new("", 1, ShortenDirection::Left, None).collect::<String>());

        assert_eq!(
            "H",
            &StrShortener::new(s, 1, ShortenDirection::Right, None).collect::<String>()
        );

        assert_eq!("o", &StrShortener::new(s, 1, ShortenDirection::Left, None).collect::<String>());

        assert_eq!(
            "He",
            &StrShortener::new(s, 2, ShortenDirection::Right, None).collect::<String>()
        );

        assert_eq!(
            "lo",
            &StrShortener::new(s, 2, ShortenDirection::Left, None).collect::<String>()
        );

        assert_eq!(
            &s,
            &StrShortener::new(s, s.len(), ShortenDirection::Right, None).collect::<String>()
        );

        assert_eq!(
            &s,
            &StrShortener::new(s, s.len(), ShortenDirection::Left, None).collect::<String>()
        );

        let s = "こJんにちはP";
        let len = 2 + 1 + 2 + 2 + 2 + 2 + 1;
        assert_eq!("", &StrShortener::new(s, 1, ShortenDirection::Right, None).collect::<String>());

        assert_eq!("P", &StrShortener::new(s, 1, ShortenDirection::Left, None).collect::<String>());

        assert_eq!(
            "こ ",
            &StrShortener::new(s, 2, ShortenDirection::Right, None).collect::<String>()
        );

        assert_eq!("P", &StrShortener::new(s, 2, ShortenDirection::Left, None).collect::<String>());

        assert_eq!(
            "こ J",
            &StrShortener::new(s, 3, ShortenDirection::Right, None).collect::<String>()
        );

        assert_eq!(
            "は P",
            &StrShortener::new(s, 3, ShortenDirection::Left, None).collect::<String>()
        );

        assert_eq!(
            "こ Jん に ち は P",
            &StrShortener::new(s, len, ShortenDirection::Left, None).collect::<String>()
        );

        assert_eq!(
            "こ Jん に ち は P",
            &StrShortener::new(s, len, ShortenDirection::Right, None).collect::<String>()
        );
    }
}