use std::fmt;
use std::ops::Deref;
use std::sync::Arc;
use once_cell::sync::OnceCell;
use smallvec::SmallVec;
use vortex_error::VortexResult;
use vortex_error::vortex_bail;
use vortex_error::vortex_err;
use crate::plan::PlanRef;
type SlotInitializer = dyn Fn() -> VortexResult<PlanRef> + 'static + Send + Sync;
#[derive(Clone)]
pub struct LazyPlanRef(Arc<LazyPlan<SlotInitializer>>);
struct LazyPlan<F: ?Sized> {
cell: OnceCell<PlanRef>,
init: F, }
impl LazyPlanRef {
pub fn lazy(init: impl Fn() -> VortexResult<PlanRef> + 'static + Send + Sync) -> Self {
Self(Arc::new(LazyPlan {
cell: OnceCell::new(),
init,
}))
}
pub fn ready(plan: PlanRef) -> Self {
Self(Arc::new(LazyPlan {
cell: OnceCell::with_value(plan),
init: || Err(vortex_err!("A built plan slot was initialized again")),
}))
}
pub fn get(&self) -> VortexResult<&PlanRef> {
self.0.cell.get_or_try_init(|| (self.0.init)())
}
pub fn is_initialized(&self) -> bool {
self.0.cell.get().is_some()
}
}
impl From<PlanRef> for LazyPlanRef {
fn from(plan: PlanRef) -> Self {
Self::ready(plan)
}
}
impl fmt::Debug for LazyPlanRef {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
match self.0.cell.get() {
Some(plan) => write!(formatter, "{plan}"),
None => formatter.write_str("<unbuilt>"),
}
}
}
#[derive(Clone, Default)]
pub struct PlanSlots(SmallVec<[Option<LazyPlanRef>; 4]>);
impl PlanSlots {
pub fn with_capacity(capacity: usize) -> Self {
Self(SmallVec::with_capacity(capacity))
}
pub fn push(&mut self, slot: Option<LazyPlanRef>) {
self.0.push(slot);
}
pub fn get(&self, slot: usize) -> VortexResult<Option<&PlanRef>> {
match self.0.get(slot) {
Some(Some(lazy)) => lazy.get().map(Some),
Some(None) => Ok(None),
None => vortex_bail!(
"Plan slot {slot} is out of bounds for {} slots",
self.0.len()
),
}
}
pub fn required(&self, slot: usize) -> VortexResult<&PlanRef> {
self.get(slot)?
.ok_or_else(|| vortex_err!("Plan slot {slot} is absent"))
}
pub fn present(&self) -> impl Iterator<Item = (usize, &LazyPlanRef)> + '_ {
self.0
.iter()
.enumerate()
.filter_map(|(slot, lazy)| Some((slot, lazy.as_ref()?)))
}
pub fn children(&self) -> impl Iterator<Item = VortexResult<&PlanRef>> + '_ {
self.present().map(|(_, lazy)| lazy.get())
}
pub fn check_len(&self, name: &str, expected: usize) -> VortexResult<()> {
if self.0.len() != expected {
vortex_bail!("{name} expects {expected} slots but got {}", self.0.len());
}
Ok(())
}
}
impl Deref for PlanSlots {
type Target = [Option<LazyPlanRef>];
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl FromIterator<Option<LazyPlanRef>> for PlanSlots {
fn from_iter<I: IntoIterator<Item = Option<LazyPlanRef>>>(iter: I) -> Self {
Self(iter.into_iter().collect())
}
}
impl FromIterator<Option<PlanRef>> for PlanSlots {
fn from_iter<I: IntoIterator<Item = Option<PlanRef>>>(iter: I) -> Self {
Self(
iter.into_iter()
.map(|plan| plan.map(LazyPlanRef::ready))
.collect(),
)
}
}
impl From<Vec<Option<LazyPlanRef>>> for PlanSlots {
fn from(slots: Vec<Option<LazyPlanRef>>) -> Self {
Self(SmallVec::from_vec(slots))
}
}
impl From<Vec<PlanRef>> for PlanSlots {
fn from(children: Vec<PlanRef>) -> Self {
let slots: Vec<Option<LazyPlanRef>> = children
.into_iter()
.map(|child| Some(LazyPlanRef::ready(child)))
.collect();
Self(SmallVec::from_vec(slots))
}
}
impl<const N: usize> From<[PlanRef; N]> for PlanSlots {
fn from(children: [PlanRef; N]) -> Self {
children.into_iter().map(Some).collect()
}
}
impl fmt::Debug for PlanSlots {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter
.debug_struct("PlanSlots")
.field("len", &self.0.len())
.field("present", &self.present().count())
.field(
"built",
&self
.present()
.filter(|(_, lazy)| lazy.is_initialized())
.count(),
)
.finish()
}
}