Skip to content

Commit f663241

Browse files
authored
buffer_dimensions simplification (#21957)
# Objective ```rust /// Calculate the size of the text area for the given buffer. fn buffer_dimensions(buffer: &Buffer) -> Vec2 { let (width, height) = buffer .layout_runs() .map(|run| (run.line_w, run.line_height)) .reduce(|(w1, h1), (w2, h2)| (w1.max(w2), h1 + h2)) .unwrap_or((0.0, 0.0)); Vec2::new(width, height).ceil() } ``` This function is unnecessarily complicated, there's no need to map and then reduce, it could just use a fold. ## Solution A for-loop seems like the most straightforward solution: ```rust /// Calculate the size of the text area for the given buffer. fn buffer_dimensions(buffer: &Buffer) -> Vec2 { let mut size = Vec2::ZERO; for run in buffer.layout_runs() { size.x = size.x.max(run.line_w); size.y += run.line_height; } size.ceil() } ``` Naive benchmarks suggest this is a bit more efficient as well, but the difference is quite small. ## Testing `testbed_ui`'s output remaining unchanged should be enough to verify that this is correct.
1 parent df72a54 commit f663241

File tree

1 file changed

+6
-7
lines changed

1 file changed

+6
-7
lines changed

crates/bevy_text/src/pipeline.rs

Lines changed: 6 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -678,13 +678,12 @@ fn get_attrs<'a>(
678678

679679
/// Calculate the size of the text area for the given buffer.
680680
fn buffer_dimensions(buffer: &Buffer) -> Vec2 {
681-
let (width, height) = buffer
682-
.layout_runs()
683-
.map(|run| (run.line_w, run.line_height))
684-
.reduce(|(w1, h1), (w2, h2)| (w1.max(w2), h1 + h2))
685-
.unwrap_or((0.0, 0.0));
686-
687-
Vec2::new(width, height).ceil()
681+
let mut size = Vec2::ZERO;
682+
for run in buffer.layout_runs() {
683+
size.x = size.x.max(run.line_w);
684+
size.y += run.line_height;
685+
}
686+
size.ceil()
688687
}
689688

690689
/// Discards stale data cached in `FontSystem`.

0 commit comments

Comments
 (0)