Cole-Greer commented on code in PR #3153:
URL: https://github.com/apache/tinkerpop/pull/3153#discussion_r2226368605
##########
gremlin-core/src/main/java/org/apache/tinkerpop/gremlin/util/NumberHelper.java:
##########
@@ -721,6 +723,86 @@ public static Number coerceTo(final Number a, final
Class<? extends Number> claz
return a;
}
+ /**
+ * Casts the given number to the specified numeric type if it can fit into
it.
+ * Otherwise, throw.
+ *
+ * @param a the number to be cast
+ * @param numberToken the number token denoting the desired type to cast
+ * @return the number cast to the specified type
+ * @throws IllegalArgumentException if the specified numeric type is
unsupported
+ * @throws ArithmeticException if the number overflows
+ */
+ public static Number castTo(final Number a, final N numberToken) {
+ Class<?> clazz = numberToken.getType();
+ if (a.getClass().equals(clazz)) {
+ return a;
+ } else if (clazz.equals(Integer.class)) {
+ Long val = getLong(a, numberToken);
+ if (val >= Integer.MIN_VALUE && val <= Integer.MAX_VALUE) {
+ return a.intValue();
+ }
+ } else if (clazz.equals(Long.class)) {
+ return getLong(a, numberToken);
Review Comment:
There's a strange inconsistency that arises by using long as the
intermediate form for all of these integer types.
```
gremlin> g.inject(new Double(Integer.MAX_VALUE+"1")).asNumber(N.nint)
Can't convert number of type Double to Integer due to overflow.
Type ':help' or ':h' for help.
gremlin> g.inject(new Double(Long.MAX_VALUE+"1")).asNumber(N.nlong)
==>9223372036854775807
```
Double.longValue() does a primitive cast from `double` to `long`, which
implicitly binds out-of-range values to Long.MAX_VALUE or Long.MIN_VALUE.
Perhaps an extra check is needed in getLong() to throw an exception if the
value exceeds the range of a long. The same concern would apply to
float-to-long conversions.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: [email protected]
For queries about this service, please contact Infrastructure at:
[email protected]