use std::sync::Arc;
use super::RawKey;
use crate::{
errors::{Diagnostic, DiagnosticKind, DiagnosticReference, ErrorContext, OperationPhase},
Error, NumericValues, Result,
};
#[derive(Debug, Clone)]
pub struct NamedNumericValues {
pub key: RawKey,
pub values: NumericValues,
}
#[derive(Debug, Clone)]
pub struct VariableValues(Arc<[NamedNumericValues]>);
impl VariableValues {
pub(crate) fn from_columns(values: Vec<NumericValues>) -> Self {
Self(
values
.into_iter()
.map(|values| {
let key = values
.field_key()
.cloned()
.unwrap_or_else(|| RawKey::from(values.name()));
NamedNumericValues { key, values }
})
.collect(),
)
}
pub fn variables(&self) -> &[NamedNumericValues] {
&self.0
}
pub fn get(&self, key: &RawKey) -> Result<&NumericValues> {
let matches: Vec<_> = self
.0
.iter()
.enumerate()
.filter(|(_, variable)| &variable.key == key)
.collect();
let context = ErrorContext::new()
.with_operation(OperationPhase::Check)
.with_binding(key.clone());
match matches.as_slice() {
[] => Err(Error::Data(
Diagnostic::new(
DiagnosticKind::UnknownKey {
key: Some(key.clone()),
},
format!("no matrix variable {key:?}"),
)
.with_context(context),
)),
[(_, value)] => Ok(&value.values),
_ => Err(Error::Data(
Diagnostic::new(
DiagnosticKind::Ambiguous {
candidates: matches
.into_iter()
.map(|(slot, _)| DiagnosticReference::Member {
domain: None,
address: super::MemberAddress::Slot(slot),
})
.collect(),
},
format!("ambiguous matrix variable {key:?}"),
)
.with_context(context),
)),
}
}
pub fn get_at(&self, index: usize) -> Option<&NamedNumericValues> {
self.0.get(index)
}
pub fn len(&self) -> usize {
self.0.len()
}
pub fn is_empty(&self) -> bool {
self.0.is_empty()
}
pub(crate) fn columns(&self) -> impl ExactSizeIterator<Item = &NumericValues> {
self.0.iter().map(|variable| &variable.values)
}
}