sclass FreeList64 { MultiSetMap byLength = multiSetMap_innerCustomCompactTreeSet_outerTreeMap(longRangeComparatorByStart()); CompactTreeSet inOrder = new(longRangeComparatorByStart()); long totalFree; void add(LongRange r) { if (empty(r)) ret; // only special case here is merging with previous and/or following entry LongRange before = inOrder.floor(r), after = inOrder.ceiling(r); if (before != null && before.end == r.start) { r = LongRange(before.start, r.end); remove(before); } if (after != null && after.start == r.end) { r = LongRange(r.start, after.end); remove(after); } inOrder.add(r); byLength.add(r.length(), r); totalFree += r.length(); } void remove(LongRange r) { if (empty(r)) ret; LongRange r2 = inOrder.floor(r); if (r2 == null) fail("User error"); if (eq(r, r2)) { inOrder.remove(r2); byLength.remove(r2.length(), r2); totalFree -= r2.length(); ret; } // remove full range, add back left and right remainders remove(r2); add(LongRange(r2.start, r.start)); add(LongRange(r.end, r2.end)); } LongRange findFreeSpace(long minSize) { Map.Entry> e = ((NavigableMap) byLength.data).ceilingEntry(minSize); ret e == null ? null : first(e.getValue()); } long totalFree() { ret totalFree; } void clear { byLength.clear(); inOrder.clear(); totalFree = 0; } LongRange highestFreeRange() { ret last(inOrder); } }