| 1 |
use core::alloc::Layout; |
| 2 |
use core::{cmp, mem, ptr}; |
| 3 |
|
| 4 |
use super::capacity::Capacity; |
| 5 |
use super::{Repr, MAX_SIZE}; |
| 6 |
use crate::{ReserveError, UnwrapWithMsg}; |
| 7 |
|
| 8 |
/// The minimum size we'll allocate on the heap is one usize larger than our max inline size |
| 9 |
const MIN_HEAP_SIZE: usize = MAX_SIZE + mem::size_of::<usize>(); |
| 10 |
|
| 11 |
const UNKNOWN: usize = 0; |
| 12 |
pub(crate) type StrBuffer = [u8; UNKNOWN]; |
| 13 |
|
| 14 |
/// [`HeapBuffer`] grows at an amortized rates of 1.5x |
| 15 |
/// |
| 16 |
/// Note: this is different than [`std::string::String`], which grows at a rate of 2x. It's debated |
| 17 |
/// which is better, for now we'll stick with a rate of 1.5x |
| 18 |
#[inline(always)] |
| 19 |
pub(crate) fn amortized_growth(cur_len: usize, additional: usize) -> usize { |
| 20 |
let required = cur_len.saturating_add(additional); |
| 21 |
let amortized = cur_len.saturating_mul(3) / 2; |
| 22 |
amortized.max(required) |
| 23 |
} |
| 24 |
|
| 25 |
#[repr(C)] |
| 26 |
pub(crate) struct HeapBuffer { |
| 27 |
pub(crate) ptr: ptr::NonNull<u8>, |
| 28 |
pub(crate) len: usize, |
| 29 |
pub(crate) cap: Capacity, |
| 30 |
} |
| 31 |
static_assertions::assert_eq_size!(HeapBuffer, Repr); |
| 32 |
static_assertions::assert_eq_align!(HeapBuffer, Repr); |
| 33 |
|
| 34 |
impl HeapBuffer { |
| 35 |
/// Allocate a heap buffer, copy `text` into it, and return the raw `(ptr, capacity)` pair |
| 36 |
/// instead of a full [`HeapBuffer`]. The shared cold core behind `new` / `alloc_copy_panic`. |
| 37 |
/// |
| 38 |
/// N.B. The caller assembles the [`HeapBuffer`] themself. Returning the two-word |
| 39 |
/// `(ptr, capacity)`, which gets passed in registers, rather than a 24-byte |
| 40 |
/// `HeapBuffer` avoids a by-value aggregate return across this outlined call boundary. |
| 41 |
/// |
| 42 |
/// The aggregate return otherwise forced the whole of `Repr::new`/`new_panic`, including |
| 43 |
/// their hot inline arm, through a stack temporary that LLVM scatter-copied into the |
| 44 |
/// return slot on x86, causing a forwarding stall on every construction. |
| 45 |
/// |
| 46 |
/// `#[cold]`/`#[inline(never)]` keeps the alloc/copy machinery out of line and lays |
| 47 |
/// the heap arm out cold at every callsite. |
| 48 |
#[cold] |
| 49 |
#[inline(never)] |
| 50 |
pub(crate) fn alloc_copy(text: &str) -> Result<(ptr::NonNull<u8>, Capacity), ReserveError> { |
| 51 |
let len = text.len(); |
| 52 |
let (cap, ptr) = allocate_ptr(len)?; |
| 53 |
|
| 54 |
// copy our string into the buffer we just allocated |
| 55 |
// |
| 56 |
// SAFETY: `src` (`text`) and `dest` (`ptr`) are both valid for `len` bytes. `len` |
| 57 |
// comes from `src`, and `dest` was freshly allocated with at least that length. |
| 58 |
// And they don't overlap because `dest` is newly allocated. |
| 59 |
unsafe { super::copy_medium(text.as_ptr(), ptr.as_ptr(), len) }; |
| 60 |
|
| 61 |
Ok((ptr, cap)) |
| 62 |
} |
| 63 |
|
| 64 |
/// Create a [`HeapBuffer`] with the provided text. |
| 65 |
/// |
| 66 |
/// N.B. `#[inline(always)]` so the `HeapBuffer` is assembled at the callsite from |
| 67 |
/// the register-passed `(ptr, capacity)`. It's important only that pair crosses the |
| 68 |
/// cold [`alloc_copy`] boundary. |
| 69 |
#[inline(always)] |
| 70 |
pub(crate) fn new(text: &str) -> Result<Self, ReserveError> { |
| 71 |
let (ptr, cap) = Self::alloc_copy(text)?; |
| 72 |
Ok(HeapBuffer { |
| 73 |
ptr, |
| 74 |
len: text.len(), |
| 75 |
cap, |
| 76 |
}) |
| 77 |
} |
| 78 |
|
| 79 |
/// Infallible [`alloc_copy`], panicking on allocation failure. |
| 80 |
/// |
| 81 |
/// N.B. `#[inline(always)]` so the `HeapBuffer` is assembled at the callsite from |
| 82 |
/// the register-passed `(ptr, capacity)`. It's important only that pair crosses the |
| 83 |
/// cold [`alloc_copy`] boundary. |
| 84 |
#[inline(always)] |
| 85 |
#[track_caller] |
| 86 |
pub(crate) fn alloc_copy_panic(text: &str) -> HeapBuffer { |
| 87 |
let (ptr, cap) = Self::alloc_copy(text).unwrap_with_msg(); |
| 88 |
HeapBuffer { |
| 89 |
ptr, |
| 90 |
len: text.len(), |
| 91 |
cap, |
| 92 |
} |
| 93 |
} |
| 94 |
|
| 95 |
/// Create an empty [`HeapBuffer`] with a specific capacity |
| 96 |
/// |
| 97 |
/// N.B. `#[inline(always)]` so the `HeapBuffer` is assembled at the callsite from |
| 98 |
/// the register-passed `(ptr, capacity)`. It's important only that pair crosses the |
| 99 |
/// cold [`alloc_copy`] boundary. |
| 100 |
#[inline(always)] |
| 101 |
pub(crate) fn with_capacity(capacity: usize) -> Result<Self, ReserveError> { |
| 102 |
let (ptr, cap) = Self::alloc(capacity)?; |
| 103 |
Ok(HeapBuffer { ptr, len: 0, cap }) |
| 104 |
} |
| 105 |
|
| 106 |
/// Out-of-line allocation core for [`Self::with_capacity`]. |
| 107 |
/// |
| 108 |
/// See [`Self::alloc_copy`] for why it returns the two-word pair instead of a `HeapBuffer`. |
| 109 |
#[cold] |
| 110 |
#[inline(never)] |
| 111 |
fn alloc(capacity: usize) -> Result<(ptr::NonNull<u8>, Capacity), ReserveError> { |
| 112 |
let (cap, ptr) = allocate_ptr(capacity)?; |
| 113 |
Ok((ptr, cap)) |
| 114 |
} |
| 115 |
|
| 116 |
/// Create a [`HeapBuffer`] with `text` that has _at least_ `additional` bytes of capacity |
| 117 |
/// |
| 118 |
/// To prevent frequent re-allocations, this method will create a [`HeapBuffer`] with a capacity |
| 119 |
/// of `text.len() + additional` or `text.len() * 1.5`, whichever is greater |
| 120 |
/// |
| 121 |
/// N.B. `#[inline(always)]` so the `HeapBuffer` is assembled at the callsite from |
| 122 |
/// the register-passed `(ptr, capacity)`. It's important only that pair crosses the |
| 123 |
/// cold [`alloc_copy`] boundary. |
| 124 |
#[inline(always)] |
| 125 |
pub(crate) fn with_additional(text: &str, additional: usize) -> Result<Self, ReserveError> { |
| 126 |
let (ptr, cap) = Self::alloc_copy_extra(text, additional)?; |
| 127 |
Ok(HeapBuffer { |
| 128 |
ptr, |
| 129 |
len: text.len(), |
| 130 |
cap, |
| 131 |
}) |
| 132 |
} |
| 133 |
|
| 134 |
/// Out-of-line allocate+copy core for [`Self::with_additional`]. |
| 135 |
/// |
| 136 |
/// See [`Self::alloc_copy`] for why it returns the two-word pair instead of a `HeapBuffer`. |
| 137 |
#[cold] |
| 138 |
#[inline(never)] |
| 139 |
fn alloc_copy_extra( |
| 140 |
text: &str, |
| 141 |
additional: usize, |
| 142 |
) -> Result<(ptr::NonNull<u8>, Capacity), ReserveError> { |
| 143 |
let len = text.len(); |
| 144 |
let new_capacity = amortized_growth(len, additional); |
| 145 |
let (cap, ptr) = allocate_ptr(new_capacity)?; |
| 146 |
|
| 147 |
// copy our string into the buffer we just allocated |
| 148 |
// |
| 149 |
// SAFETY: We know both `src` and `dest` are valid for respectively reads and writes of |
| 150 |
// length `len` because `len` comes from `src`, and `dest` was allocated to be at least that |
| 151 |
// length. We also know they're non-overlapping because `dest` is newly allocated |
| 152 |
unsafe { super::copy_medium(text.as_ptr(), ptr.as_ptr(), len) }; |
| 153 |
|
| 154 |
Ok((ptr, cap)) |
| 155 |
} |
| 156 |
|
| 157 |
/// Return the capacity of the [`HeapBuffer`] |
| 158 |
#[inline] |
| 159 |
pub(crate) fn capacity(&self) -> usize { |
| 160 |
#[cold] |
| 161 |
fn read_capacity_from_heap(this: &HeapBuffer) -> usize { |
| 162 |
// re-adjust the pointer to include the capacity that's on the heap |
| 163 |
let adj_ptr: *const u8 = this.ptr.as_ptr().wrapping_sub(mem::size_of::<usize>()); |
| 164 |
let mut buf = [0u8; mem::size_of::<usize>()]; |
| 165 |
// SAFETY: `src` and `dst` don't overlap, and are valid for usize number of bytes |
| 166 |
unsafe { |
| 167 |
ptr::copy_nonoverlapping(adj_ptr, buf.as_mut_ptr(), mem::size_of::<usize>()); |
| 168 |
} |
| 169 |
usize::from_ne_bytes(buf) |
| 170 |
} |
| 171 |
|
| 172 |
if self.cap.is_heap() { |
| 173 |
read_capacity_from_heap(self) |
| 174 |
} else { |
| 175 |
// SAFETY: Checked above that the capacity is on the stack |
| 176 |
unsafe { self.cap.as_usize() } |
| 177 |
} |
| 178 |
} |
| 179 |
|
| 180 |
/// Try to grow the [`HeapBuffer`] by reallocating, returning an error if we fail |
| 181 |
pub(crate) fn realloc(&mut self, new_capacity: usize) -> Result<usize, ()> { |
| 182 |
// We can't reallocate to a size less than our length, or else we'd clip the string |
| 183 |
if new_capacity < self.len { |
| 184 |
return Err(()); |
| 185 |
} |
| 186 |
|
| 187 |
// HeapBuffer doesn't support 0 byte heap sizes |
| 188 |
if new_capacity == 0 { |
| 189 |
return Err(()); |
| 190 |
} |
| 191 |
|
| 192 |
// Always allocate at least MIN_HEAP_SIZE |
| 193 |
let new_capacity = cmp::max(new_capacity, MIN_HEAP_SIZE); |
| 194 |
// N.B. must be computed _after_ the MIN_HEAP_SIZE clamp so the stored capacity matches the |
| 195 |
// layout we actually (re)allocate with, otherwise dealloc/realloc get a mismatched layout. |
| 196 |
let new_cap = Capacity::new(new_capacity); |
| 197 |
|
| 198 |
let (new_cap, new_ptr) = match (self.cap.is_heap(), new_cap.is_heap()) { |
| 199 |
// both current and new capacity can be stored inline |
| 200 |
(false, false) => { |
| 201 |
// SAFETY: checked above that our capacity is valid |
| 202 |
let cap = unsafe { self.cap.as_usize() }; |
| 203 |
|
| 204 |
// current capacity is the same as the new, nothing to do! |
| 205 |
if cap == new_capacity { |
| 206 |
return Ok(new_capacity); |
| 207 |
} |
| 208 |
|
| 209 |
let cur_layout = inline_capacity::layout(cap); |
| 210 |
let new_layout = inline_capacity::layout(new_capacity); |
| 211 |
let new_size = new_layout.size(); |
| 212 |
|
| 213 |
// It's possible `new_size` could overflow since inline_capacity::layout pads for |
| 214 |
// alignment |
| 215 |
if new_size < new_capacity { |
| 216 |
return Err(()); |
| 217 |
} |
| 218 |
|
| 219 |
// SAFETY: |
| 220 |
// * We're using the same allocator that we used for `ptr` |
| 221 |
// * The layout is the same because we checked that the capacity is inline |
| 222 |
// * `new_size` will be > 0, we return early if the requested capacity is 0 |
| 223 |
// * Checked above if `new_size` overflowed when rounding to alignment |
| 224 |
match ptr::NonNull::new(unsafe { |
| 225 |
::alloc::alloc::realloc(self.ptr.as_ptr(), cur_layout, new_size) |
| 226 |
}) { |
| 227 |
Some(ptr) => (new_cap, ptr), |
| 228 |
None => return Err(()), |
| 229 |
} |
| 230 |
} |
| 231 |
// both current and new capacity need to be stored on the heap |
| 232 |
(true, true) => { |
| 233 |
let cur_layout = heap_capacity::layout(self.capacity()); |
| 234 |
let new_layout = heap_capacity::layout(new_capacity); |
| 235 |
let new_size = new_layout.size(); |
| 236 |
|
| 237 |
// alloc::realloc requires that size > 0 |
| 238 |
debug_assert!(new_size > 0); |
| 239 |
|
| 240 |
// It's possible `new_size` could overflow since heap_capacity::layout requires a |
| 241 |
// few additional bytes |
| 242 |
if new_size < new_capacity { |
| 243 |
return Err(()); |
| 244 |
} |
| 245 |
|
| 246 |
// move our pointer back one WORD since our capacity is behind it |
| 247 |
let raw_ptr = self.ptr.as_ptr(); |
| 248 |
let adj_ptr = raw_ptr.wrapping_sub(mem::size_of::<usize>()); |
| 249 |
|
| 250 |
// SAFETY: |
| 251 |
// * We're using the same allocator that we used for `ptr` |
| 252 |
// * The layout is the same because we checked that the capacity is on the heap |
| 253 |
// * `new_size` will be > 0, we return early if the requested capacity is 0 |
| 254 |
// * Checked above if `new_size` overflowed when rounding to alignment |
| 255 |
let cap_ptr = unsafe { alloc::alloc::realloc(adj_ptr, cur_layout, new_size) }; |
| 256 |
// Check if reallocation succeeded |
| 257 |
if cap_ptr.is_null() { |
| 258 |
return Err(()); |
| 259 |
} |
| 260 |
|
| 261 |
// Our allocation succeeded! Write the new capacity |
| 262 |
// |
| 263 |
// SAFETY: |
| 264 |
// * `src` and `dst` are both valid for reads of `usize` number of bytes |
| 265 |
// * `src` and `dst` don't overlap because we created `src` |
| 266 |
unsafe { |
| 267 |
ptr::copy_nonoverlapping( |
| 268 |
new_capacity.to_ne_bytes().as_ptr(), |
| 269 |
cap_ptr, |
| 270 |
mem::size_of::<usize>(), |
| 271 |
) |
| 272 |
}; |
| 273 |
|
| 274 |
// Finally, adjust our pointer backup so it points at the string content |
| 275 |
let str_ptr = cap_ptr.wrapping_add(mem::size_of::<usize>()); |
| 276 |
// SAFETY: We checked above to make sure the pointer was non-null |
| 277 |
let ptr = unsafe { ptr::NonNull::new_unchecked(str_ptr) }; |
| 278 |
|
| 279 |
(new_cap, ptr) |
| 280 |
} |
| 281 |
// capacity is currently inline or on the heap, but needs to move, can't realloc because |
| 282 |
// we'd need to change the layout! |
| 283 |
(false, true) | (true, false) => return Err(()), |
| 284 |
}; |
| 285 |
|
| 286 |
// set our new pointer and new capacity |
| 287 |
self.ptr = new_ptr; |
| 288 |
self.cap = new_cap; |
| 289 |
|
| 290 |
Ok(new_capacity) |
| 291 |
} |
| 292 |
|
| 293 |
/// Set's the length of the content for this [`HeapBuffer`] |
| 294 |
/// |
| 295 |
/// # SAFETY: |
| 296 |
/// * The caller must guarantee that `len` bytes in the buffer are valid UTF-8 |
| 297 |
#[inline] |
| 298 |
pub(crate) unsafe fn set_len(&mut self, len: usize) { |
| 299 |
self.len = len; |
| 300 |
} |
| 301 |
|
| 302 |
/// Deallocates the memory owned by the provided [`HeapBuffer`] |
| 303 |
#[inline] |
| 304 |
pub(crate) fn dealloc(&mut self) { |
| 305 |
deallocate_ptr(self.ptr, self.cap); |
| 306 |
} |
| 307 |
} |
| 308 |
|
| 309 |
impl Clone for HeapBuffer { |
| 310 |
fn clone(&self) -> Self { |
| 311 |
// Create a new HeapBuffer with the same capacity as the original |
| 312 |
let mut new = Self::with_capacity(self.capacity()).unwrap_with_msg(); |
| 313 |
|
| 314 |
// SAFETY: |
| 315 |
// * `src` and `dst` don't overlap because we just created `dst` |
| 316 |
// * `src` and `dst` are both valid for `self.len` bytes because self.len < capacity |
| 317 |
unsafe { super::copy_medium(self.ptr.as_ptr(), new.ptr.as_ptr(), self.len) }; |
| 318 |
// SAFETY: |
| 319 |
// * We copied the text from self, which is valid UTF-8 |
| 320 |
unsafe { new.set_len(self.len) }; |
| 321 |
|
| 322 |
new |
| 323 |
} |
| 324 |
} |
| 325 |
|
| 326 |
impl Drop for HeapBuffer { |
| 327 |
fn drop(&mut self) { |
| 328 |
self.dealloc() |
| 329 |
} |
| 330 |
} |
| 331 |
|
| 332 |
/// Allocates a buffer on the heap that we can use to store a string, optionally stores the capacity |
| 333 |
/// of said buffer on the heap. |
| 334 |
/// |
| 335 |
/// Returns a [`Capacity`] that either indicates the capacity is stored on the heap, or is stored |
| 336 |
/// in the `Capacity` itself. |
| 337 |
#[inline] |
| 338 |
pub(crate) fn allocate_ptr(capacity: usize) -> Result<(Capacity, ptr::NonNull<u8>), ReserveError> { |
| 339 |
// We allocate at least MIN_HEAP_SIZE bytes because we need to allocate at least one byte |
| 340 |
let capacity = capacity.max(MIN_HEAP_SIZE); |
| 341 |
let cap = Capacity::new(capacity); |
| 342 |
|
| 343 |
// HeapBuffer doesn't support 0 sized allocations, we should always allocate at least |
| 344 |
// MIN_HEAP_SIZE bytes |
| 345 |
debug_assert!(capacity > 0); |
| 346 |
|
| 347 |
#[cold] |
| 348 |
fn allocate_with_capacity_on_heap(capacity: usize) -> Result<ptr::NonNull<u8>, ReserveError> { |
| 349 |
// write our capacity onto the heap |
| 350 |
// SAFETY: we know that the capacity is not zero |
| 351 |
let ptr = unsafe { heap_capacity::alloc(capacity)? }; |
| 352 |
// SAFETY: |
| 353 |
// * `src` and `dst` don't overlap and are both valid for `usize` bytes |
| 354 |
unsafe { |
| 355 |
ptr::copy_nonoverlapping( |
| 356 |
capacity.to_ne_bytes().as_ptr(), |
| 357 |
ptr.as_ptr(), |
| 358 |
mem::size_of::<usize>(), |
| 359 |
) |
| 360 |
}; |
| 361 |
let raw_ptr = ptr.as_ptr().wrapping_add(core::mem::size_of::<usize>()); |
| 362 |
// SAFETY: We know `raw_ptr` is non-null because we just created it |
| 363 |
Ok(unsafe { ptr::NonNull::new_unchecked(raw_ptr) }) |
| 364 |
} |
| 365 |
|
| 366 |
let ptr = if cap.is_heap() { |
| 367 |
allocate_with_capacity_on_heap(capacity) |
| 368 |
} else { |
| 369 |
unsafe { inline_capacity::alloc(capacity) } |
| 370 |
}; |
| 371 |
|
| 372 |
Ok((cap, ptr?)) |
| 373 |
} |
| 374 |
|
| 375 |
/// Deallocates a buffer on the heap, handling when the capacity is also stored on the heap |
| 376 |
#[inline] |
| 377 |
pub(crate) fn deallocate_ptr(ptr: ptr::NonNull<u8>, cap: Capacity) { |
| 378 |
#[cold] |
| 379 |
fn deallocate_with_capacity_on_heap(ptr: ptr::NonNull<u8>) { |
| 380 |
// re-adjust the pointer to include the capacity that's on the heap |
| 381 |
let adj_ptr = ptr.as_ptr().wrapping_sub(mem::size_of::<usize>()); |
| 382 |
// read the capacity from the heap so we know how much to deallocate |
| 383 |
let mut buf = [0u8; mem::size_of::<usize>()]; |
| 384 |
// SAFETY: `src` and `dst` don't overlap, and are valid for usize number of bytes |
| 385 |
unsafe { |
| 386 |
ptr::copy_nonoverlapping(adj_ptr, buf.as_mut_ptr(), mem::size_of::<usize>()); |
| 387 |
} |
| 388 |
let capacity = usize::from_ne_bytes(buf); |
| 389 |
// SAFETY: We know the pointer is not null since we got it as a NonNull |
| 390 |
let ptr = unsafe { ptr::NonNull::new_unchecked(adj_ptr) }; |
| 391 |
// SAFETY: We checked above that our capacity is on the heap, and we readjusted the |
| 392 |
// pointer to reference the capacity |
| 393 |
unsafe { heap_capacity::dealloc(ptr, capacity) } |
| 394 |
} |
| 395 |
|
| 396 |
if cap.is_heap() { |
| 397 |
deallocate_with_capacity_on_heap(ptr); |
| 398 |
} else { |
| 399 |
// SAFETY: Our capacity is always inline on 64-bit archs |
| 400 |
unsafe { inline_capacity::dealloc(ptr, cap.as_usize()) } |
| 401 |
} |
| 402 |
} |
| 403 |
|
| 404 |
/// SAFETY: `layout` must not be zero sized |
| 405 |
#[inline] |
| 406 |
pub(crate) unsafe fn do_alloc(layout: Layout) -> Result<ptr::NonNull<u8>, ReserveError> { |
| 407 |
debug_assert!(layout.size() > 0); |
| 408 |
|
| 409 |
// SAFETY: `alloc(...)` has undefined behavior if the layout is zero-sized. We specify that |
| 410 |
// `capacity` must be > 0 as a constraint to uphold the safety of this method. If capacity |
| 411 |
// is greater than 0, then our layout will be non-zero-sized. |
| 412 |
let raw_ptr = ::alloc::alloc::alloc(layout); |
| 413 |
|
| 414 |
// Check to make sure our pointer is non-null. |
| 415 |
// Implementations are encouraged to return null on memory exhaustion rather than aborting. |
| 416 |
ptr::NonNull::new(raw_ptr).ok_or(ReserveError(())) |
| 417 |
} |
| 418 |
|
| 419 |
mod heap_capacity { |
| 420 |
use core::{alloc, ptr}; |
| 421 |
|
| 422 |
use super::{do_alloc, StrBuffer}; |
| 423 |
use crate::ReserveError; |
| 424 |
|
| 425 |
/// SAFETY: `capacity` must not be zero |
| 426 |
pub(crate) unsafe fn alloc(capacity: usize) -> Result<ptr::NonNull<u8>, ReserveError> { |
| 427 |
do_alloc(layout(capacity)) |
| 428 |
} |
| 429 |
|
| 430 |
/// Deallocates a pointer which references a `HeapBuffer` whose capacity is on the heap |
| 431 |
/// |
| 432 |
/// # Safety |
| 433 |
/// * `ptr` must point to the start of a `HeapBuffer` whose capacity is on the heap. i.e. we |
| 434 |
/// must have `ptr -> [cap<usize> ; string<bytes>]` |
| 435 |
pub(crate) unsafe fn dealloc(ptr: ptr::NonNull<u8>, capacity: usize) { |
| 436 |
let layout = layout(capacity); |
| 437 |
::alloc::alloc::dealloc(ptr.as_ptr(), layout); |
| 438 |
} |
| 439 |
|
| 440 |
#[repr(C)] |
| 441 |
struct HeapBufferInnerHeapCapacity { |
| 442 |
capacity: usize, |
| 443 |
buffer: StrBuffer, |
| 444 |
} |
| 445 |
|
| 446 |
#[inline(always)] |
| 447 |
pub(crate) fn layout(capacity: usize) -> alloc::Layout { |
| 448 |
let buffer_layout = alloc::Layout::array::<u8>(capacity).expect("valid capacity"); |
| 449 |
alloc::Layout::new::<HeapBufferInnerHeapCapacity>() |
| 450 |
.extend(buffer_layout) |
| 451 |
.expect("valid layout") |
| 452 |
.0 |
| 453 |
.pad_to_align() |
| 454 |
} |
| 455 |
} |
| 456 |
|
| 457 |
mod inline_capacity { |
| 458 |
use core::{alloc, ptr}; |
| 459 |
|
| 460 |
use super::{do_alloc, StrBuffer}; |
| 461 |
use crate::ReserveError; |
| 462 |
|
| 463 |
/// # SAFETY: |
| 464 |
/// * `capacity` must be > 0 |
| 465 |
pub(crate) unsafe fn alloc(capacity: usize) -> Result<ptr::NonNull<u8>, ReserveError> { |
| 466 |
do_alloc(layout(capacity)) |
| 467 |
} |
| 468 |
|
| 469 |
/// Deallocates a pointer which references a `HeapBuffer` whose capacity is stored inline |
| 470 |
/// |
| 471 |
/// # Safety |
| 472 |
/// * `ptr` must point to the start of a `HeapBuffer` whose capacity is on the inline |
| 473 |
pub(crate) unsafe fn dealloc(ptr: ptr::NonNull<u8>, capacity: usize) { |
| 474 |
let layout = layout(capacity); |
| 475 |
::alloc::alloc::dealloc(ptr.as_ptr(), layout); |
| 476 |
} |
| 477 |
|
| 478 |
#[repr(C)] |
| 479 |
struct HeapBufferInnerInlineCapacity { |
| 480 |
buffer: StrBuffer, |
| 481 |
} |
| 482 |
|
| 483 |
#[inline(always)] |
| 484 |
pub(crate) fn layout(capacity: usize) -> alloc::Layout { |
| 485 |
let buffer_layout = alloc::Layout::array::<u8>(capacity).expect("valid capacity"); |
| 486 |
alloc::Layout::new::<HeapBufferInnerInlineCapacity>() |
| 487 |
.extend(buffer_layout) |
| 488 |
.expect("valid layout") |
| 489 |
.0 |
| 490 |
.pad_to_align() |
| 491 |
} |
| 492 |
} |
| 493 |
|
| 494 |
#[cfg(test)] |
| 495 |
mod test { |
| 496 |
use test_case::test_case; |
| 497 |
|
| 498 |
use super::{HeapBuffer, MIN_HEAP_SIZE}; |
| 499 |
|
| 500 |
const EIGHTEEN_MB: usize = 18 * 1024 * 1024; |
| 501 |
|
| 502 |
#[test] |
| 503 |
fn test_min_capacity() { |
| 504 |
let h = HeapBuffer::new("short").unwrap(); |
| 505 |
assert_eq!(h.capacity(), MIN_HEAP_SIZE); |
| 506 |
} |
| 507 |
|
| 508 |
#[test_case(&[42; 8]; "short")] |
| 509 |
#[test_case(&[42; 50]; "long")] |
| 510 |
#[test_case(&[42; EIGHTEEN_MB]; "huge")] |
| 511 |
fn test_capacity(buf: &[u8]) { |
| 512 |
// we know the buffer is valid UTF-8 |
| 513 |
let s = unsafe { core::str::from_utf8_unchecked(buf) }; |
| 514 |
let h = HeapBuffer::new(s).unwrap(); |
| 515 |
|
| 516 |
assert_eq!(h.capacity(), core::cmp::max(s.len(), MIN_HEAP_SIZE)); |
| 517 |
} |
| 518 |
|
| 519 |
#[test_case(&[42; 0], 0, Err(MIN_HEAP_SIZE); "empty_empty")] |
| 520 |
#[test_case(&[42; 64], 0, Err(64); "short_empty")] |
| 521 |
#[test_case(&[42; 64], 32, Err(64); "short_to_shorter")] |
| 522 |
#[test_case(&[42; 64], 128, Ok(128); "short_to_longer")] |
| 523 |
#[test_case(&[42; EIGHTEEN_MB], EIGHTEEN_MB + 128, Ok(EIGHTEEN_MB + 128); "heap_to_heap")] |
| 524 |
fn test_realloc(buf: &[u8], realloc: usize, result: Result<usize, usize>) { |
| 525 |
// we know the buffer is valid UTF-8 |
| 526 |
let s = unsafe { core::str::from_utf8_unchecked(buf) }; |
| 527 |
let mut h = HeapBuffer::new(s).unwrap(); |
| 528 |
|
| 529 |
// reallocate, asserting our result |
| 530 |
let expected_cap = match result { |
| 531 |
Ok(c) | Err(c) => c, |
| 532 |
}; |
| 533 |
let expected_res = result.map_err(|_| ()); |
| 534 |
assert_eq!(h.realloc(realloc), expected_res); |
| 535 |
assert_eq!(h.capacity(), expected_cap); |
| 536 |
} |
| 537 |
|
| 538 |
#[test] |
| 539 |
fn test_realloc_inline_to_heap() { |
| 540 |
// we know the buffer is valid UTF-8 |
| 541 |
let s = unsafe { core::str::from_utf8_unchecked(&[42; 128]) }; |
| 542 |
let mut h = HeapBuffer::new(s).unwrap(); |
| 543 |
|
| 544 |
cfg_if::cfg_if! { |
| 545 |
if #[cfg(target_pointer_width = "64")] { |
| 546 |
let expected_result = Ok(EIGHTEEN_MB); |
| 547 |
let expected_capacity = EIGHTEEN_MB; |
| 548 |
} else if #[cfg(target_pointer_width = "32")] { |
| 549 |
// on 32-bit architectures we'd need to change the layout from capacity being inline |
| 550 |
// to the capacity being on the heap, which isn't possible |
| 551 |
let expected_result = Err(()); |
| 552 |
let expected_capacity = 128; |
| 553 |
} else { |
| 554 |
compile_error!("Unsupported pointer width!"); |
| 555 |
} |
| 556 |
} |
| 557 |
assert_eq!(h.realloc(EIGHTEEN_MB), expected_result); |
| 558 |
assert_eq!(h.capacity(), expected_capacity); |
| 559 |
} |
| 560 |
|
| 561 |
#[test_case(&[42; 64], 128, 100, Ok(100); "sanity")] |
| 562 |
fn test_realloc_shrink( |
| 563 |
buf: &[u8], |
| 564 |
realloc_one: usize, |
| 565 |
realloc_two: usize, |
| 566 |
exp_result: Result<usize, usize>, |
| 567 |
) { |
| 568 |
// we know the buffer is valid UTF-8 |
| 569 |
let s = unsafe { core::str::from_utf8_unchecked(buf) }; |
| 570 |
let mut h = HeapBuffer::new(s).unwrap(); |
| 571 |
|
| 572 |
assert!( |
| 573 |
realloc_one > realloc_two, |
| 574 |
"we have to grow before we can shrink" |
| 575 |
); |
| 576 |
|
| 577 |
// grow our allocation |
| 578 |
assert_eq!(h.realloc(realloc_one), Ok(realloc_one)); |
| 579 |
|
| 580 |
// shrink our allocation, asserting our result |
| 581 |
let expected_cap = match exp_result { |
| 582 |
Ok(c) | Err(c) => c, |
| 583 |
}; |
| 584 |
let expected_res = exp_result.map_err(|_| ()); |
| 585 |
assert_eq!(h.realloc(realloc_two), expected_res); |
| 586 |
assert_eq!(h.capacity(), expected_cap); |
| 587 |
} |
| 588 |
|
| 589 |
#[test] |
| 590 |
fn test_realloc_shrink_heap_to_inline() { |
| 591 |
// TODO: test this case |
| 592 |
assert_eq!(1, 1); |
| 593 |
} |
| 594 |
|
| 595 |
#[test] |
| 596 |
fn test_realloc_shrink_to_min_heap_gap() { |
| 597 |
// Shrinking to a size in (MAX_SIZE, MIN_HEAP_SIZE) must store the clamped |
| 598 |
// capacity, otherwise the recorded capacity won't match the actual allocation |
| 599 |
// layout. |
| 600 |
let mut h = HeapBuffer::with_capacity(100).unwrap(); |
| 601 |
let target = super::MAX_SIZE + 1; |
| 602 |
assert!(target < MIN_HEAP_SIZE); |
| 603 |
|
| 604 |
assert_eq!(h.realloc(target), Ok(MIN_HEAP_SIZE)); |
| 605 |
assert_eq!(h.capacity(), MIN_HEAP_SIZE); |
| 606 |
// Drop runs dealloc with the stored capacity; under miri this fails if the layout is wrong. |
| 607 |
} |
| 608 |
|
| 609 |
#[test_case(&[42; 0]; "empty")] |
| 610 |
#[test_case(&[42; 3]; "short")] |
| 611 |
#[test_case(&[42; 64]; "long")] |
| 612 |
#[test_case(&[42; EIGHTEEN_MB]; "huge")] |
| 613 |
fn test_clone(buf: &[u8]) { |
| 614 |
let s = unsafe { core::str::from_utf8_unchecked(buf) }; |
| 615 |
let h_a = HeapBuffer::new(s).unwrap(); |
| 616 |
let h_b = h_a.clone(); |
| 617 |
|
| 618 |
assert_eq!(h_a.capacity(), h_b.capacity()); |
| 619 |
} |
| 620 |
} |