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#[derive(Clone, Debug)]
15pub struct Registry<T>(Arc<DashMap<String, T>>);
16
17impl<T> Default for Registry<T> {
18    fn default() -> Self {
19        Self(Default::default())
20    }
21}
22
23impl<T: Clone + Display + Eq> Registry<T> {
24    pub fn empty() -> Self {
25        Self(Default::default())
26    }
27
28    /// List the items in the registry.
29    pub fn items(&self) -> impl Iterator<Item = T> + '_ {
30        self.0.iter().map(|i| i.value().clone())
31    }
32
33    /// Return the items with the given IDs.
34    pub fn find_many<'a>(
35        &self,
36        ids: impl IntoIterator<Item = &'a str>,
37    ) -> impl Iterator<Item = Option<impl Deref<Target = T>>> {
38        ids.into_iter().map(|id| self.0.get(id))
39    }
40
41    /// Find the item with the given ID.
42    pub fn find(&self, id: &str) -> Option<T> {
43        self.0.get(id).as_deref().cloned()
44    }
45
46    /// Register a new item, replacing any existing item with the same ID.
47    pub fn register(&self, item: T) {
48        self.0.insert(item.to_string(), item);
49    }
50
51    /// Register a new item, replacing any existing item with the same ID.
52    pub fn register_many<I: IntoIterator<Item = T>>(&self, items: I) {
53        for item in items {
54            self.0.insert(item.to_string(), item);
55        }
56    }
57}