arrow_buffer/bytes.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//! This module contains an implementation of a contiguous immutable memory region that knows
6//! how to de-allocate itself, [`Bytes`].
7//! Note that this is a low-level functionality of this crate.
8
9use core::slice;
10use std::ptr::NonNull;
11use std::{fmt::Debug, fmt::Formatter};
12
13use crate::alloc::Deallocation;
14use crate::buffer::dangling_ptr;
15#[cfg(feature = "pool")]
16use crate::{MemoryPool, TrackedReservation};
17
18/// A continuous, fixed-size, immutable memory region that knows how to de-allocate itself.
19///
20/// Note that this structure is an internal implementation detail of the
21/// arrow-rs crate. While it has the same name and similar API as
22/// [`bytes::Bytes`] it is not limited to rust's global allocator nor u8
23/// alignment. It is possible to create a `Bytes` from `bytes::Bytes` using the
24/// `From` implementation.
25///
26/// In the most common case, this buffer is allocated using [`alloc`](std::alloc::alloc)
27/// with an alignment of [`ALIGNMENT`](crate::alloc::ALIGNMENT)
28///
29/// When the region is allocated by a different allocator, [Deallocation::Custom], this calls the
30/// custom deallocator to deallocate the region when it is no longer needed.
31///
32pub(crate) struct Bytes {
33 /// The raw pointer to be beginning of the region
34 ptr: NonNull<u8>,
35
36 /// The number of bytes visible to this region. This is always smaller than its capacity (when available).
37 len: usize,
38
39 /// how to deallocate this region
40 deallocation: Deallocation,
41
42 /// Memory reservation for tracking memory usage
43 #[cfg(feature = "pool")]
44 pub(super) reservation: TrackedReservation,
45}
46
47impl Bytes {
48 /// Takes ownership of an allocated memory region,
49 ///
50 /// # Arguments
51 ///
52 /// * `ptr` - Pointer to raw parts
53 /// * `len` - Length of raw parts in **bytes**
54 /// * `deallocation` - Type of allocation
55 ///
56 /// # Safety
57 ///
58 /// This function is unsafe as there is no guarantee that the given pointer is valid for `len`
59 /// bytes. If the `ptr` and `capacity` come from a `Buffer`, then this is guaranteed.
60 #[inline]
61 pub(crate) unsafe fn new(ptr: NonNull<u8>, len: usize, deallocation: Deallocation) -> Bytes {
62 Bytes {
63 ptr,
64 len,
65 deallocation,
66 #[cfg(feature = "pool")]
67 reservation: TrackedReservation::default(),
68 }
69 }
70
71 fn as_slice(&self) -> &[u8] {
72 self
73 }
74
75 #[inline]
76 pub(crate) fn len(&self) -> usize {
77 self.len
78 }
79
80 #[inline]
81 pub(crate) fn ptr(&self) -> NonNull<u8> {
82 self.ptr
83 }
84
85 pub(crate) fn capacity(&self) -> usize {
86 match self.deallocation {
87 Deallocation::Standard(layout) => layout.size(),
88 // we only know the size of the custom allocation
89 // its underlying capacity might be larger
90 Deallocation::Custom(_, size) => size,
91 }
92 }
93
94 /// Register this [`Bytes`] with the provided [`MemoryPool`], replacing any prior reservation.
95 #[cfg(feature = "pool")]
96 pub(crate) fn claim(&self, pool: &dyn MemoryPool) {
97 self.reservation.claim(pool, self.capacity());
98 }
99
100 /// Resize the memory reservation of this buffer
101 ///
102 /// This is a no-op if this buffer doesn't have a reservation.
103 #[cfg(feature = "pool")]
104 fn resize_reservation(&self, new_size: usize) {
105 self.reservation.resize(new_size);
106 }
107
108 /// Try to reallocate the underlying memory region to a new size (smaller or larger).
109 ///
110 /// Only works for bytes allocated with the standard allocator.
111 /// Returns `Err` if the memory was allocated with a custom allocator,
112 /// or the call to `realloc` failed, for whatever reason.
113 /// In case of `Err`, the [`Bytes`] will remain as it was (i.e. have the old size).
114 ///
115 /// `on_reallocated` is called after [`Bytes`] has updated its internal
116 /// pointer, but before resizing the memory reservation, which may call user
117 /// code.
118 pub(crate) fn try_realloc(
119 &mut self,
120 new_len: usize,
121 on_reallocated: impl FnOnce(NonNull<u8>),
122 ) -> Result<(), ()> {
123 if let Deallocation::Standard(old_layout) = self.deallocation {
124 if old_layout.size() == new_len {
125 return Ok(()); // Nothing to do
126 }
127
128 if let Ok(new_layout) = std::alloc::Layout::from_size_align(new_len, old_layout.align())
129 {
130 let old_ptr = self.ptr.as_ptr();
131
132 let new_ptr = match new_layout.size() {
133 0 => {
134 // SAFETY: Verified that old_layout.size != new_len (0)
135 unsafe { std::alloc::dealloc(self.ptr.as_ptr(), old_layout) };
136 Some(dangling_ptr())
137 }
138 // SAFETY: the call to `realloc` is safe if all the following hold (from https://doc.rust-lang.org/stable/std/alloc/trait.GlobalAlloc.html#method.realloc):
139 // * `old_ptr` must be currently allocated via this allocator (guaranteed by the invariant/contract of `Bytes`)
140 // * `old_layout` must be the same layout that was used to allocate that block of memory (same)
141 // * `new_len` must be greater than zero
142 // * `new_len`, when rounded up to the nearest multiple of `layout.align()`, must not overflow `isize` (guaranteed by the success of `Layout::from_size_align`)
143 _ => NonNull::new(unsafe { std::alloc::realloc(old_ptr, old_layout, new_len) }),
144 };
145
146 if let Some(ptr) = new_ptr {
147 self.ptr = ptr;
148 self.len = new_len;
149 self.deallocation = Deallocation::Standard(new_layout);
150 on_reallocated(ptr);
151
152 #[cfg(feature = "pool")]
153 {
154 // Resize reservation
155 self.resize_reservation(new_len);
156 }
157
158 return Ok(());
159 }
160 }
161 }
162
163 Err(())
164 }
165
166 #[inline]
167 pub(crate) fn deallocation(&self) -> &Deallocation {
168 &self.deallocation
169 }
170}
171
172// Deallocation is Send + Sync, repeating the bound here makes that refactoring safe
173// The only field that is not automatically Send+Sync then is the NonNull ptr
174unsafe impl Send for Bytes where Deallocation: Send {}
175unsafe impl Sync for Bytes where Deallocation: Sync {}
176
177impl Drop for Bytes {
178 #[inline]
179 fn drop(&mut self) {
180 match &self.deallocation {
181 Deallocation::Standard(layout) => match layout.size() {
182 0 => {} // Nothing to do
183 _ => unsafe { std::alloc::dealloc(self.ptr.as_ptr(), *layout) },
184 },
185 // The automatic drop implementation will free the memory once the reference count reaches zero
186 Deallocation::Custom(_allocation, _size) => (),
187 }
188 }
189}
190
191impl std::ops::Deref for Bytes {
192 type Target = [u8];
193
194 fn deref(&self) -> &[u8] {
195 unsafe { slice::from_raw_parts(self.ptr.as_ptr(), self.len) }
196 }
197}
198
199impl PartialEq for Bytes {
200 fn eq(&self, other: &Bytes) -> bool {
201 self.as_slice() == other.as_slice()
202 }
203}
204
205impl Debug for Bytes {
206 fn fmt(&self, f: &mut Formatter) -> std::fmt::Result {
207 write!(f, "Bytes {{ ptr: {:?}, len: {}, data: ", self.ptr, self.len)?;
208
209 f.debug_list().entries(self.iter()).finish()?;
210
211 write!(f, " }}")
212 }
213}
214
215impl From<bytes::Bytes> for Bytes {
216 fn from(value: bytes::Bytes) -> Self {
217 let len = value.len();
218 Self {
219 len,
220 // `bytes::Bytes` is shared and immutable, so the buffer is never written
221 // through this pointer; the cast only changes constness.
222 ptr: NonNull::new(value.as_ptr().cast_mut()).unwrap(),
223 deallocation: Deallocation::Custom(std::sync::Arc::new(value), len),
224 #[cfg(feature = "pool")]
225 reservation: TrackedReservation::default(),
226 }
227 }
228}
229
230#[cfg(test)]
231mod tests {
232 use super::*;
233
234 #[test]
235 fn test_from_bytes() {
236 let message = b"hello arrow";
237
238 // we can create a Bytes from bytes::Bytes (created from slices)
239 let c_bytes: bytes::Bytes = message.as_ref().into();
240 let a_bytes: Bytes = c_bytes.into();
241 assert_eq!(a_bytes.as_slice(), message);
242
243 // we can create a Bytes from bytes::Bytes (created from Vec)
244 let c_bytes: bytes::Bytes = bytes::Bytes::from(message.to_vec());
245 let a_bytes: Bytes = c_bytes.into();
246 assert_eq!(a_bytes.as_slice(), message);
247 }
248
249 #[cfg(feature = "pool")]
250 mod pool_tests {
251 use super::*;
252
253 use crate::pool::TrackingMemoryPool;
254
255 #[test]
256 fn test_bytes_with_pool() {
257 // Create a standard allocation
258 let buffer = unsafe {
259 let layout =
260 std::alloc::Layout::from_size_align(1024, crate::alloc::ALIGNMENT).unwrap();
261 let ptr = std::alloc::alloc(layout);
262 assert!(!ptr.is_null());
263
264 Bytes::new(
265 NonNull::new(ptr).unwrap(),
266 1024,
267 Deallocation::Standard(layout),
268 )
269 };
270
271 // Create a memory pool
272 let pool = TrackingMemoryPool::default();
273 assert_eq!(pool.used(), 0);
274
275 // Reserve memory and assign to buffer. Claim twice.
276 buffer.claim(&pool);
277 assert_eq!(pool.used(), 1024);
278 buffer.claim(&pool);
279 assert_eq!(pool.used(), 1024);
280
281 // Memory should be released when buffer is dropped
282 drop(buffer);
283 assert_eq!(pool.used(), 0);
284 }
285
286 #[test]
287 fn test_bytes_drop_releases_pool() {
288 let pool = TrackingMemoryPool::default();
289
290 {
291 // Create a buffer with pool
292 let _buffer = unsafe {
293 let layout =
294 std::alloc::Layout::from_size_align(1024, crate::alloc::ALIGNMENT).unwrap();
295 let ptr = std::alloc::alloc(layout);
296 assert!(!ptr.is_null());
297
298 let bytes = Bytes::new(
299 NonNull::new(ptr).unwrap(),
300 1024,
301 Deallocation::Standard(layout),
302 );
303
304 bytes.claim(&pool);
305 bytes
306 };
307
308 assert_eq!(pool.used(), 1024);
309 }
310
311 // Buffer has been dropped, memory should be released
312 assert_eq!(pool.used(), 0);
313 }
314 }
315}