1use std::{
4 fmt,
5 hash::{Hash, Hasher},
6 sync::Arc,
7};
8
9use super::{AxisValues, ExactInteger, RawKey};
10use crate::{BooleanValues, CategoryValues, Error, NumericValues, Result};
11
12#[derive(Clone)]
17pub struct DataSourceRef {
18 logical: Arc<()>,
19 capture: Arc<()>,
20}
21
22impl DataSourceRef {
23 #[doc(hidden)]
25 pub fn capture() -> Self {
26 Self {
27 logical: Arc::new(()),
28 capture: Arc::new(()),
29 }
30 }
31
32 #[doc(hidden)]
34 #[must_use]
35 pub fn recapture(&self) -> Self {
36 Self {
37 logical: Arc::clone(&self.logical),
38 capture: Arc::new(()),
39 }
40 }
41
42 pub fn same_source(&self, other: &Self) -> bool {
44 Arc::ptr_eq(&self.logical, &other.logical)
45 }
46}
47
48impl PartialEq for DataSourceRef {
49 fn eq(&self, other: &Self) -> bool {
50 self.same_source(other) && Arc::ptr_eq(&self.capture, &other.capture)
51 }
52}
53
54impl Eq for DataSourceRef {}
55
56impl Hash for DataSourceRef {
57 fn hash<H: Hasher>(&self, state: &mut H) {
58 Arc::as_ptr(&self.logical).hash(state);
59 Arc::as_ptr(&self.capture).hash(state);
60 }
61}
62
63impl fmt::Debug for DataSourceRef {
64 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
65 f.debug_struct("DataSourceRef").finish_non_exhaustive()
66 }
67}
68
69#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
71#[non_exhaustive]
72pub enum BindingSelectorKind {
73 Key,
75 Keys,
77 Index,
79 Indices,
81 Slice,
83 All,
85 NumericOnly,
87 Whole,
89}
90
91#[derive(Debug, Clone, PartialEq, Eq, Hash)]
94pub struct BindingSlice {
95 start: Option<isize>,
96 stop: Option<isize>,
97 step: ExactInteger,
98}
99
100impl BindingSlice {
101 pub fn new(start: Option<isize>, end: Option<isize>, stride: ExactInteger) -> Result<Self> {
103 if stride == ExactInteger::from(0) {
104 return Err(Error::Data("binding slice step must not be zero".into()));
105 }
106 Ok(Self {
107 start,
108 stop: end,
109 step: stride,
110 })
111 }
112
113 pub const fn start(&self) -> Option<isize> {
115 self.start
116 }
117
118 pub const fn stop(&self) -> Option<isize> {
120 self.stop
121 }
122
123 pub const fn step(&self) -> &ExactInteger {
125 &self.step
126 }
127}
128
129#[derive(Debug, Clone, PartialEq, Eq, Hash)]
131#[non_exhaustive]
132pub enum BindingSelector {
133 Key(RawKey),
135 Keys(Vec<RawKey>),
137 Index(isize),
139 Indices(Vec<isize>),
141 Slice(BindingSlice),
143 All,
145 NumericOnly,
147 Whole,
149}
150
151impl BindingSelector {
152 pub const fn kind(&self) -> BindingSelectorKind {
154 match self {
155 Self::Key(_) => BindingSelectorKind::Key,
156 Self::Keys(_) => BindingSelectorKind::Keys,
157 Self::Index(_) => BindingSelectorKind::Index,
158 Self::Indices(_) => BindingSelectorKind::Indices,
159 Self::Slice(_) => BindingSelectorKind::Slice,
160 Self::All => BindingSelectorKind::All,
161 Self::NumericOnly => BindingSelectorKind::NumericOnly,
162 Self::Whole => BindingSelectorKind::Whole,
163 }
164 }
165
166 pub const fn get_key(&self) -> Option<&RawKey> {
168 if let Self::Key(key) = self {
169 Some(key)
170 } else {
171 None
172 }
173 }
174
175 pub fn get_keys(&self) -> Option<&[RawKey]> {
177 if let Self::Keys(keys) = self {
178 Some(keys)
179 } else {
180 None
181 }
182 }
183
184 pub const fn get_index(&self) -> Option<isize> {
186 if let Self::Index(index) = self {
187 Some(*index)
188 } else {
189 None
190 }
191 }
192
193 pub fn get_indices(&self) -> Option<&[isize]> {
195 if let Self::Indices(indices) = self {
196 Some(indices)
197 } else {
198 None
199 }
200 }
201
202 pub const fn get_slice(&self) -> Option<&BindingSlice> {
204 if let Self::Slice(slice) = self {
205 Some(slice)
206 } else {
207 None
208 }
209 }
210}
211
212#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
214#[non_exhaustive]
215pub enum BindingGeneration {
216 RowPosition,
218 ColumnNames,
220 GridPosition,
222 WideExpansion,
224}
225
226#[derive(Debug, Clone, PartialEq, Eq)]
231pub struct DataSourceInfo(Arc<SourceInfo>);
232
233#[derive(Debug, Clone, PartialEq, Eq)]
234struct SourceInfo {
235 reference: DataSourceRef,
236 binding_name: Option<String>,
237 generation: Option<BindingGeneration>,
238 relation_shape: Option<Vec<usize>>,
239 grid_axis: Option<usize>,
240 selector: Option<BindingSelector>,
241 selected_keys: Option<Vec<RawKey>>,
242 selected_names: Option<Vec<String>>,
243 selected_indices: Option<Vec<usize>>,
244 source_shape: Vec<usize>,
245 selected_shape: Vec<usize>,
246}
247
248impl DataSourceInfo {
249 #[doc(hidden)]
251 pub fn direct(shape: Vec<usize>) -> Self {
252 Self(Arc::new(SourceInfo {
253 reference: DataSourceRef::capture(),
254 binding_name: None,
255 generation: None,
256 relation_shape: None,
257 grid_axis: None,
258 selector: None,
259 selected_keys: None,
260 selected_names: None,
261 selected_indices: None,
262 source_shape: shape.clone(),
263 selected_shape: shape,
264 }))
265 }
266
267 #[doc(hidden)]
269 pub fn selected(
270 reference: DataSourceRef,
271 selector: BindingSelector,
272 keys: Option<Vec<RawKey>>,
273 indices: Vec<usize>,
274 source_shape: Vec<usize>,
275 selected_shape: Vec<usize>,
276 ) -> Self {
277 Self(Arc::new(SourceInfo {
278 reference,
279 binding_name: None,
280 generation: None,
281 relation_shape: None,
282 grid_axis: None,
283 selector: Some(selector),
284 selected_keys: keys,
285 selected_names: None,
286 selected_indices: Some(indices),
287 source_shape,
288 selected_shape,
289 }))
290 }
291
292 #[doc(hidden)]
294 pub fn direct_fields(shape: Vec<usize>, keys: Option<Vec<RawKey>>) -> Self {
295 let mut info = Self::direct(shape);
296 Arc::make_mut(&mut info.0).selected_keys = keys;
297 info
298 }
299
300 #[doc(hidden)]
302 #[must_use]
303 pub fn generated(mut self, generation: BindingGeneration, shape: Vec<usize>) -> Self {
304 let info = Arc::make_mut(&mut self.0);
305 info.generation = Some(generation);
306 info.relation_shape = Some(shape);
307 self
308 }
309
310 #[doc(hidden)]
312 #[must_use]
313 pub fn generated_grid_axis(mut self, axis: usize, extent: usize) -> Self {
314 let info = Arc::make_mut(&mut self.0);
315 info.generation = Some(BindingGeneration::GridPosition);
316 info.grid_axis = Some(axis);
317 info.relation_shape = Some(vec![extent]);
318 self
319 }
320
321 pub(crate) fn grid_axis(&self) -> Option<usize> {
322 self.0.grid_axis
323 }
324
325 pub fn binding_name(&self) -> Option<&str> {
327 self.0.binding_name.as_deref()
328 }
329
330 pub fn logical_keys(&self) -> Option<&[RawKey]> {
332 self.selected_keys()
333 }
334
335 pub fn generation(&self) -> Option<BindingGeneration> {
337 self.0.generation
338 }
339
340 pub fn reference(&self) -> &DataSourceRef {
342 &self.0.reference
343 }
344
345 pub fn selector(&self) -> Option<&BindingSelector> {
347 self.0.selector.as_ref()
348 }
349
350 #[doc(hidden)]
352 pub fn with_selected_names(mut self, names: Vec<String>) -> Result<Self> {
353 if self.0.selected_keys.as_ref().map(Vec::len) != Some(names.len()) {
354 return Err(Error::Data(
355 "captured field names must match their actual keys".into(),
356 ));
357 }
358 Arc::make_mut(&mut self.0).selected_names = Some(names);
359 Ok(self)
360 }
361
362 #[doc(hidden)]
364 pub fn selected_names(&self) -> Option<&[String]> {
365 self.0.selected_names.as_deref()
366 }
367
368 #[doc(hidden)]
370 pub fn field(&self, position: usize) -> Option<(RawKey, String)> {
371 let key = self.0.selected_keys.as_ref()?.get(position)?;
372 let name = if let Some(names) = &self.0.selected_names {
373 names.get(position)?.clone()
374 } else if let RawKey::String(name) = key {
375 name.clone()
376 } else {
377 return None;
378 };
379 Some((key.clone(), name))
380 }
381
382 pub fn selected_keys(&self) -> Option<&[RawKey]> {
384 self.0.selected_keys.as_deref()
385 }
386
387 pub fn selected_indices(&self) -> Option<&[usize]> {
389 self.0.selected_indices.as_deref()
390 }
391
392 pub fn source_shape(&self) -> &[usize] {
394 &self.0.source_shape
395 }
396
397 pub fn selected_shape(&self) -> &[usize] {
399 &self.0.selected_shape
400 }
401
402 pub(crate) fn member_shape(&self) -> &[usize] {
403 self.0
404 .relation_shape
405 .as_deref()
406 .unwrap_or(&self.0.selected_shape)
407 }
408
409 fn selected_count(&self) -> Option<usize> {
410 self.member_shape()
411 .iter()
412 .try_fold(1usize, |n, &size| n.checked_mul(size))
413 }
414}
415
416#[derive(Debug, Clone)]
418pub(crate) struct VectorSource {
419 info: DataSourceInfo,
420 projection: Option<Arc<SourceProjection>>,
421}
422
423#[derive(Debug, Clone)]
424enum SlotProjection {
425 Identity,
426 Repeated(usize),
427 Cycled(usize),
428 Gathered(Arc<[usize]>),
429}
430
431#[derive(Debug, Clone)]
432struct SourceProjection {
433 slots: SlotProjection,
434 original_nulls: bool,
435 field_nulls: Option<Arc<[bool]>>,
436 distinct_rows: bool,
437 field_axis_keys: Option<Arc<super::RawKeyValues>>,
438}
439
440impl Default for SourceProjection {
441 fn default() -> Self {
442 Self {
443 slots: SlotProjection::Identity,
444 original_nulls: false,
445 field_nulls: None,
446 distinct_rows: true,
447 field_axis_keys: None,
448 }
449 }
450}
451
452impl VectorSource {
453 pub(crate) fn direct(len: usize) -> Self {
454 Self::new(DataSourceInfo::direct(vec![len]))
455 }
456
457 pub(crate) fn direct_nullable(len: usize, has_nulls: bool) -> Self {
458 let mut source = Self::direct(len);
459 if has_nulls {
460 source.projection_mut().original_nulls = true;
461 }
462 source
463 }
464
465 pub(crate) fn new(info: DataSourceInfo) -> Self {
466 Self {
467 info,
468 projection: None,
469 }
470 }
471
472 fn projection_mut(&mut self) -> &mut SourceProjection {
473 Arc::make_mut(
474 self.projection
475 .get_or_insert_with(|| Arc::new(SourceProjection::default())),
476 )
477 }
478
479 pub(crate) fn repeated(info: DataSourceInfo, copies: usize, len: usize) -> Result<Self> {
480 if copies == 0 || info.selected_count().and_then(|n| n.checked_mul(copies)) != Some(len) {
481 return Err(Error::Data(
482 "captured source shape and repetition must match the actual value count".into(),
483 ));
484 }
485 let mut source = Self::new(info);
486 if copies != 1 {
487 let projection = source.projection_mut();
488 projection.slots = SlotProjection::Repeated(copies);
489 projection.distinct_rows = false;
490 }
491 Ok(source)
492 }
493
494 pub(crate) fn cycled(info: DataSourceInfo, len: usize) -> Result<Self> {
495 let count = info.selected_count().unwrap_or(0);
496 if count == 0 || !len.is_multiple_of(count) {
497 return Err(Error::Data(
498 "captured column identity count must divide the actual value count".into(),
499 ));
500 }
501 let field_axis_keys = complete_field_axis(&info)?;
502 Ok(Self {
503 info,
504 projection: Some(super::source::source_arc(SourceProjection {
505 slots: SlotProjection::Cycled(count),
506 distinct_rows: false,
507 field_axis_keys,
508 ..SourceProjection::default()
509 })?),
510 })
511 }
512
513 pub(crate) fn gathered(info: DataSourceInfo, slots: Vec<usize>, len: usize) -> Result<Self> {
514 if slots.len() != len
515 || !info
516 .selected_count()
517 .is_some_and(|count| slots.iter().all(|&slot| slot < count))
518 {
519 return Err(Error::Data(
520 "captured source slots must match the actual value domain".into(),
521 ));
522 }
523 let distinct_rows = info.member_shape().len() == 1 && distinct_slots(&slots)?;
524 let field_axis_keys = complete_field_axis(&info)?;
525 Ok(Self {
526 info,
527 projection: Some(super::source::source_arc(SourceProjection {
528 slots: SlotProjection::Gathered(slots.into()),
529 distinct_rows,
530 field_axis_keys,
531 ..SourceProjection::default()
532 })?),
533 })
534 }
535
536 pub(crate) fn info(&self) -> &DataSourceInfo {
537 &self.info
538 }
539
540 pub(crate) fn slot(&self, index: usize) -> usize {
541 match self
542 .projection
543 .as_deref()
544 .map(|projection| &projection.slots)
545 {
546 None | Some(SlotProjection::Identity) => index,
547 Some(SlotProjection::Repeated(copies)) => index / copies,
548 Some(SlotProjection::Cycled(count)) => index % count,
549 Some(SlotProjection::Gathered(slots)) => slots[index],
550 }
551 }
552
553 pub(crate) fn is_identity(&self) -> bool {
554 self.projection
555 .as_deref()
556 .is_none_or(|entry| matches!(entry.slots, SlotProjection::Identity))
557 }
558
559 pub(crate) fn has_distinct_rows(&self) -> bool {
560 self.info.member_shape().len() == 1
561 && self
562 .projection
563 .as_deref()
564 .is_none_or(|entry| entry.distinct_rows)
565 }
566
567 pub(crate) fn field_axis_keys(&self) -> Option<&super::RawKeyValues> {
568 self.projection.as_deref()?.field_axis_keys.as_deref()
569 }
570
571 pub(crate) fn with_original_validity(
574 mut self,
575 length: usize,
576 has_nulls: bool,
577 is_valid: impl Fn(usize) -> bool,
578 ) -> Result<Self> {
579 if !has_nulls && self.projection.is_none() {
580 return Ok(self);
581 }
582 let mut field_nulls = None;
583 if has_nulls && self.info.selected_keys().is_some() {
584 if let [_, width] = self.info.member_shape() {
585 let mut fields = Vec::new();
586 super::source::reserve_source(&mut fields, *width)?;
587 fields.resize(*width, false);
588 crate::operation::work(length)?;
589 for slot in 0..length {
590 if !is_valid(slot) {
591 fields[self.slot(slot) % width] = true;
592 }
593 }
594 field_nulls = Some(fields.into());
595 }
596 }
597 let projection = self.projection_mut();
598 projection.original_nulls = has_nulls;
599 projection.field_nulls = field_nulls;
600 Ok(self)
601 }
602
603 pub(crate) fn original_has_nulls(&self, field: Option<usize>) -> bool {
604 let Some(projection) = self.projection.as_deref() else {
605 return false;
606 };
607 field
608 .and_then(|field| projection.field_nulls.as_ref()?.get(field).copied())
609 .unwrap_or(projection.original_nulls)
610 }
611
612 pub(crate) fn retain_original_validity(&mut self, source: &Self) {
613 if let Some(original) = source.projection.as_deref() {
614 let projection = self.projection_mut();
615 projection.original_nulls = original.original_nulls;
616 projection.field_nulls.clone_from(&original.field_nulls);
617 projection.distinct_rows &= original.distinct_rows;
618 projection
619 .field_axis_keys
620 .clone_from(&original.field_axis_keys);
621 }
622 }
623
624 pub(crate) fn select(&self, indices: &[usize]) -> Result<Self> {
625 let slots =
626 super::source::collect_source(indices.iter().map(|&index| Ok(self.slot(index))))?;
627 let distinct_rows = self.has_distinct_rows() && distinct_slots(&slots)?;
628 let mut projection = self.projection.as_deref().cloned().unwrap_or_default();
629 projection.slots = SlotProjection::Gathered(slots.into());
630 projection.distinct_rows = distinct_rows;
631 Ok(Self {
632 info: self.info.clone(),
633 projection: Some(super::source::source_arc(projection)?),
634 })
635 }
636}
637
638fn complete_field_axis(info: &DataSourceInfo) -> Result<Option<Arc<super::RawKeyValues>>> {
639 if info.generation() != Some(BindingGeneration::ColumnNames) && info.grid_axis() != Some(1) {
640 return Ok(None);
641 }
642 let (Some(keys), Some(&width)) = (info.selected_keys(), info.source_shape().get(1)) else {
643 return Ok(None);
644 };
645 if keys.len() != width {
646 return Ok(None);
648 }
649 let mut ordered = Vec::new();
650 super::source::reserve_source(&mut ordered, width)?;
651 ordered.resize(width, None);
652 for (slot, key) in keys.iter().enumerate() {
653 let position = info
654 .selected_indices()
655 .and_then(|indices| indices.get(slot))
656 .copied()
657 .unwrap_or(slot);
658 let Some(target) = ordered.get_mut(position) else {
659 return Ok(None);
660 };
661 if target.replace(key.clone()).is_some() {
662 return Ok(None);
663 }
664 }
665 Ok(Some(Arc::new(super::RawKeyValues::nullable(
666 "field", ordered,
667 )?)))
668}
669
670fn distinct_slots(slots: &[usize]) -> Result<bool> {
671 crate::operation::work(slots.len())?;
672 if slots.windows(2).all(|pair| pair[0] < pair[1]) {
673 return Ok(true);
674 }
675 let mut sorted = super::source::collect_source(slots.iter().copied().map(Ok))?;
676 super::source::sort_source_by(&mut sorted, usize::cmp)?;
677 Ok(sorted.windows(2).all(|pair| pair[0] != pair[1]))
678}
679
680#[doc(hidden)]
682pub trait CapturedValue: Sized {
683 fn len(&self) -> usize;
685 fn is_empty(&self) -> bool {
687 self.len() == 0
688 }
689 fn retain(
691 self,
692 source: DataSourceInfo,
693 copies: usize,
694 field: Option<(RawKey, String)>,
695 ) -> Result<Self>;
696}
697
698macro_rules! captured_values {
699 ($($ty:ident),+) => {$(
700 impl CapturedValue for $ty {
701 fn len(&self) -> usize { self.len() }
702
703 fn retain(
704 self, source: DataSourceInfo, copies: usize, field: Option<(RawKey, String)>,
705 ) -> Result<Self> {
706 let value = self.with_repeated_source(source, copies)?;
707 Ok(if let Some((key, name)) = field {
708 value.with_field_key(key, name)
709 } else {
710 value
711 })
712 }
713 }
714 )+};
715}
716captured_values!(NumericValues, CategoryValues, BooleanValues);
717
718impl CapturedValue for super::SourceRows {
719 fn len(&self) -> usize {
720 self.len()
721 }
722
723 fn retain(
724 self,
725 source: DataSourceInfo,
726 copies: usize,
727 _: Option<(RawKey, String)>,
728 ) -> Result<Self> {
729 if copies != 1 {
730 return Err(Error::Data(
731 "source row identities cannot be repeated".into(),
732 ));
733 }
734 self.with_source(source)
735 }
736}
737
738impl CapturedValue for AxisValues {
739 fn len(&self) -> usize {
740 self.len()
741 }
742
743 fn retain(
744 self,
745 source: DataSourceInfo,
746 copies: usize,
747 field: Option<(RawKey, String)>,
748 ) -> Result<Self> {
749 Ok(match self {
750 Self::Numeric(values) => Self::Numeric(values.retain(source, copies, field)?),
751 Self::Category(values) => Self::Category(values.retain(source, copies, field)?),
752 Self::Keys(values) => {
753 let len = values.len();
754 let source = VectorSource::repeated(source, copies, len)?.with_original_validity(
755 len,
756 values.has_nulls(),
757 |slot| values.is_valid(slot) == Some(true),
758 )?;
759 Self::Keys(values.with_vector_source(source))
760 }
761 })
762 }
763}