pub fn free(&mut self, pointer: Pointer, mut slots: usize) -> usize {
        let mut pointer: PointerIdx = pointer.into();

        // merge it with any other nearby ranges
        // start with the range before
        if let Some((pointer_before, size)) = self.ranges.range(..pointer).rev().next() {
            let (pointer_before, size) = (*pointer_before, *size);

            // if the free ranges are back-to-back, we merge them by extending the old range
            if pointer_before + size as u64 == pointer {
                // use the new combined pointer
                self.mark(pointer_before);
                pointer = pointer_before;
                slots = size + slots;
            }
        }

        // then do the range after
        // pointer has not yet beed added to the ranges map,
        // so `pointer..` is technically exclusive
        if let Some((pointer_after, size)) = self.ranges.range(pointer..).next() {
            let (pointer_after, size) = (*pointer_after, *size);
            if pointer + size as u64 == pointer_after {
                // extend the pointer to be longer
                self.mark(pointer_after);
                slots += size;
            }
        }

        // if this is a tail free, reduce the size of the heap
        if pointer.to_usize() + slots== self.capacity {
            self.capacity -= slots;
            return slots;
        }

        // add the pointer with its new size in the free map
        // add the pointer with its new size to the ranges map
        if let Some(s) = self.free.get_mut(&slots) {
            s.insert(pointer);
        } else {
            let mut pointers = BTreeSet::new();
            pointers.insert(pointer);
            self.free.insert(slots, pointers);
        }

        // not a tail free, there still may be an allocation after this one
        // return 0 to keep slots
        assert!(self.ranges.insert(pointer, slots).is_none());
        return 0;
    }
Returns capacity that the heap can be shrunk by if freeing a tail allocation
passerine-qualm/src/heap/range_set.rs