fix(barchart): empty groups causes panic (#333)

This unlikely to happen, since nobody wants to add an empty group.
Even we fix the panic, things will not render correctly.
So it is better to just not add them to the BarChart.

Signed-off-by: Ben Fekih, Hichem <hichem.f@live.de>
This commit is contained in:
Hichem 2023-07-19 11:37:59 +02:00 committed by GitHub
parent 13fb11a62c
commit 9c956733f7
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -87,7 +87,10 @@ impl<'a> BarChart<'a> {
/// .data(BarGroup::default().bars(&[Bar::default().value(10), Bar::default().value(20)]));
/// ```
pub fn data(mut self, data: impl Into<BarGroup<'a>>) -> BarChart<'a> {
self.data.push(data.into());
let group: BarGroup = data.into();
if !group.bars.is_empty() {
self.data.push(group);
}
self
}
@ -737,4 +740,20 @@ mod tests {
.add_modifier(Modifier::BOLD)
)
}
#[test]
fn test_empty_group() {
let chart = BarChart::default()
.data(BarGroup::default().label("invisible".into()))
.data(
BarGroup::default()
.label("G".into())
.bars(&[Bar::default().value(1), Bar::default().value(2)]),
);
let mut buffer = Buffer::empty(Rect::new(0, 0, 3, 3));
chart.render(buffer.area, &mut buffer);
let expected = Buffer::with_lines(vec!["", "█ █", " G "]);
assert_buffer_eq!(buffer, expected);
}
}