Skip to content

Commit d22bd40

Browse files
author
vidy
committed
Replace for loop with while inside concat_text function
1 parent 7e415ea commit d22bd40

File tree

1 file changed

+18
-10
lines changed

1 file changed

+18
-10
lines changed

src/text.rs

Lines changed: 18 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,12 @@ pub fn concat_text<'a, E: Encoder + 'a>(out: &mut String, items: impl Iterator<I
1111

1212
let mut end = 0.; // trailing edge of the last char
1313

14-
// Whether the last processed TextChar is a space
14+
// Whether the last processed TextChar is a whitespace
15+
// ' ' Space
16+
// '\t' Tab
17+
// '\n' Line feed
18+
// '\r' Carriage return
19+
// '\u{00A0}' Non-breaking space
1520
let mut trailing_space = out.chars().last().map(|c| c.is_whitespace()).unwrap_or(true);
1621

1722
let mut word_start_idx = out.len();
@@ -29,10 +34,15 @@ pub fn concat_text<'a, E: Encoder + 'a>(out: &mut String, items: impl Iterator<I
2934
let tr_inv = span.transform.matrix.inverse();
3035
let x_off = (tr_inv * span.transform.vector).x();
3136

32-
let chars = span.chars.as_slice();
33-
for (i, c) in chars.iter().enumerate() {
34-
let next_offset = chars.get(i + 1).map_or(span.text.len(), |next| next.offset);
35-
let s: &str = &span.text[offset..next_offset];
37+
let mut chars = span.chars.iter().peekable();
38+
while let Some(current) = chars.next() {
39+
let s;
40+
if let Some(next) = chars.peek() {
41+
s = &span.text[offset..next.offset];
42+
offset = next.offset;
43+
} else {
44+
s = &span.text[offset..];
45+
}
3646

3747
let is_whitespace = s.chars().all(|c| c.is_whitespace());
3848

@@ -56,7 +66,7 @@ pub fn concat_text<'a, E: Encoder + 'a>(out: &mut String, items: impl Iterator<I
5666
});
5767
out.push_str(" ");
5868
word_start_idx = out.len();
59-
} else if c.pos + x_off > end + word_gap {
69+
} else if current.pos + x_off > end + word_gap {
6070
words.push(Word {
6171
text: out[word_start_idx..].into(),
6272
rect: Rect {
@@ -78,20 +88,18 @@ pub fn concat_text<'a, E: Encoder + 'a>(out: &mut String, items: impl Iterator<I
7888

7989
trailing_space = is_whitespace;
8090

81-
end = c.pos + x_off + c.width;
91+
end = current.pos + x_off + current.width;
8292
word_end_pos = (span.transform.matrix * Vector2F::new(end, 0.0)).x();
8393

8494
if word_start {
8595
y_min = span.rect.min_y();
8696
y_max = span.rect.max_y();
87-
word_start_pos = (span.transform.matrix * Vector2F::new(c.pos + x_off, 0.0)).x();
97+
word_start_pos = (span.transform.matrix * Vector2F::new(current.pos + x_off, 0.0)).x();
8898
word_start = false;
8999
} else {
90100
y_min = y_min.min(span.rect.min_y());
91101
y_max = y_max.max(span.rect.max_y());
92102
}
93-
94-
offset = next_offset;
95103
}
96104
}
97105

0 commit comments

Comments
 (0)