use std::{
hash::{Hash, Hasher},
sync::{
atomic::{AtomicU64, Ordering},
Arc,
},
};
use super::{
binding::VectorSource, DataSourceInfo, Date, Duration, ExactInteger, LocalTimestamp, Timestamp,
};
mod encoding;
use crate::{
errors::{Diagnostic, DiagnosticKind, ErrorContext, OperationPhase},
CategoryValues, Error, Result,
};
pub(crate) use encoding::key_bytes;
#[derive(Debug, Clone)]
#[non_exhaustive]
pub enum RawKey {
String(String),
Integer(ExactInteger),
Boolean(bool),
Float(f64),
Tuple(Vec<RawKey>),
Date(Date),
Instant(Timestamp),
Duration(Duration),
LocalTimestamp(LocalTimestamp),
Interval(IntervalKey),
Unavailable(UnavailableKey),
}
impl From<String> for RawKey {
fn from(value: String) -> Self {
Self::String(value)
}
}
impl From<&str> for RawKey {
fn from(value: &str) -> Self {
Self::String(value.to_owned())
}
}
impl From<&String> for RawKey {
fn from(value: &String) -> Self {
Self::String(value.clone())
}
}
impl PartialEq for RawKey {
fn eq(&self, other: &Self) -> bool {
match (self, other) {
(Self::String(a), Self::String(b)) => a == b,
(Self::Integer(a), Self::Integer(b)) => a == b,
(Self::Boolean(a), Self::Boolean(b)) => a == b,
(Self::Float(a), Self::Float(b)) => a.to_bits() == b.to_bits(),
(Self::Tuple(a), Self::Tuple(b)) => a == b,
(Self::Date(a), Self::Date(b)) => a == b,
(Self::Instant(a), Self::Instant(b)) => a == b,
(Self::Duration(a), Self::Duration(b)) => a == b,
(Self::LocalTimestamp(a), Self::LocalTimestamp(b)) => a == b,
(Self::Interval(a), Self::Interval(b)) => a == b,
(Self::Unavailable(a), Self::Unavailable(b)) => a == b,
_ => false,
}
}
}
impl Eq for RawKey {}
impl Hash for RawKey {
fn hash<H: Hasher>(&self, state: &mut H) {
std::mem::discriminant(self).hash(state);
match self {
Self::String(value) => value.hash(state),
Self::Integer(value) => value.hash(state),
Self::Boolean(value) => value.hash(state),
Self::Float(value) => value.to_bits().hash(state),
Self::Tuple(value) => value.hash(state),
Self::Date(value) => value.hash(state),
Self::Instant(value) => value.hash(state),
Self::Duration(value) => value.hash(state),
Self::LocalTimestamp(value) => value.hash(state),
Self::Interval(value) => value.hash(state),
Self::Unavailable(value) => value.hash(state),
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum IntervalClosed {
Left,
Right,
Both,
Neither,
}
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct IntervalKey {
left: Box<RawKey>,
right: Box<RawKey>,
closed: IntervalClosed,
}
impl IntervalKey {
pub fn new(left: RawKey, right: RawKey, closed: IntervalClosed) -> Result<Self> {
let ordered = match (&left, &right) {
(RawKey::Integer(a), RawKey::Integer(b)) => a <= b,
(RawKey::Float(a), RawKey::Float(b)) => a <= b,
(RawKey::Date(a), RawKey::Date(b)) => a <= b,
(RawKey::Duration(a), RawKey::Duration(b)) => a <= b,
(RawKey::LocalTimestamp(a), RawKey::LocalTimestamp(b)) => a <= b,
(RawKey::Instant(a), RawKey::Instant(b)) => a.unix_ns() <= b.unix_ns(),
_ => false,
};
if !ordered {
return Err(Error::Data(
"interval key requires compatible ordered endpoints".into(),
));
}
Ok(Self {
left: Box::new(left),
right: Box::new(right),
closed,
})
}
pub fn left(&self) -> &RawKey {
&self.left
}
pub fn right(&self) -> &RawKey {
&self.right
}
pub const fn closed(&self) -> IntervalClosed {
self.closed
}
}
static NEXT_UNAVAILABLE_KEY: AtomicU64 = AtomicU64::new(0);
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct UnavailableKey {
identity: u64,
reason: Arc<str>,
}
impl UnavailableKey {
#[doc(hidden)]
pub fn new(reason: impl Into<String>) -> Result<Self> {
let identity = NEXT_UNAVAILABLE_KEY
.fetch_update(Ordering::Relaxed, Ordering::Relaxed, |value| {
value.checked_add(1)
})
.map_err(|_| Error::Data("raw key identity space exhausted".into()))?;
Ok(Self {
identity,
reason: Arc::from(reason.into()),
})
}
pub(crate) fn identity(&self) -> u64 {
self.identity
}
pub fn reason(&self) -> &str {
&self.reason
}
}
#[derive(Debug, Clone)]
pub struct RawKeyValues {
name: Arc<str>,
codes: Arc<[Option<u32>]>,
levels: Arc<[RawKey]>,
source: VectorSource,
}
impl RawKeyValues {
pub fn new(name: impl Into<String>, values: impl IntoIterator<Item = RawKey>) -> Result<Self> {
Self::nullable(name, values.into_iter().map(Some))
}
pub fn nullable(
name: impl Into<String>,
values: impl IntoIterator<Item = Option<RawKey>>,
) -> Result<Self> {
let name = name.into();
let mut levels = Vec::new();
let mut indices = std::collections::HashMap::new();
let codes = super::source::collect_source(values.into_iter().map(|value| {
let Some(value) = value else { return Ok(None) };
if let Some(&index) = indices.get(&value) {
return Ok(Some(index));
}
let index = u32::try_from(levels.len()).map_err(|_| {
Error::Data(
format!("raw key column {name:?} exceeds the distinct-key limit").into(),
)
})?;
super::source::reserve_source(&mut levels, 1)?;
crate::operation::capacity::<(RawKey, u32)>(indices.capacity(), indices.len(), 1)?;
indices.try_reserve(1).map_err(|error| {
Error::Data(format!("raw key dictionary storage: {error}").into())
})?;
indices.insert(value.clone(), index);
levels.push(value);
Ok(Some(index))
}))?;
crate::operation::memory(
codes.len() as u128 * std::mem::size_of::<Option<u32>>() as u128
+ levels.len() as u128 * std::mem::size_of::<RawKey>() as u128
+ name.len() as u128,
)?;
Ok(Self {
name: Arc::from(name),
source: VectorSource::direct_nullable(codes.len(), codes.iter().any(Option::is_none)),
codes: codes.into(),
levels: levels.into(),
})
}
pub fn name(&self) -> &str {
&self.name
}
pub(crate) fn with_name(mut self, name: &str) -> Self {
self.name = Arc::from(name);
self
}
pub fn len(&self) -> usize {
self.codes.len()
}
pub fn is_empty(&self) -> bool {
self.codes.is_empty()
}
pub fn get(&self, index: usize) -> Option<Option<&RawKey>> {
self.codes
.get(index)
.map(|code| code.and_then(|code| self.levels.get(code as usize)))
}
pub fn iter(&self) -> impl ExactSizeIterator<Item = Option<&RawKey>> + '_ {
(0..self.len()).map(|index| self.get(index).expect("in-bounds raw key slot"))
}
pub fn is_valid(&self, index: usize) -> Option<bool> {
self.codes.get(index).map(Option::is_some)
}
#[doc(hidden)]
pub fn with_source(mut self, source: DataSourceInfo) -> Result<Self> {
self.source = VectorSource::repeated(source, 1, self.len())?.with_original_validity(
self.len(),
self.has_nulls(),
|slot| self.codes[slot].is_some(),
)?;
Ok(self)
}
pub(crate) fn with_vector_source(mut self, source: VectorSource) -> Self {
self.source = source;
self
}
#[doc(hidden)]
pub fn get_source(&self) -> &DataSourceInfo {
self.source.info()
}
pub(crate) fn vector_source(&self) -> &VectorSource {
&self.source
}
pub(crate) fn has_nulls(&self) -> bool {
self.codes.iter().any(Option::is_none)
}
#[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]) -> Result<Self> {
let mut selected = Self::nullable(
self.name(),
indices.iter().map(|&index| {
self.get(index)
.expect("validated raw key selection")
.cloned()
}),
)?;
selected.source = self.source.select(indices)?;
Ok(selected)
}
pub fn levels(&self) -> &[RawKey] {
&self.levels
}
}
impl PartialEq for RawKeyValues {
fn eq(&self, other: &Self) -> bool {
self.name == other.name && self.codes == other.codes && self.levels == other.levels
}
}
impl Eq for RawKeyValues {}
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum KeyValues {
Strings(CategoryValues),
Raw(RawKeyValues),
}
impl KeyValues {
pub(crate) fn key_at(&self, slot: usize) -> Option<RawKey> {
match self {
Self::Strings(values) => values.get(slot).flatten().map(RawKey::from),
Self::Raw(values) => values.get(slot).flatten().cloned(),
}
}
pub(crate) fn select(&self, indices: &[usize]) -> crate::Result<Self> {
Ok(match self {
Self::Strings(values) => Self::Strings(values.select(indices)?),
Self::Raw(values) => Self::Raw(values.select(indices)?),
})
}
#[doc(hidden)]
pub fn repeated_keys(name: &str, keys: &[RawKey], rows: usize) -> Result<Self> {
if keys.iter().all(|key| matches!(key, RawKey::String(_))) {
Ok(Self::Strings(CategoryValues::new(
name,
(0..rows).flat_map(|_| {
keys.iter().map(|key| match key {
RawKey::String(value) => value.as_str(),
_ => unreachable!("all keys are strings"),
})
}),
)?))
} else {
Ok(Self::Raw(RawKeyValues::new(
name,
(0..rows).flat_map(|_| keys.iter().cloned()),
)?))
}
}
pub const fn get_strings(&self) -> Option<&CategoryValues> {
if let Self::Strings(values) = self {
Some(values)
} else {
None
}
}
pub const fn get_raw(&self) -> Option<&RawKeyValues> {
if let Self::Raw(values) = self {
Some(values)
} else {
None
}
}
pub fn len(&self) -> usize {
match self {
Self::Strings(values) => values.len(),
Self::Raw(values) => values.len(),
}
}
pub fn is_empty(&self) -> bool {
self.len() == 0
}
pub fn is_valid(&self, index: usize) -> Option<bool> {
match self {
Self::Strings(values) => values.is_valid(index),
Self::Raw(values) => values.is_valid(index),
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct NamedKeyValues {
pub key: RawKey,
pub values: KeyValues,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct KeyColumns(Arc<[NamedKeyValues]>);
impl KeyColumns {
pub fn new(columns: Vec<NamedKeyValues>) -> Result<Self> {
let length = columns.first().map_or(0, |column| column.values.len());
let mut fields = std::collections::HashSet::new();
for column in &columns {
if column.values.len() != length {
return Err(Error::Data(
Diagnostic::new(
DiagnosticKind::ShapeMismatch {
expected: vec![length],
actual: vec![column.values.len()],
},
"key columns must have the same length",
)
.with_context(
ErrorContext::new()
.with_operation(OperationPhase::Bind)
.with_binding(column.key.clone()),
),
));
}
if !fields.insert(&column.key) {
return Err(Error::Data("duplicate key column identity".into()));
}
}
Ok(Self(columns.into()))
}
pub fn columns(&self) -> &[NamedKeyValues] {
&self.0
}
pub fn len(&self) -> usize {
self.0.len()
}
pub fn is_empty(&self) -> bool {
self.0.is_empty()
}
pub(crate) fn row_keys(&self, index: usize) -> Option<Vec<RawKey>> {
self.0
.iter()
.map(|column| match &column.values {
KeyValues::Strings(values) => values.get(index)?.map(RawKey::from),
KeyValues::Raw(values) => values.get(index)?.cloned(),
})
.collect()
}
pub fn get(&self, key: &RawKey) -> Result<&KeyValues> {
self.0
.iter()
.find(|column| &column.key == key)
.map(|column| &column.values)
.ok_or_else(|| {
Error::Data(
Diagnostic::new(
DiagnosticKind::UnknownKey {
key: Some(key.clone()),
},
format!("no key column {key:?}"),
)
.with_context(ErrorContext::new().with_operation(OperationPhase::Check)),
)
})
}
}