arrow_buffer/alloc/
mod.rs

1// Licensed to the Apache Software Foundation (ASF) under one
2// or more contributor license agreements.  See the NOTICE file
3// distributed with this work for additional information
4// regarding copyright ownership.  The ASF licenses this file
5// to you under the Apache License, Version 2.0 (the
6// "License"); you may not use this file except in compliance
7// with the License.  You may obtain a copy of the License at
8//
9//   http://www.apache.org/licenses/LICENSE-2.0
10//
11// Unless required by applicable law or agreed to in writing,
12// software distributed under the License is distributed on an
13// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
14// KIND, either express or implied.  See the License for the
15// specific language governing permissions and limitations
16// under the License.
17
18//! Defines the low-level [`Allocation`] API for shared memory regions
19
20use std::alloc::Layout;
21use std::fmt::{Debug, Formatter};
22use std::panic::RefUnwindSafe;
23use std::sync::Arc;
24
25mod alignment;
26
27pub use alignment::ALIGNMENT;
28
29/// The owner of an allocation.
30/// The trait implementation is responsible for dropping the allocations once no more references exist.
31pub trait Allocation: RefUnwindSafe + Send + Sync {}
32
33impl<T: RefUnwindSafe + Send + Sync> Allocation for T {}
34
35/// Mode of deallocating memory regions
36pub(crate) enum Deallocation {
37    /// An allocation using [`std::alloc`]
38    Standard(Layout),
39    /// An allocation from an external source like the FFI interface
40    /// Deallocation will happen on `Allocation::drop`
41    /// The size of the allocation is tracked here separately only
42    /// for memory usage reporting via `Array::get_buffer_memory_size`
43    Custom(Arc<dyn Allocation>, usize),
44}
45
46impl Debug for Deallocation {
47    fn fmt(&self, f: &mut Formatter) -> std::fmt::Result {
48        match self {
49            Deallocation::Standard(layout) => {
50                write!(f, "Deallocation::Standard {layout:?}")
51            }
52            Deallocation::Custom(_, size) => {
53                write!(f, "Deallocation::Custom {{ capacity: {size} }}")
54            }
55        }
56    }
57}
58
59#[cfg(test)]
60mod tests {
61    use crate::alloc::Deallocation;
62
63    #[test]
64    fn test_size_of_deallocation() {
65        assert_eq!(
66            std::mem::size_of::<Deallocation>(),
67            3 * std::mem::size_of::<usize>()
68        );
69    }
70}