Added readFloat to StringReader

This commit is contained in:
Nathan Adams
2017-11-16 14:28:46 +01:00
parent 1b32233044
commit 647f859b63
3 changed files with 83 additions and 2 deletions
@@ -16,6 +16,8 @@ public class StringReader implements ImmutableStringReader {
public static final SimpleCommandExceptionType ERROR_EXPECTED_INT = new SimpleCommandExceptionType("parsing.int.expected", "Expected integer");
public static final ParameterizedCommandExceptionType ERROR_INVALID_DOUBLE = new ParameterizedCommandExceptionType("parsing.double.invalid", "Invalid double '${value}'", "value");
public static final SimpleCommandExceptionType ERROR_EXPECTED_DOUBLE = new SimpleCommandExceptionType("parsing.double.expected", "Expected double");
public static final ParameterizedCommandExceptionType ERROR_INVALID_FLOAT = new ParameterizedCommandExceptionType("parsing.float.invalid", "Invalid float '${value}'", "value");
public static final SimpleCommandExceptionType ERROR_EXPECTED_FLOAT = new SimpleCommandExceptionType("parsing.float.expected", "Expected float");
public static final SimpleCommandExceptionType ERROR_EXPECTED_BOOL = new SimpleCommandExceptionType("parsing.bool.expected", "Expected bool");
public static final ParameterizedCommandExceptionType ERROR_EXPECTED_SYMBOL = new ParameterizedCommandExceptionType("parsing.expected", "Expected '${symbol}'", "symbol");
@@ -93,7 +95,7 @@ public class StringReader implements ImmutableStringReader {
cursor++;
}
private static boolean isAllowedNumber(final char c) {
public static boolean isAllowedNumber(final char c) {
return c >= '0' && c <= '9' || c == '.' || c == '-';
}
@@ -137,6 +139,23 @@ public class StringReader implements ImmutableStringReader {
}
}
public float readFloat() throws CommandSyntaxException {
final int start = cursor;
while (canRead() && isAllowedNumber(peek())) {
skip();
}
final String number = string.substring(start, cursor);
if (number.isEmpty()) {
throw ERROR_EXPECTED_FLOAT.createWithContext(this);
}
try {
return Float.parseFloat(number);
} catch (final NumberFormatException ex) {
cursor = start;
throw ERROR_INVALID_FLOAT.createWithContext(this, number);
}
}
public static boolean isAllowedInUnquotedString(final char c) {
return c >= '0' && c <= '9'
|| c >= 'A' && c <= 'Z'
@@ -45,7 +45,7 @@ public class FloatArgumentType implements ArgumentType<Float> {
@Override
public <S> Float parse(final StringReader reader, final CommandContextBuilder<S> contextBuilder) throws CommandSyntaxException {
final int start = reader.getCursor();
final float result = (float) reader.readDouble();
final float result = reader.readFloat();
if (result < minimum) {
reader.setCursor(start);
throw ERROR_TOO_SMALL.createWithContext(reader, result, minimum);