use core::any::Any;
use core::fmt;
use crate::data::{ChangeLog, SeriesMapping, TimeIndex, Timestamp};
use crate::drawing::{DrawingCtx, FrameBuilder, index_of_time, time_of_index};
use crate::error::{Error, Result};
use crate::frame::SeriesStyle;
use crate::geom::Px;
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum AxisMode {
Slots,
Overlay,
}
pub trait CustomSeries: Send + Any {
fn kind(&self) -> &'static str;
fn axis_mode(&self) -> AxisMode;
fn times(&self) -> &[Timestamp];
fn extremes(&self, from: usize, to: usize) -> Option<(f64, f64)>;
fn build(&self, ctx: &SeriesCtx<'_>, from: usize, to: usize, out: &mut FrameBuilder<'_>);
fn last_value(&self) -> Option<f64> {
None
}
fn crosshair_value(&self, point: usize) -> Option<f64> {
let _ = point;
None
}
fn native_params(&self, ctx: &SeriesCtx<'_>, params: &mut [f32; 8]) {
let _ = (ctx, params);
}
}
pub struct SeriesCtx<'a> {
pub(crate) coords: DrawingCtx<'a>,
pub(crate) store: &'a CustomStore,
pub(crate) shift: f64,
pub(crate) visible: (usize, usize),
pub(crate) style: SeriesStyle,
}
impl<'a> SeriesCtx<'a> {
pub fn coords(&self) -> &DrawingCtx<'a> {
&self.coords
}
pub fn x_of_point(&self, i: usize) -> Option<f32> {
let index = self.store.x_index(self.coords.index, i)? + self.shift;
let x = f64::from(self.coords.plot.x) + self.coords.time_scale.index_to_x_f64(index);
x.is_finite().then_some(x as f32)
}
pub fn visible(&self) -> (usize, usize) {
self.visible
}
pub fn bar_spacing(&self) -> Px {
Px(self.coords.time_scale.bar_spacing() as f32)
}
pub fn style(&self) -> &SeriesStyle {
&self.style
}
}
pub(crate) struct CustomStore {
pub(crate) plugin: Box<dyn CustomSeries>,
pub(crate) kind: &'static str,
pub(crate) mode: AxisMode,
mapping: SeriesMapping,
len: usize,
bounds: Option<(Timestamp, Timestamp)>,
pub(crate) log: ChangeLog,
}
impl fmt::Debug for CustomStore {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("CustomStore")
.field("kind", &self.kind)
.field("mode", &self.mode)
.field("len", &self.len)
.finish_non_exhaustive()
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum CustomChange {
None,
UpdateLast,
Append,
Prepend {
count: usize,
},
Replace,
}
impl CustomStore {
pub(crate) fn new(plugin: Box<dyn CustomSeries>) -> Self {
Self {
kind: plugin.kind(),
mode: plugin.axis_mode(),
plugin,
mapping: SeriesMapping::Aligned { first: 0 },
len: 0,
bounds: None,
log: ChangeLog::new(),
}
}
pub(crate) fn len(&self) -> usize {
self.len
}
pub(crate) fn times(&self) -> &[Timestamp] {
let t = self.plugin.times();
t.get(..self.len).unwrap_or(t)
}
pub(crate) fn heap_bytes(&self) -> usize {
match &self.mapping {
SeriesMapping::Aligned { .. } => 0,
SeriesMapping::Mapped { offsets, .. } => offsets.capacity() * 4,
}
}
fn logical(&self, i: usize) -> Option<i64> {
if i >= self.len {
return None;
}
self.mapping.logical_index(i)
}
pub(crate) fn span(&self) -> Option<(i64, i64)> {
if self.mode != AxisMode::Slots || self.len == 0 {
return None;
}
Some((self.logical(0)?, self.logical(self.len - 1)? + 1))
}
pub(crate) fn point_at(&self, j: i64) -> Option<usize> {
if self.mode != AxisMode::Slots {
return None;
}
match &self.mapping {
SeriesMapping::Aligned { first } => {
let p = usize::try_from(j.checked_sub(*first)?).ok()?;
(p < self.len).then_some(p)
}
SeriesMapping::Mapped { first, offsets } => {
let off = u32::try_from(j.checked_sub(*first)?).ok()?;
offsets.get(..self.len)?.binary_search(&off).ok()
}
}
}
pub(crate) fn x_index(&self, index: &TimeIndex, i: usize) -> Option<f64> {
match self.mode {
AxisMode::Slots => self.logical(i).map(|j| j as f64),
AxisMode::Overlay => index_of_time(index, *self.times().get(i)?),
}
}
fn slot_points(&self, from: i64, to: i64) -> (usize, usize) {
let n = self.len;
let (a, b) = match &self.mapping {
SeriesMapping::Aligned { first } => {
let rel = |j: i64| {
usize::try_from(j.saturating_sub(*first).max(0))
.unwrap_or(n)
.min(n)
};
(rel(from), rel(to))
}
SeriesMapping::Mapped { first, offsets } => {
let offsets = offsets.get(..n).unwrap_or(offsets);
let (lo, hi) = (from.saturating_sub(*first), to.saturating_sub(*first));
(
offsets.partition_point(|&o| i64::from(o) < lo),
offsets.partition_point(|&o| i64::from(o) < hi),
)
}
};
(a, b.max(a))
}
fn time_points(&self, t0: Timestamp, t1: Timestamp) -> (usize, usize) {
let times = self.times();
let a = times.partition_point(|&t| t < t0);
(a, times.partition_point(|&t| t <= t1).max(a))
}
fn points_between(&self, index: &TimeIndex, from: f64, to: f64) -> (usize, usize) {
if self.len == 0 || from.partial_cmp(&to).is_none_or(core::cmp::Ordering::is_gt) {
return (0, 0);
}
match self.mode {
AxisMode::Slots => self.slot_points(from.ceil() as i64, to.floor() as i64 + 1),
AxisMode::Overlay => match (time_of_index(index, from), time_of_index(index, to)) {
(Some(t0), Some(t1)) => self.time_points(t0, t1),
_ => (0, 0),
},
}
}
pub(crate) fn points_in(&self, index: &TimeIndex, from: f64, to: f64) -> (usize, usize) {
if self.len == 0 {
return (0, 0);
}
let (a, b) = self.points_between(index, from, to);
(a.saturating_sub(1), (b + 1).min(self.len))
}
pub(crate) fn extremes(&self, index: &TimeIndex, from: i64, to: i64) -> Option<(f64, f64)> {
let (a, b) = self.points_between(index, from as f64, (to - 1) as f64);
if a >= b {
return None;
}
self.plugin.extremes(a, b)
}
pub(crate) fn value_at(&self, j: i64) -> Option<f64> {
let v = self.plugin.crosshair_value(self.point_at(j)?)?;
v.is_finite().then_some(v)
}
pub(crate) fn classify(&self, change: crate::data::DataChange) -> Result<CustomChange> {
use crate::data::DataChange as D;
let times = self.plugin.times();
let (n, old) = (times.len(), self.len);
let change = match (change, self.bounds) {
(D::UpdateLast, Some((_, last))) if n == old && times.last() == Some(&last) => {
CustomChange::UpdateLast
}
(D::Append { count: 0 } | D::Prepend { count: 0 }, _) if n == old => CustomChange::None,
(D::Append { count }, Some((_, last))) if n == old + count => {
if times.get(old - 1) == Some(&last) {
check_increasing(×[old - 1..], old - 1)?;
CustomChange::Append
} else {
CustomChange::Replace
}
}
(D::Prepend { count }, Some((first, _))) if n == old + count => {
if times.get(count) == Some(&first) {
check_increasing(×[..=count], 0)?;
CustomChange::Prepend { count }
} else {
CustomChange::Replace
}
}
_ => CustomChange::Replace,
};
if change == CustomChange::Replace {
check_increasing(times, 0)?;
}
Ok(change)
}
pub(crate) fn accept(&mut self, mapping: SeriesMapping) {
self.mapping = mapping;
self.take_all();
}
fn take_all(&mut self) {
let times = self.plugin.times();
self.len = times.len();
self.bounds = times.first().copied().zip(times.last().copied());
}
pub(crate) fn map_onto(&mut self, index: &TimeIndex) -> Result<()> {
let mapping = if self.mode == AxisMode::Slots {
index
.map_series(self.plugin.times())?
.ok_or(Error::InvalidArgument(
"custom series times are not on the axis",
))?
} else {
SeriesMapping::Aligned { first: 0 }
};
self.accept(mapping);
Ok(())
}
pub(crate) fn extend_onto(&mut self, index: &TimeIndex) -> Result<()> {
if self.mode == AxisMode::Slots {
let times = self.plugin.times();
let new = times.get(self.len..).unwrap_or(&[]);
for (p, &t) in (self.len..).zip(new) {
let j = index.index_of(t).ok_or(Error::InvalidArgument(
"custom series times are not on the axis",
))?;
match &mut self.mapping {
SeriesMapping::Aligned { first } if p == 0 => *first = j,
SeriesMapping::Aligned { first }
if Some(j) == first.checked_add(i64::try_from(p).unwrap_or(i64::MAX)) => {}
SeriesMapping::Aligned { first } => {
let first = *first;
let mut offsets = Vec::new();
offsets.try_reserve(p + 1).map_err(|_| Error::OutOfMemory)?;
offsets.extend((0..p).filter_map(|o| u32::try_from(o).ok()));
offsets.push(offset(first, j)?);
self.mapping = SeriesMapping::Mapped { first, offsets };
}
SeriesMapping::Mapped { first, offsets } => {
let o = offset(*first, j)?;
offsets.try_reserve(1).map_err(|_| Error::OutOfMemory)?;
offsets.push(o);
}
}
}
}
self.take_all();
Ok(())
}
pub(crate) fn clear(&mut self) {
self.len = 0;
self.bounds = None;
self.mapping = SeriesMapping::Aligned { first: 0 };
self.log.replace();
}
}
fn offset(first: i64, j: i64) -> Result<u32> {
j.checked_sub(first)
.and_then(|o| u32::try_from(o).ok())
.ok_or(Error::InvalidArgument(
"mapped series spans more than u32::MAX slots",
))
}
fn check_increasing(times: &[Timestamp], base: usize) -> Result<()> {
match times.windows(2).position(|w| w[1] <= w[0]) {
Some(k) => Err(Error::TimeNotIncreasing {
index: base + k + 1,
}),
None => Ok(()),
}
}