1use std::{cell::OnceCell, collections::HashSet, marker::PhantomData, rc::Rc};
5
6use crate::{
7 data::{BindingSelector, DataSourceInfo, DataSourceRef, RawKey, RawKeyValues, SourceRows},
8 BooleanValues, CategoryValues, NumericValues, Result,
9};
10
11use super::{
12 codec::invalid,
13 keys::{integer, selector_pending},
14};
15
16#[doc(hidden)]
19pub trait BindingInput<M = ()> {
20 fn binding_object(&self) -> Result<BindingObject<'_>>;
22}
23
24trait Provider {
25 fn object(&self) -> Result<BindingObject<'_>>;
26}
27
28struct Input<T, M>(T, PhantomData<M>);
29
30impl<T: BindingInput<M>, M> Provider for Input<T, M> {
31 fn object(&self) -> Result<BindingObject<'_>> {
32 self.0.binding_object()
33 }
34}
35
36#[derive(Default)]
39pub struct Bindings<'a> {
40 inputs: Vec<(RawKey, Box<dyn Provider + 'a>)>,
41}
42
43impl<'a> Bindings<'a> {
44 pub fn new() -> Self {
46 Self::default()
47 }
48
49 pub fn bind<T: BindingInput<M> + 'a, M: 'a>(
51 mut self,
52 name: impl Into<RawKey>,
53 input: T,
54 ) -> Result<Self> {
55 let key = name.into();
56 if self.inputs.iter().any(|(existing, _)| existing == &key) {
57 return Err(invalid(format!("duplicate binding {key:?}")));
58 }
59 self.inputs.push((key, Box::new(Input(input, PhantomData))));
60 Ok(self)
61 }
62
63 pub(super) fn names(&self) -> impl Iterator<Item = &RawKey> {
64 self.inputs.iter().map(|(name, _)| name)
65 }
66
67 pub(super) fn get(&self, name: &RawKey) -> Option<BindingObject<'_>> {
68 let (_, provider) = self.inputs.iter().find(|(key, _)| key == name)?;
69 Some(BindingObject::deferred(move || provider.object()))
70 }
71}
72
73impl BindingInput for &Bindings<'_> {
74 fn binding_object(&self) -> Result<BindingObject<'_>> {
75 Ok(BindingObject::members(
76 self.inputs
77 .iter()
78 .map(|(key, provider)| {
79 (
80 key.clone(),
81 BindingObject::deferred(move || provider.object()),
82 )
83 })
84 .collect(),
85 ))
86 }
87}
88
89#[doc(hidden)]
92pub trait BindingArguments<M> {
93 fn with_bindings<T>(self, use_bindings: impl FnOnce(&Bindings<'_>) -> Result<T>) -> Result<T>;
95}
96
97#[doc(hidden)]
99pub struct RegistryArguments;
100#[doc(hidden)]
102pub struct SequenceArguments<M>(PhantomData<M>);
103
104impl BindingArguments<RegistryArguments> for &Bindings<'_> {
105 fn with_bindings<T>(self, use_bindings: impl FnOnce(&Bindings<'_>) -> Result<T>) -> Result<T> {
106 use_bindings(self)
107 }
108}
109
110impl<I, N, V, M> BindingArguments<SequenceArguments<M>> for I
111where
112 I: IntoIterator<Item = (N, V)>,
113 N: Into<RawKey>,
114 V: BindingInput<M>,
115{
116 fn with_bindings<T>(self, use_bindings: impl FnOnce(&Bindings<'_>) -> Result<T>) -> Result<T> {
117 let mut bindings = Bindings::new();
118 for (name, value) in self {
119 bindings = bindings.bind(name, value)?;
120 }
121 use_bindings(&bindings)
122 }
123}
124
125#[doc(hidden)]
128#[derive(Clone)]
129pub struct BindingField<'a> {
130 key: Option<RawKey>,
131 name: String,
132 numeric: bool,
133 value: BindingObject<'a>,
134}
135
136impl<'a> BindingField<'a> {
137 pub(super) fn logical_key(&self) -> Option<&RawKey> {
138 self.key.as_ref()
139 }
140 pub(super) fn name(&self) -> &str {
141 &self.name
142 }
143 pub(super) fn object(&self) -> &BindingObject<'a> {
144 &self.value
145 }
146 pub fn new(
148 key: Option<RawKey>,
149 name: impl Into<String>,
150 numeric: bool,
151 value: BindingObject<'a>,
152 ) -> Self {
153 Self {
154 key,
155 name: name.into(),
156 numeric,
157 value,
158 }
159 }
160}
161
162#[doc(hidden)]
165#[derive(Clone)]
166pub struct BindingObject<'a>(Rc<Object<'a>>);
167
168enum Object<'a> {
169 Column(Column),
170 Content(crate::composition::CompositionSource),
171 Table {
172 rows: usize,
173 fields: Vec<BindingField<'a>>,
174 },
175 Members(Vec<(RawKey, BindingObject<'a>)>),
176 Sequence {
177 rows: usize,
178 vector: BindingObject<'a>,
179 rectangle: BindingObject<'a>,
180 },
181 Deferred {
182 load: Box<dyn Fn() -> Result<BindingObject<'a>> + 'a>,
183 ready: OnceCell<BindingObject<'a>>,
184 },
185}
186
187#[doc(hidden)]
189#[derive(Clone, Copy, PartialEq, Eq)]
190pub enum BindingColumnType {
191 Numeric,
193 Category,
195 Boolean,
197 Null,
199 Keys,
201}
202
203#[derive(Clone, Copy)]
204pub(super) enum TextType {
205 String,
206 Boolean,
207 F32,
208 F64,
209 Signed(u32),
210 Unsigned(u32),
211}
212impl TextType {
213 pub(super) fn parse(value: &str) -> Result<Self> {
214 Ok(match value {
215 "string" => Self::String,
216 "bool" => Self::Boolean,
217 "f32" => Self::F32,
218 "f64" => Self::F64,
219 "i8" => Self::Signed(8),
220 "i16" => Self::Signed(16),
221 "i32" => Self::Signed(32),
222 "i64" => Self::Signed(64),
223 "i128" => Self::Signed(128),
224 "u8" => Self::Unsigned(8),
225 "u16" => Self::Unsigned(16),
226 "u32" => Self::Unsigned(32),
227 "u64" => Self::Unsigned(64),
228 "u128" => Self::Unsigned(128),
229 _ => return Err(invalid(format!("unsupported text dtype {value:?}"))),
230 })
231 }
232
233 pub(super) fn numeric(self) -> bool {
234 !matches!(self, Self::String | Self::Boolean)
235 }
236
237 pub(super) fn valid(self, token: &str) -> bool {
238 let token = token.trim();
239 if token.is_empty() || matches!(self, Self::String) {
240 return true;
241 }
242 match self {
243 Self::String => true,
244 Self::Boolean => {
245 token.eq_ignore_ascii_case("true") || token.eq_ignore_ascii_case("false")
246 }
247 Self::F32 => token.parse::<f32>().is_ok(),
248 Self::F64 => token.parse::<f64>().is_ok(),
249 Self::Signed(bits) => token.parse::<i128>().is_ok_and(|value| {
250 bits == 128 || (-1_i128 << (bits - 1)..1_i128 << (bits - 1)).contains(&value)
251 }),
252 Self::Unsigned(bits) => token
253 .parse::<u128>()
254 .is_ok_and(|value| bits == 128 || value < 1_u128 << bits),
255 }
256 }
257
258 fn key(self, token: &str) -> Result<Option<RawKey>> {
259 let raw = token;
260 let token = token.trim();
261 if matches!(self, Self::String) {
262 return Ok(Some(RawKey::from(raw)));
263 }
264 if token.is_empty() {
265 return Ok(None);
266 }
267 if !self.valid(token) {
268 return Err(invalid(format!("invalid typed key token {raw:?}")));
269 }
270 let key = match self {
271 Self::String => unreachable!("handled string tokens"),
272 Self::Boolean => RawKey::Boolean(token.eq_ignore_ascii_case("true")),
273 Self::F32 => RawKey::Float(f64::from(token.parse::<f32>().expect("validated f32"))),
274 Self::F64 => RawKey::Float(token.parse::<f64>().expect("validated f64")),
275 Self::Signed(_) | Self::Unsigned(_) => {
276 RawKey::Integer(super::keys::decode_integer(token)?)
277 }
278 };
279 Ok(Some(key))
280 }
281}
282
283#[derive(Clone)]
284pub(super) enum Column {
285 Numeric(NumericValues),
286 Category(CategoryValues),
287 Boolean(BooleanValues),
288 Rows(SourceRows),
289 SignificanceTargets(std::sync::Arc<[crate::elements::SignificanceTarget]>),
290 SignificanceMarks(std::sync::Arc<[crate::elements::SignificanceMark]>),
291 FacetCells(std::sync::Arc<[crate::layout::FacetCell]>),
292 Keys {
293 values: RawKeyValues,
294 dtype: BindingColumnType,
295 integer_negative_zero: std::sync::Arc<[usize]>,
296 display_labels: Option<std::sync::Arc<std::collections::HashMap<RawKey, String>>>,
297 },
298 Text {
299 values: CategoryValues,
300 numeric: bool,
301 dtype: Option<TextType>,
302 },
303}
304
305macro_rules! direct_inputs {
306 ($($native:ty => $method:ident,$variant:ident),+ $(,)?) => {$(
307 impl BindingObject<'_> {
308 #[doc(hidden)]
309 pub fn $method(values: $native) -> Self {
310 Self(Rc::new(Object::Column(Column::$variant(values))))
311 }
312 }
313
314 impl BindingInput for &$native {
315 fn binding_object(&self) -> Result<BindingObject<'_>> {
316 Ok(BindingObject::$method((*self).clone()))
317 }
318 }
319
320 impl BindingInput for $native {
321 fn binding_object(&self) -> Result<BindingObject<'_>> {
322 Ok(BindingObject::$method(self.clone()))
323 }
324 }
325 )+};
326}
327direct_inputs!(
330 NumericValues => numeric, Numeric,
331 CategoryValues => category, Category,
332 BooleanValues => boolean, Boolean,
333 SourceRows => rows, Rows,
334);
335
336macro_rules! typed_columns {
337 ($($type:ty=>$method:ident,$variant:ident),+ $(,)?)=>{$(
338 impl BindingObject<'_>{
339 pub fn $method(values:impl Into<std::sync::Arc<[$type]>>)->Self{
341 Self(Rc::new(Object::Column(Column::$variant(values.into()))))
342 }
343 }
344 impl BindingInput for &[$type]{
345 fn binding_object(&self)->Result<BindingObject<'_>>{Ok(BindingObject::$method(*self))}
346 }
347 impl BindingInput for &Vec<$type>{
348 fn binding_object(&self)->Result<BindingObject<'_>>{Ok(BindingObject::$method(self.as_slice()))}
349 }
350 impl BindingInput for Vec<$type>{
351 fn binding_object(&self)->Result<BindingObject<'_>>{Ok(BindingObject::$method(self.as_slice()))}
352 }
353 impl BindingInput for &std::sync::Arc<[$type]>{
354 fn binding_object(&self)->Result<BindingObject<'_>>{Ok(BindingObject::$method((*self).clone()))}
355 }
356 impl<const N:usize> BindingInput for &[$type;N]{
357 fn binding_object(&self)->Result<BindingObject<'_>>{Ok(BindingObject::$method(self.as_slice()))}
358 }
359 )+};
360}
361typed_columns!(
362 crate::elements::SignificanceTarget=>significance_targets,SignificanceTargets,
363 crate::elements::SignificanceMark=>significance_marks,SignificanceMarks,
364 crate::layout::FacetCell=>facet_cells,FacetCells,
365);
366
367impl BindingObject<'_> {
368 pub fn keys(values: RawKeyValues, numeric: bool) -> Self {
371 Self::typed_keys(
372 values,
373 if numeric {
374 BindingColumnType::Numeric
375 } else {
376 BindingColumnType::Keys
377 },
378 )
379 }
380
381 pub fn typed_keys(values: RawKeyValues, dtype: BindingColumnType) -> Self {
383 Self::keys_with_integer_zero(values, dtype, Vec::new())
384 }
385
386 pub(super) fn keys_with_integer_zero(
387 values: RawKeyValues,
388 dtype: BindingColumnType,
389 negative_zero: Vec<usize>,
390 ) -> Self {
391 Self(Rc::new(Object::Column(Column::Keys {
392 values,
393 dtype,
394 integer_negative_zero: negative_zero.into(),
395 display_labels: None,
396 })))
397 }
398
399 pub fn display_keys(
401 values: RawKeyValues,
402 dtype: BindingColumnType,
403 labels: Vec<(RawKey, String)>,
404 ) -> Self {
405 Self(Rc::new(Object::Column(Column::Keys {
406 values,
407 dtype,
408 integer_negative_zero: Vec::new().into(),
409 display_labels: Some(std::sync::Arc::new(labels.into_iter().collect())),
410 })))
411 }
412
413 pub(super) fn text(values: CategoryValues, numeric: bool, dtype: Option<TextType>) -> Self {
414 Self(Rc::new(Object::Column(Column::Text {
415 values,
416 numeric,
417 dtype,
418 })))
419 }
420}
421
422impl BindingInput for &RawKeyValues {
423 fn binding_object(&self) -> Result<BindingObject<'_>> {
424 Ok(BindingObject::keys((*self).clone(), false))
425 }
426}
427
428impl BindingInput for RawKeyValues {
429 fn binding_object(&self) -> Result<BindingObject<'_>> {
430 Ok(BindingObject::keys(self.clone(), false))
431 }
432}
433
434impl BindingInput for &crate::data::IntegerValues {
435 fn binding_object(&self) -> Result<BindingObject<'_>> {
436 let values = RawKeyValues::nullable(
437 self.name(),
438 self.iter().map(|value| value.cloned().map(RawKey::Integer)),
439 )?;
440 Ok(BindingObject::typed_keys(
441 values,
442 BindingColumnType::Numeric,
443 ))
444 }
445}
446
447fn status_object<'a>(values: &[crate::data::EstimateStatus]) -> Result<BindingObject<'a>> {
448 let values = CategoryValues::new(
449 "estimate_status",
450 values.iter().map(|status| match status {
451 crate::data::EstimateStatus::Estimated => "estimated",
452 crate::data::EstimateStatus::NotEstimable => "not_estimable",
453 }),
454 )?;
455 Ok(BindingObject::category(values))
456}
457impl BindingInput for &crate::data::EstimateStatusBinding {
458 fn binding_object(&self) -> Result<BindingObject<'_>> {
459 status_object(self.statuses())
460 }
461}
462impl BindingInput for &[crate::data::EstimateStatus] {
463 fn binding_object(&self) -> Result<BindingObject<'_>> {
464 status_object(self)
465 }
466}
467impl BindingInput for &Vec<crate::data::EstimateStatus> {
468 fn binding_object(&self) -> Result<BindingObject<'_>> {
469 status_object(self)
470 }
471}
472impl<const N: usize> BindingInput for &[crate::data::EstimateStatus; N] {
473 fn binding_object(&self) -> Result<BindingObject<'_>> {
474 status_object(self.as_slice())
475 }
476}
477
478macro_rules! content_inputs{
479 ($($ty:ty),+)=>{$(
480 impl BindingInput for &$ty{
481 fn binding_object(&self)->Result<BindingObject<'_>>{
482 Ok(BindingObject::content((*self).into()))
483 }
484 }
485 impl BindingInput for $ty{
486 fn binding_object(&self)->Result<BindingObject<'_>>{
487 Ok(BindingObject::content(self.into()))
488 }
489 }
490 )+};
491}
492content_inputs!(
493 crate::composition::ImageAsset,
494 crate::Output,
495 crate::Canvas,
496 crate::layout::TextPanel
497);
498
499impl<K: crate::kind::Marker> BindingInput for &crate::Plot<K> {
500 fn binding_object(&self) -> Result<BindingObject<'_>> {
501 Ok(BindingObject::content((*self).into()))
502 }
503}
504impl<K: crate::kind::Marker> BindingInput for crate::Plot<K> {
505 fn binding_object(&self) -> Result<BindingObject<'_>> {
506 Ok(BindingObject::content(self.into()))
507 }
508}
509impl BindingInput for &crate::composition::Composite {
510 fn binding_object(&self) -> Result<BindingObject<'_>> {
511 Ok(BindingObject::content(self.output().into()))
512 }
513}
514impl BindingInput for crate::composition::Composite {
515 fn binding_object(&self) -> Result<BindingObject<'_>> {
516 Ok(BindingObject::content(self.output().into()))
517 }
518}
519
520fn native_variables<'a>(values: &[NumericValues]) -> Result<BindingObject<'a>> {
521 let rows = values
522 .first()
523 .ok_or_else(|| invalid("at least one numeric variable is required"))?
524 .len();
525 let mut fields = Vec::new();
526 for value in values {
527 if value.len() != rows {
528 return Err(invalid(
529 "native variable collection must align on its row axis",
530 ));
531 }
532 let key = value
533 .field_key()
534 .cloned()
535 .unwrap_or_else(|| RawKey::from(value.name()));
536 fields.push(BindingField::new(
537 Some(key),
538 value.name(),
539 true,
540 BindingObject::numeric(value.clone()),
541 ));
542 }
543 Ok(BindingObject::table(rows, fields))
544}
545impl BindingInput for &[NumericValues] {
546 fn binding_object(&self) -> Result<BindingObject<'_>> {
547 native_variables(self)
548 }
549}
550impl BindingInput for &Vec<NumericValues> {
551 fn binding_object(&self) -> Result<BindingObject<'_>> {
552 native_variables(self)
553 }
554}
555impl BindingInput for Vec<NumericValues> {
556 fn binding_object(&self) -> Result<BindingObject<'_>> {
557 native_variables(self)
558 }
559}
560
561impl<'a> BindingObject<'a> {
562 pub fn deferred(load: impl Fn() -> Result<Self> + 'a) -> Self {
564 Self(Rc::new(Object::Deferred {
565 load: Box::new(load),
566 ready: OnceCell::new(),
567 }))
568 }
569
570 pub fn table(rows: usize, fields: Vec<BindingField<'a>>) -> Self {
572 Self(Rc::new(Object::Table { rows, fields }))
573 }
574
575 pub fn members(fields: Vec<(RawKey, BindingObject<'a>)>) -> Self {
577 Self(Rc::new(Object::Members(fields)))
578 }
579
580 pub fn sequence(rows: usize, vector: Self, rectangle: Self) -> Self {
583 Self(Rc::new(Object::Sequence {
584 rows,
585 vector,
586 rectangle,
587 }))
588 }
589
590 pub(super) fn adopt(&self, rectangle: bool) -> Result<Self> {
591 match self.object()? {
592 Object::Sequence {
593 vector,
594 rectangle: table,
595 ..
596 } => Ok(if rectangle {
597 table.clone()
598 } else {
599 vector.clone()
600 }),
601 _ => Ok(self.clone()),
602 }
603 }
604
605 fn object(&self) -> Result<&Object<'a>> {
606 if let Object::Deferred { load, ready } = self.0.as_ref() {
607 if ready.get().is_none() {
608 crate::operation::checkpoint()?;
609 let value = load()?;
610 let _ = ready.set(value);
611 }
612 return ready.get().expect("loaded binding").object();
613 }
614 Ok(self.0.as_ref())
615 }
616
617 #[doc(hidden)]
619 pub fn content(value: crate::composition::CompositionSource) -> Self {
620 Self(Rc::new(Object::Content(value)))
621 }
622
623 pub(super) fn content_value(&self) -> Result<crate::composition::CompositionSource> {
624 match self.object()? {
625 Object::Content(value) => Ok(value.clone()),
626 _ => Err(invalid("expected a native or fixed content snapshot")),
627 }
628 }
629
630 pub fn numeric_dtype(&self) -> Result<bool> {
632 self.column().map(Column::is_numeric)
633 }
634
635 pub(super) fn shape(&self) -> Result<Vec<usize>> {
636 match self.object()? {
637 Object::Column(column) => Ok(vec![column.len()]),
638 Object::Table { rows, fields } => Ok(vec![*rows, fields.len()]),
639 Object::Members(_) | Object::Content(_) => Ok(Vec::new()),
640 Object::Sequence { rows, .. } => Ok(vec![*rows]),
641 Object::Deferred { .. } => unreachable!("resolved input"),
642 }
643 }
644
645 pub(super) fn column(&self) -> Result<&Column> {
646 match self.object()? {
647 Object::Column(column) => Ok(column),
648 Object::Sequence { vector, .. } => vector.column(),
649 _ => Err(invalid(
650 "expected a rank-one value, not a table or named object",
651 )),
652 }
653 }
654
655 pub(super) fn table_fields(&self) -> Result<(usize, &[BindingField<'a>])> {
656 match self.object()? {
657 Object::Table { rows, fields } => Ok((*rows, fields)),
658 Object::Sequence { rectangle, .. } => rectangle.table_fields(),
659 _ => Err(invalid("expected an object with a logical column axis")),
660 }
661 }
662
663 pub(super) fn select(&self, selector: &BindingSelector) -> Result<Selection<'a>> {
664 if selector_pending(selector) {
665 return Err(invalid("original key is still required"));
666 }
667 if *selector == BindingSelector::Whole {
668 return Ok(Selection {
669 value: self.clone(),
670 source_shape: self.shape()?,
671 keys: None,
672 names: None,
673 positions: None,
674 });
675 }
676 match self.object()? {
677 Object::Table { rows, fields } => select_table(*rows, fields, selector),
678 Object::Members(members) => select_members(members, selector),
679 Object::Sequence { rectangle, .. } => rectangle.select(selector),
680 _ => Err(invalid(
681 "selection requires a logical column axis or named members",
682 )),
683 }
684 }
685
686 pub(super) fn map_keys(&self, mapping: &[(RawKey, BindingSelector)]) -> Result<Self> {
687 if mapping.is_empty() {
688 return Ok(self.clone());
689 }
690 match self.object()? {
691 Object::Table { rows, fields } => {
692 let mut mapped = fields.clone();
693 let mut positions = HashSet::new();
694 for (key, selector) in mapping {
695 let indices = table_indices(fields, selector)?;
696 let [index] = indices.as_slice() else {
697 return Err(invalid("key_map must select one actual field"));
698 };
699 if !positions.insert(*index) {
700 return Err(invalid("key_map references the same actual field twice"));
701 }
702 mapped[*index].key = Some(key.clone());
703 mapped[*index].name = key_name(key);
704 }
705 for (key, _) in mapping {
706 unique_key(mapped.iter().map(|field| field.key.as_ref()), key)?;
707 }
708 Ok(Self::table(*rows, mapped))
709 }
710 Object::Members(fields) => {
711 let mut mapped = fields.clone();
712 let mut positions = HashSet::new();
713 for (key, selector) in mapping {
714 let BindingSelector::Key(source) = selector else {
715 return Err(invalid("named object key_map requires one actual key"));
716 };
717 let index = unique_key(fields.iter().map(|(key, _)| Some(key)), source)?;
718 if !positions.insert(index) {
719 return Err(invalid("key_map references the same actual member twice"));
720 }
721 mapped[index].0 = key.clone();
722 }
723 for (key, _) in mapping {
724 unique_key(mapped.iter().map(|(key, _)| Some(key)), key)?;
725 }
726 Ok(Self::members(mapped))
727 }
728 _ => Err(invalid("key_map requires actual source fields")),
729 }
730 }
731}
732
733pub(super) struct Selection<'a> {
734 pub(super) value: BindingObject<'a>,
735 source_shape: Vec<usize>,
736 keys: Option<Vec<RawKey>>,
737 names: Option<Vec<String>>,
738 positions: Option<Vec<usize>>,
739}
740
741impl Selection<'_> {
742 pub(super) fn adopt(&mut self, rectangle: bool) -> Result<()> {
743 self.value = self.value.adopt(rectangle)?;
744 if self.positions.is_none() {
745 self.source_shape = self.value.shape()?;
746 }
747 Ok(())
748 }
749
750 pub(super) fn info(
751 &self,
752 source: &DataSourceRef,
753 name: &str,
754 selector: &BindingSelector,
755 ) -> Result<DataSourceInfo> {
756 let shape = self.value.shape()?;
757 let mut info = DataSourceInfo::selected_optional(
758 source.clone(),
759 selector.clone(),
760 self.keys.clone(),
761 self.positions.clone(),
762 self.source_shape.clone(),
763 shape,
764 )
765 .named(name.to_owned());
766 if let Some(names) = &self.names {
767 if self.keys.is_some() {
768 info = info.with_selected_names(names.clone())?;
769 }
770 }
771 Ok(info)
772 }
773
774 pub(super) fn field(&self) -> Option<(RawKey, String)> {
775 let keys = self.keys.as_ref()?;
776 let names = self.names.as_ref()?;
777 match (keys.as_slice(), names.as_slice()) {
778 ([key], [name]) => Some((key.clone(), name.clone())),
779 _ => None,
780 }
781 }
782
783 pub(super) fn name(&self) -> Option<&str> {
784 match self.names.as_deref() {
785 Some([name]) => Some(name),
786 _ => None,
787 }
788 }
789}
790
791fn matching_key(actual: &RawKey, query: &RawKey) -> bool {
792 if actual == query {
793 return true;
794 }
795 match (actual, query) {
796 (RawKey::Instant(actual), RawKey::Instant(query)) => {
797 actual.unix_ns() == query.unix_ns()
798 && actual.zone() == query.zone()
799 && query
800 .offset_seconds()
801 .is_none_or(|offset| actual.offset_seconds() == Some(offset))
802 && query.fold().is_none_or(|fold| actual.fold() == Some(fold))
803 }
804 (RawKey::Tuple(actual), RawKey::Tuple(query)) => {
805 actual.len() == query.len()
806 && actual
807 .iter()
808 .zip(query)
809 .all(|(actual, query)| matching_key(actual, query))
810 }
811 _ => false,
812 }
813}
814
815fn unique_key<'a>(fields: impl Iterator<Item = Option<&'a RawKey>>, key: &RawKey) -> Result<usize> {
816 let mut indices = fields.enumerate().filter_map(|(index, candidate)| {
817 candidate
818 .is_some_and(|candidate| matching_key(candidate, key))
819 .then_some(index)
820 });
821 let Some(index) = indices.next() else {
822 return Err(crate::Error::Data(crate::errors::Diagnostic::new(
823 crate::errors::DiagnosticKind::UnknownKey {
824 key: Some(key.clone()),
825 },
826 format!("no exact source key {key:?}"),
827 )));
828 };
829 if indices.next().is_some() {
830 return Err(invalid(format!("source key {key:?} is ambiguous")));
831 }
832 Ok(index)
833}
834
835fn position(value: isize, width: usize) -> Result<usize> {
836 let index = if value < 0 {
837 width.checked_sub(value.unsigned_abs())
838 } else {
839 usize::try_from(value).ok()
840 };
841 index
842 .filter(|&index| index < width)
843 .ok_or_else(|| invalid(format!("column index {value} is outside width {width}")))
844}
845
846fn slice_indices(slice: &crate::data::BindingSlice, width: usize) -> Result<Vec<usize>> {
847 let width =
848 isize::try_from(width).map_err(|_| invalid("column axis exceeds signed index range"))?;
849 let negative = slice.step().is_negative();
850 let endpoint = |value: Option<isize>, default| -> Result<isize> {
851 let Some(value) = value else {
852 return Ok(default);
853 };
854 let resolved = if value < 0 {
855 width.checked_add(value)
856 } else {
857 Some(value)
858 };
859 resolved
860 .filter(|&value| value >= 0 && value <= width && (!negative || value < width))
861 .ok_or_else(|| invalid("slice endpoint is outside the logical column axis"))
862 };
863 let start = endpoint(slice.start(), if negative { width - 1 } else { 0 })?;
864 let stop = endpoint(slice.stop(), if negative { -1 } else { width })?;
865 let stride = slice
866 .step()
867 .to_i128()
868 .and_then(|step| isize::try_from(step).ok());
869 let mut index = start;
870 let mut positions = Vec::new();
871 while if negative { index > stop } else { index < stop } {
872 crate::operation::check()?;
873 positions.push(usize::try_from(index).map_err(|_| invalid("invalid slice index"))?);
874 let Some(next) = stride.and_then(|step| index.checked_add(step)) else {
875 break;
876 };
877 index = next;
878 }
879 Ok(positions)
880}
881
882fn table_indices(fields: &[BindingField<'_>], selector: &BindingSelector) -> Result<Vec<usize>> {
883 let key = |key: &RawKey| unique_key(fields.iter().map(|field| field.key.as_ref()), key);
884 let indices = match selector {
885 BindingSelector::Key(value) => vec![key(value)?],
886 BindingSelector::Keys(values) => values.iter().map(key).collect::<Result<_>>()?,
887 BindingSelector::Index(index) => vec![position(*index, fields.len())?],
888 BindingSelector::Indices(indices) => indices
889 .iter()
890 .map(|&index| position(index, fields.len()))
891 .collect::<Result<_>>()?,
892 BindingSelector::Slice(slice) => slice_indices(slice, fields.len())?,
893 BindingSelector::Whole | BindingSelector::All => (0..fields.len()).collect(),
894 BindingSelector::NumericOnly => fields
895 .iter()
896 .enumerate()
897 .filter_map(|(index, field)| field.numeric.then_some(index))
898 .collect(),
899 };
900 check_indices(indices)
901}
902
903fn check_indices(indices: Vec<usize>) -> Result<Vec<usize>> {
904 let mut seen = HashSet::new();
905 if indices.is_empty() {
906 return Err(invalid("selection must not be empty"));
907 }
908 if indices.iter().any(|index| !seen.insert(*index)) {
909 return Err(invalid("duplicate selected source field"));
910 }
911 Ok(indices)
912}
913
914fn select_table<'a>(
915 rows: usize,
916 fields: &[BindingField<'a>],
917 selector: &BindingSelector,
918) -> Result<Selection<'a>> {
919 let indices = table_indices(fields, selector)?;
920 let selected: Vec<_> = indices.iter().map(|&index| fields[index].clone()).collect();
921 let keys = selected.iter().map(|field| field.key.clone()).collect();
922 let names = Some(selected.iter().map(|field| field.name.clone()).collect());
923 let value = if matches!(
924 selector,
925 BindingSelector::Key(_) | BindingSelector::Index(_)
926 ) {
927 let value = selected[0].value.clone();
928 if value.shape()? != [rows] {
929 return Err(invalid(
930 "selected field is not aligned with its table's row axis",
931 ));
932 }
933 value
934 } else {
935 BindingObject::table(rows, selected)
936 };
937 Ok(Selection {
938 value,
939 source_shape: vec![rows, fields.len()],
940 keys,
941 names,
942 positions: Some(indices),
943 })
944}
945
946fn select_members<'a>(
947 members: &[(RawKey, BindingObject<'a>)],
948 selector: &BindingSelector,
949) -> Result<Selection<'a>> {
950 let key = |key: &RawKey| unique_key(members.iter().map(|(key, _)| Some(key)), key);
951 let (indices, single) = match selector {
952 BindingSelector::Key(value) => (vec![key(value)?], true),
953 BindingSelector::Keys(values) => {
954 (values.iter().map(key).collect::<Result<Vec<_>>>()?, false)
955 }
956 _ => {
957 return Err(invalid(
958 "named members have no logical column positions or discovery rule",
959 ))
960 }
961 };
962 let indices = check_indices(indices)?;
963 let selected: Vec<_> = indices
964 .iter()
965 .map(|&index| members[index].clone())
966 .collect();
967 let keys = Some(selected.iter().map(|(key, _)| key.clone()).collect());
968 let names = Some(selected.iter().map(|(key, _)| key_name(key)).collect());
969 let value = if single {
970 selected[0].1.clone()
971 } else {
972 let mut rows = None;
973 let mut fields = Vec::new();
974 for (key, value) in selected {
975 let column = value.column()?;
976 if rows
977 .replace(column.len())
978 .is_some_and(|length| length != column.len())
979 {
980 return Err(invalid("selected member vectors have different lengths"));
981 }
982 fields.push(BindingField::new(
983 Some(key.clone()),
984 key_name(&key),
985 column.is_numeric(),
986 value,
987 ));
988 }
989 BindingObject::table(rows.unwrap_or(0), fields)
990 };
991 Ok(Selection {
992 source_shape: value.shape()?,
993 value,
994 keys,
995 names,
996 positions: None,
997 })
998}
999
1000pub(super) fn key_name(key: &RawKey) -> String {
1001 match key {
1002 RawKey::String(value) => value.clone(),
1003 RawKey::Integer(value) => integer(value).to_string(),
1004 RawKey::Float(value) => value.to_string(),
1005 RawKey::Boolean(value) => value.to_string(),
1006 RawKey::Tuple(values) => format!(
1007 "({})",
1008 values.iter().map(key_name).collect::<Vec<_>>().join(", ")
1009 ),
1010 RawKey::Date(value) => format!(
1011 "{:04}-{:02}-{:02}",
1012 value.year(),
1013 value.month(),
1014 value.day()
1015 ),
1016 RawKey::Duration(value) => format!("{} ns", value.nanoseconds()),
1017 RawKey::Instant(value) => format!("{} ns", value.unix_ns()),
1018 RawKey::LocalTimestamp(value) => format!(
1019 "{:04}-{:02}-{:02} {:02}:{:02}:{:02}.{:09}",
1020 value.date().year(),
1021 value.date().month(),
1022 value.date().day(),
1023 value.hour(),
1024 value.minute(),
1025 value.second(),
1026 value.nanos()
1027 ),
1028 RawKey::Interval(value) => format!(
1029 "{}{}, {}{}",
1030 if matches!(
1031 value.closed(),
1032 crate::data::IntervalClosed::Left | crate::data::IntervalClosed::Both
1033 ) {
1034 "["
1035 } else {
1036 "("
1037 },
1038 key_name(value.left()),
1039 key_name(value.right()),
1040 if matches!(
1041 value.closed(),
1042 crate::data::IntervalClosed::Right | crate::data::IntervalClosed::Both
1043 ) {
1044 "]"
1045 } else {
1046 ")"
1047 }
1048 ),
1049 RawKey::Unavailable(value) => value.reason().to_owned(),
1050 }
1051}
1052
1053#[derive(Default)]
1056pub(super) struct KeyProjection {
1057 tokens: std::collections::HashMap<(RawKey, String), String>,
1058 reserved: HashSet<String>,
1059 pub(super) labels: crate::formatting::Labels,
1060}
1061
1062impl KeyProjection {
1063 const PREFIX: &'static str = "__lichtung_recipe_key_";
1064
1065 pub(super) fn take_labels(&mut self) -> crate::formatting::Labels {
1066 self.tokens.clear();
1067 std::mem::take(&mut self.labels)
1068 }
1069
1070 pub(super) fn reserve(&mut self, value: &str) {
1071 if value.starts_with(Self::PREFIX) {
1072 self.reserved.insert(value.to_owned());
1073 }
1074 }
1075
1076 pub(super) fn reserve_column(&mut self, column: &Column) {
1077 self.reserve(column.name());
1078 match column {
1079 Column::Category(values) | Column::Text { values, .. } => {
1080 for level in values.levels() {
1081 self.reserve(level);
1082 }
1083 }
1084 Column::Keys { values, .. } => {
1085 for key in values.levels() {
1086 if let RawKey::String(value) = key {
1087 self.reserve(value);
1088 }
1089 }
1090 }
1091 _ => {}
1092 }
1093 }
1094
1095 fn fresh_token(&self) -> Result<String> {
1096 use std::sync::atomic::{AtomicU64, Ordering};
1097 static NEXT_TOKEN: AtomicU64 = AtomicU64::new(0);
1098 loop {
1099 let index = NEXT_TOKEN
1100 .fetch_update(Ordering::Relaxed, Ordering::Relaxed, |value| {
1101 value.checked_add(1)
1102 })
1103 .map_err(|_| invalid("renderer key identity space exhausted"))?;
1104 let token = format!("{}{index}", Self::PREFIX);
1105 if !self.reserved.contains(&token) {
1106 return Ok(token);
1107 }
1108 }
1109 }
1110
1111 pub(super) fn position_token(
1112 &mut self,
1113 axis: usize,
1114 index: usize,
1115 display: &str,
1116 ) -> Result<String> {
1117 let token = self.fresh_token()?;
1118 self.labels =
1119 std::mem::take(&mut self.labels).capture_grid_label(&token, axis, index, display);
1120 Ok(token)
1121 }
1122
1123 pub(super) fn display(&self, token: &str) -> String {
1124 self.labels
1125 .captured_display(token)
1126 .unwrap_or(token)
1127 .to_owned()
1128 }
1129
1130 pub(super) fn token(&mut self, key: &RawKey, display: &str) -> Result<String> {
1131 let identity = (key.clone(), display.to_owned());
1132 if let Some(token) = self.tokens.get(&identity) {
1133 return Ok(token.clone());
1134 }
1135 let token = self.fresh_token()?;
1136 self.tokens.insert(identity, token.clone());
1137 self.labels = std::mem::take(&mut self.labels).capture_alias(
1138 token.clone(),
1139 Some(key.clone()),
1140 display,
1141 );
1142 Ok(token)
1143 }
1144
1145 pub(super) fn categories(
1146 &mut self,
1147 values: &RawKeyValues,
1148 name: &str,
1149 ) -> Result<CategoryValues> {
1150 self.categories_with_labels(values, name, None)
1151 }
1152
1153 fn categories_with_labels(
1154 &mut self,
1155 values: &RawKeyValues,
1156 name: &str,
1157 labels: Option<&std::collections::HashMap<RawKey, String>>,
1158 ) -> Result<CategoryValues> {
1159 let mut levels = std::collections::HashMap::new();
1160 for key in values.levels() {
1161 crate::operation::check()?;
1162 let display = labels
1163 .and_then(|labels| labels.get(key))
1164 .cloned()
1165 .unwrap_or_else(|| key_name(key));
1166 let token = if matches!(key,RawKey::String(raw) if raw==&display) {
1167 display
1168 } else {
1169 self.token(key, &display)?
1170 };
1171 levels.insert(key, token);
1172 }
1173 let projected = crate::data::source::collect_source(
1174 values
1175 .iter()
1176 .map(|key| Ok(key.map(|key| levels[key].clone()))),
1177 )?;
1178 CategoryValues::nullable(name, projected)?
1179 .with_key_values(crate::data::KeyValues::Raw(values.clone().with_name(name)))
1180 }
1181}
1182
1183impl Column {
1184 pub(super) fn len(&self) -> usize {
1185 match self {
1186 Self::Numeric(values) => values.len(),
1187 Self::Category(values) | Self::Text { values, .. } => values.len(),
1188 Self::Boolean(values) => values.len(),
1189 Self::Rows(values) => values.len(),
1190 Self::SignificanceTargets(values) => values.len(),
1191 Self::SignificanceMarks(values) => values.len(),
1192 Self::FacetCells(values) => values.len(),
1193 Self::Keys { values, .. } => values.len(),
1194 }
1195 }
1196
1197 pub(super) fn name(&self) -> &str {
1198 match self {
1199 Self::Numeric(values) => values.name(),
1200 Self::Category(values) | Self::Text { values, .. } => values.original_name(),
1201 Self::Boolean(values) => values.name(),
1202 Self::Rows(_) => "row_id",
1203 Self::SignificanceTargets(_) => "targets",
1204 Self::SignificanceMarks(_) => "marks",
1205 Self::FacetCells(_) => "facets",
1206 Self::Keys { values, .. } => values.name(),
1207 }
1208 }
1209
1210 pub(super) fn is_numeric(&self) -> bool {
1211 match self {
1212 Self::Numeric(_) | Self::Rows(_) => true,
1213 Self::Keys { dtype, .. } => *dtype == BindingColumnType::Numeric,
1214 Self::Text { numeric, .. } => *numeric,
1215 _ => false,
1216 }
1217 }
1218
1219 pub(super) fn numeric_values(&self, name: &str) -> Result<NumericValues> {
1220 use crate::data::source::collect_source;
1221 let values = match self {
1222 Self::Numeric(values) => return Ok(values.clone().with_value_name(name)),
1223 Self::Rows(values) => collect_source(values.iter().map(|value| {
1224 crate::numeric::binary::signed_ratio(value.into(), 1_u8.into()).map(Some)
1225 }))?,
1226 Self::Keys {
1227 values,
1228 dtype:
1229 BindingColumnType::Numeric | BindingColumnType::Keys | BindingColumnType::Null,
1230 integer_negative_zero,
1231 ..
1232 } => collect_source(values.iter().enumerate().map(|(row, key)| {
1233 if integer_negative_zero.binary_search(&row).is_ok() {
1234 return Ok(Some(-0.0));
1235 }
1236 key.map(number).transpose()
1237 }))?,
1238 Self::Text { values, dtype, .. } => collect_source(values.iter().map(|value| {
1239 value
1240 .filter(|text| !text.trim().is_empty())
1241 .map(|text| {
1242 let token = text.trim();
1243 let parsed = if matches!(dtype, Some(TextType::F32)) {
1244 token.parse::<f32>().map(f64::from)
1245 } else {
1246 token.parse::<f64>()
1247 };
1248 parsed.map_err(|_| invalid(format!("invalid numeric token {text:?}")))
1249 })
1250 .transpose()
1251 }))?,
1252 _ => return Err(invalid("numeric role requires actual numeric values")),
1253 };
1254 Ok(NumericValues::nullable(name, values))
1255 }
1256
1257 pub(super) fn category_values(
1258 &self,
1259 name: &str,
1260 projection: &mut KeyProjection,
1261 ) -> Result<CategoryValues> {
1262 match self {
1263 Self::Category(values) => match values.key_values() {
1264 crate::data::KeyValues::Strings(values) => Ok(values.with_field_name(name)),
1265 crate::data::KeyValues::Raw(values) => projection.categories(&values, name),
1266 },
1267 Self::Text { values, .. } => Ok(values.clone().with_field_name(name)),
1268 Self::Keys {
1269 values,
1270 dtype:
1271 BindingColumnType::Category | BindingColumnType::Keys | BindingColumnType::Null,
1272 display_labels,
1273 ..
1274 } => {
1275 if values
1276 .levels()
1277 .iter()
1278 .all(|key| matches!(key, RawKey::String(_)))
1279 {
1280 return CategoryValues::nullable(
1281 name,
1282 values.iter().map(|key| {
1283 key.map(|key| match key {
1284 RawKey::String(value) => value.as_str(),
1285 _ => unreachable!("string key column"),
1286 })
1287 }),
1288 );
1289 }
1290 projection.categories_with_labels(values, name, display_labels.as_deref())
1291 }
1292 _ => Err(invalid("categorical role requires actual category keys")),
1293 }
1294 }
1295
1296 pub(super) fn key_category(
1297 &self,
1298 name: &str,
1299 projection: &mut KeyProjection,
1300 ) -> Result<CategoryValues> {
1301 use crate::data::source::collect_source;
1302 let keys = match self {
1303 Self::Text {
1304 values,
1305 dtype: Some(dtype),
1306 ..
1307 } if !matches!(dtype, TextType::String) => {
1308 let keys = crate::data::source::collect_source(values.iter().map(|value| {
1309 value
1310 .map(|value| dtype.key(value))
1311 .transpose()
1312 .map(Option::flatten)
1313 }))?;
1314 RawKeyValues::nullable(name, keys)?
1317 }
1318 Self::Category(_) | Self::Text { .. } => return self.category_values(name, projection),
1319 Self::Keys { values, .. } => values.clone(),
1320 Self::Numeric(values) => {
1321 RawKeyValues::nullable(name, values.iter().map(|value| value.map(RawKey::Float)))?
1322 }
1323 Self::Boolean(values) => {
1324 RawKeyValues::nullable(name, values.iter().map(|value| value.map(RawKey::Boolean)))?
1325 }
1326 Self::Rows(values) => RawKeyValues::new(
1327 name,
1328 values.iter().map(|value| RawKey::Integer(value.into())),
1329 )?,
1330 _ => {
1331 return Err(invalid(
1332 "explicit typed result members require their own role",
1333 ))
1334 }
1335 };
1336 if keys
1337 .levels()
1338 .iter()
1339 .all(|key| matches!(key, RawKey::String(_)))
1340 {
1341 let values = collect_source(keys.iter().map(|key| {
1342 Ok(key.map(|key| match key {
1343 RawKey::String(value) => value.clone(),
1344 _ => unreachable!("actual string key column"),
1345 }))
1346 }))?;
1347 CategoryValues::nullable(name, values)
1348 } else {
1349 projection.categories(&keys, name)
1350 }
1351 }
1352
1353 pub(super) fn significance_targets(
1354 &self,
1355 projection: &mut KeyProjection,
1356 ) -> Result<std::sync::Arc<[crate::elements::SignificanceTarget]>> {
1357 if let Self::SignificanceTargets(values) = self {
1358 return Ok(values.clone());
1359 }
1360 let keys = self.key_category("targets", projection)?.key_values();
1361 Ok(
1362 crate::data::source::collect_source((0..keys.len()).map(|slot| {
1363 keys.key_at(slot)
1364 .map(crate::elements::SignificanceTarget::category)
1365 .ok_or_else(|| invalid("missing significance target"))
1366 }))?
1367 .into(),
1368 )
1369 }
1370
1371 pub(super) fn facet_cells(
1372 &self,
1373 projection: &mut KeyProjection,
1374 ) -> Result<std::sync::Arc<[crate::layout::FacetCell]>> {
1375 if let Self::FacetCells(values) = self {
1376 return Ok(values.clone());
1377 }
1378 let keys = self.key_category("facets", projection)?.key_values();
1379 Ok(
1380 crate::data::source::collect_source((0..keys.len()).map(|slot| {
1381 keys.key_at(slot)
1382 .map(crate::layout::FacetCell::single)
1383 .ok_or_else(|| invalid("missing result facet"))
1384 }))?
1385 .into(),
1386 )
1387 }
1388
1389 pub(super) fn significance_marks(
1390 &self,
1391 ) -> Result<std::sync::Arc<[crate::elements::SignificanceMark]>> {
1392 use crate::elements::SignificanceMark;
1393 if let Self::SignificanceMarks(values) = self {
1394 return Ok(values.clone());
1395 }
1396 let text_mark = |value: &str| match value {
1397 "ns" => Ok(SignificanceMark::NotSignificant),
1398 "*" => Ok(SignificanceMark::OneStar),
1399 "**" => Ok(SignificanceMark::TwoStars),
1400 "***" => Ok(SignificanceMark::ThreeStars),
1401 "****" => Ok(SignificanceMark::FourStars),
1402 _ => Err(invalid(format!("unknown significance mark {value:?}"))),
1403 };
1404 let marks = match self {
1405 Self::Category(values) => {
1406 crate::data::source::collect_source(values.iter().map(|value| {
1407 value
1408 .ok_or_else(|| invalid("missing significance mark"))
1409 .and_then(text_mark)
1410 }))?
1411 }
1412 Self::Text { values, dtype, .. } => {
1413 crate::data::source::collect_source(values.iter().map(|value| {
1414 let value = value.ok_or_else(|| invalid("missing significance mark"))?;
1415 let parsed = match dtype {
1416 Some(TextType::String | TextType::Boolean) => return text_mark(value),
1417 Some(TextType::F32) => value.trim().parse::<f32>().map(f64::from),
1418 _ => value.trim().parse::<f64>(),
1419 };
1420 parsed
1421 .map(SignificanceMark::PValue)
1422 .or_else(|_| text_mark(value))
1423 }))?
1424 }
1425 Self::Keys {
1426 values,
1427 integer_negative_zero,
1428 ..
1429 } => crate::data::source::collect_source(values.iter().enumerate().map(
1430 |(index, value)| match value {
1431 Some(_) if integer_negative_zero.binary_search(&index).is_ok() => {
1432 Ok(SignificanceMark::PValue(-0.0))
1433 }
1434 Some(RawKey::String(value)) => text_mark(value),
1435 Some(key) => number(key).map(SignificanceMark::PValue),
1436 None => Err(invalid("missing significance mark")),
1437 },
1438 ))?,
1439 Self::Numeric(values) => {
1440 crate::data::source::collect_source(values.iter().map(|value| {
1441 value
1442 .map(SignificanceMark::PValue)
1443 .ok_or_else(|| invalid("missing significance mark"))
1444 }))?
1445 }
1446 _ => return Err(invalid("expected explicit significance marks")),
1447 };
1448 Ok(marks.into())
1449 }
1450
1451 pub(super) fn boolean_values(&self, name: &str) -> Result<BooleanValues> {
1452 use crate::data::source::collect_source;
1453 let values = match self {
1454 Self::Boolean(values) => return Ok(values.clone().with_value_name(name)),
1455 Self::Keys {
1456 values,
1457 dtype:
1458 BindingColumnType::Boolean | BindingColumnType::Keys | BindingColumnType::Null,
1459 ..
1460 } => collect_source(values.iter().map(|key| match key {
1461 None => Ok(None),
1462 Some(RawKey::Boolean(value)) => Ok(Some(*value)),
1463 _ => Err(invalid("Boolean role requires Boolean values")),
1464 }))?,
1465 Self::Text { values, .. } => {
1466 collect_source(values.iter().map(|value| match value.map(str::trim) {
1467 None | Some("") => Ok(None),
1468 Some("true" | "True" | "TRUE") => Ok(Some(true)),
1469 Some("false" | "False" | "FALSE") => Ok(Some(false)),
1470 Some(value) => Err(invalid(format!("invalid Boolean token {value:?}"))),
1471 }))?
1472 }
1473 _ => return Err(invalid("Boolean role requires actual Boolean values")),
1474 };
1475 Ok(BooleanValues::nullable(name, values))
1476 }
1477
1478 pub(super) fn source_rows(&self) -> Result<SourceRows> {
1479 if let Self::Rows(values) = self {
1480 return Ok(values.clone());
1481 }
1482 SourceRows::new(self.exact_indices("row identities")?)
1483 }
1484
1485 pub(super) fn exact_indices(&self, role: &str) -> Result<Vec<usize>> {
1486 match self {
1487 Self::Rows(values) => Ok(values.iter().collect()),
1488 Self::Keys { values, .. } => values
1489 .iter()
1490 .map(|key| match key {
1491 Some(RawKey::Integer(value)) => value
1492 .to_usize()
1493 .ok_or_else(|| invalid(format!("{role} exceed the native index range"))),
1494 _ => Err(invalid(format!("{role} require present exact integers"))),
1495 })
1496 .collect(),
1497 Self::Text { values, .. } => values
1498 .iter()
1499 .map(|text| {
1500 text.and_then(|text| text.trim().parse().ok())
1501 .ok_or_else(|| invalid(format!("invalid exact integer token for {role}")))
1502 })
1503 .collect(),
1504 _ => Err(invalid(format!("{role} require an exact integer source"))),
1505 }
1506 }
1507}
1508
1509fn number(key: &RawKey) -> Result<f64> {
1510 match key {
1511 RawKey::Integer(value) => crate::numeric::binary::signed_ratio(integer(value), 1_u8.into()),
1512 RawKey::Float(value) => Ok(*value),
1513 _ => Err(invalid(
1514 "numeric role requires a numeric dtype or numeric token",
1515 )),
1516 }
1517}