Skip to main content

datafusion_common/utils/
proxy.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//! [`VecAllocExt`] to help tracking of memory allocations
6
7use hashbrown::hash_table::HashTable;
8use std::mem::size_of;
9
10/// Extension trait for [`Vec`] to account for allocations.
11pub trait VecAllocExt {
12    /// Item type.
13    type T;
14
15    /// [Push](Vec::push) new element to vector and increase
16    /// `accounting` by any newly allocated bytes.
17    ///
18    /// Note that allocation counts  capacity, not size
19    ///
20    /// # Example:
21    /// ```
22    /// # use datafusion_common::utils::proxy::VecAllocExt;
23    /// // use allocated to incrementally track how much memory is allocated in the vec
24    /// let mut allocated = 0;
25    /// let mut vec = Vec::new();
26    /// // Push data into the vec and the accounting will be updated to reflect
27    /// // memory allocation
28    /// vec.push_accounted(1, &mut allocated);
29    /// assert_eq!(allocated, 16); // space for 4 u32s
30    /// vec.push_accounted(1, &mut allocated);
31    /// assert_eq!(allocated, 16); // no new allocation needed
32    ///
33    /// // push more data into the vec
34    /// for _ in 0..10 {
35    ///     vec.push_accounted(1, &mut allocated);
36    /// }
37    /// assert_eq!(allocated, 64); // underlying vec has space for 10 u32s
38    /// assert_eq!(vec.allocated_size(), 64);
39    /// ```
40    /// # Example with other allocations:
41    /// ```
42    /// # use datafusion_common::utils::proxy::VecAllocExt;
43    /// // You can use the same allocated size to track memory allocated by
44    /// // another source. For example
45    /// let mut allocated = 27;
46    /// let mut vec = Vec::new();
47    /// vec.push_accounted(1, &mut allocated); // allocates 16 bytes for vec
48    /// assert_eq!(allocated, 43); // 16 bytes for vec, 27 bytes for other
49    /// ```
50    fn push_accounted(&mut self, x: Self::T, accounting: &mut usize);
51
52    /// Return the amount of memory allocated by this Vec to store elements
53    /// (`size_of<T> * capacity`).
54    ///
55    /// Note this calculation is not recursive, and does not include any heap
56    /// allocations contained within the Vec's elements. Does not include the
57    /// size of `self`
58    ///
59    /// # Example:
60    /// ```
61    /// # use datafusion_common::utils::proxy::VecAllocExt;
62    /// let mut vec = Vec::new();
63    /// // Push data into the vec and the accounting will be updated to reflect
64    /// // memory allocation
65    /// vec.push(1);
66    /// assert_eq!(vec.allocated_size(), 16); // space for 4 u32s
67    /// vec.push(1);
68    /// assert_eq!(vec.allocated_size(), 16); // no new allocation needed
69    ///
70    /// // push more data into the vec
71    /// for _ in 0..10 {
72    ///     vec.push(1);
73    /// }
74    /// assert_eq!(vec.allocated_size(), 64); // space for 64 now
75    /// ```
76    fn allocated_size(&self) -> usize;
77}
78
79impl<T> VecAllocExt for Vec<T> {
80    type T = T;
81
82    fn push_accounted(&mut self, x: Self::T, accounting: &mut usize) {
83        let prev_capacity = self.capacity();
84        self.push(x);
85        let new_capacity = self.capacity();
86        if new_capacity > prev_capacity {
87            // capacity changed, so we allocated more
88            let bump_size = (new_capacity - prev_capacity) * size_of::<T>();
89            // Note multiplication should never overflow because `push` would
90            // have panic'd first, but the checked_add could potentially
91            // overflow since accounting could be tracking additional values, and
92            // could be greater than what is stored in the Vec
93            *accounting = (*accounting).checked_add(bump_size).expect("overflow");
94        }
95    }
96    fn allocated_size(&self) -> usize {
97        size_of::<T>() * self.capacity()
98    }
99}
100
101/// Extension trait for hash browns [`HashTable`] to account for allocations.
102pub trait HashTableAllocExt {
103    /// Item type.
104    type T;
105
106    /// Insert new element into table and increase
107    /// `accounting` by any newly allocated bytes.
108    ///
109    /// Returns the bucket where the element was inserted.
110    /// Note that allocation counts capacity, not size.
111    /// Panics:
112    ///     Assumes the element is not already present, and may panic if it does
113    ///
114    /// # Example:
115    /// ```
116    /// # use datafusion_common::utils::proxy::HashTableAllocExt;
117    /// # use hashbrown::hash_table::HashTable;
118    /// let mut table = HashTable::new();
119    /// let mut allocated = 0;
120    /// let hash_fn = |x: &u32| (*x as u64) % 1000;
121    /// // pretend 0x3117 is the hash value for 1
122    /// table.insert_accounted(1, hash_fn, &mut allocated);
123    /// assert_eq!(allocated, 64);
124    ///
125    /// // insert more values
126    /// for i in 2..100 {
127    ///     table.insert_accounted(i, hash_fn, &mut allocated);
128    /// }
129    /// assert_eq!(allocated, 400);
130    /// ```
131    fn insert_accounted(
132        &mut self,
133        x: Self::T,
134        hasher: impl Fn(&Self::T) -> u64,
135        accounting: &mut usize,
136    );
137}
138
139impl<T> HashTableAllocExt for HashTable<T>
140where
141    T: Eq,
142{
143    type T = T;
144
145    fn insert_accounted(
146        &mut self,
147        x: Self::T,
148        hasher: impl Fn(&Self::T) -> u64,
149        accounting: &mut usize,
150    ) {
151        let hash = hasher(&x);
152
153        if cfg!(debug_assertions) {
154            // In debug mode, check that the element is not already present
155            debug_assert!(
156                self.find(hash, |y| y == &x).is_none(),
157                "attempted to insert duplicate element into HashTableAllocExt::insert_accounted"
158            );
159        }
160
161        if self.len() == self.capacity() {
162            // need to request more memory
163            let bump_elements = self.capacity().max(16);
164            let bump_size = bump_elements * size_of::<T>();
165            *accounting = (*accounting).checked_add(bump_size).expect("overflow");
166
167            self.reserve(bump_elements, &hasher);
168        }
169
170        // We assume the element is not already present
171        self.insert_unique(hash, x, hasher);
172    }
173}