vortex_session/
registry.rs

1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: Copyright the Vortex contributors
3
4//! Many session types use a registry of objects that can be looked up by name to construct
5//! contexts. This module provides a generic registry type for that purpose.
6
7use std::fmt::Display;
8use std::ops::Deref;
9use std::sync::Arc;
10
11use vortex_utils::aliases::dash_map::DashMap;
12
13/// A registry of items that are keyed by a string identifier.
14// TODO(ngates): define a RegistryItem trait that has a custom key to avoid to_string calls.
15#[derive(Clone, Debug)]
16pub struct Registry<T>(Arc<DashMap<String, T>>);
17
18impl<T> Default for Registry<T> {
19    fn default() -> Self {
20        Self(Default::default())
21    }
22}
23
24impl<T: Clone + Display + Eq> Registry<T> {
25    pub fn empty() -> Self {
26        Self(Default::default())
27    }
28
29    /// List the items in the registry.
30    pub fn items(&self) -> impl Iterator<Item = T> + '_ {
31        self.0.iter().map(|i| i.value().clone())
32    }
33
34    /// Return the items with the given IDs.
35    pub fn find_many<'a>(
36        &self,
37        ids: impl IntoIterator<Item = &'a str>,
38    ) -> impl Iterator<Item = Option<impl Deref<Target = T>>> {
39        ids.into_iter().map(|id| self.0.get(id))
40    }
41
42    /// Find the item with the given ID.
43    pub fn find(&self, id: &str) -> Option<T> {
44        self.0.get(id).as_deref().cloned()
45    }
46
47    /// Register a new item, replacing any existing item with the same ID.
48    pub fn register(&self, item: T) {
49        self.0.insert(item.to_string(), item);
50    }
51
52    /// Register a new item, replacing any existing item with the same ID.
53    pub fn register_many<I: IntoIterator<Item = T>>(&self, items: I) {
54        for item in items {
55            self.0.insert(item.to_string(), item);
56        }
57    }
58}