MCPcopy Create free account
hub / github.com/apache/arrow-rs / try_realloc

Method try_realloc

arrow-buffer/src/bytes.rs:142–183  ·  view source on GitHub ↗

Try to reallocate the underlying memory region to a new size (smaller or larger). Only works for bytes allocated with the standard allocator. Returns `Err` if the memory was allocated with a custom allocator, or the call to `realloc` failed, for whatever reason. In case of `Err`, the [`Bytes`] will remain as it was (i.e. have the old size).

(&mut self, new_len: usize)

Source from the content-addressed store, hash-verified

140 /// or the call to `realloc` failed, for whatever reason.
141 /// In case of `Err`, the [`Bytes`] will remain as it was (i.e. have the old size).
142 pub fn try_realloc(&mut self, new_len: usize) -> Result<(), ()> {
143 if let Deallocation::Standard(old_layout) = self.deallocation {
144 if old_layout.size() == new_len {
145 return Ok(()); // Nothing to do
146 }
147
148 if let Ok(new_layout) = std::alloc::Layout::from_size_align(new_len, old_layout.align())
149 {
150 let old_ptr = self.ptr.as_ptr();
151
152 let new_ptr = match new_layout.size() {
153 0 => {
154 // SAFETY: Verified that old_layout.size != new_len (0)
155 unsafe { std::alloc::dealloc(self.ptr.as_ptr(), old_layout) };
156 Some(dangling_ptr())
157 }
158 // 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):
159 // * `old_ptr` must be currently allocated via this allocator (guaranteed by the invariant/contract of `Bytes`)
160 // * `old_layout` must be the same layout that was used to allocate that block of memory (same)
161 // * `new_len` must be greater than zero
162 // * `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`)
163 _ => NonNull::new(unsafe { std::alloc::realloc(old_ptr, old_layout, new_len) }),
164 };
165
166 if let Some(ptr) = new_ptr {
167 self.ptr = ptr;
168 self.len = new_len;
169 self.deallocation = Deallocation::Standard(new_layout);
170
171 #[cfg(feature = "pool")]
172 {
173 // Resize reservation
174 self.resize_reservation(new_len);
175 }
176
177 return Ok(());
178 }
179 }
180 }
181
182 Err(())
183 }
184
185 #[inline]
186 pub(crate) fn deallocation(&self) -> &Deallocation {

Callers 1

shrink_to_fitMethod · 0.80

Calls 4

dangling_ptrFunction · 0.85
resize_reservationMethod · 0.80
sizeMethod · 0.45
as_ptrMethod · 0.45

Tested by

no test coverage detected