vortex_array/
context.rs

1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: Copyright the Vortex contributors
3
4use std::fmt::Display;
5use std::sync::Arc;
6
7use itertools::Itertools;
8use parking_lot::RwLock;
9use vortex_error::{VortexExpect, VortexResult, vortex_err};
10use vortex_utils::aliases::hash_map::HashMap;
11
12use crate::EncodingRef;
13use crate::arrays::{
14    BoolEncoding, ChunkedEncoding, ConstantEncoding, DecimalEncoding, ExtensionEncoding,
15    ListEncoding, NullEncoding, PrimitiveEncoding, StructEncoding, VarBinEncoding,
16    VarBinViewEncoding,
17};
18
19/// A collection of array encodings.
20// TODO(ngates): it feels weird that this has interior mutability. I think maybe it shouldn't.
21pub type ArrayContext = VTableContext<EncodingRef>;
22pub type ArrayRegistry = VTableRegistry<EncodingRef>;
23
24impl ArrayRegistry {
25    pub fn canonical_only() -> Self {
26        let mut this = Self::empty();
27
28        // Register the canonical encodings
29        this.register_many([
30            EncodingRef::new_ref(NullEncoding.as_ref()) as EncodingRef,
31            EncodingRef::new_ref(BoolEncoding.as_ref()),
32            EncodingRef::new_ref(PrimitiveEncoding.as_ref()),
33            EncodingRef::new_ref(DecimalEncoding.as_ref()),
34            EncodingRef::new_ref(StructEncoding.as_ref()),
35            EncodingRef::new_ref(ListEncoding.as_ref()),
36            EncodingRef::new_ref(VarBinEncoding.as_ref()),
37            EncodingRef::new_ref(VarBinViewEncoding.as_ref()),
38            EncodingRef::new_ref(ExtensionEncoding.as_ref()),
39        ]);
40
41        // Register the utility encodings
42        this.register_many([
43            EncodingRef::new_ref(ConstantEncoding.as_ref()) as EncodingRef,
44            EncodingRef::new_ref(ChunkedEncoding.as_ref()),
45        ]);
46
47        this
48    }
49}
50
51/// A collection of encodings that can be addressed by a u16 positional index.
52/// This is used to map array encodings and layout encodings when reading from a file.
53#[derive(Debug, Clone)]
54pub struct VTableContext<T>(Arc<RwLock<Vec<T>>>);
55
56impl<T: Clone + Eq> VTableContext<T> {
57    pub fn empty() -> Self {
58        Self(Arc::new(RwLock::new(Vec::new())))
59    }
60
61    pub fn with(self, encoding: T) -> Self {
62        {
63            let mut write = self.0.write();
64            if write.iter().all(|e| e != &encoding) {
65                write.push(encoding);
66            }
67        }
68        self
69    }
70
71    pub fn with_many<E: IntoIterator<Item = T>>(self, items: E) -> Self {
72        items.into_iter().fold(self, |ctx, e| ctx.with(e))
73    }
74
75    pub fn encodings(&self) -> Vec<T> {
76        self.0.read().clone()
77    }
78
79    /// Returns the index of the encoding in the context, or adds it if it doesn't exist.
80    pub fn encoding_idx(&self, encoding: &T) -> u16 {
81        let mut write = self.0.write();
82        if let Some(idx) = write.iter().position(|e| e == encoding) {
83            return u16::try_from(idx).vortex_expect("Cannot have more than u16::MAX encodings");
84        }
85        assert!(
86            write.len() < u16::MAX as usize,
87            "Cannot have more than u16::MAX encodings"
88        );
89        write.push(encoding.clone());
90        u16::try_from(write.len() - 1).vortex_expect("checked already")
91    }
92
93    /// Find an encoding by its position.
94    pub fn lookup_encoding(&self, idx: u16) -> Option<T> {
95        self.0.read().get(idx as usize).cloned()
96    }
97}
98
99/// A registry of encodings that can be used to construct a context for serde.
100///
101/// In the future, we will support loading encodings from shared libraries or even from within
102/// the Vortex file itself. This registry will be used to manage the available encodings.
103#[derive(Clone, Debug)]
104pub struct VTableRegistry<T>(HashMap<String, T>);
105
106// TODO(ngates): define a trait for `T` that requires an `id` method returning a `Arc<str>` and
107//  auto-implement `Display` and `Eq` for it.
108impl<T: Clone + Display + Eq> VTableRegistry<T> {
109    pub fn empty() -> Self {
110        Self(Default::default())
111    }
112
113    /// Create a new [`VTableContext`] with the provided encodings.
114    pub fn new_context<'a>(
115        &self,
116        encoding_ids: impl Iterator<Item = &'a str>,
117    ) -> VortexResult<VTableContext<T>> {
118        let mut ctx = VTableContext::<T>::empty();
119        for id in encoding_ids {
120            let encoding = self.0.get(id).ok_or_else(|| {
121                vortex_err!(
122                    "Array encoding {} not found in registry {}",
123                    id,
124                    self.0.values().join(", ")
125                )
126            })?;
127            ctx = ctx.with(encoding.clone());
128        }
129        Ok(ctx)
130    }
131
132    /// List the vtables in the registry.
133    pub fn vtables(&self) -> impl Iterator<Item = &T> + '_ {
134        self.0.values()
135    }
136
137    /// Find the encoding with the given ID.
138    pub fn get(&self, id: &str) -> Option<&T> {
139        self.0.get(id)
140    }
141
142    /// Register a new encoding, replacing any existing encoding with the same ID.
143    pub fn register(&mut self, encoding: T) {
144        self.0.insert(encoding.to_string(), encoding);
145    }
146
147    /// Register a new encoding, replacing any existing encoding with the same ID.
148    pub fn register_many<I: IntoIterator<Item = T>>(&mut self, encodings: I) {
149        self.0
150            .extend(encodings.into_iter().map(|e| (e.to_string(), e)));
151    }
152}