vortex_scan/arrays/shared/
array.rs1use std::fmt::Display;
5use std::fmt::Formatter;
6use std::future::Future;
7use std::sync::Arc;
8use std::sync::OnceLock;
9
10use async_lock::Mutex as AsyncMutex;
11use vortex_array::Array;
12use vortex_array::ArrayParts;
13use vortex_array::ArrayRef;
14use vortex_array::Canonical;
15use vortex_array::IntoArray;
16use vortex_array::TypedArrayRef;
17use vortex_array::array_slots;
18use vortex_error::SharedVortexResult;
19use vortex_error::VortexResult;
20
21use crate::arrays::shared::Shared;
22use crate::arrays::shared::SharedArray;
23
24#[array_slots(Shared)]
26pub struct SharedSlots {
27 #[slot(0)]
29 pub source: ArrayRef,
30}
31
32#[derive(Debug, Clone)]
37pub struct SharedData {
38 cached: Arc<OnceLock<SharedVortexResult<ArrayRef>>>,
39 async_compute_lock: Arc<AsyncMutex<()>>,
40}
41
42impl Display for SharedData {
43 fn fmt(&self, _f: &mut Formatter<'_>) -> std::fmt::Result {
44 Ok(())
45 }
46}
47
48#[expect(async_fn_in_trait)]
49pub trait SharedArrayExt: TypedArrayRef<Shared> {
51 fn current_array_ref(&self) -> &ArrayRef {
53 match self.cached.get() {
54 Some(Ok(arr)) => arr,
55 _ => self.source(),
56 }
57 }
58
59 fn get_or_compute(
61 &self,
62 f: impl FnOnce(&ArrayRef) -> VortexResult<Canonical>,
63 ) -> VortexResult<ArrayRef> {
64 let result = self
65 .cached
66 .get_or_init(|| f(self.source()).map(|c| c.into_array()).map_err(Arc::new));
67 result.clone().map_err(Into::into)
68 }
69
70 async fn get_or_compute_async<F, Fut>(&self, f: F) -> VortexResult<ArrayRef>
72 where
73 F: FnOnce(ArrayRef) -> Fut,
74 Fut: Future<Output = VortexResult<Canonical>>,
75 {
76 if let Some(result) = self.cached.get() {
77 return result.clone().map_err(Into::into);
78 }
79
80 let _guard = self.async_compute_lock.lock().await;
81
82 if let Some(result) = self.cached.get() {
83 return result.clone().map_err(Into::into);
84 }
85
86 let computed = f(self.source().clone())
87 .await
88 .map(|c| c.into_array())
89 .map_err(Arc::new);
90
91 let result = self.cached.get_or_init(|| computed);
92 result.clone().map_err(Into::into)
93 }
94}
95impl<T: TypedArrayRef<Shared>> SharedArrayExt for T {}
96
97impl SharedData {
98 pub fn new() -> Self {
100 Self {
101 cached: Arc::new(OnceLock::new()),
102 async_compute_lock: Arc::new(AsyncMutex::new(())),
103 }
104 }
105}
106
107impl Default for SharedData {
108 fn default() -> Self {
109 Self::new()
110 }
111}
112
113impl Shared {
114 pub fn new(source: ArrayRef) -> SharedArray {
116 let dtype = source.dtype().clone();
117 let len = source.len();
118 unsafe {
119 Array::from_parts_unchecked(ArrayParts::new(
120 Shared,
121 dtype,
122 len,
123 SharedData::new(),
124 SharedSlots { source }.into_slots(),
125 ))
126 }
127 }
128}