1use core::any::Any;
6use core::fmt;
7
8use crate::data::{ChangeLog, SeriesMapping, TimeIndex, Timestamp};
9use crate::drawing::{DrawingCtx, FrameBuilder, index_of_time, time_of_index};
10use crate::error::{Error, Result};
11use crate::frame::SeriesStyle;
12use crate::geom::Px;
13
14#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
16pub enum AxisMode {
17 Slots,
20 Overlay,
23}
24
25pub trait CustomSeries: Send + Any {
101 fn kind(&self) -> &'static str;
104 fn axis_mode(&self) -> AxisMode;
106 fn times(&self) -> &[Timestamp];
108 fn extremes(&self, from: usize, to: usize) -> Option<(f64, f64)>;
111 fn build(&self, ctx: &SeriesCtx<'_>, from: usize, to: usize, out: &mut FrameBuilder<'_>);
115 fn last_value(&self) -> Option<f64> {
117 None
118 }
119 fn crosshair_value(&self, point: usize) -> Option<f64> {
121 let _ = point;
122 None
123 }
124 fn native_params(&self, ctx: &SeriesCtx<'_>, params: &mut [f32; 8]) {
126 let _ = (ctx, params);
127 }
128}
129
130pub struct SeriesCtx<'a> {
132 pub(crate) coords: DrawingCtx<'a>,
133 pub(crate) store: &'a CustomStore,
134 pub(crate) shift: f64,
136 pub(crate) visible: (usize, usize),
137 pub(crate) style: SeriesStyle,
138}
139
140impl<'a> SeriesCtx<'a> {
141 pub fn coords(&self) -> &DrawingCtx<'a> {
145 &self.coords
146 }
147
148 pub fn x_of_point(&self, i: usize) -> Option<f32> {
150 let index = self.store.x_index(self.coords.index, i)? + self.shift;
151 let x = f64::from(self.coords.plot.x) + self.coords.time_scale.index_to_x_f64(index);
152 x.is_finite().then_some(x as f32)
153 }
154
155 pub fn visible(&self) -> (usize, usize) {
158 self.visible
159 }
160
161 pub fn bar_spacing(&self) -> Px {
163 Px(self.coords.time_scale.bar_spacing() as f32)
164 }
165
166 pub fn style(&self) -> &SeriesStyle {
169 &self.style
170 }
171}
172
173pub(crate) struct CustomStore {
175 pub(crate) plugin: Box<dyn CustomSeries>,
176 pub(crate) kind: &'static str,
177 pub(crate) mode: AxisMode,
178 mapping: SeriesMapping,
180 len: usize,
183 bounds: Option<(Timestamp, Timestamp)>,
185 pub(crate) log: ChangeLog,
187}
188
189impl fmt::Debug for CustomStore {
190 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
191 f.debug_struct("CustomStore")
192 .field("kind", &self.kind)
193 .field("mode", &self.mode)
194 .field("len", &self.len)
195 .finish_non_exhaustive()
196 }
197}
198
199#[derive(Clone, Copy, Debug, PartialEq, Eq)]
201pub(crate) enum CustomChange {
202 None,
204 UpdateLast,
205 Append,
206 Prepend {
207 count: usize,
208 },
209 Replace,
210}
211
212impl CustomStore {
213 pub(crate) fn new(plugin: Box<dyn CustomSeries>) -> Self {
214 Self {
215 kind: plugin.kind(),
216 mode: plugin.axis_mode(),
217 plugin,
218 mapping: SeriesMapping::Aligned { first: 0 },
219 len: 0,
220 bounds: None,
221 log: ChangeLog::new(),
222 }
223 }
224
225 pub(crate) fn len(&self) -> usize {
226 self.len
227 }
228
229 pub(crate) fn times(&self) -> &[Timestamp] {
231 let t = self.plugin.times();
232 t.get(..self.len).unwrap_or(t)
233 }
234
235 pub(crate) fn heap_bytes(&self) -> usize {
236 match &self.mapping {
237 SeriesMapping::Aligned { .. } => 0,
238 SeriesMapping::Mapped { offsets, .. } => offsets.capacity() * 4,
239 }
240 }
241
242 fn logical(&self, i: usize) -> Option<i64> {
244 if i >= self.len {
245 return None;
246 }
247 self.mapping.logical_index(i)
248 }
249
250 pub(crate) fn span(&self) -> Option<(i64, i64)> {
252 if self.mode != AxisMode::Slots || self.len == 0 {
253 return None;
254 }
255 Some((self.logical(0)?, self.logical(self.len - 1)? + 1))
256 }
257
258 pub(crate) fn point_at(&self, j: i64) -> Option<usize> {
260 if self.mode != AxisMode::Slots {
261 return None;
262 }
263 match &self.mapping {
264 SeriesMapping::Aligned { first } => {
265 let p = usize::try_from(j.checked_sub(*first)?).ok()?;
266 (p < self.len).then_some(p)
267 }
268 SeriesMapping::Mapped { first, offsets } => {
269 let off = u32::try_from(j.checked_sub(*first)?).ok()?;
270 offsets.get(..self.len)?.binary_search(&off).ok()
271 }
272 }
273 }
274
275 pub(crate) fn x_index(&self, index: &TimeIndex, i: usize) -> Option<f64> {
277 match self.mode {
278 AxisMode::Slots => self.logical(i).map(|j| j as f64),
279 AxisMode::Overlay => index_of_time(index, *self.times().get(i)?),
280 }
281 }
282
283 fn slot_points(&self, from: i64, to: i64) -> (usize, usize) {
285 let n = self.len;
286 let (a, b) = match &self.mapping {
287 SeriesMapping::Aligned { first } => {
288 let rel = |j: i64| {
289 usize::try_from(j.saturating_sub(*first).max(0))
290 .unwrap_or(n)
291 .min(n)
292 };
293 (rel(from), rel(to))
294 }
295 SeriesMapping::Mapped { first, offsets } => {
296 let offsets = offsets.get(..n).unwrap_or(offsets);
297 let (lo, hi) = (from.saturating_sub(*first), to.saturating_sub(*first));
298 (
299 offsets.partition_point(|&o| i64::from(o) < lo),
300 offsets.partition_point(|&o| i64::from(o) < hi),
301 )
302 }
303 };
304 (a, b.max(a))
305 }
306
307 fn time_points(&self, t0: Timestamp, t1: Timestamp) -> (usize, usize) {
309 let times = self.times();
310 let a = times.partition_point(|&t| t < t0);
311 (a, times.partition_point(|&t| t <= t1).max(a))
312 }
313
314 fn points_between(&self, index: &TimeIndex, from: f64, to: f64) -> (usize, usize) {
316 if self.len == 0 || from.partial_cmp(&to).is_none_or(core::cmp::Ordering::is_gt) {
317 return (0, 0);
318 }
319 match self.mode {
320 AxisMode::Slots => self.slot_points(from.ceil() as i64, to.floor() as i64 + 1),
321 AxisMode::Overlay => match (time_of_index(index, from), time_of_index(index, to)) {
322 (Some(t0), Some(t1)) => self.time_points(t0, t1),
323 _ => (0, 0),
324 },
325 }
326 }
327
328 pub(crate) fn points_in(&self, index: &TimeIndex, from: f64, to: f64) -> (usize, usize) {
330 if self.len == 0 {
331 return (0, 0);
332 }
333 let (a, b) = self.points_between(index, from, to);
334 (a.saturating_sub(1), (b + 1).min(self.len))
335 }
336
337 pub(crate) fn extremes(&self, index: &TimeIndex, from: i64, to: i64) -> Option<(f64, f64)> {
339 let (a, b) = self.points_between(index, from as f64, (to - 1) as f64);
340 if a >= b {
341 return None;
342 }
343 self.plugin.extremes(a, b)
344 }
345
346 pub(crate) fn value_at(&self, j: i64) -> Option<f64> {
348 let v = self.plugin.crosshair_value(self.point_at(j)?)?;
349 v.is_finite().then_some(v)
350 }
351
352 pub(crate) fn classify(&self, change: crate::data::DataChange) -> Result<CustomChange> {
356 use crate::data::DataChange as D;
357 let times = self.plugin.times();
358 let (n, old) = (times.len(), self.len);
359 let change = match (change, self.bounds) {
360 (D::UpdateLast, Some((_, last))) if n == old && times.last() == Some(&last) => {
361 CustomChange::UpdateLast
362 }
363 (D::Append { count: 0 } | D::Prepend { count: 0 }, _) if n == old => CustomChange::None,
364 (D::Append { count }, Some((_, last))) if n == old + count => {
365 if times.get(old - 1) == Some(&last) {
366 check_increasing(×[old - 1..], old - 1)?;
367 CustomChange::Append
368 } else {
369 CustomChange::Replace
370 }
371 }
372 (D::Prepend { count }, Some((first, _))) if n == old + count => {
373 if times.get(count) == Some(&first) {
374 check_increasing(×[..=count], 0)?;
375 CustomChange::Prepend { count }
376 } else {
377 CustomChange::Replace
378 }
379 }
380 _ => CustomChange::Replace,
381 };
382 if change == CustomChange::Replace {
383 check_increasing(times, 0)?;
384 }
385 Ok(change)
386 }
387
388 pub(crate) fn accept(&mut self, mapping: SeriesMapping) {
390 self.mapping = mapping;
391 self.take_all();
392 }
393
394 fn take_all(&mut self) {
396 let times = self.plugin.times();
397 self.len = times.len();
398 self.bounds = times.first().copied().zip(times.last().copied());
399 }
400
401 pub(crate) fn map_onto(&mut self, index: &TimeIndex) -> Result<()> {
408 let mapping = if self.mode == AxisMode::Slots {
409 index
410 .map_series(self.plugin.times())?
411 .ok_or(Error::InvalidArgument(
412 "custom series times are not on the axis",
413 ))?
414 } else {
415 SeriesMapping::Aligned { first: 0 }
416 };
417 self.accept(mapping);
418 Ok(())
419 }
420
421 pub(crate) fn extend_onto(&mut self, index: &TimeIndex) -> Result<()> {
424 if self.mode == AxisMode::Slots {
425 let times = self.plugin.times();
426 let new = times.get(self.len..).unwrap_or(&[]);
427 for (p, &t) in (self.len..).zip(new) {
428 let j = index.index_of(t).ok_or(Error::InvalidArgument(
429 "custom series times are not on the axis",
430 ))?;
431 match &mut self.mapping {
432 SeriesMapping::Aligned { first } if p == 0 => *first = j,
433 SeriesMapping::Aligned { first }
434 if Some(j) == first.checked_add(i64::try_from(p).unwrap_or(i64::MAX)) => {}
435 SeriesMapping::Aligned { first } => {
436 let first = *first;
437 let mut offsets = Vec::new();
438 offsets.try_reserve(p + 1).map_err(|_| Error::OutOfMemory)?;
439 offsets.extend((0..p).filter_map(|o| u32::try_from(o).ok()));
440 offsets.push(offset(first, j)?);
441 self.mapping = SeriesMapping::Mapped { first, offsets };
442 }
443 SeriesMapping::Mapped { first, offsets } => {
444 let o = offset(*first, j)?;
445 offsets.try_reserve(1).map_err(|_| Error::OutOfMemory)?;
446 offsets.push(o);
447 }
448 }
449 }
450 }
451 self.take_all();
452 Ok(())
453 }
454
455 pub(crate) fn clear(&mut self) {
458 self.len = 0;
459 self.bounds = None;
460 self.mapping = SeriesMapping::Aligned { first: 0 };
461 self.log.replace();
462 }
463}
464
465fn offset(first: i64, j: i64) -> Result<u32> {
466 j.checked_sub(first)
467 .and_then(|o| u32::try_from(o).ok())
468 .ok_or(Error::InvalidArgument(
469 "mapped series spans more than u32::MAX slots",
470 ))
471}
472
473fn check_increasing(times: &[Timestamp], base: usize) -> Result<()> {
476 match times.windows(2).position(|w| w[1] <= w[0]) {
477 Some(k) => Err(Error::TimeNotIncreasing {
478 index: base + k + 1,
479 }),
480 None => Ok(()),
481 }
482}