ItEr49S04ValidacionEProbasFuncionaisItEr48S04: ShareDivision now takes into account integer overflows.

Now can handle very big int numbers.
This commit is contained in:
Óscar González Fernández 2010-03-03 16:48:54 +01:00
parent 74cfd2c7bf
commit 6a4e16a17c
2 changed files with 31 additions and 5 deletions

View file

@ -47,7 +47,9 @@ public class ShareDivision {
@Override
public int compareTo(ShareWrapper other) {
return share.getHours() - other.share.getHours();
long thisHours = share.getHours();
long otherHours = other.share.getHours();
return Long.signum(thisHours - otherHours);
}
@Override
@ -185,16 +187,18 @@ public class ShareDivision {
private static FillingBucket fillingBuckectFor(List<ShareWrapper> wrappers,
int end, int remaining) {
int hoursToDistribute = end == wrappers.size() ? remaining : Math.min(
hoursNeededToBeEqual(wrappers, 0, end), remaining);
int hoursToDistribute = end == wrappers.size() ? remaining : (int) Math
.min(hoursNeededToBeEqual(wrappers, 0, end), remaining);
return new FillingBucket(wrappers.subList(0, end), hoursToDistribute);
}
private static int hoursNeededToBeEqual(List<ShareWrapper> wrappers,
private static long hoursNeededToBeEqual(List<ShareWrapper> wrappers,
int startInclusive, int endExclusive) {
ShareWrapper nextLevel = wrappers.get(endExclusive);
ShareWrapper currentLevel = wrappers.get(startInclusive);
int difference = nextLevel.getHours() - currentLevel.getHours();
long currentLevelHours = (long) currentLevel.getHours();
long difference = nextLevel.getHours() - currentLevelHours;
// difference must be long in order to avoid integer overflow
assert difference > 0;
return (endExclusive - startInclusive) * difference;
}

View file

@ -20,6 +20,7 @@
package org.navalplanner.business.test.planner.entities;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;
@ -143,6 +144,27 @@ public class ShareDivisionTest {
assertTrue(Arrays.equals(difference, new int[] { -1, 6, 1 }));
}
@Test
public void canHandleMaximumValueIntegers() {
givenDivisionShare(new Share(2), new Share(0), new Share(
Integer.MAX_VALUE), new Share(Integer.MAX_VALUE), new Share(
Integer.MAX_VALUE));
ShareDivision plus = shareDivision.plus(10);
int[] difference = shareDivision.to(plus);
assertArrayEquals(new int[] { 4, 6, 0, 0, 0 }, difference);
}
@Test
public void canHandleMaximumValueIntegersAndMinimumValue() {
givenDivisionShare(new Share(Integer.MIN_VALUE), new Share(
Integer.MAX_VALUE), new Share(Integer.MAX_VALUE), new Share(
Integer.MIN_VALUE), new Share(Integer.MIN_VALUE), new Share(
Integer.MAX_VALUE));
ShareDivision plus = shareDivision.plus(9);
int[] difference = shareDivision.to(plus);
assertArrayEquals(new int[] { 3, 0, 0, 3, 3, 0 }, difference);
}
@Test
@Ignore("TODO handling substractions")
public void canDistributeSubstraction() {