use crate::data::{IntoSeries, Series};
use crate::render::Color;
#[derive(Clone)]
pub struct Bars<'a> {
pub(crate) placement: Placement,
pub(crate) values: Series<'a>,
pub(crate) color: Option<Color>,
pub(crate) label: Option<String>,
}
#[derive(Debug, Clone, PartialEq)]
pub(crate) enum Placement {
Bands(Vec<String>),
Spans { start: f64, width: f64 },
}
impl<'a> Bars<'a> {
pub fn new(
categories: impl IntoIterator<Item = impl Into<String>>,
values: impl IntoSeries<'a>,
) -> Bars<'a> {
let categories: Vec<String> = categories.into_iter().map(Into::into).collect();
let values = values.into_series();
assert_eq!(
categories.len(),
values.len(),
"Bars::new requires one category per value"
);
Bars {
placement: Placement::Bands(categories),
values,
color: None,
label: None,
}
}
pub fn spans(start: f64, width: f64, values: impl IntoSeries<'a>) -> Bars<'a> {
assert!(
start.is_finite() && width.is_finite() && width > 0.0,
"Bars::spans requires a finite start and a positive width"
);
Bars {
placement: Placement::Spans { start, width },
values: values.into_series(),
color: None,
label: None,
}
}
#[must_use]
pub fn color(mut self, color: Color) -> Bars<'a> {
self.color = Some(color);
self
}
#[must_use]
pub fn label(mut self, label: impl Into<String>) -> Bars<'a> {
self.label = Some(label.into());
self
}
pub fn into_owned(self) -> Bars<'static> {
Bars {
placement: self.placement,
values: self.values.into_owned(),
color: self.color,
label: self.label,
}
}
}
impl std::fmt::Debug for Bars<'_> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("Bars")
.field("bars", &self.values.len())
.field("color", &self.color)
.finish()
}
}
#[cfg(test)]
#[path = "tests/bars_tests.rs"]
mod tests;