From c5ea656385843c880b3bef45dccbe8ea57431d10 Mon Sep 17 00:00:00 2001 From: Josh McKinney Date: Thu, 21 Sep 2023 16:35:28 -0700 Subject: [PATCH] fix(barchart): avoid divide by zero in rendering (#525) Fixes: https://github.com/ratatui-org/ratatui/issues/521 --- src/widgets/barchart.rs | 19 ++++++++++++++++++- 1 file changed, 18 insertions(+), 1 deletion(-) diff --git a/src/widgets/barchart.rs b/src/widgets/barchart.rs index 15db9d318..0e361ec4c 100644 --- a/src/widgets/barchart.rs +++ b/src/widgets/barchart.rs @@ -506,10 +506,15 @@ impl<'a> Widget for BarChart<'a> { buf.set_style(area, self.style); self.render_block(&mut area, buf); - + if area.area() == 0 { + return; + } if self.data.is_empty() { return; } + if self.bar_width == 0 { + return; + } let label_height = self.label_height(); if area.height <= label_height { @@ -1180,4 +1185,16 @@ mod tests { ]); assert_buffer_eq!(buffer, expected); } + + #[test] + fn handles_zero_width() { + // this test is to ensure that a BarChart with zero bar / gap width does not panic + let chart = BarChart::default() + .data(&[("A", 1)]) + .bar_width(0) + .bar_gap(0); + let mut buffer = Buffer::empty(Rect::new(0, 0, 0, 10)); + chart.render(buffer.area, &mut buffer); + assert_buffer_eq!(buffer, Buffer::empty(Rect::new(0, 0, 0, 10))); + } }