use std::collections::{HashMap, HashSet};
use std::sync::Arc;
use crate::data::source::{collect_source, copy_source_string, reserve_source};
use crate::data::{binding::VectorSource, DataSourceInfo, RawKey};
use crate::Error;
#[derive(Debug, Clone)]
pub struct SourceRows {
rows: Arc<[usize]>,
source: VectorSource,
}
impl SourceRows {
pub fn new(rows: impl IntoIterator<Item = usize>) -> Result<Self, Error> {
let rows = collect_source(rows.into_iter().map(Ok))?;
let mut seen = HashSet::new();
crate::operation::check()?;
seen.try_reserve(rows.len())
.map_err(|error| Error::Data(format!("source-row identity storage: {error}").into()))?;
for &row in &rows {
crate::operation::check()?;
if !seen.insert(row) {
return Err(Error::Data(
format!("source-row identities must be unique; found duplicate {row}").into(),
));
}
}
crate::operation::check()?;
Ok(Self {
source: VectorSource::direct(rows.len()),
rows: rows.into(),
})
}
#[doc(hidden)]
pub fn with_source(mut self, source: DataSourceInfo) -> crate::Result<Self> {
self.source = VectorSource::repeated(source, 1, self.len())?;
Ok(self)
}
#[doc(hidden)]
pub fn get_source(&self) -> &DataSourceInfo {
self.source.info()
}
pub(crate) fn vector_source(&self) -> &VectorSource {
&self.source
}
#[must_use]
pub fn len(&self) -> usize {
self.rows.len()
}
#[must_use]
pub fn is_empty(&self) -> bool {
self.rows.is_empty()
}
#[must_use]
pub fn as_slice(&self) -> &[usize] {
&self.rows
}
#[must_use]
pub fn get(&self, index: usize) -> Option<usize> {
self.rows.get(index).copied()
}
pub fn iter(&self) -> impl ExactSizeIterator<Item = usize> + '_ {
self.rows.iter().copied()
}
}
impl PartialEq for SourceRows {
fn eq(&self, other: &Self) -> bool {
self.rows == other.rows
}
}
impl Eq for SourceRows {}
#[derive(Debug, Clone, PartialEq, Eq)]
enum Validity {
All,
Bitmap(Arc<[u64]>),
}
impl Validity {
fn from_flags(flags: &[bool]) -> Self {
if flags.iter().all(|valid| *valid) {
return Self::All;
}
Self::bitmap(flags, vec![0_u64; flags.len().div_ceil(64)])
}
fn try_from_flags(flags: &[bool]) -> crate::Result<Self> {
crate::operation::check()?;
if flags.iter().filter(|&&valid| valid).count() == flags.len() {
return Ok(Self::All);
}
let count = flags.len().div_ceil(64);
let mut words = Vec::new();
reserve_source(&mut words, count)?;
words.resize(count, 0);
crate::operation::check()?;
Ok(Self::bitmap(flags, words))
}
fn bitmap(flags: &[bool], mut words: Vec<u64>) -> Self {
for (index, valid) in flags.iter().copied().enumerate() {
if valid {
words[index / 64] |= 1_u64 << (index % 64);
}
}
Self::Bitmap(words.into())
}
fn is_valid(&self, index: usize) -> bool {
match self {
Self::All => true,
Self::Bitmap(words) => words
.get(index / 64)
.is_some_and(|word| word & (1_u64 << (index % 64)) != 0),
}
}
}
#[derive(Debug, Clone)]
pub struct NumericValues {
name: Arc<str>,
values: Arc<[f64]>,
validity: Validity,
field_key: Option<Arc<(RawKey, Arc<str>)>>,
source: VectorSource,
}
impl NumericValues {
pub(crate) fn with_value_name(mut self, name: &str) -> Self {
self.name = Arc::from(name);
self.field_key = None;
self
}
#[must_use]
pub fn new(name: impl Into<String>, values: impl IntoIterator<Item = f64>) -> Self {
let values = values.into_iter().collect::<Vec<_>>();
Self {
name: Arc::from(name.into()),
source: VectorSource::direct(values.len()),
values: values.into(),
validity: Validity::All,
field_key: None,
}
}
#[must_use]
pub fn nullable(
name: impl Into<String>,
values: impl IntoIterator<Item = Option<f64>>,
) -> Self {
let values = values.into_iter().collect::<Vec<_>>();
let validity =
Validity::from_flags(&values.iter().map(Option::is_some).collect::<Vec<_>>());
let values = values
.into_iter()
.map(|value| value.unwrap_or(0.0))
.collect::<Vec<_>>();
Self {
name: Arc::from(name.into()),
source: VectorSource::direct_nullable(
values.len(),
!matches!(&validity, Validity::All),
),
values: values.into(),
validity,
field_key: None,
}
}
#[must_use]
pub fn name(&self) -> &str {
self.field_key
.as_deref()
.map_or(&self.name, |(_, name)| name)
}
#[doc(hidden)]
pub fn raw_name(&self) -> &str {
&self.name
}
pub(crate) fn raw_field(&self) -> crate::data::category::RawField {
let key = self
.field_key()
.cloned()
.unwrap_or_else(|| RawKey::from(self.raw_name()));
crate::data::category::RawField::from_key(Arc::clone(&self.name), key)
}
#[doc(hidden)]
#[must_use]
pub fn with_field_key(mut self, key: RawKey, name: impl Into<String>) -> Self {
self.field_key = Some(Arc::new((key, Arc::from(name.into()))));
self
}
#[doc(hidden)]
pub fn field_key(&self) -> Option<&RawKey> {
self.field_key.as_deref().map(|(key, _)| key)
}
#[doc(hidden)]
pub fn with_source(self, source: DataSourceInfo) -> crate::Result<Self> {
self.with_repeated_source(source, 1)
}
#[doc(hidden)]
pub fn with_repeated_source(
mut self,
source: DataSourceInfo,
copies: usize,
) -> crate::Result<Self> {
self.source = VectorSource::repeated(source, copies, self.len())?.with_original_validity(
self.len(),
self.has_nulls(),
|slot| self.validity.is_valid(slot),
)?;
Ok(self)
}
#[doc(hidden)]
pub fn with_source_slots(
mut self,
source: DataSourceInfo,
slots: Vec<usize>,
) -> crate::Result<Self> {
self.source = VectorSource::gathered(source, slots, self.len())?.with_original_validity(
self.len(),
self.has_nulls(),
|slot| self.validity.is_valid(slot),
)?;
Ok(self)
}
#[doc(hidden)]
pub fn get_source(&self) -> &DataSourceInfo {
self.source.info()
}
pub(crate) fn with_row_scope(mut self) -> Self {
self.source.mark_rows();
self
}
pub(crate) fn vector_source(&self) -> &VectorSource {
&self.source
}
pub(crate) fn has_nulls(&self) -> bool {
!matches!(self.validity, Validity::All)
}
#[doc(hidden)]
pub fn source_slot(&self, index: usize) -> Option<usize> {
(index < self.len()).then(|| self.source.slot(index))
}
pub(crate) fn select(&self, indices: &[usize]) -> crate::Result<Self> {
let values = collect_source(indices.iter().map(|&index| {
self.values.get(index).copied().ok_or_else(|| {
Error::Data(format!("numeric selection index {index} is out of bounds").into())
})
}))?;
let validity = if matches!(self.validity, Validity::All) {
Validity::All
} else {
let flags = collect_source(
indices
.iter()
.map(|&index| Ok(self.validity.is_valid(index))),
)?;
Validity::try_from_flags(&flags)?
};
crate::operation::check()?;
Ok(Self {
name: self.name.clone(),
values: values.into(),
validity,
field_key: self.field_key.clone(),
source: self.source.select(indices)?,
})
}
#[must_use]
pub fn len(&self) -> usize {
self.values.len()
}
#[must_use]
pub fn is_empty(&self) -> bool {
self.values.is_empty()
}
#[must_use]
pub fn get(&self, row: usize) -> Option<Option<f64>> {
self.values
.get(row)
.map(|value| self.validity.is_valid(row).then_some(*value))
}
pub fn iter(&self) -> impl ExactSizeIterator<Item = Option<f64>> + '_ {
(0..self.len()).map(|row| self.get(row).expect("in-bounds source slot"))
}
#[must_use]
pub fn is_valid(&self, row: usize) -> Option<bool> {
(row < self.len()).then(|| self.validity.is_valid(row))
}
}
impl PartialEq for NumericValues {
fn eq(&self, other: &Self) -> bool {
self.name == other.name
&& self.field_key == other.field_key
&& self.len() == other.len()
&& self
.iter()
.map(|value| value.map(f64::to_bits))
.eq(other.iter().map(|value| value.map(f64::to_bits)))
}
}
impl Eq for NumericValues {}
#[derive(Debug, Clone)]
pub struct CategoryValues {
name: Arc<str>,
levels: Arc<[String]>,
codes: Arc<[u32]>,
validity: Validity,
original_keys: Option<Arc<crate::data::KeyValues>>,
field_key: Option<Arc<(RawKey, Arc<str>)>>,
source: VectorSource,
}
impl CategoryValues {
pub fn new<S>(
name: impl Into<String>,
values: impl IntoIterator<Item = S>,
) -> Result<Self, Error>
where
S: Into<String>,
{
Self::from_optional(
name.into(),
values.into_iter().map(|value| Ok(Some(value.into()))),
)
}
pub fn nullable<S>(
name: impl Into<String>,
values: impl IntoIterator<Item = Option<S>>,
) -> Result<Self, Error>
where
S: Into<String>,
{
Self::from_optional(
name.into(),
values.into_iter().map(|value| Ok(value.map(Into::into))),
)
}
fn from_optional(
name: String,
values: impl IntoIterator<Item = Result<Option<String>, Error>>,
) -> Result<Self, Error> {
let values = collect_source(values.into_iter())?;
let mut levels = Vec::new();
let mut indices = HashMap::new();
let mut codes = Vec::new();
let mut valid = Vec::new();
reserve_source(&mut codes, values.len())?;
reserve_source(&mut valid, values.len())?;
for value in values {
crate::operation::check()?;
let Some(value) = value else {
valid.push(false);
codes.push(0);
continue;
};
valid.push(true);
let code = if let Some(code) = indices.get(&value).copied() {
code
} else {
let code = u32::try_from(levels.len()).map_err(|_| {
Error::Data(
format!(
"categorical values {name:?} exceed the supported distinct-level count"
)
.into(),
)
})?;
reserve_source(&mut levels, 1)?;
crate::operation::check()?;
indices.try_reserve(1).map_err(|error| {
Error::Data(format!("category dictionary storage: {error}").into())
})?;
indices.insert(copy_source_string(&value)?, code);
levels.push(value);
code
};
codes.push(code);
}
let validity = Validity::try_from_flags(&valid)?;
crate::operation::check()?;
Ok(Self {
name: Arc::from(name),
levels: levels.into(),
source: VectorSource::direct_nullable(codes.len(), !matches!(validity, Validity::All)),
codes: codes.into(),
validity,
original_keys: None,
field_key: None,
})
}
#[must_use]
pub fn name(&self) -> &str {
&self.name
}
#[must_use]
pub fn len(&self) -> usize {
self.codes.len()
}
#[must_use]
pub fn is_empty(&self) -> bool {
self.codes.is_empty()
}
#[must_use]
pub fn get(&self, row: usize) -> Option<Option<&str>> {
self.codes.get(row).map(|code| {
if !self.validity.is_valid(row) {
return None;
}
usize::try_from(*code)
.ok()
.and_then(|index| self.levels.get(index))
.map(String::as_str)
})
}
pub fn iter(&self) -> impl ExactSizeIterator<Item = Option<&str>> + '_ {
(0..self.len()).map(|row| self.get(row).expect("in-bounds source slot"))
}
#[must_use]
pub fn is_valid(&self, row: usize) -> Option<bool> {
(row < self.len()).then(|| self.validity.is_valid(row))
}
#[must_use]
pub fn levels(&self) -> &[String] {
&self.levels
}
#[doc(hidden)]
pub fn with_key_values(mut self, keys: crate::data::KeyValues) -> Result<Self, Error> {
if self.len() != keys.len()
|| (0..self.len()).any(|index| self.is_valid(index) != keys.is_valid(index))
{
return Err(Error::Data(
"raw keys must align with their category projection".into(),
));
}
let key_count = match &keys {
crate::data::KeyValues::Strings(values) => values.levels().len(),
crate::data::KeyValues::Raw(values) => values.levels().len(),
};
let mut first_slots = Vec::new();
reserve_source(&mut first_slots, self.levels.len())?;
first_slots.resize(self.levels.len(), None);
let aligned = key_count == self.levels.len()
&& self.codes.iter().enumerate().all(|(row, &code)| {
if !self.validity.is_valid(row) {
return true;
}
let first = *first_slots[code as usize].get_or_insert(row);
match &keys {
crate::data::KeyValues::Strings(values) => values.get(first) == values.get(row),
crate::data::KeyValues::Raw(values) => values.get(first) == values.get(row),
}
});
if !aligned {
return Err(Error::Data(
"category projection must preserve the distinct original keys".into(),
));
}
let source = match &keys {
crate::data::KeyValues::Strings(values) => values.vector_source(),
crate::data::KeyValues::Raw(values) => values.vector_source(),
};
if self.source.info() == source.info() {
self.source.retain_original_validity(source);
}
self.original_keys = Some(Arc::new(keys));
Ok(self)
}
#[doc(hidden)]
#[must_use]
pub fn with_field_key(mut self, key: crate::data::RawKey, name: impl Into<String>) -> Self {
self.field_key = Some(Arc::new((key, Arc::from(name.into()))));
self
}
#[doc(hidden)]
pub fn original_name(&self) -> &str {
self.field_key
.as_deref()
.map_or(&self.name, |(_, name)| name)
}
#[doc(hidden)]
pub fn field_key(&self) -> Option<&RawKey> {
self.field_key.as_deref().map(|(key, _)| key)
}
#[doc(hidden)]
pub fn with_source(self, source: DataSourceInfo) -> crate::Result<Self> {
self.with_repeated_source(source, 1)
}
#[doc(hidden)]
pub fn with_repeated_source(
mut self,
source: DataSourceInfo,
copies: usize,
) -> crate::Result<Self> {
self.source = VectorSource::repeated(source, copies, self.len())?.with_original_validity(
self.len(),
self.has_nulls(),
|slot| self.validity.is_valid(slot),
)?;
Ok(self)
}
#[doc(hidden)]
pub fn with_source_slots(
mut self,
source: DataSourceInfo,
slots: Vec<usize>,
) -> crate::Result<Self> {
self.source = VectorSource::gathered(source, slots, self.len())?.with_original_validity(
self.len(),
self.has_nulls(),
|slot| self.validity.is_valid(slot),
)?;
Ok(self)
}
#[doc(hidden)]
pub fn with_cycled_source(mut self, source: DataSourceInfo) -> crate::Result<Self> {
self.source = VectorSource::cycled(source, self.len())?.with_original_validity(
self.len(),
self.has_nulls(),
|slot| self.validity.is_valid(slot),
)?;
Ok(self)
}
#[doc(hidden)]
pub fn get_source(&self) -> &DataSourceInfo {
self.source.info()
}
pub(crate) fn with_row_scope(mut self) -> Self {
self.source.mark_rows();
self
}
pub(crate) fn vector_source(&self) -> &VectorSource {
&self.source
}
pub(crate) fn has_nulls(&self) -> bool {
!matches!(self.validity, Validity::All)
}
#[doc(hidden)]
pub fn source_slot(&self, index: usize) -> Option<usize> {
(index < self.len()).then(|| self.source.slot(index))
}
pub(crate) fn select(&self, indices: &[usize]) -> crate::Result<Self> {
let mut values = Self::from_optional(
copy_source_string(self.name())?,
indices.iter().map(|&index| {
let value = self.get(index).ok_or_else(|| {
Error::Data(format!("category selection index {index} is out of bounds").into())
})?;
value.map(copy_source_string).transpose()
}),
)?;
values.field_key.clone_from(&self.field_key);
values.source = self.source.select(indices)?;
values.original_keys = self
.original_keys
.as_ref()
.map(|keys| keys.select(indices).map(Arc::new))
.transpose()?;
Ok(values)
}
pub(crate) fn original_field(&self) -> crate::data::RawKey {
self.field_key.as_deref().map_or_else(
|| crate::data::RawKey::from(self.name()),
|(key, _)| key.clone(),
)
}
#[doc(hidden)]
#[must_use]
pub fn with_field_name(mut self, name: &str) -> Self {
if self.name() != name {
self.name = Arc::from(name);
}
self.field_key = None;
self
}
#[must_use]
pub fn key_values(&self) -> crate::data::KeyValues {
if let Some(keys) = &self.original_keys {
return match keys.as_ref() {
crate::data::KeyValues::Strings(values) => {
let mut values = values.clone();
values.source = self.source.clone();
values.field_key.clone_from(&self.field_key);
crate::data::KeyValues::Strings(values)
}
crate::data::KeyValues::Raw(values) => crate::data::KeyValues::Raw(
values
.clone()
.with_name(self.original_name())
.with_vector_source(self.source.clone()),
),
};
}
let mut values = self.clone();
if let Some((_, name)) = values.field_key.as_deref() {
values.name = Arc::clone(name);
}
crate::data::KeyValues::Strings(values)
}
pub(crate) fn key_for_level(&self, level: &str) -> Option<RawKey> {
if self.original_keys.is_none() {
return self
.levels()
.iter()
.any(|value| value == level)
.then(|| RawKey::from(level));
}
self.key_at(self.iter().position(|value| value == Some(level))?)
}
pub(crate) fn key_at(&self, slot: usize) -> Option<RawKey> {
match self.original_keys.as_deref() {
None => self.get(slot)?.map(RawKey::from),
Some(crate::data::KeyValues::Strings(values)) => values.get(slot)?.map(RawKey::from),
Some(crate::data::KeyValues::Raw(values)) => values.get(slot)?.cloned(),
}
}
pub(crate) fn raw_field(&self) -> crate::data::category::RawField {
crate::data::category::RawField::from_key(Arc::clone(&self.name), self.original_field())
}
pub(crate) fn same_level_key(&self, level: &str, other: &Self, other_level: &str) -> bool {
if self.original_keys.is_none() && other.original_keys.is_none() {
level == other_level
} else {
self.key_for_level(level) == other.key_for_level(other_level)
}
}
pub(crate) fn raw_category(
&self,
level: &str,
) -> crate::Result<crate::data::category::RawCategory> {
use crate::data::category::{shared_text, RawCategory};
let key = self.key_for_level(level).ok_or_else(|| {
Error::Render(format!("guide level {level:?} has no original category").into())
})?;
if matches!(&key, RawKey::String(value) if value == level) {
RawCategory::new(level)
} else {
Ok(RawCategory::from_key(shared_text(level)?, key))
}
}
}
impl PartialEq for CategoryValues {
fn eq(&self, other: &Self) -> bool {
self.name == other.name
&& self.levels == other.levels
&& self.codes == other.codes
&& self.validity == other.validity
&& self.original_keys == other.original_keys
&& self.field_key == other.field_key
}
}
impl Eq for CategoryValues {}
#[derive(Debug, Clone)]
pub struct BooleanValues {
name: Arc<str>,
values: Arc<[bool]>,
validity: Validity,
field_key: Option<Arc<(RawKey, Arc<str>)>>,
source: VectorSource,
}
impl BooleanValues {
pub(crate) fn with_value_name(mut self, name: &str) -> Self {
self.name = Arc::from(name);
self.field_key = None;
self
}
#[must_use]
pub fn new(name: impl Into<String>, values: impl IntoIterator<Item = bool>) -> Self {
let values = values.into_iter().collect::<Vec<_>>();
Self {
name: Arc::from(name.into()),
field_key: None,
source: VectorSource::direct(values.len()),
values: values.into(),
validity: Validity::All,
}
}
#[must_use]
pub fn nullable(
name: impl Into<String>,
values: impl IntoIterator<Item = Option<bool>>,
) -> Self {
let values = values.into_iter().collect::<Vec<_>>();
let validity =
Validity::from_flags(&values.iter().map(Option::is_some).collect::<Vec<_>>());
let values = values
.into_iter()
.map(|value| value.unwrap_or(false))
.collect::<Vec<_>>();
Self {
name: Arc::from(name.into()),
field_key: None,
source: VectorSource::direct_nullable(
values.len(),
!matches!(&validity, Validity::All),
),
values: values.into(),
validity,
}
}
#[must_use]
pub fn name(&self) -> &str {
self.field_key
.as_deref()
.map_or(&self.name, |(_, name)| name)
}
#[doc(hidden)]
#[must_use]
pub fn with_field_key(mut self, key: RawKey, name: impl Into<String>) -> Self {
self.field_key = Some(Arc::new((key, Arc::from(name.into()))));
self
}
#[doc(hidden)]
pub fn field_key(&self) -> Option<&RawKey> {
self.field_key.as_deref().map(|(key, _)| key)
}
#[doc(hidden)]
pub fn with_source(self, source: DataSourceInfo) -> crate::Result<Self> {
self.with_repeated_source(source, 1)
}
#[doc(hidden)]
pub fn with_repeated_source(
mut self,
source: DataSourceInfo,
copies: usize,
) -> crate::Result<Self> {
self.source = VectorSource::repeated(source, copies, self.len())?.with_original_validity(
self.len(),
self.has_nulls(),
|slot| self.validity.is_valid(slot),
)?;
Ok(self)
}
#[doc(hidden)]
pub fn with_source_slots(
mut self,
source: DataSourceInfo,
slots: Vec<usize>,
) -> crate::Result<Self> {
self.source = VectorSource::gathered(source, slots, self.len())?.with_original_validity(
self.len(),
self.has_nulls(),
|slot| self.validity.is_valid(slot),
)?;
Ok(self)
}
#[doc(hidden)]
pub fn get_source(&self) -> &DataSourceInfo {
self.source.info()
}
pub(crate) fn with_row_scope(mut self) -> Self {
self.source.mark_rows();
self
}
pub(crate) fn vector_source(&self) -> &VectorSource {
&self.source
}
pub(crate) fn has_nulls(&self) -> bool {
!matches!(self.validity, Validity::All)
}
#[doc(hidden)]
pub fn source_slot(&self, index: usize) -> Option<usize> {
(index < self.len()).then(|| self.source.slot(index))
}
#[must_use]
pub fn len(&self) -> usize {
self.values.len()
}
#[must_use]
pub fn is_empty(&self) -> bool {
self.values.is_empty()
}
#[must_use]
pub fn get(&self, row: usize) -> Option<Option<bool>> {
self.values
.get(row)
.map(|value| self.validity.is_valid(row).then_some(*value))
}
pub fn iter(&self) -> impl ExactSizeIterator<Item = Option<bool>> + '_ {
(0..self.len()).map(|row| self.get(row).expect("in-bounds source slot"))
}
#[must_use]
pub fn is_valid(&self, row: usize) -> Option<bool> {
(row < self.len()).then(|| self.validity.is_valid(row))
}
}
impl PartialEq for BooleanValues {
fn eq(&self, other: &Self) -> bool {
self.name == other.name && self.values == other.values && self.validity == other.validity
}
}
impl Eq for BooleanValues {}