Allocations { public void reallocate(Treatment source, Treatment destination, int size) { final Iterator<Allocation> iter = allocations.iterator(); final List<Allocation> pieces = Lists.newArrayList(); int sizeLeft = size; int lastOffset = 0; while (iter.hasNext() && sizeLeft > 0) { final Allocation next = iter.next(); lastOffset = next.getOffset() + next.getSize(); if (!next.getTreatment().equals(source)) { continue; } sizeLeft -= next.getSize(); iter.remove(); if (sizeLeft < 0) { pieces.add(new Allocation(destination, next.getOffset(), next.getSize() + sizeLeft)); pieces.add(new Allocation(source, next.getOffset() + next.getSize() + sizeLeft, -sizeLeft)); } else { pieces.add(new Allocation(destination, next.getOffset(), next.getSize())); } } if (sizeLeft > 0) { pieces.add(new Allocation(destination, lastOffset, sizeLeft)); } allocations.addAll(pieces); sortAllocations(); mergeAdjacentAllocations(); rebuildAllocationTables(); } Allocations();  Allocations(Iterable<Allocation> allocations); Treatment getTreatment(int bin); void allocate(Treatment treatment, int size); void deallocate(Treatment treatment, int size); void reallocate(Treatment source, Treatment destination, int size); List<Allocation> getAllocations(); int getSize(); int getUnallocatedSize(); void clear(); static final int NUM_BINS; }
@Test public void testReallocate() { final Allocations allocations = new Allocations(Lists.<Allocation>newArrayList()); allocations.allocate(control, 5); allocations.allocate(withLogin, 5); allocations.reallocate(withLogin, control, 3); assertEquals( "reallocation should have partly replaced second allocation and merged with first allocation", Lists.newArrayList( new Allocation(control, 0, 8), new Allocation(withLogin, 8, 2) ), allocations.getAllocations() ); }