Skip to main content

vortex_scan/plan/
slots.rs

1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: Copyright the Vortex contributors
3
4use std::fmt;
5use std::ops::Deref;
6use std::sync::Arc;
7
8use once_cell::sync::OnceCell;
9use smallvec::SmallVec;
10use vortex_error::VortexResult;
11use vortex_error::vortex_bail;
12use vortex_error::vortex_err;
13
14use crate::plan::PlanRef;
15
16type SlotInitializer = dyn Fn() -> VortexResult<PlanRef> + 'static + Send + Sync;
17
18/// A plan child that may be built on first access.
19///
20/// Clones share the built plan, so a child is built at most once however many plans hold its
21/// slot. A failed build leaves the slot unbuilt, and the next access retries it.
22#[derive(Clone)]
23pub struct LazyPlanRef(Arc<LazyPlan<SlotInitializer>>);
24
25/// The built plan and its initializer, in one allocation.
26struct LazyPlan<F: ?Sized> {
27    cell: OnceCell<PlanRef>,
28    init: F, // must be last for unsized coercion
29}
30
31impl LazyPlanRef {
32    /// A slot built by `init` on first access.
33    pub fn lazy(init: impl Fn() -> VortexResult<PlanRef> + 'static + Send + Sync) -> Self {
34        Self(Arc::new(LazyPlan {
35            cell: OnceCell::new(),
36            init,
37        }))
38    }
39
40    /// A slot holding the already-built `plan`.
41    pub fn ready(plan: PlanRef) -> Self {
42        Self(Arc::new(LazyPlan {
43            cell: OnceCell::with_value(plan),
44            init: || Err(vortex_err!("A built plan slot was initialized again")),
45        }))
46    }
47
48    /// Returns the plan, building it on first access.
49    pub fn get(&self) -> VortexResult<&PlanRef> {
50        self.0.cell.get_or_try_init(|| (self.0.init)())
51    }
52
53    /// Returns whether the plan has been built.
54    pub fn is_initialized(&self) -> bool {
55        self.0.cell.get().is_some()
56    }
57}
58
59impl From<PlanRef> for LazyPlanRef {
60    fn from(plan: PlanRef) -> Self {
61        Self::ready(plan)
62    }
63}
64
65impl fmt::Debug for LazyPlanRef {
66    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
67        match self.0.cell.get() {
68            Some(plan) => write!(formatter, "{plan}"),
69            None => formatter.write_str("<unbuilt>"),
70        }
71    }
72}
73
74/// The fixed-position child slots of a plan.
75///
76/// Each operator defines what every slot position holds. A `None` slot is an absent child, such
77/// as the validity of a non-nullable struct, so the positions of the other slots never shift.
78#[derive(Clone, Default)]
79pub struct PlanSlots(SmallVec<[Option<LazyPlanRef>; 4]>);
80
81impl PlanSlots {
82    /// Creates empty slots with room for `capacity` slots.
83    pub fn with_capacity(capacity: usize) -> Self {
84        Self(SmallVec::with_capacity(capacity))
85    }
86
87    /// Appends a slot.
88    pub fn push(&mut self, slot: Option<LazyPlanRef>) {
89        self.0.push(slot);
90    }
91
92    /// Returns the plan in `slot`, building it on first access, or `None` when the slot is
93    /// absent. Errors when `slot` is out of bounds.
94    pub fn get(&self, slot: usize) -> VortexResult<Option<&PlanRef>> {
95        match self.0.get(slot) {
96            Some(Some(lazy)) => lazy.get().map(Some),
97            Some(None) => Ok(None),
98            None => vortex_bail!(
99                "Plan slot {slot} is out of bounds for {} slots",
100                self.0.len()
101            ),
102        }
103    }
104
105    /// Returns the plan in `slot`, or an error when the slot is absent or out of bounds.
106    pub fn required(&self, slot: usize) -> VortexResult<&PlanRef> {
107        self.get(slot)?
108            .ok_or_else(|| vortex_err!("Plan slot {slot} is absent"))
109    }
110
111    /// The present slots with their positions, in slot order, without building any child.
112    ///
113    /// This is the one place absent slots are dropped. Everything that walks a plan's children
114    /// goes through it, with the slot position when it needs one.
115    pub fn present(&self) -> impl Iterator<Item = (usize, &LazyPlanRef)> + '_ {
116        self.0
117            .iter()
118            .enumerate()
119            .filter_map(|(slot, lazy)| Some((slot, lazy.as_ref()?)))
120    }
121
122    /// The plans of the present slots in slot order, building each as it is visited.
123    ///
124    /// Pipelines have no absent inputs, so compiling a plan's children uses this: the `i`-th
125    /// child is the `i`-th present slot.
126    pub fn children(&self) -> impl Iterator<Item = VortexResult<&PlanRef>> + '_ {
127        self.present().map(|(_, lazy)| lazy.get())
128    }
129
130    /// Returns an error when there are not exactly `expected` slots.
131    pub fn check_len(&self, name: &str, expected: usize) -> VortexResult<()> {
132        if self.0.len() != expected {
133            vortex_bail!("{name} expects {expected} slots but got {}", self.0.len());
134        }
135        Ok(())
136    }
137}
138
139impl Deref for PlanSlots {
140    type Target = [Option<LazyPlanRef>];
141
142    fn deref(&self) -> &Self::Target {
143        &self.0
144    }
145}
146
147impl FromIterator<Option<LazyPlanRef>> for PlanSlots {
148    fn from_iter<I: IntoIterator<Item = Option<LazyPlanRef>>>(iter: I) -> Self {
149        Self(iter.into_iter().collect())
150    }
151}
152
153/// Built slots, with `None` for an absent child.
154impl FromIterator<Option<PlanRef>> for PlanSlots {
155    fn from_iter<I: IntoIterator<Item = Option<PlanRef>>>(iter: I) -> Self {
156        Self(
157            iter.into_iter()
158                .map(|plan| plan.map(LazyPlanRef::ready))
159                .collect(),
160        )
161    }
162}
163
164impl From<Vec<Option<LazyPlanRef>>> for PlanSlots {
165    fn from(slots: Vec<Option<LazyPlanRef>>) -> Self {
166        Self(SmallVec::from_vec(slots))
167    }
168}
169
170/// Built slots, every one present.
171impl From<Vec<PlanRef>> for PlanSlots {
172    fn from(children: Vec<PlanRef>) -> Self {
173        // `PlanRef` and `Option<LazyPlanRef>` have the same layout, so this collect reuses the
174        // vector's buffer, and `from_vec` keeps it when the slots do not fit inline.
175        let slots: Vec<Option<LazyPlanRef>> = children
176            .into_iter()
177            .map(|child| Some(LazyPlanRef::ready(child)))
178            .collect();
179        Self(SmallVec::from_vec(slots))
180    }
181}
182
183/// Built slots, every one present, without a temporary vector.
184impl<const N: usize> From<[PlanRef; N]> for PlanSlots {
185    fn from(children: [PlanRef; N]) -> Self {
186        children.into_iter().map(Some).collect()
187    }
188}
189
190impl fmt::Debug for PlanSlots {
191    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
192        formatter
193            .debug_struct("PlanSlots")
194            .field("len", &self.0.len())
195            .field("present", &self.present().count())
196            .field(
197                "built",
198                &self
199                    .present()
200                    .filter(|(_, lazy)| lazy.is_initialized())
201                    .count(),
202            )
203            .finish()
204    }
205}