Allocations { public void allocate(Treatment treatment, int size) { Preconditions.checkArgument( getUnallocatedSize() >= size, "not enough free bins to allocate treatment %s with size %s given %s unallocated bin(s)", treatment.getName(), size, getUnallocatedSize() ); final List<Allocation> pieces = Lists.newArrayList(); int sizeLeft = size; int offset = 0; int index = 0; while (sizeLeft > 0) { if (index < allocations.size()) { final Allocation allocation = allocations.get(index); final int pieceSize = allocation.getOffset() - offset; if (pieceSize > 0) { sizeLeft -= pieceSize; pieces.add(new Allocation(treatment, offset, pieceSize)); } offset = allocation.getOffset() + allocation.getSize(); index++; } else { pieces.add(new Allocation(treatment, offset, sizeLeft)); sizeLeft = 0; } } 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(expected = IllegalArgumentException.class) public void testAllocatingTooMuch() { final Allocations allocations = new Allocations(Lists.<Allocation>newArrayList()); allocations.allocate(control, Allocations.NUM_BINS + 1); }
@Test public void testAllocate() { final Allocations allocations = new Allocations(Lists.<Allocation>newArrayList()); allocations.allocate(control, 10); allocations.allocate(withLogin, 20); allocations.allocate(withoutLogin, 30); assertEquals( "should be three contiguous allocations of various sizes", Lists.newArrayList( new Allocation(control, 0, 10), new Allocation(withLogin, 10, 20), new Allocation(withoutLogin, 30, 30) ), allocations.getAllocations() ); }