throw exception if you getInt() and the int is out of range

This commit is contained in:
Havoc Pennington 2011-11-18 16:38:28 -05:00
parent 13362f46b4
commit 4f623d9dd5
3 changed files with 38 additions and 6 deletions

View File

@ -3,6 +3,7 @@
*/
package com.typesafe.config.impl;
import com.typesafe.config.ConfigException;
import com.typesafe.config.ConfigOrigin;
abstract class ConfigNumber extends AbstractConfigValue {
@ -17,11 +18,23 @@ abstract class ConfigNumber extends AbstractConfigValue {
this.originalText = originalText;
}
@Override
public abstract Number unwrapped();
@Override
String transformToString() {
return originalText;
}
int intValueRangeChecked(String path) {
long l = longValue();
if (l < Integer.MIN_VALUE || l > Integer.MAX_VALUE) {
throw new ConfigException.WrongType(origin(), path, "32-bit integer",
"out-of-range value " + l);
}
return (int) l;
}
protected abstract long longValue();
protected abstract double doubleValue();

View File

@ -139,15 +139,20 @@ class SimpleConfig implements Config {
return (Boolean) v.unwrapped();
}
private ConfigNumber getConfigNumber(String path) {
ConfigValue v = find(path, ConfigValueType.NUMBER, path);
return (ConfigNumber) v;
}
@Override
public Number getNumber(String path) {
ConfigValue v = find(path, ConfigValueType.NUMBER, path);
return (Number) v.unwrapped();
return getConfigNumber(path).unwrapped();
}
@Override
public int getInt(String path) {
return getNumber(path).intValue();
ConfigNumber n = getConfigNumber(path);
return n.intValueRangeChecked(path);
}
@Override
@ -255,9 +260,9 @@ class SimpleConfig implements Config {
@Override
public List<Integer> getIntList(String path) {
List<Integer> l = new ArrayList<Integer>();
List<Number> numbers = getNumberList(path);
for (Number n : numbers) {
l.add(n.intValue());
List<AbstractConfigValue> numbers = getHomogeneousWrappedList(path, ConfigValueType.NUMBER);
for (AbstractConfigValue v : numbers) {
l.add(((ConfigNumber) v).intValueRangeChecked(path));
}
return l;
}

View File

@ -504,6 +504,20 @@ class ConfigTest extends TestUtils {
testIgnoredMergesDoNothing(root)
}
@Test
def integerRangeChecks() {
val conf = parseConfig("{ tooNegative: " + (Integer.MIN_VALUE - 1L) + ", tooPositive: " + (Integer.MAX_VALUE + 1L) + "}")
val en = intercept[ConfigException.WrongType] {
conf.getInt("tooNegative")
}
assertTrue(en.getMessage.contains("range"))
val ep = intercept[ConfigException.WrongType] {
conf.getInt("tooPositive")
}
assertTrue(ep.getMessage.contains("range"))
}
@Test
def test01Getting() {
val conf = ConfigFactory.load("test01")