Skip to content

Commit

Permalink
Fix RawTable::allocation_info for empty table
Browse files Browse the repository at this point in the history
  • Loading branch information
stepancheg committed Jan 6, 2023
1 parent 09dc17e commit 3d94f27
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 1 deletion.
12 changes: 11 additions & 1 deletion src/raw/mod.rs
Expand Up @@ -531,7 +531,12 @@ impl<T, A: Allocator + Clone> RawTable<T, A> {
#[inline]
#[cfg(feature = "raw")]
pub fn allocation_info(&self) -> (NonNull<u8>, Layout) {
self.table.allocation_info(Self::TABLE_LAYOUT)
if self.table.is_empty_singleton() {
// `self.table.allocation_info` can only be called when the table is not empty.
return (NonNull::dangling(), Layout::new::<()>());
} else {
self.table.allocation_info(Self::TABLE_LAYOUT)
}
}

/// Returns the index of a bucket from a `Bucket`.
Expand Down Expand Up @@ -1589,6 +1594,11 @@ impl<A: Allocator + Clone> RawTableInner<A> {

#[inline]
fn allocation_info(&self, table_layout: TableLayout) -> (NonNull<u8>, Layout) {
debug_assert!(
!self.is_empty_singleton(),
"this function can only be called on non-empty tables"
);

// Avoid `Option::unwrap_or_else` because it bloats LLVM IR.
let (layout, ctrl_offset) = match table_layout.calculate_layout_for(self.buckets()) {
Some(lco) => lco,
Expand Down
11 changes: 11 additions & 0 deletions tests/raw.rs
@@ -0,0 +1,11 @@
#![cfg(feature = "raw")]

use hashbrown::raw::RawTable;
use std::mem;

#[test]
fn test_allocation_info() {
assert_eq!(RawTable::<()>::new().allocation_info().1.size(), 0);
assert_eq!(RawTable::<u32>::new().allocation_info().1.size(), 0);
assert!(RawTable::<u32>::with_capacity(1).allocation_info().1.size() > mem::size_of::<u32>());
}

0 comments on commit 3d94f27

Please sign in to comment.