Skip to main content

datafusion_common/
extensions.rs

1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: See the NOTICE file distributed with this work for additional information regarding copyright ownership
3// SPDX-FileContributor: Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements
4
5//! A type-keyed map of opaque, `Arc`'d objects.
6//!
7//! Used as the backing store for the various `extensions` fields throughout
8//! DataFusion (e.g. [`SessionConfig`], [`ExtendedStatistics`],
9//! [`PartitionedFile`]) so that independent components can each attach
10//! their own data without conflict, each keyed by its concrete Rust type.
11//!
12//! [`SessionConfig`]: https://docs.rs/datafusion-execution/latest/datafusion_execution/config/struct.SessionConfig.html
13//! [`ExtendedStatistics`]: https://docs.rs/datafusion-physical-plan/latest/datafusion_physical_plan/operator_statistics/struct.ExtendedStatistics.html
14//! [`PartitionedFile`]: https://docs.rs/datafusion-datasource/latest/datafusion_datasource/struct.PartitionedFile.html
15
16use std::any::{Any, TypeId};
17use std::collections::HashMap;
18use std::hash::{BuildHasherDefault, Hasher};
19use std::sync::Arc;
20
21/// A type-keyed map of opaque `Arc`'d values. Each Rust type `T` occupies
22/// its own slot, so independent components can each attach their own data
23/// without conflict.
24///
25/// Cloning is cheap: the backing values are reference-counted.
26///
27/// # Example
28///
29/// ```
30/// # use std::sync::Arc;
31/// # use datafusion_common::extensions::Extensions;
32/// struct MyData(u32);
33/// struct OtherData(&'static str);
34///
35/// let mut ext = Extensions::new();
36/// ext.insert(MyData(42));
37/// ext.insert_arc(Arc::new(OtherData("hello")));
38///
39/// assert_eq!(ext.get::<MyData>().unwrap().0, 42);
40/// assert_eq!(ext.get::<OtherData>().unwrap().0, "hello");
41/// ```
42#[derive(Debug, Clone, Default)]
43pub struct Extensions {
44    inner: HashMap<TypeId, Arc<dyn Any + Send + Sync>, BuildHasherDefault<IdHasher>>,
45}
46
47impl Extensions {
48    /// Create an empty map.
49    pub fn new() -> Self {
50        Self::default()
51    }
52
53    /// Returns true if no extensions are set.
54    pub fn is_empty(&self) -> bool {
55        self.inner.is_empty()
56    }
57
58    /// Number of extensions set.
59    pub fn len(&self) -> usize {
60        self.inner.len()
61    }
62
63    /// Insert an extension keyed by its concrete type `T`. Returns the
64    /// previous value of that type, if any.
65    ///
66    /// The value is wrapped in an [`Arc`] internally. If the caller already
67    /// has an `Arc<T>` and wants to avoid an extra allocation, use
68    /// [`Self::insert_arc`].
69    pub fn insert<T: Any + Send + Sync>(&mut self, value: T) -> Option<Arc<T>> {
70        self.insert_arc(Arc::new(value))
71    }
72
73    /// Insert an extension keyed by its concrete type `T`, taking an
74    /// already-allocated [`Arc<T>`]. Returns the previous value of that type,
75    /// if any.
76    pub fn insert_arc<T: Any + Send + Sync>(&mut self, value: Arc<T>) -> Option<Arc<T>> {
77        self.inner
78            .insert(TypeId::of::<T>(), value)
79            .map(|p| Arc::downcast::<T>(p).expect("TypeId matches T"))
80    }
81
82    /// Insert an already-type-erased value, keyed by its dynamic
83    /// [`TypeId`]. Used internally to support APIs that accept
84    /// `Arc<dyn Any + Send + Sync>` for backwards compatibility and need
85    /// to recover the concrete type for keying.
86    ///
87    /// New code should use [`Self::insert`] or [`Self::insert_arc`], which
88    /// preserve the concrete type at the call site.
89    #[deprecated(
90        since = "54.0.0",
91        note = "use `insert` or `insert_arc`; only retained to support the deprecated `PartitionedFile::with_extensions` shim"
92    )]
93    pub fn insert_dyn(
94        &mut self,
95        value: Arc<dyn Any + Send + Sync>,
96    ) -> Option<Arc<dyn Any + Send + Sync>> {
97        let id = (*value).type_id();
98        self.inner.insert(id, value)
99    }
100
101    /// Borrow the extension of type `T`, if set.
102    pub fn get<T: Any + Send + Sync>(&self) -> Option<&T> {
103        self.inner
104            .get(&TypeId::of::<T>())
105            .and_then(|a| a.downcast_ref::<T>())
106    }
107
108    /// Get a cloned `Arc<T>` of the extension, if set.
109    pub fn get_arc<T: Any + Send + Sync>(&self) -> Option<Arc<T>> {
110        self.inner
111            .get(&TypeId::of::<T>())
112            .map(|a| Arc::downcast::<T>(Arc::clone(a)).expect("TypeId matches T"))
113    }
114
115    /// Returns true if an extension of type `T` is set.
116    pub fn contains<T: Any + Send + Sync>(&self) -> bool {
117        self.inner.contains_key(&TypeId::of::<T>())
118    }
119
120    /// Merge entries from `other` into `self`. Entries in `other` take
121    /// precedence over existing entries with the same type.
122    pub fn merge(&mut self, other: &Extensions) {
123        for (id, ext) in &other.inner {
124            self.inner.insert(*id, Arc::clone(ext));
125        }
126    }
127}
128
129/// Hasher specialized for [`TypeId`] keys. Since `TypeId` is already a
130/// hash produced by the compiler, we don't need to hash it again — we
131/// just store the `u64` it writes and return it unchanged.
132#[derive(Default)]
133struct IdHasher(u64);
134
135impl Hasher for IdHasher {
136    fn write(&mut self, _: &[u8]) {
137        unreachable!("TypeId calls write_u64");
138    }
139
140    #[inline]
141    fn write_u64(&mut self, id: u64) {
142        self.0 = id;
143    }
144
145    #[inline]
146    fn finish(&self) -> u64 {
147        self.0
148    }
149}
150
151#[cfg(test)]
152mod tests {
153    use super::*;
154
155    #[derive(Debug, PartialEq)]
156    struct A(u32);
157
158    #[derive(Debug, PartialEq)]
159    struct B(&'static str);
160
161    #[test]
162    fn insert_get_replace() {
163        let mut ext = Extensions::new();
164        assert!(ext.is_empty());
165
166        ext.insert(A(1));
167        ext.insert_arc(Arc::new(B("x")));
168        assert_eq!(ext.len(), 2);
169        assert_eq!(ext.get::<A>(), Some(&A(1)));
170        assert_eq!(ext.get::<B>(), Some(&B("x")));
171        assert!(ext.contains::<A>());
172
173        let prev = ext.insert(A(2));
174        assert_eq!(prev.as_deref(), Some(&A(1)));
175        assert_eq!(ext.get::<A>(), Some(&A(2)));
176    }
177
178    #[test]
179    #[expect(deprecated)]
180    fn insert_dyn_keys_by_concrete_type() {
181        let mut ext = Extensions::new();
182        let erased: Arc<dyn Any + Send + Sync> = Arc::new(A(7));
183        ext.insert_dyn(erased);
184        assert_eq!(ext.get::<A>(), Some(&A(7)));
185    }
186
187    #[test]
188    fn merge_other_wins() {
189        let mut a = Extensions::new();
190        a.insert(A(1));
191        let mut b = Extensions::new();
192        b.insert(A(2));
193        b.insert(B("hi"));
194        a.merge(&b);
195        assert_eq!(a.get::<A>(), Some(&A(2)));
196        assert_eq!(a.get::<B>(), Some(&B("hi")));
197    }
198}