Returning full allocation causes problem with hashbrown?

โš“ Rust    ๐Ÿ“… 2026-04-05    ๐Ÿ‘ค surdeus    ๐Ÿ‘๏ธ 7      

surdeus

I have been working on my local allocators, and now have a local allocator that keeps chains of freed memory ( for different size classes ).

But something I donโ€™t understand is if I return the full amount reserved from allocate, rather than the amount requested, everything goes haywire and it seems like my hashbrown HashMaps donโ€™t work any more. I havenโ€™t investigated at all yet, it is also quite possible the problem is with my code rather than hashbrown.

Code for allocate:

fn allocate(&mut self, lay: Layout) -> Result<NonNull<[u8]>, AllocError> {
        self.alloc_count += 1;
        let n = lay.size();
        if NOT_MIRI && n <= MAX_SIZE {
            #[cfg(feature = "log-bump")]
            {
                self._alloc_bytes += n;
                self._total_count += 1;
                self._total_alloc += n;
            };
            let (sc, xn) = Self::sc(n);
            let p = self.free[sc];
            if !p.is_null() {
                let next = unsafe { (*p).next };
                self.free[sc] = next;
                let p = p as *mut u8;
                let p = slice_from_raw_parts_mut(p, n);
                Ok(unsafe { NonNull::new_unchecked(p) })
            } else {
                let m = lay.align();
                let mut i = self.idx.checked_next_multiple_of(m).unwrap();
                let e = i + xn;
                // Make a new block if necessary.
                if e > BSIZE {
                    let old = mem::replace(&mut self.cur, Block::new());
                    self.overflow.push(old);
                    i = 0;
                }
                self.idx = i + xn;
                Ok(self.cur.alloc(i, n)) // Ought to be able to return xn, but that causes problems!
            }
        } else {
            Global::allocate(&Global, lay)
        }
    }

The full source code is here:

2 posts - 1 participant

Read full topic

๐Ÿท๏ธ Rust_feed