You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@sis.apache.org by de...@apache.org on 2026/01/05 13:03:28 UTC
(sis) branch geoapi-4.0 updated: Replace the integer values in `Numbers` by a `NumberType` enumeration.
This is an automated email from the ASF dual-hosted git repository.
desruisseaux pushed a commit to branch geoapi-4.0
in repository https://gitbox.apache.org/repos/asf/sis.git
The following commit(s) were added to refs/heads/geoapi-4.0 by this push:
new cf0b508466 Replace the integer values in `Numbers` by a `NumberType` enumeration.
cf0b508466 is described below
commit cf0b50846699c97c6185248607ae5e42df5eaa19
Author: Martin Desruisseaux <ma...@geomatys.com>
AuthorDate: Mon Jan 5 13:20:22 2026 +0100
Replace the integer values in `Numbers` by a `NumberType` enumeration.
---
.../org/apache/sis/coverage/SampleDimension.java | 28 +-
.../sis/feature/builder/FeatureTypeBuilder.java | 4 +-
.../apache/sis/image/BandedSampleConverter.java | 4 +-
.../main/org/apache/sis/image/DataType.java | 28 +-
.../sis/image/internal/shared/ImageUtilities.java | 19 +-
.../image/internal/shared/ImageUtilitiesTest.java | 14 +-
.../org/apache/sis/metadata/PropertyAccessor.java | 8 +-
.../apache/sis/metadata/PropertyInformation.java | 4 +-
.../org/apache/sis/util/iso/RecordDefinition.java | 4 +-
.../main/org/apache/sis/util/iso/TypeNames.java | 6 +-
.../apache/sis/xml/bind/FinalClassExtensions.java | 5 +-
.../sis/metadata/PropertyConsistencyCheck.java | 22 +-
.../apache/sis/metadata/iso/AllMetadataTest.java | 1 +
.../main/org/apache/sis/io/wkt/ElementKind.java | 4 +-
.../main/org/apache/sis/io/wkt/Formatter.java | 4 +-
.../org/apache/sis/io/wkt/MathTransformParser.java | 6 +-
.../sis/parameter/DefaultParameterDescriptor.java | 3 +-
.../sis/parameter/DefaultParameterValue.java | 37 +-
.../org/apache/sis/parameter/MatrixParameters.java | 14 +-
.../main/org/apache/sis/parameter/Verifier.java | 15 +-
.../sis/parameter/DefaultParameterValueTest.java | 2 +-
.../apache/sis/storage/geotiff/NativeMetadata.java | 4 +-
.../apache/sis/storage/geotiff/reader/Type.java | 2 +-
.../apache/sis/storage/netcdf/base/Convention.java | 25 +-
.../apache/sis/storage/netcdf/base/DataType.java | 50 +-
.../sis/storage/netcdf/base/GridMapping.java | 6 +-
.../sis/storage/netcdf/base/RasterResource.java | 6 +-
.../apache/sis/storage/netcdf/base/Variable.java | 8 +-
.../sis/storage/netcdf/base/DataTypeTest.java | 25 +-
.../sis/storage/sql/feature/FeatureAnalyzer.java | 4 +-
.../sis/storage/sql/feature/ValueGetter.java | 8 +-
.../apache/sis/io/stream/HyperRectangleReader.java | 20 +-
.../sis/io/stream/HyperRectangleReaderTest.java | 4 +-
.../org/apache/sis/converter/ArrayConverter.java | 6 +-
.../apache/sis/converter/ConverterRegistry.java | 6 +-
.../org/apache/sis/converter/NumberConverter.java | 10 +-
.../org/apache/sis/converter/StringConverter.java | 6 +-
.../org/apache/sis/converter/SystemRegistry.java | 5 +-
.../main/org/apache/sis/io/CompoundFormat.java | 4 +-
.../main/org/apache/sis/io/DefaultFormat.java | 29 +-
.../main/org/apache/sis/math/ArrayVector.java | 44 +-
.../org/apache/sis/math/ConcatenatedVector.java | 7 +-
.../main/org/apache/sis/math/Fraction.java | 6 +-
.../org/apache/sis/math/LinearlyDerivedVector.java | 5 +-
.../main/org/apache/sis/math/NumberType.java | 791 +++++++++++++++++++++
.../main/org/apache/sis/math/PackedVector.java | 3 +-
.../main/org/apache/sis/math/Vector.java | 75 +-
.../org/apache/sis/measure/MeasurementRange.java | 18 +-
.../main/org/apache/sis/measure/NumberRange.java | 60 +-
.../main/org/apache/sis/measure/Range.java | 4 +-
.../main/org/apache/sis/measure/RangeFormat.java | 19 +-
.../main/org/apache/sis/pending/jdk/JDK12.java | 44 ++
.../main/org/apache/sis/util/Classes.java | 3 +-
.../main/org/apache/sis/util/Numbers.java | 427 ++++-------
.../org/apache/sis/util/collection/RangeSet.java | 16 +-
.../sis/util/collection/TreeTableFormat.java | 4 +-
.../apache/sis/util/internal/shared/Strings.java | 18 +
.../main/org/apache/sis/util/resources/Errors.java | 4 +-
.../apache/sis/util/resources/Errors.properties | 2 +-
.../apache/sis/util/resources/Errors_fr.properties | 2 +-
.../test/org/apache/sis/math/NumberTypeTest.java | 201 ++++++
.../test/org/apache/sis/util/NumbersTest.java | 121 +---
.../org/apache/sis/geometries/math/DataType.java | 27 +-
.../org/apache/sis/gui/coverage/CellFormat.java | 4 +-
64 files changed, 1594 insertions(+), 771 deletions(-)
diff --git a/endorsed/src/org.apache.sis.feature/main/org/apache/sis/coverage/SampleDimension.java b/endorsed/src/org.apache.sis.feature/main/org/apache/sis/coverage/SampleDimension.java
index 8822b35c08..4826bb42de 100644
--- a/endorsed/src/org.apache.sis.feature/main/org/apache/sis/coverage/SampleDimension.java
+++ b/endorsed/src/org.apache.sis.feature/main/org/apache/sis/coverage/SampleDimension.java
@@ -36,6 +36,7 @@ import org.apache.sis.feature.internal.Resources;
import org.apache.sis.measure.MeasurementRange;
import org.apache.sis.measure.NumberRange;
import org.apache.sis.math.MathFunctions;
+import org.apache.sis.math.NumberType;
import org.apache.sis.util.ArgumentChecks;
import org.apache.sis.util.Numbers;
import org.apache.sis.util.Debug;
@@ -278,7 +279,7 @@ public class SampleDimension implements IdentifiedType, Serializable {
if (converse != null) { // Null if SampleDimension does not contain at least one quantitative category.
final boolean isConverted = transferFunction.isIdentity();
final NumberRange<?>[] ranges = new NumberRange<?>[categories.size()];
- Class<? extends Number> widestClass = Byte.class;
+ final Class<?>[] rangeTypes = new Class<?>[ranges.length];
int count = 0;
for (final Category category : categories) {
final Category converted = category.converted();
@@ -287,23 +288,26 @@ public class SampleDimension implements IdentifiedType, Serializable {
if (!range.isBounded()) {
throw new IllegalStateException(Resources.format(Resources.Keys.CanNotEnumerateValuesInRange_1, range));
}
- widestClass = Numbers.widestClass(widestClass, range.getElementType());
+ rangeTypes[count] = range.getElementType();
ranges[count++] = range;
}
}
if (count != 0) {
+ final NumberType widestType = NumberType.forClasses(rangeTypes).filter(NumberType::isConvertible).orElse(null);
final Set<Number> noDataValues = new TreeSet<>(SampleDimension::compare);
for (int i=0; i<count; i++) {
final NumberRange<?> range = ranges[i];
final Number minimum = range.getMinValue();
final Number maximum = range.getMaxValue();
- if (range.isMinIncluded()) noDataValues.add(Numbers.cast(minimum, widestClass));
- if (range.isMaxIncluded()) noDataValues.add(Numbers.cast(maximum, widestClass));
- if (Numbers.isInteger(range.getElementType())) {
+ if (widestType != null) {
+ if (range.isMinIncluded()) noDataValues.add(widestType.cast(minimum));
+ if (range.isMaxIncluded()) noDataValues.add(widestType.cast(maximum));
+ }
+ if (NumberType.isInteger(range.getElementType())) {
long value = minimum.longValue() + 1; // If value was inclusive, then it has already been added to the set.
long stop = maximum.longValue() - 1;
while (value <= stop) {
- noDataValues.add(Numbers.wrap(value, widestClass));
+ noDataValues.add(widestType.wrapExact(value));
}
} else if (!minimum.equals(maximum)) {
throw new IllegalStateException(Resources.format(Resources.Keys.CanNotEnumerateValuesInRange_1, range));
@@ -710,12 +714,12 @@ public class SampleDimension implements IdentifiedType, Serializable {
* <p>This method is invoked for qualitative categories only. For that reason, it accepts NaN values.</p>
*/
private static NumberRange<?> range(final Class<?> type, Number minimum, Number maximum) {
- switch (Numbers.getEnumConstant(type)) {
- case Numbers.BYTE: return NumberRange.create(minimum.byteValue(), true, maximum.byteValue(), true);
- case Numbers.SHORT: return NumberRange.create(minimum.shortValue(), true, maximum.shortValue(), true);
- case Numbers.INTEGER: return NumberRange.create(minimum.intValue(), true, maximum.intValue(), true);
- case Numbers.LONG: return NumberRange.create(minimum.longValue(), true, maximum.longValue(), true);
- case Numbers.FLOAT: {
+ switch (NumberType.forNumberClass(type)) {
+ case BYTE: return NumberRange.create(minimum.byteValue(), true, maximum.byteValue(), true);
+ case SHORT: return NumberRange.create(minimum.shortValue(), true, maximum.shortValue(), true);
+ case INTEGER: return NumberRange.create(minimum.intValue(), true, maximum.intValue(), true);
+ case LONG: return NumberRange.create(minimum.longValue(), true, maximum.longValue(), true);
+ case FLOAT: {
final float min = minimum.floatValue();
final float max = maximum.floatValue();
if (!Float.isNaN(min) || !Float.isNaN(max)) { // Let `create` throws an exception if only one value is NaN.
diff --git a/endorsed/src/org.apache.sis.feature/main/org/apache/sis/feature/builder/FeatureTypeBuilder.java b/endorsed/src/org.apache.sis.feature/main/org/apache/sis/feature/builder/FeatureTypeBuilder.java
index 7c997f3072..5991933326 100644
--- a/endorsed/src/org.apache.sis.feature/main/org/apache/sis/feature/builder/FeatureTypeBuilder.java
+++ b/endorsed/src/org.apache.sis.feature/main/org/apache/sis/feature/builder/FeatureTypeBuilder.java
@@ -36,9 +36,9 @@ import org.apache.sis.feature.FeatureOperations;
import org.apache.sis.feature.internal.Resources;
import org.apache.sis.feature.internal.shared.AttributeConvention;
import org.apache.sis.geometry.wrapper.Geometries;
+import org.apache.sis.math.NumberType;
import org.apache.sis.util.CorruptedObjectException;
import org.apache.sis.util.ArraysExt;
-import org.apache.sis.util.Numbers;
import org.apache.sis.util.OptionalCandidate;
import org.apache.sis.util.iso.DefaultNameFactory;
import org.apache.sis.util.resources.Errors;
@@ -684,7 +684,7 @@ public class FeatureTypeBuilder extends TypeBuilder {
// We disallow Feature.class because that type shall be handled as association instead of attribute.
throw new IllegalArgumentException(errors().getString(Errors.Keys.IllegalArgumentValue_2, "valueClass", valueClass));
}
- final var property = new AttributeTypeBuilder<V>(this, Numbers.primitiveToWrapper(valueClass));
+ final var property = new AttributeTypeBuilder<V>(this, NumberType.primitiveToWrapper(valueClass));
properties.add(property);
clearCache();
return property;
diff --git a/endorsed/src/org.apache.sis.feature/main/org/apache/sis/image/BandedSampleConverter.java b/endorsed/src/org.apache.sis.feature/main/org/apache/sis/image/BandedSampleConverter.java
index 1e24e62d2d..1c3c2140b4 100644
--- a/endorsed/src/org.apache.sis.feature/main/org/apache/sis/image/BandedSampleConverter.java
+++ b/endorsed/src/org.apache.sis.feature/main/org/apache/sis/image/BandedSampleConverter.java
@@ -36,10 +36,10 @@ import org.apache.sis.coverage.internal.shared.SampleDimensions;
import org.apache.sis.image.internal.shared.ImageUtilities;
import org.apache.sis.image.internal.shared.TileOpExecutor;
import org.apache.sis.image.internal.shared.ColorScaleBuilder;
-import org.apache.sis.util.Numbers;
import org.apache.sis.util.Disposable;
import org.apache.sis.util.logging.Logging;
import org.apache.sis.math.DecimalFunctions;
+import org.apache.sis.math.NumberType;
import org.apache.sis.measure.NumberRange;
import static org.apache.sis.image.internal.shared.ImageUtilities.LOGGER;
@@ -135,7 +135,7 @@ class BandedSampleConverter extends WritableComputedImage {
boolean hasResolutions = false;
final double[] resolutions = new double[converters.length];
final Object sr = source.getProperty(SAMPLE_RESOLUTIONS_KEY);
- final int n = (sr != null && Numbers.isNumber(sr.getClass().getComponentType())) ? Array.getLength(sr) : 0;
+ final int n = (sr != null && NumberType.isReal(sr.getClass().getComponentType())) ? Array.getLength(sr) : 0;
for (int i=0; i<resolutions.length; i++) {
/*
* Get the sample value in the middle of the range of valid values for the current band.
diff --git a/endorsed/src/org.apache.sis.feature/main/org/apache/sis/image/DataType.java b/endorsed/src/org.apache.sis.feature/main/org/apache/sis/image/DataType.java
index 7e73ee93d6..75782ed869 100644
--- a/endorsed/src/org.apache.sis.feature/main/org/apache/sis/image/DataType.java
+++ b/endorsed/src/org.apache.sis.feature/main/org/apache/sis/image/DataType.java
@@ -23,9 +23,9 @@ import java.awt.image.RasterFormatException;
import java.awt.image.SampleModel;
import java.awt.image.MultiPixelPackedSampleModel;
import java.awt.image.SinglePixelPackedSampleModel;
-import org.apache.sis.util.Numbers;
import org.apache.sis.util.ArraysExt;
import org.apache.sis.util.resources.Errors;
+import org.apache.sis.math.NumberType;
import org.apache.sis.measure.NumberRange;
import org.apache.sis.image.internal.shared.ImageUtilities;
import org.apache.sis.feature.internal.Resources;
@@ -39,7 +39,10 @@ import static org.apache.sis.util.internal.shared.Numerics.MAX_INTEGER_CONVERTIB
*
* @author Martin Desruisseaux (Geomatys)
* @version 1.5
- * @since 1.1
+ *
+ * @see org.apache.sis.math.NumberType
+ *
+ * @since 1.1
*/
public enum DataType {
/**
@@ -187,14 +190,13 @@ public enum DataType {
* @return smallest data type for the given range of values.
*/
public static DataType forRange(final NumberRange<?> range, final boolean forceInteger) {
- final byte nt = Numbers.getEnumConstant(range.getElementType());
- if (!forceInteger) {
- if (nt >= Numbers.DOUBLE) return DOUBLE;
- if (nt >= Numbers.FRACTION) return FLOAT;
+ final NumberType nt = NumberType.forClass(range.getElementType()).orElse(NumberType.NULL);
+ if (!forceInteger && nt.isFractional()) {
+ return nt.isNarrowerThan(NumberType.DOUBLE) ? FLOAT : DOUBLE;
}
final double min = range.getMinDouble();
final double max = range.getMaxDouble();
- if (nt < Numbers.BYTE || nt > Numbers.FLOAT || nt == Numbers.LONG) {
+ if (!nt.isReal() || nt.ordinal() >= NumberType.LONG.ordinal()) {
/*
* Value type is long, double, BigInteger, BigDecimal or unknown type.
* If conversions to 32 bits integers would lost integer digits, or if
@@ -234,12 +236,12 @@ public enum DataType {
* @throws RasterFormatException if the given type is not a recognized.
*/
public static DataType forPrimitiveType(final Class<?> type, final boolean unsigned) {
- switch (Numbers.getEnumConstant(type)) {
- case Numbers.BYTE: return unsigned ? BYTE : SHORT;
- case Numbers.SHORT: return unsigned ? USHORT : SHORT;
- case Numbers.INTEGER: return unsigned ? UINT : INT;
- case Numbers.FLOAT: return FLOAT;
- case Numbers.DOUBLE: return DOUBLE;
+ switch (NumberType.forClass(type).orElse(NumberType.NULL)) {
+ case BYTE: return unsigned ? BYTE : SHORT;
+ case SHORT: return unsigned ? USHORT : SHORT;
+ case INTEGER: return unsigned ? UINT : INT;
+ case FLOAT: return FLOAT;
+ case DOUBLE: return DOUBLE;
}
throw new RasterFormatException(Resources.format(Resources.Keys.UnknownDataType_1, type));
}
diff --git a/endorsed/src/org.apache.sis.feature/main/org/apache/sis/image/internal/shared/ImageUtilities.java b/endorsed/src/org.apache.sis.feature/main/org/apache/sis/image/internal/shared/ImageUtilities.java
index 77deb1af80..36b7481e2b 100644
--- a/endorsed/src/org.apache.sis.feature/main/org/apache/sis/image/internal/shared/ImageUtilities.java
+++ b/endorsed/src/org.apache.sis.feature/main/org/apache/sis/image/internal/shared/ImageUtilities.java
@@ -39,7 +39,7 @@ import org.apache.sis.feature.internal.Resources;
import org.apache.sis.image.DataType;
import org.apache.sis.image.PlanarImage;
import org.apache.sis.system.Modules;
-import org.apache.sis.util.Numbers;
+import org.apache.sis.math.NumberType;
import org.apache.sis.util.internal.shared.Numerics;
import org.apache.sis.util.resources.Vocabulary;
import static org.apache.sis.util.internal.shared.Numerics.COMPARISON_THRESHOLD;
@@ -350,18 +350,23 @@ public final class ImageUtilities {
/**
* The values to be returned by {@link #toNumberEnum(DataType)}.
*/
- private static final byte[] NUMBER_ENUMS = {
- Numbers.BYTE, Numbers.SHORT, Numbers.SHORT, Numbers.INTEGER, Numbers.FLOAT, Numbers.DOUBLE
+ private static final NumberType[] NUMBER_ENUMS = {
+ NumberType.BYTE,
+ NumberType.SHORT,
+ NumberType.SHORT,
+ NumberType.INTEGER,
+ NumberType.FLOAT,
+ NumberType.DOUBLE
};
/**
- * Converts a {@link DataBuffer} enumeration value to {@link Numbers} enumeration value.
+ * Converts a {@link DataBuffer} enumeration value to {@link NumberType} enumeration value.
* This method ignores whether the type is signed or unsigned.
*
* @param type the {@link DataBuffer} enumeration value.
- * @return the {@link Numbers} enumeration value.
+ * @return the enumeration value.
*/
- public static byte toNumberEnum(final DataType type) {
+ public static NumberType toNumberEnum(final DataType type) {
return NUMBER_ENUMS[type.toDataBufferType()];
}
@@ -551,7 +556,7 @@ public final class ImageUtilities {
* Converts tile indices from the specified source image to the specified target image.
*
* @param source image for which tile indices are given.
- * @param tartet image for which tile indices are desired.
+ * @param target image for which tile indices are desired.
* @param tiles ranges of indices of tiles in the source image.
* @return ranges of indices of tiles in the target image.
*/
diff --git a/endorsed/src/org.apache.sis.feature/test/org/apache/sis/image/internal/shared/ImageUtilitiesTest.java b/endorsed/src/org.apache.sis.feature/test/org/apache/sis/image/internal/shared/ImageUtilitiesTest.java
index 517ffdff6b..335ebfb151 100644
--- a/endorsed/src/org.apache.sis.feature/test/org/apache/sis/image/internal/shared/ImageUtilitiesTest.java
+++ b/endorsed/src/org.apache.sis.feature/test/org/apache/sis/image/internal/shared/ImageUtilitiesTest.java
@@ -25,7 +25,7 @@ import java.awt.image.BufferedImage;
import java.awt.image.SampleModel;
import java.awt.image.BandedSampleModel;
import org.apache.sis.image.DataType;
-import org.apache.sis.util.Numbers;
+import org.apache.sis.math.NumberType;
import org.apache.sis.util.resources.Vocabulary;
import static org.apache.sis.util.internal.shared.Numerics.COMPARISON_THRESHOLD;
@@ -181,12 +181,12 @@ public final class ImageUtilitiesTest extends TestCase {
*/
@Test
public void testToNumberEnum() {
- assertEquals(Numbers.BYTE, ImageUtilities.toNumberEnum(DataType.BYTE));
- assertEquals(Numbers.SHORT, ImageUtilities.toNumberEnum(DataType.SHORT));
- assertEquals(Numbers.SHORT, ImageUtilities.toNumberEnum(DataType.USHORT));
- assertEquals(Numbers.INTEGER, ImageUtilities.toNumberEnum(DataType.INT));
- assertEquals(Numbers.FLOAT, ImageUtilities.toNumberEnum(DataType.FLOAT));
- assertEquals(Numbers.DOUBLE, ImageUtilities.toNumberEnum(DataType.DOUBLE));
+ assertEquals(NumberType.BYTE, ImageUtilities.toNumberEnum(DataType.BYTE));
+ assertEquals(NumberType.SHORT, ImageUtilities.toNumberEnum(DataType.SHORT));
+ assertEquals(NumberType.SHORT, ImageUtilities.toNumberEnum(DataType.USHORT));
+ assertEquals(NumberType.INTEGER, ImageUtilities.toNumberEnum(DataType.INT));
+ assertEquals(NumberType.FLOAT, ImageUtilities.toNumberEnum(DataType.FLOAT));
+ assertEquals(NumberType.DOUBLE, ImageUtilities.toNumberEnum(DataType.DOUBLE));
}
/**
diff --git a/endorsed/src/org.apache.sis.metadata/main/org/apache/sis/metadata/PropertyAccessor.java b/endorsed/src/org.apache.sis.metadata/main/org/apache/sis/metadata/PropertyAccessor.java
index 7ecdaf9d7a..fab97967a8 100644
--- a/endorsed/src/org.apache.sis.metadata/main/org/apache/sis/metadata/PropertyAccessor.java
+++ b/endorsed/src/org.apache.sis.metadata/main/org/apache/sis/metadata/PropertyAccessor.java
@@ -31,8 +31,8 @@ import org.opengis.annotation.UML;
import org.opengis.annotation.Obligation;
import org.opengis.metadata.ExtendedElementInformation;
import org.opengis.metadata.citation.Citation;
+import org.apache.sis.math.NumberType;
import org.apache.sis.util.Classes;
-import org.apache.sis.util.Numbers;
import org.apache.sis.util.ArraysExt;
import org.apache.sis.util.Utilities;
import org.apache.sis.util.Workaround;
@@ -358,7 +358,7 @@ class PropertyAccessor {
} else if (Map.class.isAssignableFrom(elementType)) {
elementType = Map.Entry.class;
}
- elementTypes[i] = Numbers.primitiveToWrapper(elementType);
+ elementTypes[i] = NumberType.primitiveToWrapper(elementType);
}
this.setters = setters;
}
@@ -1082,7 +1082,7 @@ class PropertyAccessor {
if (newValue == null) {
// Cannot test elementType, because it has been converted to the wrapper class.
if (targetType.isPrimitive()) {
- newValues[0] = Numbers.valueOfNil(targetType);
+ newValues[0] = NumberType.forNumberClass(targetType).nilValue();
}
return null;
}
@@ -1111,7 +1111,7 @@ class PropertyAccessor {
* cause an exception later. The message should be appropriate.
*/
}
- targetType = Numbers.primitiveToWrapper(targetType);
+ targetType = NumberType.primitiveToWrapper(targetType);
} else {
/*
* We expect a collection. Collections are handled in one of the two ways below:
diff --git a/endorsed/src/org.apache.sis.metadata/main/org/apache/sis/metadata/PropertyInformation.java b/endorsed/src/org.apache.sis.metadata/main/org/apache/sis/metadata/PropertyInformation.java
index 48773e075e..acc08bebe1 100644
--- a/endorsed/src/org.apache.sis.metadata/main/org/apache/sis/metadata/PropertyInformation.java
+++ b/endorsed/src/org.apache.sis.metadata/main/org/apache/sis/metadata/PropertyInformation.java
@@ -28,7 +28,7 @@ import org.opengis.util.CodeList;
import org.opengis.util.InternationalString;
import org.apache.sis.metadata.simple.SimpleIdentifier;
import org.apache.sis.measure.ValueRange;
-import org.apache.sis.util.Numbers;
+import org.apache.sis.math.NumberType;
import org.apache.sis.util.iso.Types;
import org.apache.sis.util.collection.CheckedContainer;
import org.apache.sis.util.logging.Logging;
@@ -217,7 +217,7 @@ final class PropertyInformation<E> extends SimpleIdentifier // Impleme
if (CharSequence.class.isAssignableFrom(elementType)) return Datatype.CHARACTER_STRING;
if (CodeList .class.isAssignableFrom(elementType)) return Datatype.CODE_LIST;
if (Enum .class.isAssignableFrom(elementType)) return Datatype.ENUMERATION;
- if (Numbers.isInteger(elementType)) {
+ if (NumberType.isInteger(elementType)) {
return Datatype.INTEGER;
}
// TODO: check the org.opengis.annotation.Classifier annotation here.
diff --git a/endorsed/src/org.apache.sis.metadata/main/org/apache/sis/util/iso/RecordDefinition.java b/endorsed/src/org.apache.sis.metadata/main/org/apache/sis/util/iso/RecordDefinition.java
index d366995265..b9cb36b691 100644
--- a/endorsed/src/org.apache.sis.metadata/main/org/apache/sis/util/iso/RecordDefinition.java
+++ b/endorsed/src/org.apache.sis.metadata/main/org/apache/sis/util/iso/RecordDefinition.java
@@ -26,9 +26,9 @@ import org.opengis.util.Type;
import org.opengis.util.RecordType;
import org.opengis.util.MemberName;
import org.apache.sis.util.Classes;
-import org.apache.sis.util.Numbers;
import org.apache.sis.util.CharSequences;
import org.apache.sis.util.collection.Containers;
+import org.apache.sis.math.NumberType;
import org.apache.sis.pending.jdk.JDK19;
// Specific to the geoapi-3.1 and geoapi-4.0 branches:
@@ -168,7 +168,7 @@ abstract class RecordDefinition { // Inten
i++;
}
fieldIndices = Containers.unmodifiable(fieldIndices);
- baseValueClass = (baseValueClass != null) ? Numbers.wrapperToPrimitive(baseValueClass) : Object.class;
+ baseValueClass = (baseValueClass != null) ? NumberType.wrapperToPrimitive(baseValueClass) : Object.class;
return types;
}
diff --git a/endorsed/src/org.apache.sis.metadata/main/org/apache/sis/util/iso/TypeNames.java b/endorsed/src/org.apache.sis.metadata/main/org/apache/sis/util/iso/TypeNames.java
index dc90f4c062..0725d44b5b 100644
--- a/endorsed/src/org.apache.sis.metadata/main/org/apache/sis/util/iso/TypeNames.java
+++ b/endorsed/src/org.apache.sis.metadata/main/org/apache/sis/util/iso/TypeNames.java
@@ -29,7 +29,7 @@ import org.opengis.util.NameSpace;
import org.opengis.util.NameFactory;
import org.opengis.util.InternationalString;
import org.opengis.geometry.Geometry;
-import org.apache.sis.util.Numbers;
+import org.apache.sis.math.NumberType;
import org.apache.sis.util.internal.shared.Constants;
import org.apache.sis.util.resources.Errors;
@@ -100,8 +100,8 @@ final class TypeNames {
NameSpace ns = ogcNS;
search: if (CharSequence.class.isAssignableFrom(valueClass)) {
name = InternationalString.class.isAssignableFrom(valueClass) ? "FreeText" : "CharacterString";
- } else if (Numbers.isNumber(valueClass)) {
- name = Numbers.isInteger(valueClass) ? "Integer" : "Real";
+ } else if (NumberType.isReal(valueClass)) {
+ name = NumberType.isInteger(valueClass) ? "Integer" : "Real";
} else {
/*
* Iterate over the special cases, excluding the numbers and character sequences
diff --git a/endorsed/src/org.apache.sis.metadata/main/org/apache/sis/xml/bind/FinalClassExtensions.java b/endorsed/src/org.apache.sis.metadata/main/org/apache/sis/xml/bind/FinalClassExtensions.java
index 6631c07c58..0cb55221dd 100644
--- a/endorsed/src/org.apache.sis.metadata/main/org/apache/sis/xml/bind/FinalClassExtensions.java
+++ b/endorsed/src/org.apache.sis.metadata/main/org/apache/sis/xml/bind/FinalClassExtensions.java
@@ -19,7 +19,7 @@ package org.apache.sis.xml.bind;
import java.util.Map;
import java.util.IdentityHashMap;
import java.lang.reflect.Modifier;
-import org.apache.sis.util.Numbers;
+import org.apache.sis.math.NumberType;
import org.apache.sis.xml.NilReason;
@@ -80,7 +80,8 @@ public final class FinalClassExtensions {
* Primitive wrappers are not allowed neither because they will become value objects.
*/
private static boolean isValidKey(final Class<?> type) {
- return Modifier.isFinal(type.getModifiers()) && Numbers.getEnumConstant(type) == Numbers.OTHER;
+ return Modifier.isFinal(type.getModifiers()) && !type.isPrimitive() &&
+ !NumberType.forClass(type).orElse(NumberType.NULL).isConvertible();
}
/**
diff --git a/endorsed/src/org.apache.sis.metadata/test/org/apache/sis/metadata/PropertyConsistencyCheck.java b/endorsed/src/org.apache.sis.metadata/test/org/apache/sis/metadata/PropertyConsistencyCheck.java
index 1451268699..f9859c1928 100644
--- a/endorsed/src/org.apache.sis.metadata/test/org/apache/sis/metadata/PropertyConsistencyCheck.java
+++ b/endorsed/src/org.apache.sis.metadata/test/org/apache/sis/metadata/PropertyConsistencyCheck.java
@@ -23,7 +23,7 @@ import java.util.Collection;
import java.util.Map;
import java.lang.reflect.Method;
import org.opengis.util.CodeList;
-import org.apache.sis.util.Numbers;
+import org.apache.sis.math.NumberType;
import org.apache.sis.util.ArraysExt;
import org.apache.sis.util.collection.CheckedContainer;
import org.apache.sis.metadata.internal.Dependencies;
@@ -120,14 +120,14 @@ public abstract class PropertyConsistencyCheck extends AnnotationConsistencyChec
if (CharSequence.class.isAssignableFrom(type)) {
return "Dummy value for " + property + '.';
}
- switch (Numbers.getEnumConstant(type)) {
- case Numbers.DOUBLE: return random.nextDouble() * 90;
- case Numbers.FLOAT: return random.nextFloat() * 90f;
- case Numbers.LONG: return (long) random.nextInt(1000000) + 1;
- case Numbers.INTEGER: return random.nextInt( 10000) + 1;
- case Numbers.SHORT: return (short) random.nextInt( 1000) + 1;
- case Numbers.BYTE: return (byte) random.nextInt( 100) + 1;
- case Numbers.BOOLEAN: return random.nextBoolean();
+ switch (NumberType.forClass(type).orElse(NumberType.NULL)) {
+ case DOUBLE: return random.nextDouble() * 90;
+ case FLOAT: return random.nextFloat() * 90f;
+ case LONG: return (long) random.nextInt(1000000) + 1;
+ case INTEGER: return random.nextInt( 10000) + 1;
+ case SHORT: return (short) random.nextInt( 1000) + 1;
+ case BYTE: return (byte) random.nextInt( 100) + 1;
+ case BOOLEAN: return random.nextBoolean();
}
if (Date.class.isAssignableFrom(type)) {
return new Date(random.nextInt() * 1000L);
@@ -239,8 +239,8 @@ public abstract class PropertyConsistencyCheck extends AnnotationConsistencyChec
* Get the property type. In the special case where the property type
* is a collection, this is the type of elements in that collection.
*/
- final Class<?> propertyType = Numbers.primitiveToWrapper(accessor.type(i, TypeValuePolicy.PROPERTY_TYPE));
- final Class<?> elementType = Numbers.primitiveToWrapper(accessor.type(i, TypeValuePolicy.ELEMENT_TYPE));
+ final Class<?> propertyType = NumberType.primitiveToWrapper(accessor.type(i, TypeValuePolicy.PROPERTY_TYPE));
+ final Class<?> elementType = NumberType.primitiveToWrapper(accessor.type(i, TypeValuePolicy.ELEMENT_TYPE));
assertNotNull(propertyType, testingMethod);
assertNotNull(elementType, testingMethod);
final boolean isMap = Map.class.isAssignableFrom(propertyType);
diff --git a/endorsed/src/org.apache.sis.metadata/test/org/apache/sis/metadata/iso/AllMetadataTest.java b/endorsed/src/org.apache.sis.metadata/test/org/apache/sis/metadata/iso/AllMetadataTest.java
index 4bc46763dc..12befe0a08 100644
--- a/endorsed/src/org.apache.sis.metadata/test/org/apache/sis/metadata/iso/AllMetadataTest.java
+++ b/endorsed/src/org.apache.sis.metadata/test/org/apache/sis/metadata/iso/AllMetadataTest.java
@@ -34,6 +34,7 @@ import org.opengis.util.ControlledVocabulary;
*
* @author Martin Desruisseaux (Geomatys)
*/
+@SuppressWarnings("exports")
public final class AllMetadataTest extends PropertyConsistencyCheck {
/**
* Creates a new test case with all GeoAPI interfaces and code lists to test.
diff --git a/endorsed/src/org.apache.sis.referencing/main/org/apache/sis/io/wkt/ElementKind.java b/endorsed/src/org.apache.sis.referencing/main/org/apache/sis/io/wkt/ElementKind.java
index 68f1f858db..a126c18307 100644
--- a/endorsed/src/org.apache.sis.referencing/main/org/apache/sis/io/wkt/ElementKind.java
+++ b/endorsed/src/org.apache.sis.referencing/main/org/apache/sis/io/wkt/ElementKind.java
@@ -25,7 +25,7 @@ import org.opengis.referencing.datum.Datum;
import org.opengis.referencing.cs.CoordinateSystemAxis;
import org.opengis.referencing.operation.OperationMethod;
import org.opengis.parameter.GeneralParameterValue;
-import org.apache.sis.util.Numbers;
+import org.apache.sis.math.NumberType;
// Specific to the geoapi-3.1 and geoapi-4.0 branches:
import org.opengis.referencing.datum.DatumEnsemble;
@@ -188,7 +188,7 @@ public enum ElementKind {
if (Extent .class.isAssignableFrom(type)) return EXTENT;
if (Unit .class.isAssignableFrom(type)) return UNIT;
if (Number.class.isAssignableFrom(type)) {
- return Numbers.isInteger(type) ? INTEGER : NUMBER;
+ return NumberType.isInteger(type) ? INTEGER : NUMBER;
}
}
return null;
diff --git a/endorsed/src/org.apache.sis.referencing/main/org/apache/sis/io/wkt/Formatter.java b/endorsed/src/org.apache.sis.referencing/main/org/apache/sis/io/wkt/Formatter.java
index 00572ca121..cbab020e1f 100644
--- a/endorsed/src/org.apache.sis.referencing/main/org/apache/sis/io/wkt/Formatter.java
+++ b/endorsed/src/org.apache.sis.referencing/main/org/apache/sis/io/wkt/Formatter.java
@@ -60,9 +60,9 @@ import org.apache.sis.measure.Units;
import org.apache.sis.measure.UnitFormat;
import org.apache.sis.measure.MeasurementRange;
import org.apache.sis.math.DecimalFunctions;
+import org.apache.sis.math.NumberType;
import org.apache.sis.math.Vector;
import org.apache.sis.util.Classes;
-import org.apache.sis.util.Numbers;
import org.apache.sis.util.Localized;
import org.apache.sis.util.Characters;
import org.apache.sis.util.CharSequences;
@@ -1611,7 +1611,7 @@ public class Formatter implements Localized {
final boolean appendValue(final Object value) {
if (value instanceof Number) {
final var number = (Number) value;
- if (Numbers.isInteger(number.getClass())) {
+ if (NumberType.isInteger(number.getClass())) {
append(number.longValue());
} else {
append(number.doubleValue());
diff --git a/endorsed/src/org.apache.sis.referencing/main/org/apache/sis/io/wkt/MathTransformParser.java b/endorsed/src/org.apache.sis.referencing/main/org/apache/sis/io/wkt/MathTransformParser.java
index b7b8f36dc0..a26587b14e 100644
--- a/endorsed/src/org.apache.sis.referencing/main/org/apache/sis/io/wkt/MathTransformParser.java
+++ b/endorsed/src/org.apache.sis.referencing/main/org/apache/sis/io/wkt/MathTransformParser.java
@@ -40,10 +40,10 @@ import org.opengis.referencing.operation.OperationMethod;
import org.apache.sis.referencing.internal.shared.ReferencingFactoryContainer;
import org.apache.sis.referencing.internal.shared.WKTKeywords;
import org.apache.sis.parameter.DefaultParameterValue;
-import org.apache.sis.util.Numbers;
import org.apache.sis.util.resources.Errors;
import org.apache.sis.util.internal.shared.Constants;
import org.apache.sis.math.DecimalFunctions;
+import org.apache.sis.math.NumberType;
import org.apache.sis.measure.UnitFormat;
import org.apache.sis.measure.Units;
@@ -229,7 +229,7 @@ class MathTransformParser extends AbstractParser {
if (unitID != null) unitID[0] = code;
if (Constants.EPSG.equalsIgnoreCase(codeSpace)) try {
final int n;
- if (Numbers.isInteger(code.getClass())) {
+ if (NumberType.isInteger(code.getClass())) {
n = ((Number) code).intValue();
} else {
n = Integer.parseInt(code.toString());
@@ -388,7 +388,7 @@ class MathTransformParser extends AbstractParser {
if (unit != null) {
parameter.setValue(param.pullDouble("doubleValue"), unit);
} else if (isNumeric) {
- if (Numbers.isInteger(valueClass)) {
+ if (NumberType.isInteger(valueClass)) {
parameter.setValue(param.pullInteger("intValue"));
} else {
parameter.setValue(param.pullDouble("doubleValue"));
diff --git a/endorsed/src/org.apache.sis.referencing/main/org/apache/sis/parameter/DefaultParameterDescriptor.java b/endorsed/src/org.apache.sis.referencing/main/org/apache/sis/parameter/DefaultParameterDescriptor.java
index 03da0e8f1d..a4e91daf94 100644
--- a/endorsed/src/org.apache.sis.referencing/main/org/apache/sis/parameter/DefaultParameterDescriptor.java
+++ b/endorsed/src/org.apache.sis.referencing/main/org/apache/sis/parameter/DefaultParameterDescriptor.java
@@ -36,6 +36,7 @@ import org.apache.sis.util.ArgumentChecks;
import org.apache.sis.util.resources.Errors;
import org.apache.sis.util.collection.Containers;
import org.apache.sis.util.collection.CodeListSet;
+import org.apache.sis.math.NumberType;
import org.apache.sis.measure.Range;
import org.apache.sis.measure.MeasurementRange;
import org.apache.sis.pending.jdk.JDK19;
@@ -211,7 +212,7 @@ public class DefaultParameterDescriptor<T> extends AbstractParameterDescriptor i
if (valueDomain != null) {
Class<?> componentType = valueClass.getComponentType();
if (componentType != null) {
- componentType = Numbers.primitiveToWrapper(componentType);
+ componentType = NumberType.primitiveToWrapper(componentType);
} else {
componentType = valueClass;
}
diff --git a/endorsed/src/org.apache.sis.referencing/main/org/apache/sis/parameter/DefaultParameterValue.java b/endorsed/src/org.apache.sis.referencing/main/org/apache/sis/parameter/DefaultParameterValue.java
index d9dab48e33..e9abbe2160 100644
--- a/endorsed/src/org.apache.sis.referencing/main/org/apache/sis/parameter/DefaultParameterValue.java
+++ b/endorsed/src/org.apache.sis.referencing/main/org/apache/sis/parameter/DefaultParameterValue.java
@@ -52,6 +52,7 @@ import org.apache.sis.referencing.internal.Resources;
import org.apache.sis.referencing.internal.shared.WKTUtilities;
import org.apache.sis.referencing.internal.shared.WKTKeywords;
import org.apache.sis.math.DecimalFunctions;
+import org.apache.sis.math.NumberType;
import org.apache.sis.measure.Units;
import org.apache.sis.system.Loggers;
import org.apache.sis.util.Utilities;
@@ -60,7 +61,6 @@ import org.apache.sis.util.ComparisonMode;
import org.apache.sis.util.LenientComparable;
import org.apache.sis.util.ObjectConverters;
import org.apache.sis.util.UnconvertibleObjectException;
-import org.apache.sis.util.Numbers;
import org.apache.sis.util.internal.shared.Numerics;
import org.apache.sis.util.resources.Errors;
import org.apache.sis.util.logging.Logging;
@@ -650,13 +650,12 @@ public class DefaultParameterValue<T> extends FormattableObject implements Param
private static Number cast(final Number value, final Class<?> expectedClass) {
if (expectedClass == Double.class && value instanceof Float) {
return DecimalFunctions.floatToDouble(value.floatValue());
- } else if (Number.class.isAssignableFrom(expectedClass)) {
- final Number n = Numbers.cast(value, (Class<? extends Number>) expectedClass);
- if (Numerics.equals(n.doubleValue(), value.doubleValue())) {
- return n;
- }
}
- return value;
+ return NumberType.forClass(expectedClass)
+ .filter(NumberType::isConvertible)
+ .map((type) -> type.cast(value))
+ .filter((n) -> Numerics.equals(n.doubleValue(), value.doubleValue()))
+ .orElse(value);
}
/**
@@ -707,7 +706,7 @@ convert: if (componentType != null) {
final int length = Array.getLength(array);
if (length > 0) {
final Object copy = Array.newInstance(componentType, length);
- componentType = Numbers.primitiveToWrapper(componentType);
+ componentType = NumberType.primitiveToWrapper(componentType);
for (int i=0; i<length; i++) {
Object element = Array.get(array, i);
if (element != null) {
@@ -778,15 +777,15 @@ convert: if (componentType != null) {
* If the value cannot be wrapped, then this method fallbacks on the {@link Double} class
* consistently with this method being invoked only by {@code setValue(double, …)} methods.
*
- * @throws IllegalArgumentException if the given value cannot be converted to the given type.
+ * @throws UnsupportedOperationException if the given value cannot be converted to the given type.
+ * @throws ArithmeticException if the given value cannot be converted without precision lost.
*/
@SuppressWarnings("unchecked")
private static Number wrap(final double value, final Class<?> valueClass) throws IllegalArgumentException {
- if (Number.class.isAssignableFrom(valueClass)) {
- return Numbers.wrap(value, (Class<? extends Number>) valueClass);
- } else {
- return value;
- }
+ return NumberType.forClass(valueClass)
+ .filter(NumberType::isConvertible)
+ .map((type) -> type.wrapExact(value))
+ .orElse(value);
}
/**
@@ -805,7 +804,7 @@ convert: if (componentType != null) {
final Number n;
try {
n = wrap(newValue, descriptor.getValueClass());
- } catch (IllegalArgumentException e) {
+ } catch (RuntimeException e) {
throw (InvalidParameterValueException) new InvalidParameterValueException(
e.getLocalizedMessage(), Verifier.getDisplayName(descriptor), newValue).initCause(e);
}
@@ -834,7 +833,7 @@ convert: if (componentType != null) {
final Number n;
try {
n = wrap(newValue, descriptor.getValueClass());
- } catch (IllegalArgumentException e) {
+ } catch (RuntimeException e) {
throw (InvalidParameterValueException) new InvalidParameterValueException(
e.getLocalizedMessage(), Verifier.getDisplayName(descriptor), newValue).initCause(e);
}
@@ -1248,7 +1247,7 @@ convert: if (componentType != null) {
if (value != null) {
if (value instanceof Number) {
final Number n = (Number) value;
- if (Numbers.isInteger(n.getClass())) {
+ if (NumberType.isInteger(n.getClass())) {
final int xmlValue = n.intValue();
if (xmlValue >= 0 && xmlValue == n.doubleValue()) {
return xmlValue;
@@ -1262,9 +1261,9 @@ convert: if (componentType != null) {
if (isFile(value)) {
return ObjectConverters.convert(value, URI.class);
}
- final Class<?> type = Numbers.primitiveToWrapper(value.getClass().getComponentType());
+ final Class<?> type = NumberType.primitiveToWrapper(value.getClass().getComponentType());
if (type != null && Number.class.isAssignableFrom(type)) {
- if (Numbers.isInteger(type)) {
+ if (NumberType.isInteger(type)) {
return new IntegerList(value);
}
return new MeasureList(value, type, getUnit());
diff --git a/endorsed/src/org.apache.sis.referencing/main/org/apache/sis/parameter/MatrixParameters.java b/endorsed/src/org.apache.sis.referencing/main/org/apache/sis/parameter/MatrixParameters.java
index e3e34a3378..c2be667bdd 100644
--- a/endorsed/src/org.apache.sis.referencing/main/org/apache/sis/parameter/MatrixParameters.java
+++ b/endorsed/src/org.apache.sis.referencing/main/org/apache/sis/parameter/MatrixParameters.java
@@ -23,6 +23,7 @@ import java.util.Arrays;
import java.util.Objects;
import java.io.Serializable;
import java.io.ObjectStreamException;
+import org.apache.sis.math.NumberType;
import org.opengis.parameter.ParameterValue;
import org.opengis.parameter.ParameterValueGroup;
import org.opengis.parameter.ParameterDescriptor;
@@ -39,13 +40,13 @@ import org.apache.sis.referencing.operation.matrix.Matrices;
import org.apache.sis.referencing.operation.provider.Affine;
import org.apache.sis.referencing.operation.provider.EPSGName;
import org.apache.sis.referencing.internal.Resources;
-import org.apache.sis.util.Numbers;
import org.apache.sis.util.ArgumentChecks;
import org.apache.sis.util.internal.shared.Constants;
import org.apache.sis.util.internal.shared.Strings;
import org.apache.sis.metadata.iso.citation.Citations;
import org.apache.sis.measure.NumberRange;
import org.apache.sis.util.collection.CheckedContainer;
+import org.apache.sis.util.logging.Logging;
import org.apache.sis.util.resources.Errors;
@@ -461,12 +462,13 @@ public class MatrixParameters<E> implements CheckedContainer<E>, Serializable {
* The values are {@link #zero}, {@link #one} and the {@link #parameters} array.
* Callers shall assign the returned value to the {@link #parameters} field.
*/
- @SuppressWarnings({"unchecked", "rawtypes"})
private <T> ParameterDescriptor<T>[] createCache() {
- if (Number.class.isAssignableFrom(elementType)) try {
- one = (E) Numbers.wrap(1, (Class) elementType);
- zero = (E) Numbers.wrap(0, (Class) elementType);
- } catch (IllegalArgumentException e) {
+ try {
+ final NumberType type = NumberType.forNumberClass(elementType);
+ one = elementType.cast(type.wrapExact(1));
+ zero = elementType.cast(type.wrapExact(0));
+ } catch (RuntimeException e) {
+ Logging.ignorableException(DefaultParameterValue.LOGGER, MatrixParameters.class, "<init>", e);
// Ignore - zero and one will be left to null.
}
int length = 1;
diff --git a/endorsed/src/org.apache.sis.referencing/main/org/apache/sis/parameter/Verifier.java b/endorsed/src/org.apache.sis.referencing/main/org/apache/sis/parameter/Verifier.java
index c1bdb64899..3c1a56ad0d 100644
--- a/endorsed/src/org.apache.sis.referencing/main/org/apache/sis/parameter/Verifier.java
+++ b/endorsed/src/org.apache.sis.referencing/main/org/apache/sis/parameter/Verifier.java
@@ -30,14 +30,14 @@ import org.opengis.parameter.GeneralParameterDescriptor;
import org.opengis.parameter.InvalidParameterValueException;
import org.apache.sis.referencing.internal.Resources;
import org.apache.sis.system.Semaphores;
-import org.apache.sis.util.Numbers;
import org.apache.sis.util.internal.shared.Strings;
-import org.apache.sis.measure.Range;
-import org.apache.sis.measure.Units;
import org.apache.sis.util.logging.Logging;
import org.apache.sis.util.resources.Errors;
import org.apache.sis.util.resources.Vocabulary;
import org.apache.sis.util.resources.IndexedResourceBundle;
+import org.apache.sis.math.NumberType;
+import org.apache.sis.measure.Range;
+import org.apache.sis.measure.Units;
/**
@@ -151,17 +151,17 @@ final class Verifier {
if (componentType == null) {
// Usual case where the expected value is a singleton.
Number n = converter.convert((Number) value);
- convertedValue = Numbers.cast(n, expectedClass.asSubclass(Number.class));
+ convertedValue = NumberType.forNumberClass(expectedClass).cast(n);
} else {
final int length = Array.getLength(value);
if (length != 0) {
final Class<? extends Number> numberType =
- Numbers.primitiveToWrapper(componentType).asSubclass(Number.class);
+ NumberType.primitiveToWrapper(componentType).asSubclass(Number.class);
convertedValue = Array.newInstance(componentType, length);
for (i=0; i<length; i++) {
Number n = (Number) Array.get(value, i);
n = converter.convert(n); // Value in units that we can compare.
- n = Numbers.cast(n, numberType);
+ n = NumberType.forNumberClass(numberType).cast(n);
Array.set(convertedValue, i, n);
}
}
@@ -231,7 +231,8 @@ final class Verifier {
* It could fail if the user overrides DefaultParameterDescriptor.getValueDomain()
* in a way that break the method contract.
*/
- assert valueDomain.getElementType() == (isArray ? Numbers.primitiveToWrapper(valueClass.getComponentType()) : valueClass) : valueDomain;
+ assert valueDomain.getElementType() ==
+ (isArray ? NumberType.primitiveToWrapper(valueClass.getComponentType()) : valueClass) : valueDomain;
final int length = isArray ? Array.getLength(convertedValue) : 1;
for (int i=0; i<length; i++) {
final Object value = isArray ? Array.get(convertedValue, i) : convertedValue;
diff --git a/endorsed/src/org.apache.sis.referencing/test/org/apache/sis/parameter/DefaultParameterValueTest.java b/endorsed/src/org.apache.sis.referencing/test/org/apache/sis/parameter/DefaultParameterValueTest.java
index bf2c3b202b..ab6487b625 100644
--- a/endorsed/src/org.apache.sis.referencing/test/org/apache/sis/parameter/DefaultParameterValueTest.java
+++ b/endorsed/src/org.apache.sis.referencing/test/org/apache/sis/parameter/DefaultParameterValueTest.java
@@ -42,7 +42,7 @@ import static org.apache.sis.referencing.Assertions.assertWktEquals;
*
* @author Martin Desruisseaux (IRD, Geomatys)
*/
-@SuppressWarnings("UnnecessaryBoxing")
+@SuppressWarnings({"exports", "UnnecessaryBoxing"})
public final class DefaultParameterValueTest extends TestCase {
/**
* Small tolerance factor for floating point comparisons resulting from some calculation.
diff --git a/endorsed/src/org.apache.sis.storage.geotiff/main/org/apache/sis/storage/geotiff/NativeMetadata.java b/endorsed/src/org.apache.sis.storage.geotiff/main/org/apache/sis/storage/geotiff/NativeMetadata.java
index 2ad11cf80b..05c813c8e2 100644
--- a/endorsed/src/org.apache.sis.storage.geotiff/main/org/apache/sis/storage/geotiff/NativeMetadata.java
+++ b/endorsed/src/org.apache.sis.storage.geotiff/main/org/apache/sis/storage/geotiff/NativeMetadata.java
@@ -27,7 +27,7 @@ import static java.lang.Math.addExact;
import static javax.imageio.plugins.tiff.GeoTIFFTagSet.*;
import static javax.imageio.plugins.tiff.BaselineTIFFTagSet.*;
import org.apache.sis.math.Vector;
-import org.apache.sis.util.Numbers;
+import org.apache.sis.math.NumberType;
import org.apache.sis.util.resources.Vocabulary;
import org.apache.sis.util.collection.TreeTable;
import org.apache.sis.util.collection.TableColumn;
@@ -254,7 +254,7 @@ final class NativeMetadata extends GeoKeysLoader {
* Replaces an integer code by its enumeration value if that value is different than {@code unknown}.
*/
private static Object toString(final Object value, final IntFunction<Enum<?>> valueOf, final Enum<?> unknown) {
- if (value != null && Numbers.isInteger(value.getClass())) {
+ if (value != null && NumberType.isInteger(value.getClass())) {
final Enum<?> c = valueOf.apply(((Number) value).intValue());
if (c != unknown) return c.name();
}
diff --git a/endorsed/src/org.apache.sis.storage.geotiff/main/org/apache/sis/storage/geotiff/reader/Type.java b/endorsed/src/org.apache.sis.storage.geotiff/main/org/apache/sis/storage/geotiff/reader/Type.java
index 89532b5401..22678b84c9 100644
--- a/endorsed/src/org.apache.sis.storage.geotiff/main/org/apache/sis/storage/geotiff/reader/Type.java
+++ b/endorsed/src/org.apache.sis.storage.geotiff/main/org/apache/sis/storage/geotiff/reader/Type.java
@@ -441,7 +441,7 @@ public enum Type {
if (isUnsigned) {
return Numerics.fraction(input.readUnsignedInt(), input.readUnsignedInt());
} else {
- return new Fraction(input.readInt(), input.readInt()).unique();
+ return new Fraction(input.readInt(), input.readInt());
}
}
diff --git a/endorsed/src/org.apache.sis.storage.netcdf/main/org/apache/sis/storage/netcdf/base/Convention.java b/endorsed/src/org.apache.sis.storage.netcdf/main/org/apache/sis/storage/netcdf/base/Convention.java
index a36eb9dcb0..60798cdb08 100644
--- a/endorsed/src/org.apache.sis.storage.netcdf/main/org/apache/sis/storage/netcdf/base/Convention.java
+++ b/endorsed/src/org.apache.sis.storage.netcdf/main/org/apache/sis/storage/netcdf/base/Convention.java
@@ -39,7 +39,7 @@ import org.apache.sis.image.internal.shared.ColorModelFactory;
import org.apache.sis.measure.MeasurementRange;
import org.apache.sis.measure.NumberRange;
import org.apache.sis.math.Vector;
-import org.apache.sis.util.Numbers;
+import org.apache.sis.math.NumberType;
import org.apache.sis.util.resources.Errors;
import org.apache.sis.system.Reflect;
@@ -604,7 +604,7 @@ public class Convention {
public NumberRange<?> validRange(final Variable data) {
Number minimum = null;
Number maximum = null;
- Class<? extends Number> type = null;
+ NumberType rangeType = NumberType.VOID;
for (final String attribute : RANGE_ATTRIBUTES) {
final Vector values = data.getAttributeAsVector(attribute);
if (values != null) {
@@ -620,10 +620,13 @@ public class Convention {
if (fp == +Double.MAX_VALUE) value = Double.POSITIVE_INFINITY;
else if (fp == -Double.MAX_VALUE) value = Double.NEGATIVE_INFINITY;
}
- type = Numbers.widestClass(type, value.getClass());
- minimum = Numbers.cast(minimum, type);
- maximum = Numbers.cast(maximum, type);
- value = Numbers.cast(value, type);
+ final NumberType other = NumberType.forNumberClass(value.getClass());
+ if (rangeType.isNarrowerThan(other)) {
+ rangeType = other;
+ }
+ minimum = rangeType.cast(minimum);
+ maximum = rangeType.cast(maximum);
+ value = rangeType.cast(value);
if (!attribute.endsWith("max") && (minimum == null || compare(value, minimum) < 0)) minimum = value;
if (!attribute.endsWith("min") && (maximum == null || compare(value, maximum) > 0)) maximum = value;
} catch (NumberFormatException e) {
@@ -642,14 +645,12 @@ public class Convention {
*/
final Class<?> scaleType = data.getAttributeType(CDM.SCALE_FACTOR);
final Class<?> offsetType = data.getAttributeType(CDM.ADD_OFFSET);
- final int rangeType = Numbers.getEnumConstant(type);
if ((scaleType != null || offsetType != null)
- && rangeType >= data.getDataType().number
- && rangeType >= Math.max(Numbers.getEnumConstant(scaleType),
- Numbers.getEnumConstant(offsetType)))
+ && !rangeType.isNarrowerThan(NumberType.forNumberClasses(scaleType, offsetType))
+ && !data.getDataType().number.isWiderThan(rangeType))
{
@SuppressWarnings({"unchecked", "rawtypes"})
- final NumberRange<?> range = new MeasurementRange(type, minimum, true, maximum, true, data.getUnit());
+ final NumberRange<?> range = new MeasurementRange(rangeType.classOfValues(false), minimum, true, maximum, true, data.getUnit());
return range;
} else {
/*
@@ -671,7 +672,7 @@ public class Convention {
}
}
@SuppressWarnings({"unchecked", "rawtypes"})
- final NumberRange<?> range = new NumberRange(type, minimum, isMinIncluded, maximum, isMaxIncluded);
+ final NumberRange<?> range = new NumberRange(rangeType.classOfValues(false), minimum, isMinIncluded, maximum, isMaxIncluded);
return range;
}
}
diff --git a/endorsed/src/org.apache.sis.storage.netcdf/main/org/apache/sis/storage/netcdf/base/DataType.java b/endorsed/src/org.apache.sis.storage.netcdf/main/org/apache/sis/storage/netcdf/base/DataType.java
index d41f1d36a5..f8b3134ead 100644
--- a/endorsed/src/org.apache.sis.storage.netcdf/main/org/apache/sis/storage/netcdf/base/DataType.java
+++ b/endorsed/src/org.apache.sis.storage.netcdf/main/org/apache/sis/storage/netcdf/base/DataType.java
@@ -17,8 +17,8 @@
package org.apache.sis.storage.netcdf.base;
import java.awt.image.DataBuffer;
+import org.apache.sis.math.NumberType;
import org.apache.sis.math.Vector;
-import org.apache.sis.util.Numbers;
/**
@@ -43,82 +43,82 @@ public enum DataType {
/**
* The enumeration for unknown data type. This is not a valid netCDF type.
*/
- UNKNOWN(Numbers.OTHER, Object.class, false, false, (byte) 0, null),
+ UNKNOWN(NumberType.VOID, Object.class, false, false, (byte) 0, null),
/**
* 8 bits signed integer (netCDF type 1).
* Can be made unsigned by assigning the “_Unsigned” attribute to a netCDF variable.
*/
- BYTE(Numbers.BYTE, Byte.class, true, false, (byte) 7, org.apache.sis.image.DataType.BYTE),
+ BYTE(NumberType.BYTE, Byte.class, true, false, (byte) 7, org.apache.sis.image.DataType.BYTE),
/**
* Character type as unsigned 8 bits (netCDF type 2).
* Encoding can be specified by assigning the “_Encoding” attribute to a netCDF variable.
*/
- CHAR(Numbers.BYTE, Character.class, false, true, (byte) 2, null), // NOT Numbers.CHARACTER
+ CHAR(NumberType.BYTE, Character.class, false, true, (byte) 2, null), // NOT Numbers.CHARACTER
/**
* 16 bits signed integer (netCDF type 3).
*/
- SHORT(Numbers.SHORT, Short.class, true, false, (byte) 8, org.apache.sis.image.DataType.SHORT),
+ SHORT(NumberType.SHORT, Short.class, true, false, (byte) 8, org.apache.sis.image.DataType.SHORT),
/**
* 32 bits signed integer (netCDF type 4).
* This is also called "long", but that name is deprecated.
*/
- INT(Numbers.INTEGER, Integer.class, true, false, (byte) 9, org.apache.sis.image.DataType.INT),
+ INT(NumberType.INTEGER, Integer.class, true, false, (byte) 9, org.apache.sis.image.DataType.INT),
/**
* 32 bits floating point number (netCDF type 5)
* This is also called "real".
*/
- FLOAT(Numbers.FLOAT, Float.class, false, false, (byte) 5, org.apache.sis.image.DataType.FLOAT),
+ FLOAT(NumberType.FLOAT, Float.class, false, false, (byte) 5, org.apache.sis.image.DataType.FLOAT),
/**
* 64 bits floating point number (netCDF type 6).
*/
- DOUBLE(Numbers.DOUBLE, Double.class, false, false, (byte) 6, org.apache.sis.image.DataType.DOUBLE),
+ DOUBLE(NumberType.DOUBLE, Double.class, false, false, (byte) 6, org.apache.sis.image.DataType.DOUBLE),
/**
* 8 bits unsigned integer (netCDF type 7).
* Not available in netCDF classic format.
*/
- UBYTE(Numbers.BYTE, Short.class, true, true, (byte) 1, org.apache.sis.image.DataType.BYTE),
+ UBYTE(NumberType.BYTE, Short.class, true, true, (byte) 1, org.apache.sis.image.DataType.BYTE),
/**
* 16 bits unsigned integer (netCDF type 8).
* Not available in netCDF classic format.
*/
- USHORT(Numbers.SHORT, Integer.class, true, true, (byte) 3, org.apache.sis.image.DataType.USHORT),
+ USHORT(NumberType.SHORT, Integer.class, true, true, (byte) 3, org.apache.sis.image.DataType.USHORT),
/**
* 32 bits unsigned integer (netCDF type 9).
* Not available in netCDF classic format.
*/
- UINT(Numbers.INTEGER, Long.class, true, true, (byte) 4, org.apache.sis.image.DataType.UINT),
+ UINT(NumberType.INTEGER, Long.class, true, true, (byte) 4, org.apache.sis.image.DataType.UINT),
/**
* 64 bits signed integer (netCDF type 10).
* Not available in netCDF classic format.
*/
- INT64(Numbers.LONG, Long.class, true, false, (byte) 11, null),
+ INT64(NumberType.LONG, Long.class, true, false, (byte) 11, null),
/**
* 64 bits unsigned integer (netCDF type 11).
* Not available in netCDF classic format.
*/
- UINT64(Numbers.LONG, Number.class, true, true, (byte) 10, null),
+ UINT64(NumberType.LONG, Number.class, true, true, (byte) 10, null),
/**
* Character string (netCDF type 12).
* Not available in netCDF classic format.
*/
- STRING(Numbers.OTHER, String.class, false, false, (byte) 12, null);
+ STRING(NumberType.VOID, String.class, false, false, (byte) 12, null);
/**
- * Mapping from the netCDF data type to the enumeration used by our {@link Numbers} class.
+ * Mapping from the netCDF data type to the enumeration used by Apache <abbr>SIS</abbr>.
*/
- public final byte number;
+ public final NumberType number;
/**
* {@code true} for data type that are signed or unsigned integers.
@@ -156,8 +156,8 @@ public enum DataType {
/**
* Creates a new enumeration value.
*/
- private DataType(final byte number, final Class<?> classe, final boolean isInteger, final boolean isUnsigned,
- final byte opposite, final org.apache.sis.image.DataType rasterDataType)
+ private DataType(final NumberType number, final Class<?> classe, final boolean isInteger, final boolean isUnsigned,
+ final byte opposite, final org.apache.sis.image.DataType rasterDataType)
{
this.number = number;
this.classe = classe;
@@ -193,13 +193,13 @@ public enum DataType {
*/
public final int size() {
switch (number) {
- case Numbers.BYTE: return Byte.BYTES;
- case Numbers.SHORT: return Short.BYTES;
- case Numbers.INTEGER: // Same as float
- case Numbers.FLOAT: return Float.BYTES;
- case Numbers.LONG: // Same as double
- case Numbers.DOUBLE: return Double.BYTES;
- default: return 0;
+ case BYTE: return Byte.BYTES;
+ case SHORT: return Short.BYTES;
+ case INTEGER: // Same as float
+ case FLOAT: return Float.BYTES;
+ case LONG: // Same as double
+ case DOUBLE: return Double.BYTES;
+ default: return 0;
}
}
diff --git a/endorsed/src/org.apache.sis.storage.netcdf/main/org/apache/sis/storage/netcdf/base/GridMapping.java b/endorsed/src/org.apache.sis.storage.netcdf/main/org/apache/sis/storage/netcdf/base/GridMapping.java
index 732e1b21a7..5b45db26ad 100644
--- a/endorsed/src/org.apache.sis.storage.netcdf/main/org/apache/sis/storage/netcdf/base/GridMapping.java
+++ b/endorsed/src/org.apache.sis.storage.netcdf/main/org/apache/sis/storage/netcdf/base/GridMapping.java
@@ -77,7 +77,6 @@ import org.apache.sis.system.Modules;
import org.apache.sis.util.ComparisonMode;
import org.apache.sis.util.CharSequences;
import org.apache.sis.util.ArraysExt;
-import org.apache.sis.util.Numbers;
import org.apache.sis.util.Utilities;
import org.apache.sis.util.internal.shared.Strings;
import org.apache.sis.util.internal.shared.Constants;
@@ -86,6 +85,7 @@ import org.apache.sis.util.resources.Errors;
import org.apache.sis.util.resources.IndexedResourceBundle;
import org.apache.sis.io.wkt.WKTFormat;
import org.apache.sis.io.wkt.Warnings;
+import org.apache.sis.math.NumberType;
import org.apache.sis.measure.Units;
// Specific to the geoapi-3.1 and geoapi-4.0 branches:
@@ -301,10 +301,10 @@ final class GridMapping {
continue;
}
final Class<?> type = parameter.getDescriptor().getValueClass();
- if (Numbers.isNumber(type)) {
+ if (NumberType.isReal(type)) {
it.remove();
parameter.setValue(Double.parseDouble(text));
- } else if (Numbers.isNumber(type.getComponentType())) {
+ } else if (NumberType.isReal(type.getComponentType())) {
it.remove();
parameter.setValue(parseDoubles(text), null);
}
diff --git a/endorsed/src/org.apache.sis.storage.netcdf/main/org/apache/sis/storage/netcdf/base/RasterResource.java b/endorsed/src/org.apache.sis.storage.netcdf/main/org/apache/sis/storage/netcdf/base/RasterResource.java
index 4face347a5..3e02b53b18 100644
--- a/endorsed/src/org.apache.sis.storage.netcdf/main/org/apache/sis/storage/netcdf/base/RasterResource.java
+++ b/endorsed/src/org.apache.sis.storage.netcdf/main/org/apache/sis/storage/netcdf/base/RasterResource.java
@@ -37,7 +37,6 @@ import org.apache.sis.storage.DataStoreContentException;
import org.apache.sis.storage.Resource;
import org.apache.sis.storage.base.MetadataBuilder;
import org.apache.sis.storage.base.StoreResource;
-import org.apache.sis.util.Numbers;
import org.apache.sis.util.CharSequences;
import org.apache.sis.util.internal.shared.Strings;
import org.apache.sis.coverage.SampleDimension;
@@ -50,6 +49,7 @@ import org.apache.sis.coverage.grid.GridRoundingMode;
import org.apache.sis.coverage.internal.shared.RangeArgument;
import org.apache.sis.image.internal.shared.RasterFactory;
import org.apache.sis.math.MathFunctions;
+import org.apache.sis.math.NumberType;
import org.apache.sis.measure.MeasurementRange;
import org.apache.sis.measure.NumberRange;
import org.apache.sis.util.resources.Errors;
@@ -495,7 +495,9 @@ public final class RasterResource extends AbstractGridCoverageResource implement
isMaxIncluded = isMinIncluded;
isMinIncluded = sb;
}
- if (band.getDataType().number <= Numbers.LONG && minimum >= Long.MIN_VALUE && maximum <= Long.MAX_VALUE) {
+ if (!band.getDataType().number.isWiderThan(NumberType.LONG)
+ && minimum >= Long.MIN_VALUE && maximum <= Long.MAX_VALUE)
+ {
range = NumberRange.create(Math.round(minimum), isMinIncluded, Math.round(maximum), isMaxIncluded);
} else {
range = NumberRange.create(minimum, isMinIncluded, maximum, isMaxIncluded);
diff --git a/endorsed/src/org.apache.sis.storage.netcdf/main/org/apache/sis/storage/netcdf/base/Variable.java b/endorsed/src/org.apache.sis.storage.netcdf/main/org/apache/sis/storage/netcdf/base/Variable.java
index 9e325e443b..901adff21d 100644
--- a/endorsed/src/org.apache.sis.storage.netcdf/main/org/apache/sis/storage/netcdf/base/Variable.java
+++ b/endorsed/src/org.apache.sis.storage.netcdf/main/org/apache/sis/storage/netcdf/base/Variable.java
@@ -38,9 +38,9 @@ import org.apache.sis.storage.netcdf.internal.Resources;
import org.apache.sis.coverage.grid.GridGeometry;
import org.apache.sis.coverage.grid.GridExtent;
import org.apache.sis.math.Vector;
+import org.apache.sis.math.NumberType;
import org.apache.sis.math.MathFunctions;
import org.apache.sis.measure.NumberRange;
-import org.apache.sis.util.Numbers;
import org.apache.sis.util.ArraysExt;
import org.apache.sis.util.collection.Containers;
import org.apache.sis.util.collection.WeakHashSet;
@@ -418,8 +418,8 @@ public abstract class Variable extends Node {
* @return whether this variable contains values in unit of measurement, ignoring fill and missing values.
*/
final boolean hasRealValues() {
- final int n = getDataType().number;
- if (n == Numbers.FLOAT | n == Numbers.DOUBLE) {
+ final NumberType n = getDataType().number;
+ if (n == NumberType.FLOAT | n == NumberType.DOUBLE) {
final Convention convention = decoder.convention();
if (convention != Convention.DEFAULT) {
return convention.transferFunction(this).isIdentity();
@@ -1135,7 +1135,7 @@ public abstract class Variable extends Node {
* (i.e. it does not increase the risk of data loss).
*/
double tolerance = 0;
- if (Numbers.isFloat(data.getElementType())) {
+ if (NumberType.isFractional(data.getElementType())) {
final int n = data.size() - 1;
if (n >= 0) {
double first = data.doubleValue(0);
diff --git a/endorsed/src/org.apache.sis.storage.netcdf/test/org/apache/sis/storage/netcdf/base/DataTypeTest.java b/endorsed/src/org.apache.sis.storage.netcdf/test/org/apache/sis/storage/netcdf/base/DataTypeTest.java
index 906032f9a6..02dbbd4db8 100644
--- a/endorsed/src/org.apache.sis.storage.netcdf/test/org/apache/sis/storage/netcdf/base/DataTypeTest.java
+++ b/endorsed/src/org.apache.sis.storage.netcdf/test/org/apache/sis/storage/netcdf/base/DataTypeTest.java
@@ -16,7 +16,7 @@
*/
package org.apache.sis.storage.netcdf.base;
-import org.apache.sis.util.Numbers;
+import org.apache.sis.math.NumberType;
// Test dependencies
import org.junit.jupiter.api.Test;
@@ -112,17 +112,20 @@ public final class DataTypeTest extends TestCase {
*/
@Test
public void testClasses() {
- for (final DataType type : DataType.values()) {
- final String name = type.name();
- final int code = Numbers.getEnumConstant(type.getClass(false));
- if (type.isInteger) {
- if (!type.isUnsigned) {
- assertEquals(type.number, code, name);
- } else if (type != DataType.UINT64) {
- assertTrue(code > type.number, name);
+ for (final DataType dataType : DataType.values()) {
+ final Class<?> c = dataType.getClass(false);
+ if (Number.class.isAssignableFrom(c)) {
+ final NumberType numberType = NumberType.forNumberClass(c);
+ final String name = dataType.name();
+ if (dataType.isInteger) {
+ if (!dataType.isUnsigned) {
+ assertEquals(dataType.number, numberType, name);
+ } else if (dataType != DataType.UINT64) {
+ assertTrue(numberType.isWiderThan(dataType.number), name);
+ }
+ } else {
+ assertEquals((dataType == DataType.CHAR) ? NumberType.CHARACTER : dataType.number, numberType, name);
}
- } else {
- assertEquals((type == DataType.CHAR) ? Numbers.CHARACTER : type.number, code, name);
}
}
}
diff --git a/endorsed/src/org.apache.sis.storage.sql/main/org/apache/sis/storage/sql/feature/FeatureAnalyzer.java b/endorsed/src/org.apache.sis.storage.sql/main/org/apache/sis/storage/sql/feature/FeatureAnalyzer.java
index 7918ac1fd5..db117660cb 100644
--- a/endorsed/src/org.apache.sis.storage.sql/main/org/apache/sis/storage/sql/feature/FeatureAnalyzer.java
+++ b/endorsed/src/org.apache.sis.storage.sql/main/org/apache/sis/storage/sql/feature/FeatureAnalyzer.java
@@ -32,9 +32,9 @@ import org.apache.sis.feature.builder.AssociationRoleBuilder;
import org.apache.sis.feature.builder.AttributeTypeBuilder;
import org.apache.sis.feature.builder.AttributeRole;
import org.apache.sis.geometry.wrapper.Geometries;
+import org.apache.sis.math.NumberType;
import org.apache.sis.util.CharSequences;
import org.apache.sis.util.Classes;
-import org.apache.sis.util.Numbers;
// Specific to the geoapi-3.1 and geoapi-4.0 branches:
import org.opengis.feature.FeatureType;
@@ -308,7 +308,7 @@ abstract class FeatureAnalyzer {
final PrimaryKey createAssociations(final Relation[] exportedKeys) throws Exception {
if (primaryKey.size() > 1) {
if (!primaryKeyNullable) {
- primaryKeyClass = Numbers.wrapperToPrimitive(primaryKeyClass);
+ primaryKeyClass = NumberType.wrapperToPrimitive(primaryKeyClass);
}
primaryKeyClass = Classes.changeArrayDimension(primaryKeyClass, 1);
}
diff --git a/endorsed/src/org.apache.sis.storage.sql/main/org/apache/sis/storage/sql/feature/ValueGetter.java b/endorsed/src/org.apache.sis.storage.sql/main/org/apache/sis/storage/sql/feature/ValueGetter.java
index 6c069424ee..f4918a2f82 100644
--- a/endorsed/src/org.apache.sis.storage.sql/main/org/apache/sis/storage/sql/feature/ValueGetter.java
+++ b/endorsed/src/org.apache.sis.storage.sql/main/org/apache/sis/storage/sql/feature/ValueGetter.java
@@ -32,7 +32,7 @@ import java.time.OffsetTime;
import java.time.ZoneOffset;
import java.math.BigDecimal;
import org.apache.sis.math.Vector;
-import org.apache.sis.util.Numbers;
+import org.apache.sis.math.NumberType;
import org.apache.sis.util.collection.Containers;
import org.apache.sis.util.internal.shared.Constants;
@@ -493,7 +493,7 @@ public class ValueGetter<T> {
*/
cmget = stmts.database.getMapping(new Column(array.getBaseType(), array.getBaseTypeName(), "element"));
}
- Class<?> componentType = Numbers.primitiveToWrapper(result.getClass().getComponentType());
+ Class<?> componentType = NumberType.primitiveToWrapper(result.getClass().getComponentType());
if (cmget != null && !cmget.valueType.isAssignableFrom(componentType)) {
/*
* If the elements in the `result` array are not of the expected type, fetch them again
@@ -502,7 +502,7 @@ public class ValueGetter<T> {
* hopefully not be needed most of the time. It is also the only way to have the number
* of elements in advance.
*/
- componentType = Numbers.wrapperToPrimitive(cmget.valueType);
+ componentType = NumberType.wrapperToPrimitive(cmget.valueType);
final int length = java.lang.reflect.Array.getLength(result);
result = java.lang.reflect.Array.newInstance(componentType, length);
try (ResultSet r = array.getResultSet()) {
@@ -512,7 +512,7 @@ public class ValueGetter<T> {
}
}
array.free();
- if (Numbers.isNumber(componentType)) {
+ if (NumberType.isReal(componentType)) {
return Vector.create(result, true);
}
return Containers.viewAsUnmodifiableList((Object[]) result);
diff --git a/endorsed/src/org.apache.sis.storage/main/org/apache/sis/io/stream/HyperRectangleReader.java b/endorsed/src/org.apache.sis.storage/main/org/apache/sis/io/stream/HyperRectangleReader.java
index 9059649563..512e06d849 100644
--- a/endorsed/src/org.apache.sis.storage/main/org/apache/sis/io/stream/HyperRectangleReader.java
+++ b/endorsed/src/org.apache.sis.storage/main/org/apache/sis/io/stream/HyperRectangleReader.java
@@ -19,7 +19,7 @@ package org.apache.sis.io.stream;
import java.nio.Buffer;
import java.nio.ByteBuffer;
import java.io.IOException;
-import org.apache.sis.util.Numbers;
+import org.apache.sis.math.NumberType;
import org.apache.sis.util.resources.Errors;
import org.apache.sis.storage.DataStoreContentException;
@@ -60,19 +60,19 @@ public class HyperRectangleReader {
/**
* Creates a new reader for the given input.
*
- * @param dataType the type of elements to read, as one of the constants defined in {@link Numbers}.
+ * @param dataType the type of elements to read.
* @param input the channel from which to read the values, together with a buffer for transferring data.
* @throws DataStoreContentException if the given {@code dataType} is not one of the supported values.
*/
- public HyperRectangleReader(final byte dataType, final ChannelDataInput input) throws DataStoreContentException {
+ public HyperRectangleReader(final NumberType dataType, final ChannelDataInput input) throws DataStoreContentException {
switch (dataType) {
- case Numbers.BYTE: reader = input.new BytesReader ((byte[]) null); break;
- case Numbers.CHARACTER: reader = input.new CharsReader ((char[]) null); break;
- case Numbers.SHORT: reader = input.new ShortsReader ((short[]) null); break;
- case Numbers.INTEGER: reader = input.new IntsReader ((int[]) null); break;
- case Numbers.LONG: reader = input.new LongsReader ((long[]) null); break;
- case Numbers.FLOAT: reader = input.new FloatsReader ((float[]) null); break;
- case Numbers.DOUBLE: reader = input.new DoublesReader((double[]) null); break;
+ case BYTE: reader = input.new BytesReader ((byte[]) null); break;
+ case CHARACTER: reader = input.new CharsReader ((char[]) null); break;
+ case SHORT: reader = input.new ShortsReader ((short[]) null); break;
+ case INTEGER: reader = input.new IntsReader ((int[]) null); break;
+ case LONG: reader = input.new LongsReader ((long[]) null); break;
+ case FLOAT: reader = input.new FloatsReader ((float[]) null); break;
+ case DOUBLE: reader = input.new DoublesReader((double[]) null); break;
default: throw new DataStoreContentException(Errors.format(Errors.Keys.UnknownType_1, dataType));
}
final ByteBuffer buffer = input.buffer;
diff --git a/endorsed/src/org.apache.sis.storage/test/org/apache/sis/io/stream/HyperRectangleReaderTest.java b/endorsed/src/org.apache.sis.storage/test/org/apache/sis/io/stream/HyperRectangleReaderTest.java
index 79b77059a0..d32dc7e649 100644
--- a/endorsed/src/org.apache.sis.storage/test/org/apache/sis/io/stream/HyperRectangleReaderTest.java
+++ b/endorsed/src/org.apache.sis.storage/test/org/apache/sis/io/stream/HyperRectangleReaderTest.java
@@ -22,7 +22,7 @@ import java.nio.ByteOrder;
import java.nio.ByteBuffer;
import java.nio.ShortBuffer;
import java.io.IOException;
-import org.apache.sis.util.Numbers;
+import org.apache.sis.math.NumberType;
import org.apache.sis.storage.DataStoreException;
// Test dependencies
@@ -136,7 +136,7 @@ public final class HyperRectangleReaderTest extends TestCase {
final var channel = new ByteArrayChannel(array, true);
final var buffer = ByteBuffer.allocate(random.nextInt(20) + 20).order(ByteOrder.nativeOrder());
final var input = new ChannelDataInput("HyperRectangle in channel", channel, buffer, false);
- reader = new HyperRectangleReader(Numbers.SHORT, input);
+ reader = new HyperRectangleReader(NumberType.SHORT, input);
reader.setOrigin(origin);
} else {
view.clear();
diff --git a/endorsed/src/org.apache.sis.util/main/org/apache/sis/converter/ArrayConverter.java b/endorsed/src/org.apache.sis.util/main/org/apache/sis/converter/ArrayConverter.java
index 2a925e5458..e0091128e8 100644
--- a/endorsed/src/org.apache.sis.util/main/org/apache/sis/converter/ArrayConverter.java
+++ b/endorsed/src/org.apache.sis.util/main/org/apache/sis/converter/ArrayConverter.java
@@ -20,7 +20,7 @@ import java.util.Set;
import java.util.EnumSet;
import java.lang.reflect.Array;
import org.apache.sis.math.FunctionProperty;
-import org.apache.sis.util.Numbers;
+import org.apache.sis.math.NumberType;
import org.apache.sis.util.ObjectConverter;
import org.apache.sis.util.UnconvertibleObjectException;
@@ -71,8 +71,8 @@ final class ArrayConverter<S,T> extends SystemConverter<S,T> {
*/
ArrayConverter(final Class<S> sourceClass, final Class<T> targetClass, final ObjectConverter<?,?> converter) {
super(sourceClass, targetClass);
- assert converter.getSourceClass().isAssignableFrom(Numbers.primitiveToWrapper(sourceClass.getComponentType())) : sourceClass;
- assert Numbers.primitiveToWrapper(targetClass.getComponentType()).isAssignableFrom(converter.getTargetClass()) : targetClass;
+ assert converter.getSourceClass().isAssignableFrom(NumberType.primitiveToWrapper(sourceClass.getComponentType())) : sourceClass;
+ assert NumberType.primitiveToWrapper(targetClass.getComponentType()).isAssignableFrom(converter.getTargetClass()) : targetClass;
this.converter = converter;
}
diff --git a/endorsed/src/org.apache.sis.util/main/org/apache/sis/converter/ConverterRegistry.java b/endorsed/src/org.apache.sis.util/main/org/apache/sis/converter/ConverterRegistry.java
index 8fc1453f9e..e59c2562b9 100644
--- a/endorsed/src/org.apache.sis.util/main/org/apache/sis/converter/ConverterRegistry.java
+++ b/endorsed/src/org.apache.sis.util/main/org/apache/sis/converter/ConverterRegistry.java
@@ -18,8 +18,8 @@ package org.apache.sis.converter;
import java.util.Map;
import java.util.LinkedHashMap;
+import org.apache.sis.math.NumberType;
import org.apache.sis.util.Classes;
-import org.apache.sis.util.Numbers;
import org.apache.sis.util.ArgumentChecks;
import org.apache.sis.util.ObjectConverter;
import org.apache.sis.util.UnconvertibleObjectException;
@@ -522,8 +522,8 @@ public class ConverterRegistry {
final Class<?> targetComponent = targetClass.getComponentType();
if (targetComponent != null) {
converter = new ArrayConverter<>(sourceClass, targetClass, find(
- Numbers.primitiveToWrapper(sourceComponent),
- Numbers.primitiveToWrapper(targetComponent)));
+ NumberType.primitiveToWrapper(sourceComponent),
+ NumberType.primitiveToWrapper(targetComponent)));
put(key, converter);
return converter;
}
diff --git a/endorsed/src/org.apache.sis.util/main/org/apache/sis/converter/NumberConverter.java b/endorsed/src/org.apache.sis.util/main/org/apache/sis/converter/NumberConverter.java
index 7fb968d353..9633ff19e5 100644
--- a/endorsed/src/org.apache.sis.util/main/org/apache/sis/converter/NumberConverter.java
+++ b/endorsed/src/org.apache.sis.util/main/org/apache/sis/converter/NumberConverter.java
@@ -22,6 +22,7 @@ import org.apache.sis.util.Numbers;
import org.apache.sis.util.ObjectConverter;
import org.apache.sis.util.UnconvertibleObjectException;
import org.apache.sis.math.FunctionProperty;
+import org.apache.sis.math.NumberType;
import org.apache.sis.util.resources.Errors;
@@ -97,9 +98,12 @@ final class NumberConverter<S extends Number, T extends Number> extends SystemCo
*/
@Override
public Set<FunctionProperty> properties() {
- return EnumSet.of(Numbers.widestClass(sourceClass, targetClass) == targetClass
- ? FunctionProperty.INJECTIVE : FunctionProperty.SURJECTIVE,
- FunctionProperty.ORDER_PRESERVING, FunctionProperty.INVERTIBLE);
+ var properties = EnumSet.of(FunctionProperty.ORDER_PRESERVING, FunctionProperty.INVERTIBLE);
+ NumberType source = NumberType.forClass(sourceClass).orElse(NumberType.NULL);
+ NumberType target = NumberType.forClass(targetClass).orElse(NumberType.NULL);
+ if (source.isConversionLossless(target)) properties.add(FunctionProperty.INJECTIVE);
+ if (target.isConversionLossless(source)) properties.add(FunctionProperty.SURJECTIVE);
+ return properties;
}
/**
diff --git a/endorsed/src/org.apache.sis.util/main/org/apache/sis/converter/StringConverter.java b/endorsed/src/org.apache.sis.util/main/org/apache/sis/converter/StringConverter.java
index 7b59d99e92..1cfd70527f 100644
--- a/endorsed/src/org.apache.sis.util/main/org/apache/sis/converter/StringConverter.java
+++ b/endorsed/src/org.apache.sis.util/main/org/apache/sis/converter/StringConverter.java
@@ -320,10 +320,8 @@ abstract class StringConverter<T> extends SystemConverter<String, T> {
/** See {@link StringConverter} for the conversion table. */
@Override java.lang.Boolean doConvert(final String source) throws UnconvertibleObjectException {
- switch (source.toLowerCase(java.util.Locale.ROOT)) {
- case "true": case "yes": case "on": case "1": return java.lang.Boolean.TRUE;
- case "false": case "no": case "off": case "0": return java.lang.Boolean.FALSE;
- }
+ var value = Strings.parseBoolean(source);
+ if (value != null) return value;
throw new UnconvertibleObjectException(formatErrorMessage(source));
}
}
diff --git a/endorsed/src/org.apache.sis.util/main/org/apache/sis/converter/SystemRegistry.java b/endorsed/src/org.apache.sis.util/main/org/apache/sis/converter/SystemRegistry.java
index 8e6ada3b27..b6f9c47eb3 100644
--- a/endorsed/src/org.apache.sis.util/main/org/apache/sis/converter/SystemRegistry.java
+++ b/endorsed/src/org.apache.sis.util/main/org/apache/sis/converter/SystemRegistry.java
@@ -18,8 +18,8 @@ package org.apache.sis.converter;
import java.util.Date;
import java.util.ServiceLoader;
+import org.apache.sis.math.NumberType;
import org.opengis.util.CodeList;
-import org.apache.sis.util.Numbers;
import org.apache.sis.util.ObjectConverter;
import org.apache.sis.util.UnconvertibleObjectException;
import org.apache.sis.system.SystemListener;
@@ -231,7 +231,6 @@ public final class SystemRegistry extends ConverterRegistry {
* by {@link NumberConverter}.
*/
private static boolean isSupportedNumber(final Class<?> type) {
- final int code = Numbers.getEnumConstant(type);
- return (code >= Numbers.BYTE && code <= Numbers.BIG_DECIMAL);
+ return NumberType.forClass(type).filter(NumberType::isReal).isPresent();
}
}
diff --git a/endorsed/src/org.apache.sis.util/main/org/apache/sis/io/CompoundFormat.java b/endorsed/src/org.apache.sis.util/main/org/apache/sis/io/CompoundFormat.java
index 1e2b084de3..b3ad608ad6 100644
--- a/endorsed/src/org.apache.sis.util/main/org/apache/sis/io/CompoundFormat.java
+++ b/endorsed/src/org.apache.sis.util/main/org/apache/sis/io/CompoundFormat.java
@@ -50,7 +50,7 @@ import org.apache.sis.measure.Range;
import org.apache.sis.measure.RangeFormat;
import org.apache.sis.measure.UnitFormat;
import org.apache.sis.measure.QuantityFormat;
-import org.apache.sis.util.Numbers;
+import org.apache.sis.math.NumberType;
import org.apache.sis.util.Classes;
import org.apache.sis.util.Localized;
import org.apache.sis.util.ArraysExt;
@@ -510,7 +510,7 @@ public abstract class CompoundFormat<T> extends Format implements Localized {
return DefaultFormat.getInstance(valueType);
} else if (valueType == Number.class) {
return NumberFormat.getInstance(locale);
- } else if (Numbers.isInteger(valueType)) {
+ } else if (NumberType.isInteger(valueType)) {
return NumberFormat.getIntegerInstance(locale);
}
} else if (TemporalAccessor.class.isAssignableFrom(valueType)) {
diff --git a/endorsed/src/org.apache.sis.util/main/org/apache/sis/io/DefaultFormat.java b/endorsed/src/org.apache.sis.util/main/org/apache/sis/io/DefaultFormat.java
index 67603e9191..3c474d3012 100644
--- a/endorsed/src/org.apache.sis.util/main/org/apache/sis/io/DefaultFormat.java
+++ b/endorsed/src/org.apache.sis.util/main/org/apache/sis/io/DefaultFormat.java
@@ -16,11 +16,13 @@
*/
package org.apache.sis.io;
+import java.util.EnumMap;
import java.text.Format;
import java.text.FieldPosition;
import java.text.ParsePosition;
import java.text.ParseException;
import java.io.ObjectStreamException;
+import org.apache.sis.math.NumberType;
import org.apache.sis.util.Numbers;
import org.apache.sis.util.CharSequences;
import org.apache.sis.util.internal.shared.LocalizedParseException;
@@ -46,10 +48,9 @@ final class DefaultFormat extends Format {
private static final long serialVersionUID = -2309270763519060316L;
/**
- * The array for storing singleton instances for types {@code byte} to {@code double}.
- * The value at index 0 is reserved for the generic {@link Number} type.
+ * The array for storing singleton instances.
*/
- private static final Format[] INSTANCES = new Format[Numbers.DOUBLE - Numbers.BYTE + 2];
+ private static final EnumMap<NumberType, Format> INSTANCES = new EnumMap<>(NumberType.class);
/**
* The type of the objects to parse.
@@ -58,31 +59,21 @@ final class DefaultFormat extends Format {
/**
* Gets an instance of the given type, or {@code null} if the given type is not supported.
+ * The given type should be a subclass of {@link Number}.
+ *
+ * @throws IllegalArgumentException if the given type is not recognized.
*/
static Format getInstance(final Class<?> type) {
- final int index;
- if (type == Number.class) {
- index = 0;
- } else {
- index = Numbers.getEnumConstant(type) - (Numbers.BYTE - 1);
- if (index < 0 || index >= INSTANCES.length) {
- return null;
- }
- }
synchronized (INSTANCES) {
- Format format = INSTANCES[index];
- if (format == null) {
- INSTANCES[index] = format = new DefaultFormat(type);
- }
- return format;
+ return INSTANCES.computeIfAbsent(NumberType.forNumberClass(type), DefaultFormat::new);
}
}
/**
* Creates a new instance for parsing and formatting objects of the given type.
*/
- private DefaultFormat(final Class<?> type) {
- this.type = type;
+ private DefaultFormat(final NumberType type) {
+ this.type = type.classOfValues(false);
}
/**
diff --git a/endorsed/src/org.apache.sis.util/main/org/apache/sis/math/ArrayVector.java b/endorsed/src/org.apache.sis.util/main/org/apache/sis/math/ArrayVector.java
index 351af7ba51..f6218e723c 100644
--- a/endorsed/src/org.apache.sis.util/main/org/apache/sis/math/ArrayVector.java
+++ b/endorsed/src/org.apache.sis.util/main/org/apache/sis/math/ArrayVector.java
@@ -183,14 +183,12 @@ abstract class ArrayVector<E extends Number> extends Vector implements CheckedCo
/**
* Verifies that the given value can be cast to the expected type.
- * The expected type must be one of the {@link Numbers} constants.
*/
- void verifyType(final Number value, final byte expected) {
+ void verifyType(final Number value, final NumberType expected) {
final Class<? extends Number> type = value.getClass();
- final byte t = Numbers.getEnumConstant(type);
- if (t < Numbers.BYTE || t > expected) {
- throw new ClassCastException(Errors.format(Errors.Keys.CanNotConvertFromType_2,
- type, Numbers.wrapperToPrimitive(getElementType())));
+ final NumberType t = NumberType.forNumberClass(type);
+ if (t.isWiderThan(expected)) {
+ throw new ClassCastException(Errors.format(Errors.Keys.CanNotConvertFromType_2, type, expected.primitive));
}
}
@@ -541,7 +539,7 @@ abstract class ArrayVector<E extends Number> extends Vector implements CheckedCo
@Override public long longValue(int index) {return array[index];}
@Override public final Number get(int index) {return longValue(index);}
@Override public final Number set(int index, final Number value) {
- verifyType(value, Numbers.LONG);
+ verifyType(value, NumberType.LONG);
final Number old = get(index);
array[index] = value.longValue();
modCount++;
@@ -550,7 +548,7 @@ abstract class ArrayVector<E extends Number> extends Vector implements CheckedCo
/** Sets the value of all elements in the given range. */
@Override public void fill(final int fromIndex, final int toIndex, final Number value) {
- verifyType(value, Numbers.LONG);
+ verifyType(value, NumberType.LONG);
Arrays.fill(array, fromIndex, toIndex, value.longValue());
modCount++;
}
@@ -671,7 +669,7 @@ abstract class ArrayVector<E extends Number> extends Vector implements CheckedCo
@Override public int intValue(int index) {return array[index];}
@Override public Number get(int index) {return array[index];}
@Override public final Number set(int index, final Number value) {
- verifyType(value, Numbers.INTEGER);
+ verifyType(value, NumberType.INTEGER);
final Number old = get(index);
array[index] = value.intValue();
modCount++;
@@ -680,7 +678,7 @@ abstract class ArrayVector<E extends Number> extends Vector implements CheckedCo
/** Sets the value of all elements in the given range. */
@Override public void fill(final int fromIndex, final int toIndex, final Number value) {
- verifyType(value, Numbers.INTEGER);
+ verifyType(value, NumberType.INTEGER);
Arrays.fill(array, fromIndex, toIndex, value.intValue());
modCount++;
}
@@ -805,7 +803,7 @@ abstract class ArrayVector<E extends Number> extends Vector implements CheckedCo
@Override public short shortValue(int index) {return array[index];}
@Override public Number get(int index) {return array[index];}
@Override public final Number set(int index, final Number value) {
- verifyType(value, Numbers.SHORT);
+ verifyType(value, NumberType.SHORT);
final Number old = get(index);
array[index] = value.shortValue();
modCount++;
@@ -814,7 +812,7 @@ abstract class ArrayVector<E extends Number> extends Vector implements CheckedCo
/** Sets the value of all elements in the given range. */
@Override public void fill(final int fromIndex, final int toIndex, final Number value) {
- verifyType(value, Numbers.SHORT);
+ verifyType(value, NumberType.SHORT);
Arrays.fill(array, fromIndex, toIndex, value.shortValue());
modCount++;
}
@@ -914,7 +912,7 @@ abstract class ArrayVector<E extends Number> extends Vector implements CheckedCo
@Override public byte byteValue(int index) {return array[index];}
@Override public Number get(int index) {return array[index];}
@Override public final Number set(int index, final Number value) {
- verifyType(value, Numbers.BYTE);
+ verifyType(value, NumberType.BYTE);
final Number old = get(index);
array[index] = value.byteValue();
modCount++;
@@ -923,7 +921,7 @@ abstract class ArrayVector<E extends Number> extends Vector implements CheckedCo
/** Sets the value of all elements in the given range. */
@Override public void fill(final int fromIndex, final int toIndex, final Number value) {
- verifyType(value, Numbers.BYTE);
+ verifyType(value, NumberType.BYTE);
Arrays.fill(array, fromIndex, toIndex, value.byteValue());
modCount++;
}
@@ -1052,9 +1050,11 @@ abstract class ArrayVector<E extends Number> extends Vector implements CheckedCo
}
/** Verifies that the given value can be stored as an unsigned integer. */
- @Override void verifyType(final Number value, byte expected) {
+ @Override void verifyType(final Number value, NumberType expected) {
final long v = value.longValue();
- if ((v & ~0xFFFFFFFFL) == 0) expected = Numbers.LONG;
+ if ((v & ~0xFFFFFFFFL) == 0) {
+ expected = NumberType.LONG;
+ }
super.verifyType(value, expected);
}
@@ -1106,9 +1106,11 @@ abstract class ArrayVector<E extends Number> extends Vector implements CheckedCo
}
/** Verifies that the given value can be stored as an unsigned integer. */
- @Override void verifyType(final Number value, byte expected) {
+ @Override void verifyType(final Number value, NumberType expected) {
final int v = value.intValue();
- if ((v & ~0xFFFF) == 0) expected = Numbers.INTEGER;
+ if ((v & ~0xFFFF) == 0) {
+ expected = NumberType.INTEGER;
+ }
super.verifyType(value, expected);
}
@@ -1161,9 +1163,11 @@ abstract class ArrayVector<E extends Number> extends Vector implements CheckedCo
}
/** Verifies that the given value can be stored as an unsigned integer. */
- @Override void verifyType(final Number value, byte expected) {
+ @Override void verifyType(final Number value, NumberType expected) {
final int v = value.intValue();
- if ((v & ~0xFF) == 0) expected = Numbers.SHORT;
+ if ((v & ~0xFF) == 0) {
+ expected = NumberType.SHORT;
+ }
super.verifyType(value, expected);
}
diff --git a/endorsed/src/org.apache.sis.util/main/org/apache/sis/math/ConcatenatedVector.java b/endorsed/src/org.apache.sis.util/main/org/apache/sis/math/ConcatenatedVector.java
index d71f54a3ee..c0a16a0e72 100644
--- a/endorsed/src/org.apache.sis.util/main/org/apache/sis/math/ConcatenatedVector.java
+++ b/endorsed/src/org.apache.sis.util/main/org/apache/sis/math/ConcatenatedVector.java
@@ -18,7 +18,6 @@ package org.apache.sis.math;
import java.io.Serializable;
import org.apache.sis.util.Classes;
-import org.apache.sis.util.Numbers;
import org.apache.sis.measure.NumberRange;
@@ -272,9 +271,9 @@ final class ConcatenatedVector extends Vector implements Serializable {
if (inc != null) {
Number check = second.increment(tolerance);
if (check != null) {
- final Class<? extends Number> type = Numbers.widestClass(inc.getClass(), check.getClass());
- inc = Numbers.cast(inc, type);
- check = Numbers.cast(check, type);
+ NumberType type = NumberType.forNumberClasses(inc.getClass(), check.getClass());
+ inc = type.cast(inc);
+ check = type.cast(check);
if (inc.equals(check)) {
return inc;
}
diff --git a/endorsed/src/org.apache.sis.util/main/org/apache/sis/math/Fraction.java b/endorsed/src/org.apache.sis.util/main/org/apache/sis/math/Fraction.java
index 668a00db40..825e0319a7 100644
--- a/endorsed/src/org.apache.sis.util/main/org/apache/sis/math/Fraction.java
+++ b/endorsed/src/org.apache.sis.util/main/org/apache/sis/math/Fraction.java
@@ -32,7 +32,7 @@ import static org.apache.sis.pending.jdk.JDK19.DOUBLE_PRECISION;
* All {@code Fraction} instances are immutable and thus inherently thread-safe.
*
* @author Martin Desruisseaux (MPO, Geomatys)
- * @version 1.4
+ * @version 1.6
* @since 0.8
*/
public final class Fraction extends Number implements Comparable<Fraction>, Serializable {
@@ -210,7 +210,11 @@ public final class Fraction extends Number implements Comparable<Fraction>, Seri
* It is usually not worth to invoke this method for short-lived instances.</p>
*
* @return a unique instance of a fraction equals to {@code this}.
+ *
+ * @deprecated {@code Fraction} may become a value object with a future Java version,
+ * and this method is incompatible with value objects.
*/
+ @Deprecated(since="1.6", forRemoval=true)
public Fraction unique() {
return POOL.unique(this);
}
diff --git a/endorsed/src/org.apache.sis.util/main/org/apache/sis/math/LinearlyDerivedVector.java b/endorsed/src/org.apache.sis.util/main/org/apache/sis/math/LinearlyDerivedVector.java
index 7a180cc351..89b05004ad 100644
--- a/endorsed/src/org.apache.sis.util/main/org/apache/sis/math/LinearlyDerivedVector.java
+++ b/endorsed/src/org.apache.sis.util/main/org/apache/sis/math/LinearlyDerivedVector.java
@@ -19,7 +19,6 @@ package org.apache.sis.math;
import java.util.Objects;
import java.io.Serializable;
import java.util.function.IntSupplier;
-import org.apache.sis.util.Numbers;
import org.apache.sis.util.internal.shared.Numerics;
import org.apache.sis.measure.NumberRange;
@@ -254,8 +253,8 @@ final class LinearlyDerivedVector extends Vector implements Serializable {
boolean ti = isMinIncluded; isMinIncluded = isMaxIncluded; isMaxIncluded = ti;
}
range = new NumberRange<>(Double.class,
- Numbers.cast(min, Double.class), isMinIncluded,
- Numbers.cast(max, Double.class), isMaxIncluded);
+ (min != null) ? min.doubleValue() : null, isMinIncluded,
+ (max != null) ? max.doubleValue() : null, isMaxIncluded);
}
}
return range;
diff --git a/endorsed/src/org.apache.sis.util/main/org/apache/sis/math/NumberType.java b/endorsed/src/org.apache.sis.util/main/org/apache/sis/math/NumberType.java
new file mode 100644
index 0000000000..0417d7744f
--- /dev/null
+++ b/endorsed/src/org.apache.sis.util/main/org/apache/sis/math/NumberType.java
@@ -0,0 +1,791 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.sis.math;
+
+import java.util.Map;
+import java.util.IdentityHashMap;
+import java.util.Objects;
+import java.util.Optional;
+import java.util.OptionalInt;
+import java.math.BigDecimal;
+import java.math.BigInteger;
+import org.apache.sis.util.resources.Errors;
+import org.apache.sis.util.internal.shared.DoubleDouble;
+import org.apache.sis.util.internal.shared.Strings;
+
+
+/**
+ * Type of numbers recognized by Apache <abbr>SIS</abbr>, together with primitive types by extension.
+ * This enumeration includes the standard Java numeric types together with subclasses of {@link Number}
+ * provided by <abbr>SIS</abbr>.
+ *
+ * <h2>Order</h2>
+ * Loosely speaking, enumeration values are ordered from narrowest type (with {@link #VOID} viewed
+ * as if it was a numeric type of size 0) to widest type, with types of variable size ordered last.
+ * Some ambiguity exist, in particular between {@link #FRACTION}, {@link #LONG} and {@link #DOUBLE}.
+ * Nevertheless, this enumeration provides the following guarantees:
+ *
+ * <ul>
+ * <li>The ordinal value of the {@link #VOID} value is 0.</li>
+ * <li>Primitive types are enumerated in this exact order, but not necessarily as consecutive values:
+ * {@link #BYTE}, {@link #SHORT}, {@link #INTEGER}, {@link #LONG}, {@link #FLOAT}, {@link #DOUBLE}.</li>
+ * <li>{@link #BIG_INTEGER} and {@link #BIG_DECIMAL} are ordered after primitive types.</li>
+ * </ul>
+ *
+ * @author Martin Desruisseaux (IRD, Geomatys)
+ * @version 1.6
+ *
+ * @see org.apache.sis.util.Numbers
+ * @see org.apache.sis.image.DataType
+ *
+ * @since 1.6
+ */
+public enum NumberType {
+ /**
+ * The void type, viewed as if it was a numeric type with a size of 0 bit.
+ */
+ VOID(Void.TYPE, Void.class, (byte) 0, (byte) 0),
+
+ /**
+ * The {@code boolean} primitive type or its wrapper class.
+ * This is sometime handled as an integer value which accepts only the values 0 and 1.
+ * This is considered as a type with a {@linkplain #size() size} of 1 bit.
+ */
+ BOOLEAN(Boolean.TYPE, Boolean.class, (byte) 0, (byte) 1) {
+ @Override public Comparable<?> nilValue() {return Boolean.FALSE;}
+ @Override public Comparable<?> parse(String text) {
+ Boolean n = Strings.parseBoolean(Objects.requireNonNull(text));
+ if (n != null) return n;
+ throw new IllegalArgumentException(Errors.format(Errors.Keys.CanNotParse_1, text));
+ }
+ },
+
+ /**
+ * The {@code byte} primitive type or its wrapper class.
+ */
+ BYTE(Byte.TYPE, Byte.class, (byte) 1, (byte) Byte.SIZE) {
+ @Override public Comparable<?> nilValue() {return (byte) 0;}
+ @Override public Comparable<?> parse (String n) {return Byte.valueOf(n);}
+ @Override public Number cast (Number n) {return (n == null || n instanceof Byte) ? n : n.byteValue();}
+ @Override public Number wrapExact(long n) {return verify((byte) n, n);}
+ @Override public Number wrapExact(double n) {return verify((byte) n, n);}
+ },
+
+ /**
+ * The {@code char} primitive type or its wrapper class.
+ * This is sometime handled as a 16 bits unsigned integer value.
+ * This enumeration value is defined for completeness but is rarely used by <abbr>SIS</abbr>.
+ */
+ CHARACTER(Character.TYPE, Character.class, (byte) 0, (byte) Character.SIZE) {
+ @Override public boolean isWiderThan (NumberType other) {return other.ordinal() <= BYTE.ordinal();}
+ @Override public boolean isNarrowerThan(NumberType other) {return other.isBetween(INTEGER, BIG_DECIMAL);}
+ @Override public Comparable<?> nilValue() {return (char) 0;}
+ @Override public Comparable<?> parse(String text) {
+ switch (text.length()) {
+ case 0: return (char) 0; // Means "end of string" in C/C++ and NULL in Unicode standard.
+ case 1: return text.charAt(0);
+ default: throw new IllegalArgumentException(Errors.format(Errors.Keys.CanNotParse_1, text));
+ }
+ }
+ },
+
+ /**
+ * The {@code short} primitive type or its wrapper class.
+ */
+ SHORT(Short.TYPE, Short.class, (byte) 1, (byte) Short.SIZE) {
+ @Override public Comparable<?> nilValue() {return (short) 0;}
+ @Override public Comparable<?> parse (String n) {return Short.valueOf(n);}
+ @Override public Number cast (Number n) {return (n == null || n instanceof Short) ? n : n.shortValue();}
+ @Override public Number wrapExact(long n) {return verify((short) n, n);}
+ @Override public Number wrapExact(double n) {return verify((short) n, n);}
+ },
+
+ /**
+ * The {@code int} primitive type or its wrapper class.
+ */
+ INTEGER(Integer.TYPE, Integer.class, (byte) 1, (byte) Integer.SIZE) {
+ @Override public Comparable<?> nilValue() {return 0;}
+ @Override public Comparable<?> parse (String n) {return Integer.valueOf(n);}
+ @Override public Number cast (Number n) {return (n == null || n instanceof Integer) ? n : n.intValue();}
+ @Override public Number wrapExact(long n) {return verify((int) n, n);}
+ @Override public Number wrapExact(double n) {return verify((int) n, n);}
+ @Override public boolean isConversionLossless(NumberType target) {
+ return target.isBetween(INTEGER, BIG_DECIMAL) && target != FLOAT;
+ }
+ },
+
+ /**
+ * The {@link Fraction} class. This is a ratio of two {@link #INTEGER} values.
+ */
+ FRACTION(Fraction.class, Fraction.class, (byte) 2, (byte) (2 * Integer.SIZE)) {
+ @Override public Comparable<?> nilValue() {return new Fraction(0, 0);}
+ @Override public Comparable<?> parse (String n) {return new Fraction(n);}
+ @Override public Number cast (Number n) {return (n == null || n instanceof Fraction) ? n : Fraction.valueOf(n.doubleValue());}
+ @Override public Number wrapExact(double n) {return Fraction.valueOf(n);} // Verification done by constructor.
+ @Override public Number wrapExact(long n) {return verify(new Fraction((int) n, 1), n);}
+ @Override public boolean isConversionLossless(NumberType target) {
+ return equals(target); // Implicit null check.
+ }
+ },
+
+ /**
+ * The {@code long} primitive type or its wrapper class.
+ */
+ LONG(Long.TYPE, Long.class, (byte) 1, (byte) Long.SIZE) {
+ @Override public Comparable<?> nilValue() {return 0L;}
+ @Override public Comparable<?> parse (String n) {return Long.valueOf(n);}
+ @Override public Number cast (Number n) {return (n == null || n instanceof Long) ? n : n.longValue();}
+ @Override public Number wrapExact(long n) {return n;}
+ @Override public Number wrapExact(double n) {return verify((long) n, n);}
+ @Override public boolean isConversionLossless(NumberType target) {
+ return target.isBetween(DOUBLE_DOUBLE, BIG_DECIMAL) || target == this;
+ }
+ },
+
+ /**
+ * The {@code float} primitive type or its wrapper class.
+ */
+ FLOAT(Float.TYPE, Float.class, (byte) 2, (byte) Float.SIZE) {
+ @Override public Comparable<?> nilValue() {return Float.NaN;}
+ @Override public Comparable<?> parse (String n) {return Float.valueOf(n);}
+ @Override public Number cast (Number n) {return (n == null || n instanceof Float) ? n : n.floatValue();}
+ @Override public Number wrapExact(double n) {return verify((float) n, n);}
+ @Override public Number wrapExact(long n) {return verify((float) n, n);}
+ @Override public boolean isConversionLossless(NumberType target) {
+ return target.isBetween(FLOAT, DOUBLE_DOUBLE);
+ }
+ },
+
+ /**
+ * The {@code double} primitive type or its wrapper class.
+ */
+ DOUBLE(Double.TYPE, Double.class, (byte) 2, (byte) Double.SIZE) {
+ @Override public Comparable<?> nilValue() {return Double.NaN;}
+ @Override public Comparable<?> parse (String n) {return Double.valueOf(n);}
+ @Override public Number cast (Number n) {return (n == null || n instanceof Double) ? n : n.doubleValue();}
+ @Override public Number wrapExact(double n) {return n;}
+ @Override public Number wrapExact(long n) {return verify((double) n, n);}
+ @Override public boolean isConversionLossless(NumberType target) {
+ return target.isBetween(DOUBLE, DOUBLE_DOUBLE);
+ }
+ },
+
+ /**
+ * An internal type used by <abbr>SIS</abbr> for double-double precision arithmetic.
+ *
+ * @hidden
+ */
+ DOUBLE_DOUBLE(DoubleDouble.class, DoubleDouble.class, (byte) 2, (byte) (2 * Double.SIZE)) {
+ @Override public Comparable<?> nilValue() {return DoubleDouble.NaN;}
+ @Override public Number wrapExact(long n) {return DoubleDouble.of(n);}
+ @Override public Number wrapExact(double n) {return DoubleDouble.of(n, false);}
+ @Override public Number cast (Number n) {return DoubleDouble.of(n, false);}
+ },
+
+ /**
+ * The {@link BigInteger} class.
+ */
+ BIG_INTEGER(BigInteger.class, BigInteger.class, (byte) 1, (byte) -1) {
+ @Override public Comparable<?> nilValue() {return BigInteger.ZERO;}
+ @Override public Number wrapExact(long n) {return BigInteger.valueOf(n);}
+ @Override public Number wrapExact(double n) {return verify(BigDecimal.valueOf((long) n), n);}
+ @Override public Comparable<?> parse (String n) {return new BigInteger(n);}
+ @Override public Number cast (Number n) {
+ if (n == null || n instanceof BigInteger) {
+ return n;
+ } else if (n instanceof BigDecimal) {
+ return ((BigDecimal) n).toBigInteger();
+ } else {
+ return BigInteger.valueOf(n.longValue());
+ }
+ }
+ },
+
+ /**
+ * The {@link BigDecimal} class.
+ */
+ BIG_DECIMAL(BigDecimal.class, BigDecimal.class, (byte) 2, (byte) -1) {
+ @Override public Comparable<?> nilValue() {return BigDecimal.ZERO;}
+ @Override public Number wrapExact(long n) {return BigDecimal.valueOf(n);}
+ @Override public Number wrapExact(double n) {return BigDecimal.valueOf(n);}
+ @Override public Comparable<?> parse (String n) {return new BigDecimal(n);}
+ @Override public Number cast (Number n) {
+ if (n == null || n instanceof BigDecimal) {
+ return n;
+ } else if (n instanceof BigInteger) {
+ return new BigDecimal((BigInteger) n);
+ } else if (isInteger(n.getClass())) {
+ return BigDecimal.valueOf(n.longValue());
+ } else {
+ return new BigDecimal(n.toString()); // Like `BigDecimal.valueOf(double)` but better with `Float`.
+ }
+ }
+ },
+
+ /**
+ * Any {@link Number} class not recognized by Apache <abbr>SIS</abbr>.
+ */
+ NUMBER(Number.class, Number.class, (byte) 3, (byte) -1),
+
+ /**
+ * The null type, used when a {@code Class} argument is {@code null}.
+ * This is the only enumeration value for which {@link #classOfValues(boolean)} returns {@code null}.
+ */
+ NULL(null, null, (byte) 0, (byte) -1);
+
+ /**
+ * The primitive type, or {@link #wrapper} if none.
+ *
+ * @see #classOfValues(boolean)
+ * @see Class#isPrimitive()
+ */
+ final Class<?> primitive;
+
+ /**
+ * The wrapper for the primitive type.
+ *
+ * @see #classOfValues(boolean)
+ */
+ final Class<?> wrapper;
+
+ /**
+ * A classification of the set that contains this type. Supported values are:
+ *
+ * <ul>
+ * <li>0 for non-numeric types ({@link #VOID}, {@link #BOOLEAN}, {@link #CHARACTER}, {@link #NULL}).</li>
+ * <li>1 for integers.</li>
+ * <li>2 for types capable to store fractional digits.</li>
+ * <li>3 for unknown numeric type ({@link #NUMBER}).</li>
+ * </ul>
+ *
+ * These values are mutually exclusive.
+ *
+ * @see #isInteger()
+ * @see #isFractional()
+ * @see #isNumber()
+ */
+ private final byte category;
+
+ /**
+ * The size in bits, or -1 if variable.
+ */
+ private final byte size;
+
+ /**
+ * Creates an enumeration value.
+ *
+ * @param primitive the primitive type, or {@code wrapper} if none.
+ * @param wrapper the wrapper for the primitive type.
+ * @param category 0=non-numeric, 1=integers, 2=fractional, 3=other.
+ * @param size the size in bits, or -1 if variable.
+ */
+ private NumberType(final Class<?> primitive, final Class<?> wrapper, final byte category, final byte size) {
+ this.primitive = primitive;
+ this.wrapper = wrapper;
+ this.category = category;
+ this.size = size;
+ }
+
+ /**
+ * Mapping between a type and the enumeration value, if any.
+ *
+ * <h4>Implementation note</h4>
+ * In the particular case of {@code Class} keys, {@code IdentityHashMap} and {@code HashMap} have identical
+ * behavior since {@code Class} is final and does not override the {@code equals(Object)} and {@code hashCode()}
+ * methods. The {@code IdentityHashMap} Javadoc claims that it is faster than the regular {@code HashMap}.
+ * But maybe the most interesting property is that it allocates less objects since {@code IdentityHashMap}
+ * implementation does not need the chain of objects created by {@code HashMap}.
+ */
+ private static final Map<Class<?>, NumberType> MAPPING = new IdentityHashMap<>(13);
+ static {
+ for (NumberType e : values()) {
+ MAPPING.put(e.primitive, e);
+ MAPPING.put(e.wrapper, e);
+ }
+ }
+
+ /**
+ * Returns the enumeration value for the given type, or {@code null} if none.
+ * This method does not handle the {@link Number} special case.
+ *
+ * @param type the primitive type or {@link Number} class to test (can be {@code null}).
+ * @return the enumeration value for the given type, or {@code null} if none.
+ */
+ private static NumberType valueOrNull(final Class<?> type) {
+ return MAPPING.get(type);
+ }
+
+ /**
+ * Returns the enumeration value for the given class.
+ * If the {@code type} argument is null, returns {@link #NULL}.
+ * If the {@code type} is an unrecognized {@link Number} class, returns the generic {@link #NUMBER} value.
+ * If the {@code type} is an unrecognized non-numerical class, returns an empty value.
+ *
+ * @param type the primitive type or {@link Number} class for which to get an enumeration value, or {@code null}.
+ * @return the enumeration value for the given type. May be {@link #NULL} if the given value was null.
+ */
+ public static Optional<NumberType> forClass(final Class<?> type) {
+ NumberType value = valueOrNull(type); // This is `NULL` if `type` is null.
+ if (value == null && Number.class.isAssignableFrom(type)) {
+ value = NUMBER;
+ }
+ return Optional.ofNullable(value);
+ }
+
+ /**
+ * Returns the enumeration value for the given numeric class. This method is equivalent to
+ * <code>{@linkplain #forClass(Class) forClass}(type).orElseThrow()</code> except that the
+ * exception is an {@link IllegalArgumentException}. The exception is never thrown if the
+ * given class is a primitive type, its wrapper, or a class assignable to {@link Number}.
+ *
+ * @param type the primitive type or {@link Number} class for which to get an enumeration value, or {@code null}.
+ * @return the enumeration value for the given type. Never {@code null} but may be {@link #NULL}.
+ * @throws IllegalArgumentException if the given class cannot be mapped to any enumeration value.
+ */
+ public static NumberType forNumberClass(final Class<?> type) {
+ NumberType value = valueOrNull(type);
+ if (value != null) return value;
+ if (Number.class.isAssignableFrom(type)) return NUMBER;
+ throw new IllegalArgumentException(Errors.format(Errors.Keys.NotANumericalType_1, type));
+ }
+
+ /**
+ * Returns an enumeration value capable to represent at least approximately all the given classes.
+ * Null elements are ignored. If the given array is null or does not contain at least one non-null
+ * element, then {@link #NULL} is returned. If the array contains at least one element that cannot
+ * be mapped to an enumeration value, then an empty value is returned.
+ *
+ * <h4>Accuracy</h4>
+ * This method does not guarantee that conversions from the given classes to the returned type will be lossless.
+ * For example, conversions form {@code long} to {@code double} are not lossless.
+ * However, the results of those conversions should be reasonable approximations.
+ *
+ * @param types the primitive types or {@link Number} classes for which to get a common enumeration value.
+ * @return the enumeration value for the given types. May be {@link #NULL} if all given values were null.
+ */
+ public static Optional<NumberType> forClasses(final Class<?>... types) {
+ return Optional.ofNullable(forClasses(true, types));
+ }
+
+ /**
+ * Returns an enumeration value capable to represent at least approximately all the given numeric classes.
+ * This method is equivalent to <code>{@linkplain #forClasses(Class) forClass}(types).orElseThrow()</code>
+ * except that the exception is an {@link IllegalArgumentException}. The exception is never thrown if all
+ * the given classes are primitive types, their wrappers, or classes assignable to {@link Number}.
+ *
+ * @param types the primitive types or {@link Number} classes for which to get a common enumeration value.
+ * @return the enumeration value for the given types. Never {@code null} but may be {@link #NULL}.
+ * @throws IllegalArgumentException if one of the given classes cannot be mapped to any enumeration value.
+ */
+ public static NumberType forNumberClasses(final Class<?>... types) {
+ return forClasses(false, types);
+ }
+
+ /**
+ * Implementation of the public {@code forClasses(…)} and {@code forNumberClasses(…)} methods.
+ *
+ * @param optional whether to return {@code null} instead of throwing an exception.
+ * @param types the primitive types or {@link Number} classes for which to get a common enumeration value.
+ * @return the enumeration value for the given types, or {@code null}.
+ */
+ private static NumberType forClasses(final boolean optional, final Class<?>... types) {
+ NumberType widest = VOID;
+ boolean found = false;
+ if (types != null) {
+ for (final Class<?> type : types) {
+ final NumberType other = forClass(type).orElse(null);
+ if (other == null) {
+ if (optional) return null;
+ throw new IllegalArgumentException(Errors.format(Errors.Keys.NotANumericalType_1, type));
+ }
+ switch (other) {
+ case NULL: continue;
+ case NUMBER: widest = other; continue;
+ }
+ found = true;
+ if (widest.isNarrowerThan(other)) {
+ widest = other;
+ }
+ }
+ }
+ return found ? widest : NULL;
+ }
+
+ /**
+ * Returns {@code true} if this type is an integer type.
+ * Those types are {@link #BYTE}, {@link #SHORT}, {@link #INTEGER}, {@link #LONG} and {@link #BIG_INTEGER}.
+ *
+ * @return whether this type is an integer type.
+ */
+ public final boolean isInteger() {
+ return category == 1;
+ }
+
+ /**
+ * Returns {@code true} if the argument is one of the integer types known to <abbr>SIS</abbr>.
+ * Those types are {@code byte}, {@link Byte}, {@code short}, {@link Short}, {@code int}, {@link Integer},
+ * {@code long}, {@link Long} and {@link BigInteger}.
+ *
+ * <p>This method is mutually exclusive with {@link #isFractional()}:
+ * only one of those two methods may return {@code true}.
+ * However, both methods may return {@code false}.</p>
+ *
+ * @param type the primitive type or {@link Number} subclass to test (can be {@code null}).
+ * @return {@code true} if {@code type} is one of the known types used to represent integers.
+ */
+ public static boolean isInteger(final Class<?> type) {
+ final NumberType value = valueOrNull(type);
+ return (value != null) && value.isInteger();
+ }
+
+ /**
+ * Returns {@code true} if this type is capable to store fractional digits.
+ * Those types are {@link #FRACTION}, {@link #FLOAT}, {@link #DOUBLE} and {@link #BIG_DECIMAL}.
+ * Floating point types are considered as types or rational numbers where the denominator is a power of 2 or 10.
+ *
+ * <p>This method is mutually exclusive with {@link #isInteger()}:
+ * only one of those two methods may return {@code true}.
+ * However, both methods may return {@code false}.</p>
+ *
+ * @return whether this type is a rational or floating point type.
+ */
+ public final boolean isFractional() {
+ return category == 2;
+ }
+
+ /**
+ * Returns {@code true} if the argument is one of the types known to <abbr>SIS</abbr>
+ * as capable to store fractional digits. This method returns {@code true} for the following types:
+ * {@link Fraction}, {@code float}, {@link Float}, {@code double}, {@link Double} and {@link BigDecimal}.
+ *
+ * @param type the primitive type or {@link Number} subclass to test (can be {@code null}).
+ * @return {@code true} if {@code type} is one of the known types capable to store fractional digits.
+ */
+ public static boolean isFractional(final Class<?> type) {
+ final NumberType value = valueOrNull(type);
+ return (value != null) && value.isFractional();
+ }
+
+ /**
+ * Returns {@code true} if this type is any type of real numbers. This method returns {@code true}
+ * for all {@linkplain #isInteger() integer} and {@linkplain #isFractional() fractional} types.
+ *
+ * @return whether this type is any type of real numbers.
+ */
+ public final boolean isReal() {
+ return category != 0;
+ }
+
+ /**
+ * Returns whether this type supports the {@code cast(…)} and {@code wrap(…)} methods.
+ * This is true for all {@linkplain #isReal() real numbers} except {@link #NUMBER}.
+ *
+ * @return whether this type supports the {@code cast(…)} and {@code wrap(…)} methods.
+ */
+ public final boolean isConvertible() {
+ return category == 1 || category == 2;
+ }
+
+ /**
+ * Returns {@code true} if the argument is one of the real number types known to <abbr>SIS</abbr>.
+ * This method returns {@code true} for all {@linkplain #isInteger(Class) integer}
+ * and {@linkplain #isFractional(Class) fractional} types.
+ *
+ * @param type the primitive type or {@link Number} subclass to test (can be {@code null}).
+ * @return {@code true} if {@code type} is one of the known types used to represent real numbers.
+ */
+ public static boolean isReal(final Class<?> type) {
+ final NumberType value = valueOrNull(type);
+ return (value != null) && value.isReal();
+ }
+
+ /**
+ * Returns whether the ordinal value is between the given boundaries. Both bounds are inclusive.
+ * If {@code lower} ≥ {@code upper}, then this method always returns {@code false}.
+ *
+ * @param lower the lower bound, inclusive.
+ * @param upper the upper bound, inclusive.
+ * @return whether this enumeration value is between the given bounds.
+ */
+ final boolean isBetween(final NumberType lower, final NumberType upper) {
+ return ordinal() >= lower.ordinal() && ordinal() <= upper.ordinal();
+ }
+
+ /**
+ * Returns whether this type is considered narrower than the specified type.
+ * If one of the type is unknown, then this method conservatively returns {@code false}.
+ *
+ * <h4>Accuracy</h4>
+ * Note that conversions from the narrowest class are not guaranteed to be lossless.
+ * For example, {@code long} is considered a narrower class than {@code double},
+ * but conversion from {@code long} to {@code double} can nevertheless loose accuracy.
+ * However, if this method returns {@code true}, then conversions to {@code other} type
+ * should produce at least a reasonable approximation of the original value.
+ *
+ * @param other the other type.
+ * @return whether this type is considered narrower than the specified type.
+ */
+ public boolean isNarrowerThan(final NumberType other) {
+ if (other == CHARACTER) {
+ return other.isWiderThan(this);
+ }
+ return other.ordinal() < NUMBER.ordinal()
+ && ordinal() < other.ordinal()
+ && category <= other.category; // Integers considered narrower than floating-point types.
+ }
+
+ /**
+ * Returns whether this type is considered wider than the specified type.
+ * If one of the type is unknown, then this method conservatively returns {@code false}.
+ *
+ * <h4>Accuracy</h4>
+ * Note that conversions to the widest class are not guaranteed to be lossless.
+ * For example, {@code double} is considered a wider class than {@code long}, but
+ * conversion from {@code long} to {@code double} can nevertheless loose accuracy.
+ * However, if this method returns {@code true}, then conversions to this type
+ * should produce at least a reasonable approximation of the original value.
+ *
+ * @param other the other type.
+ * @return whether this type is considered wider than the specified type.
+ */
+ public boolean isWiderThan(final NumberType other) {
+ if (other == CHARACTER) {
+ return other.isNarrowerThan(this);
+ }
+ return ordinal() < NUMBER.ordinal()
+ && ordinal() > other.ordinal()
+ && category >= other.category; // Floating-point types considered wider than integers.
+ }
+
+ /**
+ * Returns whether conversion of values from this type to the specified type would be lossless.
+ * If this type supports negative zero and NaN values, then the target type must also supports
+ * these values for the conversion to be considered lossless.
+ *
+ * @param target the target type.
+ * @return whether conversions to the target type would be lossless, including negative zero and NaN.
+ */
+ public boolean isConversionLossless(final NumberType target) {
+ return target == this || isNarrowerThan(target);
+ }
+
+ /**
+ * Returns the primitive or wrapper class represented by this enumeration value.
+ * If there is no primitive type, then this method always returns the class.
+ * The returned class is null in the particular case of the {@link #NULL} type,
+ * and non-null for all other types.
+ *
+ * @param primitive {@code true} for the primitive type, or {@code false} for the wrapper class.
+ * @return the primitive or wrapper class represented by this enumeration value, or {@code null}.
+ *
+ * @see Class#isPrimitive()
+ */
+ public final Class<?> classOfValues(final boolean primitive) {
+ return primitive ? this.primitive : wrapper;
+ }
+
+ /**
+ * Changes a primitive class to its wrapper (for example {@code int} to {@link Integer}).
+ * If the specified class is not a primitive type, then it is returned unchanged.
+ *
+ * @param <N> the primitive and wrapper type (both have the same parametric declaration).
+ * @param type the primitive type (can be {@code null}).
+ * @return the type as a wrapper.
+ *
+ * @see #wrapperToPrimitive(Class)
+ * @see Class#isPrimitive()
+ */
+ @SuppressWarnings("unchecked")
+ public static <N> Class<N> primitiveToWrapper(final Class<N> type) {
+ final NumberType value = valueOrNull(type);
+ return (value != null) ? (Class<N>) value.wrapper : type;
+ }
+
+ /**
+ * Changes a wrapper class to its primitive (for example {@link Integer} to {@code int}).
+ * If the specified class is not a wrapper type, then it is returned unchanged.
+ *
+ * @param <N> the primitive and wrapper type (both have the same parametric declaration).
+ * @param type the wrapper type (can be {@code null}).
+ * @return the type as a primitive.
+ *
+ * @see #primitiveToWrapper(Class)
+ * @see Class#isPrimitive()
+ */
+ @SuppressWarnings("unchecked")
+ public static <N> Class<N> wrapperToPrimitive(final Class<N> type) {
+ final NumberType value = valueOrNull(type);
+ return (value != null) ? (Class<N>) value.primitive : type;
+ }
+
+ /**
+ * Returns the number of bits used in the representation of this type.
+ * This size is accurate for values objects such as primitive types.
+ * For other objects, the returned size does not include the space
+ * occupied by object headers and object references.
+ *
+ * @return the number of bits, or empty if the size is unknown or variable.
+ */
+ public final OptionalInt size() {
+ return (size != -1) ? OptionalInt.of(Byte.toUnsignedInt(size)) : OptionalInt.empty();
+ }
+
+ /**
+ * Verifies that the given number contains the expected value.
+ * This is a helper method for {@code wrapExact(…)} implementations.
+ *
+ * @param number the wrapped value.
+ * @param expected the value which has been wrapped.
+ * @throws ArithmeticException if the given number does not contain the expected value.
+ */
+ final Number verify(final Number number, final long expected) {
+ if (number.longValue() == expected) {
+ return number;
+ }
+ throw new ArithmeticException(Errors.format(Errors.Keys.CanNotConvertValue_2, expected, wrapper));
+ }
+
+ /**
+ * Verifies that the given number contains the expected value.
+ * This is a helper method for {@code wrapExact(…)} implementations.
+ * This method does not distinguish positive zero from negative zero and the various NaN values.
+ *
+ * @param number the wrapped value.
+ * @param expected the value which has been wrapped.
+ * @throws ArithmeticException if the given number does not contain the expected value.
+ */
+ final Number verify(final Number number, final double expected) {
+ final double unwrap = number.doubleValue();
+ if (unwrap == expected || (Double.isNaN(unwrap) && Double.isNaN(expected))) {
+ return number;
+ }
+ throw new ArithmeticException(Errors.format(Errors.Keys.CanNotConvertValue_2, expected, wrapper));
+ }
+
+ /**
+ * Casts a value to the specified type without checking whether is would cause precision lost.
+ * This method makes the following choice:
+ *
+ * <ul>
+ * <li>If this type is {@link #DOUBLE}, then this method returns
+ * <code>{@linkplain Double#valueOf(double) Double.valueOf}(number.doubleValue())</code>;</li>
+ * <li>Otherwise if this type is {@link #FLOAT}, then this method returns
+ * <code>{@linkplain Float#valueOf(float) Float.valueOf}(number.floatValue())</code>;</li>
+ * <li>And likewise for other types in this enumeration.</li>
+ * </ul>
+ *
+ * This method does not verify if this type is wide enough for the given number,
+ * If this type is not wide enough, then the behavior depends on the implementation of the corresponding
+ * {@code Number.fooValue()} method - typically, the value is just rounded or truncated.
+ *
+ * @param number the number to cast, or {@code null}.
+ * @return the number cast to this type, or {@code null} if the given number was null.
+ * @throws UnsupportedOperationException if this type cannot cast numbers.
+ * @throws NullPointerException if {@code number} is null.
+ * @throws IllegalArgumentException if the number cannot be converted to this type
+ * (e.g., {@link Double#NaN} cannot be converted to {@link BigDecimal}).
+ *
+ * @see org.apache.sis.util.Numbers#cast(Number, Class)
+ */
+ public Number cast(Number number) {
+ if (number == null) {
+ return number;
+ }
+ throw new UnsupportedOperationException(Errors.format(Errors.Keys.UnknownType_1, this));
+ }
+
+ /**
+ * Wraps the given floating-point value in an object of the type represented by this enumeration value.
+ * The returned value is an instance of the wrapper class returned by
+ * <code>{@link #classOfValues(boolean) classOfValues}(false)</code>.
+ * The given value shall be convertible to that type without precision lost,
+ * otherwise an {@link ArithmeticException} will be thrown.
+ *
+ * <p>This method does not guaranteed that the sign of zero is preserved
+ * (i.e., negative zero is considered equivalent to positive zero)
+ * and does not guaranteed that the various NaN values are preserved
+ * (i.e., NaN may be replaced by the canonical {@link Double#NaN}).</p>
+ *
+ * @param number the number to wrap.
+ * @return the value wrapped in an object of the wrapper class represented by this enumeration value.
+ * @throws UnsupportedOperationException if this type cannot wrap numbers.
+ * @throws ArithmeticException if the given value cannot be converted without precision lost.
+ *
+ * @see org.apache.sis.util.Numbers#wrap(double, Class)
+ */
+ public Number wrapExact(final double number) {
+ throw new UnsupportedOperationException(Errors.format(Errors.Keys.CanNotConvertValue_2, number, wrapper));
+ }
+
+ /**
+ * Wraps the given integer value in an object of the type represented by this enumeration value.
+ * The returned value is an instance of the wrapper class returned by
+ * <code>{@link #classOfValues(boolean) classOfValues}(false)</code>.
+ * The given value shall be convertible to that type without precision lost,
+ * otherwise an {@link ArithmeticException} will be thrown.
+ *
+ * @param number the number to wrap.
+ * @return the value wrapped in an object of the wrapper class represented by this enumeration value.
+ * @throws UnsupportedOperationException if this type cannot wrap numbers.
+ * @throws ArithmeticException if the given value cannot be converted without precision lost.
+ *
+ * @see org.apache.sis.util.Numbers#wrap(long, Class)
+ */
+ public Number wrapExact(final long number) {
+ throw new UnsupportedOperationException(Errors.format(Errors.Keys.CanNotConvertValue_2, number, wrapper));
+ }
+
+ /**
+ * Converts the specified string into a value object.
+ * The returned value is an instance of the wrapper class returned by
+ * <code>{@link #classOfValues(boolean) classOfValues}(false)</code>.
+ *
+ * <ul>
+ * <li>If this type is {@link #DOUBLE}, then this method returns
+ * <code>{@linkplain Double#valueOf(String) Double.valueOf}(value)</code>;</li>
+ * <li>If this type is {@link #FLOAT}, then this method returns
+ * <code>{@linkplain Float#valueOf(String) Float.valueOf}(value)</code>;</li>
+ * <li>And likewise for all other known types.</li>
+ * </ul>
+ *
+ * @param text the value to parse.
+ * @return the value object.
+ * @throws UnsupportedOperationException if this type does not support parsing.
+ * @throws NullPointerException if {@code text} is null.
+ * @throws IllegalArgumentException if {@code text} is not parsable as a value of this type.
+ *
+ * @see org.apache.sis.util.Numbers#valueOf(String, Class)
+ */
+ public Comparable<?> parse(String text) {
+ throw new UnsupportedOperationException(Errors.format(Errors.Keys.UnparsableStringForClass_2, wrapper, text));
+ }
+
+ /**
+ * Returns the closest value that can be interpreted as <q>no data</q>, which is not the same as zero.
+ * This method returns {@code NaN}, {@code 0} or {@code false} or {@code null}, in this preference order.
+ * The returned value is an instance of the wrapper class returned by
+ * <code>{@link #classOfValues(boolean) classOfValues}(false)</code>.
+ *
+ * @return the {@code NaN}, {@code 0} or {@code false} or {@code null} value, in this preference order.
+ *
+ * @see org.apache.sis.util.Numbers#valueOfNil(Class)
+ */
+ public Comparable<?> nilValue() {
+ // Defined in subclasses rather than stored in a field for deferrred class loading.
+ return null;
+ }
+}
diff --git a/endorsed/src/org.apache.sis.util/main/org/apache/sis/math/PackedVector.java b/endorsed/src/org.apache.sis.util/main/org/apache/sis/math/PackedVector.java
index 28d372ef57..35022f8262 100644
--- a/endorsed/src/org.apache.sis.util/main/org/apache/sis/math/PackedVector.java
+++ b/endorsed/src/org.apache.sis.util/main/org/apache/sis/math/PackedVector.java
@@ -16,7 +16,6 @@
*/
package org.apache.sis.math;
-import org.apache.sis.util.Numbers;
import org.apache.sis.util.collection.IntegerList;
import org.apache.sis.util.resources.Errors;
@@ -205,7 +204,7 @@ final class PackedVector extends ArrayVector<Long> {
*/
@Override
public Number set(final int index, final Number value) {
- verifyType(value, Numbers.LONG);
+ verifyType(value, NumberType.LONG);
long v = value.longValue();
if (v >= offset) {
v -= offset;
diff --git a/endorsed/src/org.apache.sis.util/main/org/apache/sis/math/Vector.java b/endorsed/src/org.apache.sis.util/main/org/apache/sis/math/Vector.java
index e3d9f87d1d..103815c47d 100644
--- a/endorsed/src/org.apache.sis.util/main/org/apache/sis/math/Vector.java
+++ b/endorsed/src/org.apache.sis.util/main/org/apache/sis/math/Vector.java
@@ -90,7 +90,7 @@ import org.apache.sis.system.Loggers;
* method and by accepting buffer in the {@link #create(Object, boolean)} method.
*
* @author Martin Desruisseaux (MPO, Geomatys)
- * @version 1.4
+ * @version 1.6
*
* @see org.apache.sis.util.collection.IntegerList
*
@@ -207,25 +207,25 @@ public abstract class Vector extends AbstractList<Number> implements RandomAcces
* @return the given sequence as a vector.
*/
public static Vector createSequence(final Number first, final Number increment, final int length) {
- Class<? extends Number> type;
- type = Numbers.widestClass(first, increment);
- type = Numbers.widestClass(type,
- Numbers.narrowestClass(first.doubleValue() + increment.doubleValue() * (length-1)));
+ final double last = Math.fma(length - 1, increment.doubleValue(), first.doubleValue());
+ final NumberType type = NumberType.forNumberClasses(
+ Numbers.widestClass(first, increment),
+ Numbers.narrowestClass(last));
return createSequence(type, first, increment, length);
}
/**
* Creates a sequence of the given type.
*/
- static Vector createSequence(final Class<? extends Number> type, final Number first, final Number increment, final int length) {
- final int t = Numbers.getEnumConstant(type);
- if (t >= Numbers.BYTE && t <= Numbers.LONG) {
+ private static Vector createSequence(final NumberType type, final Number first, final Number increment, final int length) {
+ final Class<? extends Number> c = type.wrapper.asSubclass(Number.class);
+ if (type.isConversionLossless(NumberType.LONG)) {
// Use the long type if possible because not all long values can be represented as double.
- return new SequenceVector.Longs(type, first, increment, length);
- } else if (t == Numbers.FLOAT) {
- return new SequenceVector.Floats(type, first, increment, length);
+ return new SequenceVector.Longs(c, first, increment, length);
+ } else if (type == NumberType.FLOAT) {
+ return new SequenceVector.Floats(c, first, increment, length);
} else {
- return new SequenceVector.Doubles(type, first, increment, length);
+ return new SequenceVector.Doubles(c, first, increment, length);
}
}
@@ -265,6 +265,13 @@ public abstract class Vector extends AbstractList<Number> implements RandomAcces
*/
public abstract Class<? extends Number> getElementType();
+ /**
+ * Convenience method for a frequently requested information.
+ */
+ private NumberType getNumberType() {
+ return NumberType.forNumberClass(getElementType());
+ }
+
/**
* Returns {@code true} if values in this vector can be cast to single-precision floating point numbers
* ({@code float}) without precision lost. In case of doubt, this method conservatively returns {@code false}.
@@ -279,8 +286,7 @@ public abstract class Vector extends AbstractList<Number> implements RandomAcces
* @since 1.1
*/
public boolean isSinglePrecision() {
- final byte type = Numbers.getEnumConstant(getElementType());
- return (type == Numbers.FLOAT) || (type >= Numbers.BYTE && type <= Numbers.SHORT);
+ return getNumberType().isConversionLossless(NumberType.FLOAT);
}
/**
@@ -288,11 +294,8 @@ public abstract class Vector extends AbstractList<Number> implements RandomAcces
* This is an estimation only and should be used only as a hint.
*/
private int getBitCount() {
- try {
- return Numbers.primitiveBitCount(getElementType());
- } catch (IllegalArgumentException e) {
- return Integer.SIZE; // Assume references compressed on 32 bits.
- }
+ // If empty, assume references compressed on 32 bits.
+ return getNumberType().size().orElse(Integer.SIZE);
}
/**
@@ -302,7 +305,7 @@ public abstract class Vector extends AbstractList<Number> implements RandomAcces
* @return {@code true} if this vector contains only integer values.
*/
public boolean isInteger() {
- if (!Numbers.isInteger(getElementType())) {
+ if (!NumberType.isInteger(getElementType())) {
for (int i=size(); --i >= 0;) {
if (!Numerics.isInteger(doubleValue(i))) {
return false;
@@ -769,14 +772,14 @@ search: for (;;) {
ArgumentChecks.ensurePositive("tolerance", tolerance);
int i = size();
if (i >= 2) try {
- final int type = Numbers.getEnumConstant(getElementType());
+ final NumberType type = getNumberType();
/*
* For integer types, verify if the increment is constant. We do not use the "first + inc*i"
* formula because some `long` values cannot be represented accurately as `double` values.
* The result will be converted to the same type as the vector element type if possible,
* or the next wider type if the increment is an unsigned value too big for the element type.
*/
- if (type >= Numbers.BYTE && type <= Numbers.LONG && tolerance < 0.5) {
+ if (type.isConversionLossless(NumberType.LONG) && tolerance < 0.5) {
long p;
final long inc = subtract(longValue(--i), p = longValue(--i));
while (i != 0) {
@@ -785,9 +788,9 @@ search: for (;;) {
}
}
switch (type) {
- case Numbers.BYTE: if (inc >= Byte .MIN_VALUE && inc <= Byte .MAX_VALUE) return (byte) inc; // else fallthrough
- case Numbers.SHORT: if (inc >= Short .MIN_VALUE && inc <= Short .MAX_VALUE) return (short) inc; // else fallthrough
- case Numbers.INTEGER: if (inc >= Integer.MIN_VALUE && inc <= Integer.MAX_VALUE) return (int) inc; // else fallthrough
+ case BYTE: if (inc >= Byte .MIN_VALUE && inc <= Byte .MAX_VALUE) return (byte) inc; // else fallthrough
+ case SHORT: if (inc >= Short .MIN_VALUE && inc <= Short .MAX_VALUE) return (short) inc; // else fallthrough
+ case INTEGER: if (inc >= Integer.MIN_VALUE && inc <= Integer.MAX_VALUE) return (int) inc; // else fallthrough
default: return inc;
}
}
@@ -802,7 +805,7 @@ search: for (;;) {
*/
final double first = doubleValue(0);
double inc = (doubleValue(--i) - first) / i; // First estimation of increment.
- if (type == Numbers.DOUBLE || type == Numbers.BIG_DECIMAL) {
+ if (type == NumberType.DOUBLE || type == NumberType.BIG_DECIMAL) {
final int pz = Math.max(0, Math.min(i, (int) Math.rint(-first / inc))); // Presumed index of value zero.
if (doubleValue(pz) == 0) {
final Number value = (pz == i) ? get(pz-1) : get(pz+1); // Value adjacent to zero.
@@ -812,7 +815,7 @@ search: for (;;) {
}
}
}
- if (type == Numbers.FLOAT) {
+ if (type == NumberType.FLOAT) {
while (i >= 1) {
final float value = floatValue(i);
final double delta = Math.abs(first + inc*i-- - value);
@@ -1416,7 +1419,7 @@ search: for (;;) {
final int length = size();
final Number inc = increment(tolerance);
if (inc != null) {
- return createSequence(getElementType(), get(0), inc, length);
+ return createSequence(getNumberType(), get(0), inc, length);
}
/*
* Verify if the vector contains only NaN values. This extra check is useful because `increment()`
@@ -1426,7 +1429,7 @@ search: for (;;) {
int i = 0;
do if (i >= length) {
final Double NaN = Double.NaN;
- return createSequence(getElementType(), NaN, NaN, length);
+ return createSequence(getNumberType(), NaN, NaN, length);
} while (isNaN(i++));
/*
* Verify if the vector contains repetitions. If yes, then we can keep only a subregion of this vector.
@@ -1543,19 +1546,19 @@ search: for (;;) {
final Vector copy() {
final Object array;
final int size = size();
- switch (Numbers.getEnumConstant(getElementType())) {
- case Numbers.DOUBLE: {
+ switch (getNumberType()) {
+ case DOUBLE: {
array = doubleValues();
break;
}
- case Numbers.FLOAT: {
+ case FLOAT: {
array = floatValues();
if (size != 0 && get(0) instanceof Double) {
return createForDecimal((float[]) array);
}
break;
}
- case Numbers.LONG: {
+ case LONG: {
final long[] data = new long[size];
for (int i=0; i<size; i++) {
data[i] = longValue(i);
@@ -1563,7 +1566,7 @@ search: for (;;) {
array = data;
break;
}
- case Numbers.INTEGER: {
+ case INTEGER: {
final int[] data = new int[size];
for (int i=0; i<size; i++) {
data[i] = (int) longValue(i); // For handling both signed and unsigned integers.
@@ -1571,7 +1574,7 @@ search: for (;;) {
array = data;
break;
}
- case Numbers.SHORT: {
+ case SHORT: {
final short[] data = new short[size];
for (int i=0; i<size; i++) {
data[i] = (short) intValue(i); // For handling both signed and unsigned integers.
@@ -1579,7 +1582,7 @@ search: for (;;) {
array = data;
break;
}
- case Numbers.BYTE: {
+ case BYTE: {
final byte[] data = new byte[size];
for (int i=0; i<size; i++) {
data[i] = (byte) intValue(i); // For handling both signed and unsigned integers.
diff --git a/endorsed/src/org.apache.sis.util/main/org/apache/sis/measure/MeasurementRange.java b/endorsed/src/org.apache.sis.util/main/org/apache/sis/measure/MeasurementRange.java
index 00b4bd8552..4c36100b25 100644
--- a/endorsed/src/org.apache.sis.util/main/org/apache/sis/measure/MeasurementRange.java
+++ b/endorsed/src/org.apache.sis.util/main/org/apache/sis/measure/MeasurementRange.java
@@ -20,6 +20,7 @@ import java.util.Objects;
import javax.measure.Unit;
import javax.measure.UnitConverter;
import javax.measure.IncommensurableException;
+import org.apache.sis.math.NumberType;
import org.apache.sis.util.Numbers;
import org.apache.sis.util.resources.Errors;
@@ -161,19 +162,20 @@ public class MeasurementRange<E extends Number & Comparable<? super E>> extends
public static MeasurementRange<?> createBestFit(final Number minValue, final boolean isMinIncluded,
final Number maxValue, final boolean isMaxIncluded, final Unit<?> unit)
{
- final Class<? extends Number> type;
- type = Numbers.widestClass(Numbers.narrowestClass(minValue),
- Numbers.narrowestClass(maxValue));
- if (type == null) {
+ final NumberType type = bestFit(minValue, maxValue);
+ if (type == NumberType.NULL) {
return null;
}
- Number min = Numbers.cast(minValue, type);
- Number max = Numbers.cast(maxValue, type);
+ Number min = type.cast(minValue);
+ Number max = type.cast(maxValue);
final boolean isCacheable = isCacheable(min) && isCacheable(max);
if (isCacheable && Objects.equals(min, max)) {
max = min; // Share the same instance.
}
- MeasurementRange range = new MeasurementRange(type, min, isMinIncluded, max, isMaxIncluded, unit);
+ var range = new MeasurementRange(
+ type.classOfValues(false),
+ min, isMinIncluded,
+ max, isMaxIncluded, unit);
if (isCacheable) {
range = unique(range);
}
@@ -372,7 +374,7 @@ public class MeasurementRange<E extends Number & Comparable<? super E>> extends
final double td = minimum; minimum = maximum; maximum = td;
final boolean tb = minInc; minInc = maxInc; maxInc = tb;
}
- if (Numbers.isInteger(type)) {
+ if (NumberType.isInteger(type)) {
minInc &= (minimum == (minimum = Math.floor(minimum)));
maxInc &= (maximum == (maximum = Math.ceil (maximum)));
}
diff --git a/endorsed/src/org.apache.sis.util/main/org/apache/sis/measure/NumberRange.java b/endorsed/src/org.apache.sis.util/main/org/apache/sis/measure/NumberRange.java
index ef73902440..1593451f3f 100644
--- a/endorsed/src/org.apache.sis.util/main/org/apache/sis/measure/NumberRange.java
+++ b/endorsed/src/org.apache.sis.util/main/org/apache/sis/measure/NumberRange.java
@@ -22,6 +22,7 @@ import org.opengis.referencing.operation.TransformException;
import org.apache.sis.util.Numbers;
import org.apache.sis.util.resources.Errors;
import org.apache.sis.util.internal.shared.Numerics;
+import org.apache.sis.math.NumberType;
import org.apache.sis.math.MathFunctions;
import org.apache.sis.util.collection.WeakHashSet;
@@ -140,7 +141,7 @@ public class NumberRange<E extends Number & Comparable<? super E>> extends Range
final float value = (Float) n;
return !Float.isNaN(value) || Float.floatToRawIntBits(value) == 0x7FC00000;
} else {
- return Numbers.getEnumConstant(n.getClass()) != Numbers.OTHER;
+ return NumberType.isReal(n.getClass());
}
}
@@ -365,39 +366,44 @@ public class NumberRange<E extends Number & Comparable<? super E>> extends Range
final Number minValue, final boolean isMinIncluded,
final Number maxValue, final boolean isMaxIncluded)
{
- final Class<? extends Number> type;
+ final NumberType type;
if (asFloat) {
if (minValue == null && maxValue == null) {
return null;
}
// Types supported below should be consistent with the comment in next block.
- type = (isFloat(minValue) && isFloat(maxValue)) ? Float.class : Double.class;
+ type = (isFloat(minValue) && isFloat(maxValue)) ? NumberType.FLOAT : NumberType.DOUBLE;
} else {
- /*
- * The `narrowestClass(…)` method currently returns only wrappers of primitive types.
- * The `Fraction`, `BigInteger` or `BigDecimal` types accepted by `widestClass(…)` are lost.
- * We could support those additional classes as well (by improving `narrowestClass(…)` and
- * updating above Javadoc), but we do not yet have a need for them.
- */
- type = Numbers.widestClass(Numbers.narrowestClass(minValue),
- Numbers.narrowestClass(maxValue));
- if (type == null) {
+ type = bestFit(minValue, maxValue);
+ if (type == NumberType.NULL) {
return null;
}
}
- Number min = Numbers.cast(minValue, type);
- Number max = Numbers.cast(maxValue, type);
+ Number min = type.cast(minValue);
+ Number max = type.cast(maxValue);
final boolean isCacheable = isCacheable(min) && isCacheable(max);
if (isCacheable && Objects.equals(min, max)) {
max = min; // Share the same instance.
}
- NumberRange range = new NumberRange(type, min, isMinIncluded, max, isMaxIncluded);
+ var range = new NumberRange(
+ type.classOfValues(false),
+ min, isMinIncluded,
+ max, isMaxIncluded);
if (isCacheable) {
range = unique(range);
}
return range;
}
+ /**
+ * Returns the number type which is the best fit for the given values.
+ * If both values are {@code null}, returns {@link NumberType#NULL}.
+ */
+ static NumberType bestFit(final Number minValue, final Number maxValue) {
+ return NumberType.forNumberClasses(Numbers.narrowestClass(minValue),
+ Numbers.narrowestClass(maxValue));
+ }
+
/**
* Returns {@code true} if the given value can be cast to the {@code Float} type.
*/
@@ -677,7 +683,7 @@ public class NumberRange<E extends Number & Comparable<? super E>> extends Range
} else if (maxValue == null) {
return Double.POSITIVE_INFINITY;
}
- if (Numbers.isInteger(getElementType())) {
+ if (NumberType.isInteger(getElementType())) {
long min = minValue.longValue();
long max = maxValue.longValue();
if (!isMinIncluded) min++;
@@ -709,17 +715,17 @@ public class NumberRange<E extends Number & Comparable<? super E>> extends Range
* @return the adjacent value.
*/
private static double next(final Class<?> type, double value, final boolean up) {
- if (Numbers.isInteger(type)) {
+ if (NumberType.isInteger(type)) {
if (up) value++; else value--;
- } else if (type.equals(Float.class)) {
+ } else if (type == Float.class) {
final float fv = (float) value;
value = up ? Math.nextUp(fv) : Math.nextDown(fv);
- } else if (type.equals(Double.class)) {
+ } else if (type == Double.class) {
value = up ? Math.nextUp(value) : Math.nextDown(value);
} else {
// Thrown IllegalStateException instead of IllegalArgumentException because
// the `type` argument given to this method come from a NumberRange field.
- throw new IllegalStateException(Errors.format(Errors.Keys.NotAPrimitiveWrapper_1, type));
+ throw new IllegalStateException(Errors.format(Errors.Keys.NotANumericalType_1, type));
}
return value;
}
@@ -731,25 +737,29 @@ public class NumberRange<E extends Number & Comparable<? super E>> extends Range
*
* @param value the value to check for inclusion in this range, or {@code null}.
* @return {@code true} if the given value is non-null and included in this range.
- * @throws IllegalArgumentException if the given range cannot be converted to a valid type
+ * @throws IllegalArgumentException if the given value cannot be converted to a valid type
* through widening conversion.
*/
public boolean containsAny(Number value) throws IllegalArgumentException {
if (value == null) {
return false;
}
- final Class<? extends Number> type = Numbers.widestClass(elementType, value.getClass());
- value = Numbers.cast(value, type);
+ final NumberType type = NumberType.forNumberClasses(elementType, value.getClass());
+ try {
+ value = type.cast(value);
+ } catch (UnsupportedOperationException e) {
+ throw new IllegalArgumentException(Errors.format(Errors.Keys.CanNotConvertValue_2, value, type), e);
+ }
if (minValue != null) {
@SuppressWarnings("unchecked")
- final int c = ((Comparable) Numbers.cast(minValue, type)).compareTo(value);
+ final int c = ((Comparable) type.cast(minValue)).compareTo(value);
if (isMinIncluded ? (c > 0) : (c >= 0)) {
return false;
}
}
if (maxValue != null) {
@SuppressWarnings("unchecked")
- final int c = ((Comparable) Numbers.cast(maxValue, type)).compareTo(value);
+ final int c = ((Comparable) type.cast(maxValue)).compareTo(value);
if (isMaxIncluded ? (c < 0) : (c <= 0)) {
return false;
}
diff --git a/endorsed/src/org.apache.sis.util/main/org/apache/sis/measure/Range.java b/endorsed/src/org.apache.sis.util/main/org/apache/sis/measure/Range.java
index 21334eab86..016ff2169c 100644
--- a/endorsed/src/org.apache.sis.util/main/org/apache/sis/measure/Range.java
+++ b/endorsed/src/org.apache.sis.util/main/org/apache/sis/measure/Range.java
@@ -22,10 +22,10 @@ import java.util.Formattable;
import java.util.FormattableFlags;
import java.io.Serializable;
import javax.measure.Unit;
+import org.apache.sis.math.NumberType;
import org.apache.sis.util.ArgumentChecks;
import org.apache.sis.util.ArgumentCheckByAssertion;
import org.apache.sis.util.Emptiable;
-import org.apache.sis.util.Numbers;
import org.apache.sis.util.internal.shared.Strings;
import org.apache.sis.util.collection.CheckedContainer;
@@ -725,7 +725,7 @@ public class Range<E extends Comparable<? super E>> implements CheckedContainer<
buffer.append(minValue);
}
// Compact representation for integers, more space for real numbers.
- if (Numbers.isInteger(elementType) && isCompact(minValue, false) && isCompact(maxValue, true)) {
+ if (NumberType.isInteger(elementType) && isCompact(minValue, false) && isCompact(maxValue, true)) {
buffer.append('…');
} else {
buffer.append(" … ");
diff --git a/endorsed/src/org.apache.sis.util/main/org/apache/sis/measure/RangeFormat.java b/endorsed/src/org.apache.sis.util/main/org/apache/sis/measure/RangeFormat.java
index ad0335cda0..22e95ae8a4 100644
--- a/endorsed/src/org.apache.sis.util/main/org/apache/sis/measure/RangeFormat.java
+++ b/endorsed/src/org.apache.sis.util/main/org/apache/sis/measure/RangeFormat.java
@@ -44,6 +44,7 @@ import java.time.format.DateTimeFormatterBuilder;
import java.time.temporal.Temporal;
import java.lang.reflect.InaccessibleObjectException;
import javax.measure.Unit;
+import org.apache.sis.math.NumberType;
import org.apache.sis.util.Numbers;
import org.apache.sis.util.Localized;
import org.apache.sis.util.UnconvertibleObjectException;
@@ -1036,21 +1037,23 @@ public class RangeFormat extends Format implements Localized {
* than a more specialized type, the finest suitable type will be determined.
*/
if (Number.class.isAssignableFrom(elementType)) {
- Class<? extends Number> type = (Class) elementType;
Number min = (Number) minValue;
Number max = (Number) maxValue;
- if (type == Number.class) {
- type = Numbers.widestClass(Numbers.narrowestClass(min), Numbers.narrowestClass(max));
- min = Numbers.cast(min, type);
- max = Numbers.cast(max, type);
+ NumberType type = NumberType.forNumberClass(elementType);
+ if (type == NumberType.NUMBER) {
+ type = NumberType.forNumberClasses(Numbers.narrowestClass(min), Numbers.narrowestClass(max));
+ min = type.cast(min);
+ max = type.cast(max);
}
if (min != null && min.doubleValue() == Double.NEGATIVE_INFINITY) min = null;
if (max != null && max.doubleValue() == Double.POSITIVE_INFINITY) max = null;
if (unit != null) {
- final MeasurementRange<?> range = new MeasurementRange(type, min, isMinIncluded, max, isMaxIncluded, unit);
- return range;
+ return new MeasurementRange(
+ type.classOfValues(false),
+ min, isMinIncluded,
+ max, isMaxIncluded, unit);
}
- return new NumberRange(type, min, isMinIncluded, max, isMaxIncluded);
+ return new NumberRange(type.classOfValues(false), min, isMinIncluded, max, isMaxIncluded);
} else if (Date.class.isAssignableFrom(elementType)) {
return new Range(Date.class, (Date) minValue, isMinIncluded, (Date) maxValue, isMaxIncluded);
} else {
diff --git a/endorsed/src/org.apache.sis.util/main/org/apache/sis/pending/jdk/JDK12.java b/endorsed/src/org.apache.sis.util/main/org/apache/sis/pending/jdk/JDK12.java
new file mode 100644
index 0000000000..680835fdec
--- /dev/null
+++ b/endorsed/src/org.apache.sis.util/main/org/apache/sis/pending/jdk/JDK12.java
@@ -0,0 +1,44 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.sis.pending.jdk;
+
+
+/**
+ * Place holder for some functionalities defined in a JDK more recent than Java 11.
+ *
+ * @author Martin Desruisseaux (Geomatys)
+ */
+public final class JDK12 {
+ /**
+ * Do not allow instantiation of this class.
+ */
+ private JDK12() {
+ }
+
+ public static String descriptorString(Class<?> c) {
+ if (c == Double.TYPE) return "D";
+ if (c == Float.TYPE) return "F";
+ if (c == Long.TYPE) return "J";
+ if (c == Integer.TYPE) return "I";
+ if (c == Short.TYPE) return "S";
+ if (c == Byte.TYPE) return "B";
+ if (c == Character.TYPE) return "C";
+ if (c == Boolean.TYPE) return "Z";
+ if (c == Void.TYPE) return "V";
+ return "L" + c.getCanonicalName() + ';';
+ }
+}
diff --git a/endorsed/src/org.apache.sis.util/main/org/apache/sis/util/Classes.java b/endorsed/src/org.apache.sis.util/main/org/apache/sis/util/Classes.java
index 1fc1bea51d..7cd51e0f68 100644
--- a/endorsed/src/org.apache.sis.util/main/org/apache/sis/util/Classes.java
+++ b/endorsed/src/org.apache.sis.util/main/org/apache/sis/util/Classes.java
@@ -34,6 +34,7 @@ import java.lang.reflect.GenericDeclaration;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Modifier;
import org.opengis.annotation.UML;
+import org.apache.sis.pending.jdk.JDK12;
import org.apache.sis.pending.jdk.JDK19;
@@ -121,7 +122,7 @@ public final class Classes {
do buffer.insert(0, '[');
while (--change != 0);
if (element.isPrimitive()) {
- buffer.append(Numbers.getInternal(element));
+ buffer.append(JDK12.descriptorString(element));
} else if (element.isArray()) {
buffer.append(element.getName());
} else {
diff --git a/endorsed/src/org.apache.sis.util/main/org/apache/sis/util/Numbers.java b/endorsed/src/org.apache.sis.util/main/org/apache/sis/util/Numbers.java
index e71a206da0..36edf994e7 100644
--- a/endorsed/src/org.apache.sis.util/main/org/apache/sis/util/Numbers.java
+++ b/endorsed/src/org.apache.sis.util/main/org/apache/sis/util/Numbers.java
@@ -17,7 +17,6 @@
package org.apache.sis.util;
import java.util.Map;
-import java.util.IdentityHashMap;
import java.util.List;
import java.util.Queue;
import java.util.Set;
@@ -29,6 +28,7 @@ import java.math.BigDecimal;
import java.math.BigInteger;
import static java.lang.Double.doubleToLongBits;
import org.apache.sis.math.Fraction;
+import org.apache.sis.math.NumberType;
import org.apache.sis.util.resources.Errors;
import org.apache.sis.util.collection.Containers;
import org.apache.sis.util.internal.shared.DoubleDouble;
@@ -38,16 +38,13 @@ import org.apache.sis.util.internal.shared.DoubleDouble;
* Static methods working with {@code Number} objects, and a few primitive types by extension.
*
* @author Martin Desruisseaux (IRD, Geomatys)
- * @version 1.4
+ * @version 1.6
*
* @see org.apache.sis.math.MathFunctions
*
* @since 0.3
*/
-@SuppressWarnings({
- "UnnecessaryBoxing",
- "ResultOfObjectAllocationIgnored"
-})
+@SuppressWarnings("UnnecessaryBoxing")
public final class Numbers {
/**
* Constant of value {@value} used in {@code switch} statements or as index in arrays.
@@ -62,93 +59,18 @@ public final class Numbers {
* and {@code BIG_INTEGER}) have higher enumeration values.</li>
* <li>{@link Fraction} is considered as a kind of floating point value.</li>
* </ul>
+ *
+ * @deprecated Replaced by the {@link NumberType} enumeration.
*/
+ @Deprecated(since="1.6", forRemoval=true)
public static final byte
BIG_DECIMAL=11, BIG_INTEGER=10, FRACTION=7,
DOUBLE=9, FLOAT=8, LONG=6, INTEGER=5, SHORT=4, BYTE=3, CHARACTER=2, BOOLEAN=1, OTHER=0;
- /** Undocumented type internal to SIS. */
- private static final byte DOUBLE_DOUBLE = 12;
-
- /**
- * Mapping between a primitive type and its wrapper, if any.
- *
- * <h4>Implementation note</h4>
- * In the particular case of {@code Class} keys, {@code IdentityHashMap} and {@code HashMap} have identical
- * behavior since {@code Class} is final and does not override the {@code equals(Object)} and {@code hashCode()}
- * methods. The {@code IdentityHashMap} Javadoc claims that it is faster than the regular {@code HashMap}.
- * But maybe the most interesting property is that it allocates less objects since {@code IdentityHashMap}
- * implementation does not need the chain of objects created by {@code HashMap}.
- */
- private static final Map<Class<?>,Numbers> MAPPING = new IdentityHashMap<>(13);
- static {
- new Numbers(DoubleDouble.class, true, false, DOUBLE_DOUBLE);
- new Numbers(BigDecimal .class, true, false, BIG_DECIMAL);
- new Numbers(BigInteger .class, false, true, BIG_INTEGER);
- new Numbers(Fraction .class, true, false, FRACTION);
- new Numbers(Double .TYPE, Double .class, true, false, (byte) Double .SIZE, DOUBLE, 'D', Double .valueOf(Double.NaN));
- new Numbers(Float .TYPE, Float .class, true, false, (byte) Float .SIZE, FLOAT, 'F', Float .valueOf(Float .NaN));
- new Numbers(Long .TYPE, Long .class, false, true, (byte) Long .SIZE, LONG, 'J', Long .valueOf( 0L));
- new Numbers(Integer .TYPE, Integer .class, false, true, (byte) Integer .SIZE, INTEGER, 'I', Integer .valueOf( 0));
- new Numbers(Short .TYPE, Short .class, false, true, (byte) Short .SIZE, SHORT, 'S', Short .valueOf((short) 0));
- new Numbers(Byte .TYPE, Byte .class, false, true, (byte) Byte .SIZE, BYTE, 'B', Byte .valueOf((byte) 0));
- new Numbers(Character.TYPE, Character.class, false, false, (byte) Character.SIZE, CHARACTER, 'C', Character.valueOf((char) 0));
- new Numbers(Boolean .TYPE, Boolean .class, false, false, (byte) 1, BOOLEAN, 'Z', Boolean.FALSE);
- new Numbers(Void .TYPE, Void .class, false, false, (byte) 0, OTHER, 'V', null);
- }
-
- /** The primitive type. */ private final Class<?> primitive;
- /** The wrapper for the primitive type. */ private final Class<?> wrapper;
- /** {@code true} for floating point number. */ private final boolean isFloat;
- /** {@code true} for integer number. */ private final boolean isInteger;
- /** The size in bits, or -1 if variable. */ private final byte size;
- /** Constant to be used in switch statement. */ private final byte ordinal;
- /** The internal form of the primitive name. */ private final char internal;
- /** The null, NaN, 0 or false value. */ private final Object nullValue;
-
/**
- * Creates an entry for a type which is not a primitive type.
+ * Do not allow instantiation of this class.
*/
- private Numbers(final Class<?> type, final boolean isFloat, final boolean isInteger, final byte ordinal) {
- primitive = wrapper = type;
- this.isFloat = isFloat;
- this.isInteger = isInteger;
- this.size = -1;
- this.ordinal = ordinal;
- this.internal = 'L'; // Defined by Java, and tested elsewhere in this class.
- this.nullValue = null;
- if (MAPPING.put(type, this) != null) {
- throw new AssertionError(); // Should never happen.
- }
- }
-
- /**
- * Creates a mapping between a primitive type and its wrapper.
- */
- private Numbers(final Class<?> primitive, final Class<?> wrapper,
- final boolean isFloat, final boolean isInteger,
- final byte size, final byte ordinal,
- final char internal, final Object nullValue)
- {
- this.primitive = primitive;
- this.wrapper = wrapper;
- this.isFloat = isFloat;
- this.isInteger = isInteger;
- this.size = size;
- this.ordinal = ordinal;
- this.internal = internal;
- this.nullValue = nullValue;
- if (MAPPING.put(primitive, this) != null || MAPPING.put(wrapper, this) != null) {
- throw new AssertionError(); // Should never happen.
- }
- }
-
- /**
- * Returns the Java letter used for the internal representation of this given primitive type.
- * This method shall be invoked only when the caller knows that the given type is a primitive.
- */
- static char getInternal(final Class<?> type) {
- return MAPPING.get(type).internal;
+ private Numbers() {
}
/**
@@ -160,10 +82,12 @@ public final class Numbers {
* @return {@code true} if {@code type} is one of the known types capable to represent floating point numbers.
*
* @see #isInteger(Class)
+ *
+ * @deprecated Moved to {@link NumberType#isFractional(Class)}.
*/
+ @Deprecated(since="1.6", forRemoval=true)
public static boolean isFloat(final Class<?> type) {
- final Numbers mapping = MAPPING.get(type);
- return (mapping != null) && mapping.isFloat;
+ return NumberType.isFractional(type);
}
/**
@@ -176,10 +100,12 @@ public final class Numbers {
*
* @see #isFloat(Class)
* @see #round(Number)
+ *
+ * @deprecated Moved to {@link NumberType#isInteger(Class)}.
*/
+ @Deprecated(since="1.6", forRemoval=true)
public static boolean isInteger(final Class<?> type) {
- final Numbers mapping = MAPPING.get(type);
- return (mapping != null) && mapping.isInteger;
+ return NumberType.isInteger(type);
}
/**
@@ -194,11 +120,12 @@ public final class Numbers {
* @see #isInteger(Class)
*
* @since 1.1
+ *
+ * @deprecated Moved to {@link NumberType#isReal(Class)}.
*/
+ @Deprecated(since="1.6", forRemoval=true)
public static boolean isNumber(final Class<?> type) {
- final Numbers mapping = MAPPING.get(type);
- return ((mapping != null) && (mapping.isInteger | mapping.isFloat)) ||
- ((type != null) && Number.class.isAssignableFrom(type));
+ return NumberType.isReal(type);
}
/**
@@ -249,15 +176,12 @@ public final class Numbers {
* @since 1.4
*/
public static long round(final Number value) {
- final Numbers mapping = MAPPING.get(value.getClass());
-asLong: if (mapping != null) {
- switch (mapping.ordinal) {
- case DOUBLE_DOUBLE: break;
- case BIG_DECIMAL: return ((BigDecimal) value).longValueExact();
- case BIG_INTEGER: return ((BigInteger) value).longValueExact();
- default: if (!mapping.isInteger) break asLong;
- }
- return value.longValue(); // Does rounding in `DoubleDouble` case.
+ final NumberType mapping = NumberType.forNumberClass(value.getClass());
+ switch (mapping) {
+ case DOUBLE_DOUBLE: return value.longValue(); // Does rounding.
+ case BIG_DECIMAL: return ((BigDecimal) value).longValueExact();
+ case BIG_INTEGER: return ((BigInteger) value).longValueExact();
+ default: if (mapping.isInteger()) return value.longValue();
}
final double v = value.doubleValue();
final long n = Math.round(v);
@@ -272,18 +196,15 @@ asLong: if (mapping != null) {
* @param type the primitive type (can be {@code null}).
* @return the number of bits, or 0 if {@code type} is null.
* @throws IllegalArgumentException if the given type is not one of the types supported by this {@code Numbers} class.
+ *
+ * @deprecated Replaced by {@link NumberType#size()}.
*/
+ @Deprecated(since="1.6", forRemoval=true)
public static int primitiveBitCount(final Class<?> type) throws IllegalArgumentException {
- final Numbers mapping = MAPPING.get(type);
- if (mapping != null) {
- final int size = mapping.size;
- if (size >= 0) {
- return size;
- }
- } else if (type == null) {
+ if (type == null) {
return 0;
}
- throw unknownType(type);
+ return NumberType.forNumberClass(type).size().orElseThrow();
}
/**
@@ -294,12 +215,11 @@ asLong: if (mapping != null) {
* @param type the primitive type (can be {@code null}).
* @return the type as a wrapper.
*
- * @see #wrapperToPrimitive(Class)
+ * @deprecated Moved to {@link NumberType#primitiveToWrapper(Class)}.
*/
- @SuppressWarnings("unchecked")
+ @Deprecated(since="1.6", forRemoval=true)
public static <N> Class<N> primitiveToWrapper(final Class<N> type) {
- final Numbers mapping = MAPPING.get(type);
- return (mapping != null) ? (Class<N>) mapping.wrapper : type;
+ return NumberType.primitiveToWrapper(type);
}
/**
@@ -310,12 +230,11 @@ asLong: if (mapping != null) {
* @param type the wrapper type (can be {@code null}).
* @return the type as a primitive.
*
- * @see #primitiveToWrapper(Class)
+ * @deprecated Moved to {@link NumberType#wrapperToPrimitive(Class)}.
*/
- @SuppressWarnings("unchecked")
+ @Deprecated(since="1.6", forRemoval=true)
public static <N> Class<N> wrapperToPrimitive(final Class<N> type) {
- final Numbers mapping = MAPPING.get(type);
- return (mapping != null) ? (Class<N>) mapping.primitive : type;
+ return NumberType.wrapperToPrimitive(type);
}
/**
@@ -323,7 +242,7 @@ asLong: if (mapping != null) {
* {@link Byte}, {@link Short}, {@link Integer}, {@link Long}, {@link Float}, {@link Double},
* {@link Fraction}, {@link BigInteger} or {@link BigDecimal} types.
*
- * <p>If one of the given argument is null, then this method returns the class of the non-null argument.
+ * <p>If one of the given arguments is null, then this method returns the class of the non-null argument.
* If both arguments are null, then this method returns {@code null}.</p>
*
* @param n1 the first number, or {@code null}.
@@ -334,7 +253,9 @@ asLong: if (mapping != null) {
* @see #widestClass(Number, Number)
* @see #narrowestClass(Number, Number)
*/
- public static Class<? extends Number> widestClass(final Number n1, final Number n2) throws IllegalArgumentException {
+ public static Class<? extends Number> widestClass(final Number n1, final Number n2)
+ throws IllegalArgumentException
+ {
return widestClass((n1 != null) ? n1.getClass() : null,
(n2 != null) ? n2.getClass() : null);
}
@@ -344,16 +265,21 @@ asLong: if (mapping != null) {
* {@link Byte}, {@link Short}, {@link Integer}, {@link Long}, {@link Float}, {@link Double},
* {@link Fraction}, {@link BigInteger} or {@link BigDecimal} types.
*
- * <p>If one of the given argument is null, then this method returns the non-null argument.
+ * <p>If one of the given arguments is null, then this method returns the non-null argument.
* If both arguments are null, then this method returns {@code null}.</p>
*
* <h4>Example</h4>
- * in the following code, {@code type} is set to {@code Long.class}:
+ * in the following code, the result stored in {@code type} will be {@code Long.class}:
*
* {@snippet lang="java" :
* Class<?> type = widestClass(Short.class, Long.class);
* }
*
+ * <h4>Accuracy</h4>
+ * Note that conversions to the widest class are not guaranteed to be lossless.
+ * For example, {@code double} is considered a wider class than {@code long}, but
+ * conversion from {@code long} to {@code double} can nevertheless loose accuracy.
+ *
* @param c1 the first number type, or {@code null}.
* @param c2 the second number type, or {@code null}.
* @return the widest of the given types, or {@code null} if both {@code c1} and {@code c2} are null.
@@ -366,17 +292,10 @@ asLong: if (mapping != null) {
final Class<? extends Number> c2)
throws IllegalArgumentException
{
+ if (c1 == c2) return c2; // Avoid IllegalArgumentException if the type is unknown.
if (c1 == null) return c2;
if (c2 == null) return c1;
- final Numbers m1 = MAPPING.get(c1);
- if (m1 == null) {
- throw unknownType(c1);
- }
- final Numbers m2 = MAPPING.get(c2);
- if (m2 == null) {
- throw unknownType(c2);
- }
- return (m1.ordinal >= m2.ordinal) ? c1 : c2;
+ return NumberType.forNumberClass(c1).isWiderThan(NumberType.forNumberClass(c2)) ? c1 : c2;
}
/**
@@ -384,6 +303,9 @@ asLong: if (mapping != null) {
* {@link Byte}, {@link Short}, {@link Integer}, {@link Long}, {@link Float}, {@link Double},
* {@link Fraction}, {@link BigInteger} or {@link BigDecimal} types.
*
+ * <p>If one of the given arguments is null, then this method returns the class of the non-null argument.
+ * If both arguments are null, then this method returns {@code null}.</p>
+ *
* @param n1 the first number, or {@code null}.
* @param n2 the second number, or {@code null}.
* @return the narrowest type of the given numbers, or {@code null} if both {@code n1} and {@code n2} are null.
@@ -404,14 +326,14 @@ asLong: if (mapping != null) {
* {@link Byte}, {@link Short}, {@link Integer}, {@link Long}, {@link Float}, {@link Double},
* {@link Fraction}, {@link BigInteger} or {@link BigDecimal} types.
*
- * <p>If one of the given argument is null, then this method returns the non-null argument.
+ * <p>If one of the given arguments is null, then this method returns the non-null argument.
* If both arguments are null, then this method returns {@code null}.</p>
*
* <h4>Example</h4>
- * in the following code, {@code type} is set to {@code Short.class}:
+ * in the following code, the result stored in {@code type} will be {@code Short.class}:
*
* {@snippet lang="java" :
- * Class<?> type = widestClass(Short.class, Long.class);
+ * Class<?> type = narrowestClass(Short.class, Long.class);
* }
*
* @param c1 the first number type, or {@code null}.
@@ -426,17 +348,10 @@ asLong: if (mapping != null) {
final Class<? extends Number> c2)
throws IllegalArgumentException
{
+ if (c1 == c2) return c2; // Avoid IllegalArgumentException if the type is unknown.
if (c1 == null) return c2;
if (c2 == null) return c1;
- final Numbers m1 = MAPPING.get(c1);
- if (m1 == null) {
- throw unknownType(c1);
- }
- final Numbers m2 = MAPPING.get(c2);
- if (m2 == null) {
- throw unknownType(c2);
- }
- return (m1.ordinal < m2.ordinal) ? c1 : c2;
+ return NumberType.forNumberClass(c1).isNarrowerThan(NumberType.forNumberClass(c2)) ? c1 : c2;
}
/**
@@ -470,7 +385,7 @@ asLong: if (mapping != null) {
}
boolean isFloat = false;
final long longValue = value.longValue();
- switch (getEnumConstant(value.getClass())) {
+ switch (NumberType.forNumberClass(value.getClass())) {
default: {
final double doubleValue = value.doubleValue();
final float floatValue = (float) doubleValue;
@@ -509,7 +424,7 @@ asLong: if (mapping != null) {
final Number candidate;
boolean isFloat = false;
final long longValue = value.longValue();
- switch (getEnumConstant(value.getClass())) {
+ switch (NumberType.forNumberClass(value.getClass())) {
default: {
final double doubleValue = value.doubleValue();
final float floatValue = (float) doubleValue;
@@ -591,7 +506,7 @@ asLong: if (mapping != null) {
* </ul>
*
* This method does not verify if the given type is wide enough for the given value,
- * because the type has typically been calculated by {@link #widestClass(Class, Class)}
+ * because the type has typically been calculated by {@link #widestClass(Number, Number)}
* or {@link #narrowestClass(Number)}. If nevertheless the given type is not wide enough,
* then the behavior depends on the implementation of the corresponding
* {@code Number.fooValue()} method - typically, the value is just rounded or truncated.
@@ -603,54 +518,18 @@ asLong: if (mapping != null) {
* @throws IllegalArgumentException if the given type is not supported by this {@code Numbers} class,
* or the number cannot be converted to the specified type (e.g. {@link Double#NaN} cannot
* be converted to {@link BigDecimal}).
+ *
+ * @see NumberType#cast(Number)
*/
@SuppressWarnings("unchecked")
public static <N extends Number> N cast(final Number number, final Class<N> type) throws IllegalArgumentException {
- if (number == null || number.getClass() == type) {
+ if (number == null || type.isInstance(number)) {
return (N) number;
}
- switch (getEnumConstant(type)) {
- case BYTE: return (N) Byte .valueOf(number. byteValue());
- case SHORT: return (N) Short .valueOf(number. shortValue());
- case INTEGER: return (N) Integer .valueOf(number. intValue());
- case LONG: return (N) Long .valueOf(number. longValue());
- case FLOAT: return (N) Float .valueOf(number. floatValue());
- case DOUBLE: return (N) Double .valueOf(number.doubleValue());
- case FRACTION: return (N) Fraction.valueOf(number.doubleValue());
- case BIG_INTEGER: {
- final BigInteger c;
- if (number instanceof BigInteger) {
- c = (BigInteger) number;
- } else if (number instanceof BigDecimal) {
- c = ((BigDecimal) number).toBigInteger();
- } else {
- c = BigInteger.valueOf(number.longValue());
- }
- return (N) c;
- }
- case BIG_DECIMAL: {
- final BigDecimal c;
- if (number instanceof BigDecimal) {
- c = (BigDecimal) number;
- } else if (number instanceof BigInteger) {
- c = new BigDecimal((BigInteger) number);
- } else if (isInteger(number.getClass())) {
- c = BigDecimal.valueOf(number.longValue());
- } else {
- /*
- * Same implementation as BigDecimal.valueOf(double)
- * but better result if number is a Float instance.
- */
- c = new BigDecimal(number.toString());
- }
- return (N) c;
- }
- default: {
- if (type.isInstance(number)) {
- return (N) number;
- }
- throw unknownType(type);
- }
+ try {
+ return type.cast(NumberType.forNumberClass(type).cast(number));
+ } catch (UnsupportedOperationException | ArithmeticException e) {
+ throw new IllegalArgumentException(Errors.format(Errors.Keys.NotANumericalType_1, type), e);
}
}
@@ -667,26 +546,15 @@ asLong: if (mapping != null) {
* @return the value wrapped in an object of the given class.
* @throws IllegalArgumentException if the given type is not supported by this {@code Numbers} class,
* or if the given value cannot be wrapped in an instance of the given class without precision lost.
+ *
+ * @see NumberType#wrapExact(double)
*/
- @SuppressWarnings("unchecked")
public static <N extends Number> N wrap(final double value, final Class<N> type) throws IllegalArgumentException {
- final N number;
- switch (getEnumConstant(type)) {
- case BYTE: number = (N) Byte .valueOf((byte) value); break;
- case SHORT: number = (N) Short .valueOf((short) value); break;
- case INTEGER: number = (N) Integer .valueOf((int) value); break;
- case LONG: number = (N) Long .valueOf((long) value); break;
- case FLOAT: number = (N) Float .valueOf((float) value); break;
- case DOUBLE: return (N) Double .valueOf(value); // No need to verify.
- case FRACTION: return (N) Fraction .valueOf(value); // No need to verify.
- case BIG_INTEGER: number = (N) BigInteger.valueOf((long) value); break;
- case BIG_DECIMAL: return (N) BigDecimal.valueOf(value); // No need to verify.
- default: throw unknownType(type);
- }
- if (doubleToLongBits(number.doubleValue()) != doubleToLongBits(value)) {
- throw new IllegalArgumentException(Errors.format(Errors.Keys.CanNotConvertValue_2, value, type));
+ try {
+ return type.cast(NumberType.forNumberClass(type).wrapExact(value));
+ } catch (UnsupportedOperationException | ArithmeticException e) {
+ throw new IllegalArgumentException(Errors.format(Errors.Keys.CanNotConvertValue_2, value, type), e);
}
- return number;
}
/**
@@ -704,26 +572,15 @@ asLong: if (mapping != null) {
* or if the given value cannot be wrapped in an instance of the given class without precision lost.
*
* @since 0.8
+ *
+ * @see NumberType#wrapExact(long)
*/
- @SuppressWarnings("unchecked")
public static <N extends Number> N wrap(final long value, final Class<N> type) throws IllegalArgumentException {
- final N number;
- switch (getEnumConstant(type)) {
- case BYTE: number = (N) Byte .valueOf((byte) value); break;
- case SHORT: number = (N) Short .valueOf((short) value); break;
- case INTEGER: number = (N) Integer .valueOf((int) value); break;
- case LONG: return (N) Long .valueOf(value); // No need to verify.
- case FLOAT: number = (N) Float .valueOf((float) value); break;
- case DOUBLE: number = (N) Double .valueOf((double) value); break;
- case FRACTION: number = (N) new Fraction ((int) value, 1); break;
- case BIG_INTEGER: return (N) BigInteger.valueOf(value); // No need to verify.
- case BIG_DECIMAL: return (N) BigDecimal.valueOf(value); // No need to verify.
- default: throw unknownType(type);
+ try {
+ return type.cast(NumberType.forNumberClass(type).wrapExact(value));
+ } catch (UnsupportedOperationException | ArithmeticException e) {
+ throw new IllegalArgumentException(Errors.format(Errors.Keys.CanNotConvertValue_2, value, type), e);
}
- if (number.longValue() != value) {
- throw new IllegalArgumentException(Errors.format(Errors.Keys.CanNotConvertValue_2, value, type));
- }
- return number;
}
/**
@@ -742,51 +599,31 @@ asLong: if (mapping != null) {
* </ul>
*
* @param <T> the requested type.
- * @param value the value to parse.
+ * @param text the text to parse.
* @param type the requested type.
* @return the value object, or {@code null} if {@code value} was null.
* @throws IllegalArgumentException if {@code type} is not a recognized type.
* @throws NumberFormatException if {@code type} is a subclass of {@link Number}
* and the string value is not parsable as a number of the specified type.
+ *
+ * @see NumberType#parse(String)
*/
- @SuppressWarnings("unchecked")
- public static <T> T valueOf(final String value, final Class<T> type)
+ public static <T> T valueOf(final String text, final Class<T> type)
throws IllegalArgumentException, NumberFormatException
{
- if (value == null || type == String.class) {
- return (T) value;
- }
- switch (getEnumConstant(type)) {
- case CHARACTER: {
- /*
- * If the string is empty, returns 0 which means "end of string" in C/C++
- * and NULL in Unicode standard. If non-empty, take only the first char.
- * This is somewhat consistent with Boolean.valueOf(...) which is quite
- * lenient about the parsing as well, and throwing a NumberFormatException
- * for those would not be appropriate.
- */
- return (T) Character.valueOf(value.isEmpty() ? 0 : value.charAt(0));
- }
- // Do not trim whitespaces. It is up to the caller to do that if he wants.
- // For such low level function, we are better to avoid hidden initiative.
- case BOOLEAN: return (T) Boolean.valueOf(value);
- case BYTE: return (T) Byte .valueOf(value);
- case SHORT: return (T) Short .valueOf(value);
- case INTEGER: return (T) Integer.valueOf(value);
- case LONG: return (T) Long .valueOf(value);
- case FLOAT: return (T) Float .valueOf(value);
- case DOUBLE: return (T) Double .valueOf(value);
- case FRACTION: return (T) new Fraction (value);
- case BIG_INTEGER: return (T) new BigInteger(value);
- case BIG_DECIMAL: return (T) new BigDecimal(value);
- default: throw unknownType(type);
+ Object value;
+ if (text == null || type == String.class) {
+ value = text;
+ } else {
+ value = NumberType.forNumberClass(type).parse(text);
}
+ return type.cast(value);
}
/**
- * Returns a {@code NaN}, zero, empty or {@code null} value of the given type. This method
- * tries to return the closest value that can be interpreted as <q>none</q>, which
- * is usually not the same as <q>zero</q>. More specifically:
+ * Returns a {@code NaN}, zero, empty or {@code null} value of the given type.
+ * This method tries to return the closest value that can be interpreted as <q>none</q>,
+ * which is usually not the same as <q>zero</q>. More specifically:
*
* <ul>
* <li>If the given type is a floating point <strong>primitive</strong> type ({@code float}
@@ -807,40 +644,48 @@ asLong: if (mapping != null) {
* returns {@code null}.</li>
* </ul>
*
- * Despite being defined in the {@code Numbers} class, the scope of this method has been
- * extended to array and collection types because those objects can also be seen as
- * mathematical concepts.
+ * Despite being defined in the {@code Numbers} class, the scope of this method has been extended
+ * to array and collection types because those objects can also be seen as mathematical concepts.
*
* @param <T> the compile-time type of the requested object.
* @param type the type of the object for which to get a nil value.
* @return an object of the given type which represents a nil value, or {@code null}.
*
+ * @see NumberType#nilValue()
* @see org.apache.sis.xml.NilObject
*/
- @SuppressWarnings("unchecked")
public static <T> T valueOfNil(final Class<T> type) {
- final Numbers mapping = MAPPING.get(type);
- if (mapping != null) {
- if (type.isPrimitive()) {
- return (T) mapping.nullValue;
- }
- } else if (type != null && type != Object.class) {
- if (type == Map .class) return (T) Collections.EMPTY_MAP;
- if (type == List .class) return (T) Collections.EMPTY_LIST;
- if (type == Queue .class) return (T) Containers.emptyQueue();
- if (type == SortedSet .class) return (T) Collections.emptySortedSet();
- if (type == NavigableSet.class) return (T) Collections.emptyNavigableSet();
- if (type.isAssignableFrom(Set.class)) {
- return (T) Collections.EMPTY_SET;
- }
- final Class<?> element = type.getComponentType();
- if (element != null) {
- return (T) Array.newInstance(element, 0);
+ if (type == null) {
+ return null;
+ }
+ Object value = NumberType.forClass(type).orElse(NumberType.NULL).nilValue();
+ if (value == null) {
+ value = NIL_VALUES.get(type);
+ if (value == null && type != Object.class) {
+ if (type.isAssignableFrom(Set.class)) {
+ value = Collections.EMPTY_SET;
+ } else {
+ Class<?> element = type.getComponentType();
+ if (element != null) {
+ value = Array.newInstance(element, 0);
+ }
+ }
}
}
- return null;
+ return type.cast(value);
}
+ /**
+ * Nil values for each type other than the ones managed by {@link NumberType}.
+ */
+ private static final Map<Class<?>, Object> NIL_VALUES = Map.of(
+ Map.class, Collections.EMPTY_MAP,
+ Set.class, Collections.EMPTY_SET,
+ List.class, Collections.EMPTY_LIST,
+ Queue.class, Containers.emptyQueue(),
+ SortedSet.class, Collections.emptySortedSet(),
+ NavigableSet.class, Collections.emptyNavigableSet());
+
/**
* Returns a numeric constant for the given type.
* The constants are {@link #BIG_DECIMAL}, {@link #BIG_INTEGER}, {@link #FRACTION},
@@ -850,16 +695,24 @@ asLong: if (mapping != null) {
*
* @param type a type (usually either a primitive type or its wrapper), or {@code null}.
* @return the constant for the given type, or {@link #OTHER} if unknown.
+ *
+ * @deprecated Replaced by the {@link NumberType} enumeration.
*/
+ @Deprecated(since="1.6", forRemoval=true)
public static byte getEnumConstant(final Class<?> type) {
- final Numbers mapping = MAPPING.get(type);
- return (mapping != null) ? mapping.ordinal : OTHER;
- }
-
- /**
- * Returns an exception for an unknown type.
- */
- private static IllegalArgumentException unknownType(final Class<?> type) {
- return new IllegalArgumentException(Errors.format(Errors.Keys.NotAPrimitiveWrapper_1, type));
+ switch (NumberType.forClass(type).orElse(NumberType.NULL)) {
+ case BIG_DECIMAL: return BIG_DECIMAL;
+ case BIG_INTEGER: return BIG_INTEGER;
+ case FRACTION: return FRACTION;
+ case DOUBLE: return DOUBLE;
+ case FLOAT: return FLOAT;
+ case LONG: return LONG;
+ case INTEGER: return INTEGER;
+ case SHORT: return SHORT;
+ case BYTE: return BYTE;
+ case CHARACTER: return CHARACTER;
+ case BOOLEAN: return BOOLEAN;
+ default: return OTHER;
+ }
}
}
diff --git a/endorsed/src/org.apache.sis.util/main/org/apache/sis/util/collection/RangeSet.java b/endorsed/src/org.apache.sis.util/main/org/apache/sis/util/collection/RangeSet.java
index 85b14f69b0..8fd29d4685 100644
--- a/endorsed/src/org.apache.sis.util/main/org/apache/sis/util/collection/RangeSet.java
+++ b/endorsed/src/org.apache.sis.util/main/org/apache/sis/util/collection/RangeSet.java
@@ -30,12 +30,12 @@ import java.util.SortedSet;
import java.util.AbstractSet;
import java.util.NoSuchElementException;
import java.util.ConcurrentModificationException;
+import org.apache.sis.math.NumberType;
import org.apache.sis.measure.NumberRange;
import org.apache.sis.measure.Range;
import org.apache.sis.util.ArraysExt;
import org.apache.sis.util.ArgumentChecks;
import org.apache.sis.util.resources.Errors;
-import static org.apache.sis.util.Numbers.*;
/**
@@ -115,7 +115,7 @@ public class RangeSet<E extends Comparable<? super E>> extends AbstractSet<Range
/**
* Serial number for inter-operability with different versions.
*/
- private static final long serialVersionUID = 7493555225994855486L;
+ private static final long serialVersionUID = 4996397525797174442L;
/**
* The range comparator returned by {@link RangeSet#comparator()}. This comparator
@@ -195,11 +195,10 @@ public class RangeSet<E extends Comparable<? super E>> extends AbstractSet<Range
protected final Class<E> elementType;
/**
- * The primitive type, as one of {@code DOUBLE}, {@code FLOAT}, {@code LONG}, {@code INTEGER},
- * {@code SHORT}, {@code BYTE}, {@code CHARACTER} enumeration. If the {@link #elementType} is
- * not the wrapper of a primitive type, then this field value is {@code OTHER}.
+ * The type of elements as an enumeration. If the {@link #elementType} is not a supported type,
+ * then this field is set to {@link NumberType#NULL}.
*/
- private final byte elementCode;
+ private final NumberType elementCode;
/**
* {@code true} if the minimal values of ranges in this set are inclusive, or {@code false}
@@ -260,8 +259,8 @@ public class RangeSet<E extends Comparable<? super E>> extends AbstractSet<Range
ArgumentChecks.ensureNonNull("elementType", elementType);
// Following assertion may fail only if the user bypass the parameterized type checks.
assert Comparable.class.isAssignableFrom(elementType) : elementType;
+ this.elementCode = NumberType.forClass(elementType).orElse(NumberType.NULL);
this.elementType = elementType;
- this.elementCode = getEnumConstant(elementType);
this.isMinIncluded = isMinIncluded;
this.isMaxIncluded = isMaxIncluded;
if (!isMinIncluded && !isMaxIncluded) {
@@ -518,7 +517,7 @@ public class RangeSet<E extends Comparable<? super E>> extends AbstractSet<Range
ensureOrdered(minValue, maxValue);
Class<?> type = elementType;
if (type != Boolean.class) { // Because there is no Arrays.binarySearch(boolean[], …) method.
- type = wrapperToPrimitive(type);
+ type = NumberType.wrapperToPrimitive(type);
}
array = Array.newInstance(type, 8);
Array.set(array, 0, minValue);
@@ -1043,6 +1042,7 @@ public class RangeSet<E extends Comparable<? super E>> extends AbstractSet<Range
* Recomputes the {@link #lower} and {@link #upper} indices if they are outdated.
* If the indices are already up to date, then this method does nothing.
*/
+ @SuppressWarnings("LocalVariableHidesMemberVariable")
private void updateBounds() {
if (modCount != RangeSet.this.modCount) {
int lower = 0;
diff --git a/endorsed/src/org.apache.sis.util/main/org/apache/sis/util/collection/TreeTableFormat.java b/endorsed/src/org.apache.sis.util/main/org/apache/sis/util/collection/TreeTableFormat.java
index f63cc9f68f..5146de0a14 100644
--- a/endorsed/src/org.apache.sis.util/main/org/apache/sis/util/collection/TreeTableFormat.java
+++ b/endorsed/src/org.apache.sis.util/main/org/apache/sis/util/collection/TreeTableFormat.java
@@ -34,12 +34,12 @@ import java.text.ParseException;
import org.apache.sis.io.TableAppender;
import org.apache.sis.io.TabularFormat;
import org.apache.sis.measure.UnitFormat;
-import org.apache.sis.util.Numbers;
import org.apache.sis.util.CharSequences;
import org.apache.sis.util.ArgumentChecks;
import org.apache.sis.util.resources.Errors;
import org.apache.sis.util.resources.Vocabulary;
import org.apache.sis.math.DecimalFunctions;
+import org.apache.sis.math.NumberType;
import org.apache.sis.util.internal.Acyclic;
import org.apache.sis.util.internal.shared.PropertyFormat;
import org.apache.sis.util.internal.shared.LocalizedParseException;
@@ -716,7 +716,7 @@ public class TreeTableFormat extends TabularFormat<TreeTable> {
protected final String toString(final Object value) {
final String text;
final Format format = getFormat(value.getClass());
- if (format instanceof DecimalFormat && Numbers.isFloat(value.getClass())) {
+ if (format instanceof DecimalFormat && NumberType.isFractional(value.getClass())) {
final double number = ((Number) value).doubleValue();
if (number != (int) number) { // Cast to `int` instead of `long` as a way to limit to about 2E9.
/*
diff --git a/endorsed/src/org.apache.sis.util/main/org/apache/sis/util/internal/shared/Strings.java b/endorsed/src/org.apache.sis.util/main/org/apache/sis/util/internal/shared/Strings.java
index 3dee789c3d..d37ee4cd22 100644
--- a/endorsed/src/org.apache.sis.util/main/org/apache/sis/util/internal/shared/Strings.java
+++ b/endorsed/src/org.apache.sis.util/main/org/apache/sis/util/internal/shared/Strings.java
@@ -17,6 +17,7 @@
package org.apache.sis.util.internal.shared;
import java.lang.reflect.Array;
+import java.util.Locale;
import java.util.Formatter;
import java.util.FormattableFlags;
import org.apache.sis.util.Classes;
@@ -115,6 +116,23 @@ public final class Strings {
return null;
}
+ /**
+ * Parses the given string as a Boolean value.
+ * This method implements the conversion table documented in {@link org.apache.sis.converter.StringConverter}.
+ *
+ * @param text the string to parse, or {@code null}.
+ * @return the Boolean value, or {@code null} if not recognized.
+ */
+ public static Boolean parseBoolean(final String text) {
+ if (text != null) {
+ switch (text.toLowerCase(Locale.US)) {
+ case "true": case "yes": case "on": case "1": return Boolean.TRUE;
+ case "false": case "no": case "off": case "0": return Boolean.FALSE;
+ }
+ }
+ return null;
+ }
+
/**
* Appends to the given buffer only the characters that are valid for a Unicode identifier.
* The given separator character is append before the given {@code text} only if the buffer
diff --git a/endorsed/src/org.apache.sis.util/main/org/apache/sis/util/resources/Errors.java b/endorsed/src/org.apache.sis.util/main/org/apache/sis/util/resources/Errors.java
index 557c20896b..ecba4d8358 100644
--- a/endorsed/src/org.apache.sis.util/main/org/apache/sis/util/resources/Errors.java
+++ b/endorsed/src/org.apache.sis.util/main/org/apache/sis/util/resources/Errors.java
@@ -760,9 +760,9 @@ public class Errors extends IndexedResourceBundle {
public static final short NotANumber_1 = 137;
/**
- * Class ‘{0}’ is not a primitive type wrapper.
+ * Class ‘{0}’ is not a numerical type recognized by Apache SIS.
*/
- public static final short NotAPrimitiveWrapper_1 = 138;
+ public static final short NotANumericalType_1 = 138;
/**
* Text “{0}” is not a Unicode identifier.
diff --git a/endorsed/src/org.apache.sis.util/main/org/apache/sis/util/resources/Errors.properties b/endorsed/src/org.apache.sis.util/main/org/apache/sis/util/resources/Errors.properties
index a17983d55b..61d94b843a 100644
--- a/endorsed/src/org.apache.sis.util/main/org/apache/sis/util/resources/Errors.properties
+++ b/endorsed/src/org.apache.sis.util/main/org/apache/sis/util/resources/Errors.properties
@@ -163,7 +163,7 @@ NotADivisorOrMultiple_4 = Value of \u2018{0}\u2019 shall be a {1,choic
NotAnInteger_1 = {0} is not an integer value.
NotAKeyValuePair_1 = \u201c{0}\u201d is not a key-value pair.
NotANumber_1 = Argument \u2018{0}\u2019 shall not be NaN (Not-a-Number).
-NotAPrimitiveWrapper_1 = Class \u2018{0}\u2019 is not a primitive type wrapper.
+NotANumericalType_1 = Class \u2018{0}\u2019 is not a numerical type recognized by Apache SIS.
NotAUnicodeIdentifier_1 = Text \u201c{0}\u201d is not a Unicode identifier.
NoSuchValue_1 = No value is associated to \u201c{0}\u201d.
NullArgument_1 = Argument \u2018{0}\u2019 shall not be null.
diff --git a/endorsed/src/org.apache.sis.util/main/org/apache/sis/util/resources/Errors_fr.properties b/endorsed/src/org.apache.sis.util/main/org/apache/sis/util/resources/Errors_fr.properties
index a2523ca032..dce37398d0 100644
--- a/endorsed/src/org.apache.sis.util/main/org/apache/sis/util/resources/Errors_fr.properties
+++ b/endorsed/src/org.apache.sis.util/main/org/apache/sis/util/resources/Errors_fr.properties
@@ -160,7 +160,7 @@ NotADivisorOrMultiple_4 = La valeur de \u2018{0}\u2019 doit \u00eatre
NotAnInteger_1 = {0} n\u2019est pas un nombre entier.
NotAKeyValuePair_1 = \u00ab\u202f{0}\u202f\u00bb n\u2019est pas une paire cl\u00e9-valeur.
NotANumber_1 = L\u2019argument \u2018{0}\u2019 ne doit pas \u00eatre NaN (Not-a-Number).
-NotAPrimitiveWrapper_1 = La classe \u2018{0}\u2019 n\u2019est pas un adaptateur d\u2019un type primitif.
+NotANumericalType_1 = La classe \u2018{0}\u2019 n\u2019est pas un type num\u00e9rique reconnu par Apache SIS.
NotAUnicodeIdentifier_1 = Le texte \u00ab\u202f{0}\u202f\u00bb n\u2019est pas un identifiant Unicode.
NoSuchValue_1 = Aucune valeur n\u2019est associ\u00e9e \u00e0 \u00ab\u202f{0}\u202f\u00bb.
NullArgument_1 = L\u2019argument \u2018{0}\u2019 ne doit pas \u00eatre nul.
diff --git a/endorsed/src/org.apache.sis.util/test/org/apache/sis/math/NumberTypeTest.java b/endorsed/src/org.apache.sis.util/test/org/apache/sis/math/NumberTypeTest.java
new file mode 100644
index 0000000000..506ee1f8a0
--- /dev/null
+++ b/endorsed/src/org.apache.sis.util/test/org/apache/sis/math/NumberTypeTest.java
@@ -0,0 +1,201 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.sis.math;
+
+import java.math.BigDecimal;
+import java.math.BigInteger;
+
+// Test dependencies
+import org.junit.jupiter.api.Test;
+import static org.junit.jupiter.api.Assertions.*;
+import org.apache.sis.test.TestCase;
+
+
+/**
+ * Tests {@link NumberType}.
+ *
+ * @author Martin Desruisseaux (Geomatys)
+ */
+@SuppressWarnings("exports")
+public final class NumberTypeTest extends TestCase {
+ /**
+ * Creates a new test case.
+ */
+ public NumberTypeTest() {
+ }
+
+ /**
+ * Tests {@link NumberType#forNumberClasses(Class...)}.
+ */
+ @Test
+ public void testForNumberClasses() {
+ assertEquals(NumberType.NULL, NumberType.forNumberClasses());
+ assertEquals(NumberType.FLOAT, NumberType.forNumberClasses(Float.class));
+ assertEquals(NumberType.FLOAT, NumberType.forNumberClasses(Float.TYPE, Long.class));
+ assertEquals(NumberType.DOUBLE, NumberType.forNumberClasses(Float.class, Double.TYPE, Integer.class));
+ }
+
+ /**
+ * Tests {@link NumberType#isInteger(Class)}.
+ */
+ @Test
+ public void testIsInteger() {
+ assertTrue (NumberType.isInteger(Byte .TYPE));
+ assertTrue (NumberType.isInteger(Short .TYPE));
+ assertTrue (NumberType.isInteger(Integer .TYPE));
+ assertTrue (NumberType.isInteger(Long .TYPE));
+ assertFalse(NumberType.isInteger(Float .TYPE));
+ assertFalse(NumberType.isInteger(Double .TYPE));
+ assertTrue (NumberType.isInteger(Byte .class));
+ assertTrue (NumberType.isInteger(Short .class));
+ assertTrue (NumberType.isInteger(Integer .class));
+ assertTrue (NumberType.isInteger(Long .class));
+ assertFalse(NumberType.isInteger(Float .class));
+ assertFalse(NumberType.isInteger(Double .class));
+ assertFalse(NumberType.isInteger(String .class));
+ assertFalse(NumberType.isInteger(Character .class));
+ assertFalse(NumberType.isInteger(Fraction .class));
+ assertTrue (NumberType.isInteger(BigInteger.class));
+ assertFalse(NumberType.isInteger(BigDecimal.class));
+ }
+
+ /**
+ * Tests {@link NumberType#isFractional(Class)}.
+ */
+ @Test
+ public void testIsFloat() {
+ assertFalse(NumberType.isFractional(Byte .TYPE));
+ assertFalse(NumberType.isFractional(Short .TYPE));
+ assertFalse(NumberType.isFractional(Integer .TYPE));
+ assertFalse(NumberType.isFractional(Long .TYPE));
+ assertTrue (NumberType.isFractional(Float .TYPE));
+ assertTrue (NumberType.isFractional(Double .TYPE));
+ assertFalse(NumberType.isFractional(Byte .class));
+ assertFalse(NumberType.isFractional(Short .class));
+ assertFalse(NumberType.isFractional(Integer .class));
+ assertFalse(NumberType.isFractional(Long .class));
+ assertTrue (NumberType.isFractional(Float .class));
+ assertTrue (NumberType.isFractional(Double .class));
+ assertFalse(NumberType.isFractional(String .class));
+ assertFalse(NumberType.isFractional(Character .class));
+ assertTrue (NumberType.isFractional(Fraction .class));
+ assertFalse(NumberType.isFractional(BigInteger.class));
+ assertTrue (NumberType.isFractional(BigDecimal.class));
+ }
+
+ /**
+ * Tests {@link NumberType#size()}.
+ */
+ @Test
+ public void testSize() {
+ assertEquals(Byte .SIZE, NumberType.forNumberClass(Byte .class).size().orElseThrow());
+ assertEquals(Short .SIZE, NumberType.forNumberClass(Short .class).size().orElseThrow());
+ assertEquals(Integer.SIZE, NumberType.forNumberClass(Integer.class).size().orElseThrow());
+ assertEquals(Long. SIZE, NumberType.forNumberClass(Long .class).size().orElseThrow());
+ assertEquals(Float .SIZE, NumberType.forNumberClass(Float .class).size().orElseThrow());
+ assertEquals(Double .SIZE, NumberType.forNumberClass(Double .class).size().orElseThrow());
+ }
+
+ /**
+ * Tests {@link NumberType#primitiveToWrapper(Class)}.
+ */
+ @Test
+ public void testPrimitiveToWrapper() {
+ verifyPrimitiveToWrapper(Byte .class, Byte .TYPE);
+ verifyPrimitiveToWrapper(Short .class, Short .TYPE);
+ verifyPrimitiveToWrapper(Integer .class, Integer .TYPE);
+ verifyPrimitiveToWrapper(Long .class, Long .TYPE);
+ verifyPrimitiveToWrapper(Float .class, Float .TYPE);
+ verifyPrimitiveToWrapper(Double .class, Double .TYPE);
+ verifyPrimitiveToWrapper(Character.class, Character.TYPE);
+ verifyPrimitiveToWrapper(Boolean .class, Boolean .TYPE);
+ verifyPrimitiveToWrapper(Void .class, Void .TYPE);
+ assertSame(String.class, NumberType.primitiveToWrapper(String.class));
+ }
+
+ /**
+ * Asserts that calls to {@link NumberType#primitiveToWrapper(Class)} produce the expected wrapper.
+ * The {@code <N>} parameter type is for making sure that e.g. {@link Integer#TYPE} has the same
+ * type declaration as {@code Integer.class} despite being different {@link Class} instances.
+ */
+ private static <N> void verifyPrimitiveToWrapper(final Class<N> wrapper, final Class<N> primitive) {
+ assertNotSame(wrapper, primitive);
+ assertSame (wrapper, NumberType.primitiveToWrapper(primitive));
+ assertSame (wrapper, NumberType.primitiveToWrapper(wrapper));
+ }
+
+ /**
+ * Tests {@link NumberType#wrapperToPrimitive(Class)}.
+ */
+ @Test
+ public void testWrapperToPrimitive() {
+ verifyWrapperToPrimitive(Byte .TYPE, Byte .class);
+ verifyWrapperToPrimitive(Short .TYPE, Short .class);
+ verifyWrapperToPrimitive(Integer .TYPE, Integer .class);
+ verifyWrapperToPrimitive(Long .TYPE, Long .class);
+ verifyWrapperToPrimitive(Float .TYPE, Float .class);
+ verifyWrapperToPrimitive(Double .TYPE, Double .class);
+ verifyWrapperToPrimitive(Character.TYPE, Character.class);
+ verifyWrapperToPrimitive(Boolean .TYPE, Boolean .class);
+ verifyWrapperToPrimitive(Void .TYPE, Void .class);
+ assertSame(String.class, NumberType.wrapperToPrimitive(String.class));
+ }
+
+ /**
+ * Asserts that calls to {@link NumberType#wrapperToPrimitive(Class)} produce the expected wrapper.
+ * The {@code <N>} parameter type is for making sure that e.g. {@link Integer#TYPE} has the same
+ * type declaration as {@code Integer.class} despite being different {@link Class} instances.
+ */
+ private static <N> void verifyWrapperToPrimitive(final Class<N> primitive, final Class<N> wrapper) {
+ assertNotSame(primitive, wrapper);
+ assertSame (primitive, NumberType.wrapperToPrimitive(wrapper));
+ assertSame (primitive, NumberType.wrapperToPrimitive(primitive));
+ }
+
+ /**
+ * Tests {@link NumberType#isConversionLossless(NumberType)}.
+ * Opportunistically tests also related methods.
+ */
+ @Test
+ public void testIsConversionLossless() {
+ assertTrue (NumberType.FLOAT .isConversionLossless(NumberType.DOUBLE));
+ assertFalse(NumberType.DOUBLE .isConversionLossless(NumberType.FLOAT));
+ assertFalse(NumberType.INTEGER.isConversionLossless(NumberType.FLOAT));
+ assertTrue (NumberType.INTEGER.isConversionLossless(NumberType.DOUBLE));
+ assertFalse(NumberType.LONG .isConversionLossless(NumberType.DOUBLE));
+ assertTrue (NumberType.LONG .isConversionLossless(NumberType.BIG_DECIMAL));
+ final NumberType[] values = NumberType.values();
+ for (int i=0; i<values.length; i++) {
+ final NumberType value = values[i];
+ final String label = value.name();
+ assertTrue(value.isConversionLossless(value), label);
+ for (int j=0; j<i; j++) {
+ final NumberType other = values[j];
+ assertFalse(value.isConversionLossless(other), label);
+ assertFalse(value.isNarrowerThan(other), label);
+ assertFalse(other.isWiderThan(value), label);
+ }
+ for (int j=i; ++j < values.length;) {
+ final NumberType other = values[j];
+ if (value.isConversionLossless(other)) {
+ assertTrue(other.isWiderThan(value), label);
+ assertTrue(value.isNarrowerThan(other), label);
+ }
+ }
+ }
+ }
+}
diff --git a/endorsed/src/org.apache.sis.util/test/org/apache/sis/util/NumbersTest.java b/endorsed/src/org.apache.sis.util/test/org/apache/sis/util/NumbersTest.java
index b8aeba1f7e..b135f03a58 100644
--- a/endorsed/src/org.apache.sis.util/test/org/apache/sis/util/NumbersTest.java
+++ b/endorsed/src/org.apache.sis.util/test/org/apache/sis/util/NumbersTest.java
@@ -16,9 +16,6 @@
*/
package org.apache.sis.util;
-import java.math.BigDecimal;
-import java.math.BigInteger;
-import org.apache.sis.math.Fraction;
import static org.apache.sis.util.Numbers.*;
// Test dependencies
@@ -33,6 +30,7 @@ import org.apache.sis.test.TestCase;
*
* @author Martin Desruisseaux (Geomatys)
*/
+@SuppressWarnings("exports")
public final class NumbersTest extends TestCase {
/**
* Creates a new test case.
@@ -40,54 +38,6 @@ public final class NumbersTest extends TestCase {
public NumbersTest() {
}
- /**
- * Tests {@link Numbers#isInteger(Class)}.
- */
- @Test
- public void testIsInteger() {
- assertTrue (isInteger(Byte .TYPE));
- assertTrue (isInteger(Short .TYPE));
- assertTrue (isInteger(Integer .TYPE));
- assertTrue (isInteger(Long .TYPE));
- assertFalse(isInteger(Float .TYPE));
- assertFalse(isInteger(Double .TYPE));
- assertTrue (isInteger(Byte .class));
- assertTrue (isInteger(Short .class));
- assertTrue (isInteger(Integer .class));
- assertTrue (isInteger(Long .class));
- assertFalse(isInteger(Float .class));
- assertFalse(isInteger(Double .class));
- assertFalse(isInteger(String .class));
- assertFalse(isInteger(Character .class));
- assertFalse(isInteger(Fraction .class));
- assertTrue (isInteger(BigInteger.class));
- assertFalse(isInteger(BigDecimal.class));
- }
-
- /**
- * Tests {@link Numbers#isFloat(Class)}.
- */
- @Test
- public void testIsFloat() {
- assertFalse(isFloat(Byte .TYPE));
- assertFalse(isFloat(Short .TYPE));
- assertFalse(isFloat(Integer .TYPE));
- assertFalse(isFloat(Long .TYPE));
- assertTrue (isFloat(Float .TYPE));
- assertTrue (isFloat(Double .TYPE));
- assertFalse(isFloat(Byte .class));
- assertFalse(isFloat(Short .class));
- assertFalse(isFloat(Integer .class));
- assertFalse(isFloat(Long .class));
- assertTrue (isFloat(Float .class));
- assertTrue (isFloat(Double .class));
- assertFalse(isFloat(String .class));
- assertFalse(isFloat(Character .class));
- assertTrue (isFloat(Fraction .class));
- assertFalse(isFloat(BigInteger.class));
- assertTrue (isFloat(BigDecimal.class));
- }
-
/**
* Tests {@link Numbers#round(Number)}.
*/
@@ -98,75 +48,6 @@ public final class NumbersTest extends TestCase {
assertMessageContains(e);
}
- /**
- * Tests {@link Numbers#primitiveBitCount(Class)}.
- */
- @Test
- public void testPrimitiveBitCount() {
- assertEquals(Byte .SIZE, primitiveBitCount(Byte .class));
- assertEquals(Short .SIZE, primitiveBitCount(Short .class));
- assertEquals(Integer.SIZE, primitiveBitCount(Integer.class));
- assertEquals(Long. SIZE, primitiveBitCount(Long .class));
- assertEquals(Float .SIZE, primitiveBitCount(Float .class));
- assertEquals(Double .SIZE, primitiveBitCount(Double .class));
- }
-
- /**
- * Tests {@link Numbers#primitiveToWrapper(Class)}.
- */
- @Test
- public void testPrimitiveToWrapper() {
- verifyPrimitiveToWrapper(Byte .class, Byte .TYPE);
- verifyPrimitiveToWrapper(Short .class, Short .TYPE);
- verifyPrimitiveToWrapper(Integer .class, Integer .TYPE);
- verifyPrimitiveToWrapper(Long .class, Long .TYPE);
- verifyPrimitiveToWrapper(Float .class, Float .TYPE);
- verifyPrimitiveToWrapper(Double .class, Double .TYPE);
- verifyPrimitiveToWrapper(Character.class, Character.TYPE);
- verifyPrimitiveToWrapper(Boolean .class, Boolean .TYPE);
- verifyPrimitiveToWrapper(Void .class, Void .TYPE);
- assertSame(String.class, primitiveToWrapper(String.class));
- }
-
- /**
- * Asserts that calls to {@link Numbers#primitiveToWrapper(Class)} produces the expected wrapper.
- * The {@code <N>} parameter type is for making sure that e.g. {@link Integer#TYPE} has the same
- * type declaration than {@code Integer.class} despite being different {@link Class} instances.
- */
- private static <N> void verifyPrimitiveToWrapper(final Class<N> wrapper, final Class<N> primitive) {
- assertNotSame(wrapper, primitive);
- assertSame (wrapper, primitiveToWrapper(primitive));
- assertSame (wrapper, primitiveToWrapper(wrapper));
- }
-
- /**
- * Tests {@link Numbers#wrapperToPrimitive(Class)}.
- */
- @Test
- public void testWrapperToPrimitive() {
- verifyWrapperToPrimitive(Byte .TYPE, Byte .class);
- verifyWrapperToPrimitive(Short .TYPE, Short .class);
- verifyWrapperToPrimitive(Integer .TYPE, Integer .class);
- verifyWrapperToPrimitive(Long .TYPE, Long .class);
- verifyWrapperToPrimitive(Float .TYPE, Float .class);
- verifyWrapperToPrimitive(Double .TYPE, Double .class);
- verifyWrapperToPrimitive(Character.TYPE, Character.class);
- verifyWrapperToPrimitive(Boolean .TYPE, Boolean .class);
- verifyWrapperToPrimitive(Void .TYPE, Void .class);
- assertSame(String.class, wrapperToPrimitive(String.class));
- }
-
- /**
- * Asserts that calls to {@link Numbers#wrapperToPrimitive(Class)} produces the expected wrapper.
- * The {@code <N>} parameter type is for making sure that e.g. {@link Integer#TYPE} has the same
- * type declaration than {@code Integer.class} despite being different {@link Class} instances.
- */
- private static <N> void verifyWrapperToPrimitive(final Class<N> primitive, final Class<N> wrapper) {
- assertNotSame(primitive, wrapper);
- assertSame (primitive, wrapperToPrimitive(wrapper));
- assertSame (primitive, wrapperToPrimitive(primitive));
- }
-
/**
* Tests {@link Numbers#widestClass(Class, Class)}.
*/
diff --git a/incubator/src/org.apache.sis.geometry/main/org/apache/sis/geometries/math/DataType.java b/incubator/src/org.apache.sis.geometry/main/org/apache/sis/geometries/math/DataType.java
index 77d346968a..ae3ebd0269 100644
--- a/incubator/src/org.apache.sis.geometry/main/org/apache/sis/geometries/math/DataType.java
+++ b/incubator/src/org.apache.sis.geometry/main/org/apache/sis/geometries/math/DataType.java
@@ -19,8 +19,7 @@ package org.apache.sis.geometries.math;
import java.awt.image.RasterFormatException;
import static org.apache.sis.util.internal.shared.Numerics.MAX_INTEGER_CONVERTIBLE_TO_FLOAT;
import org.apache.sis.measure.NumberRange;
-import org.apache.sis.util.ArgumentChecks;
-import org.apache.sis.util.Numbers;
+import org.apache.sis.math.NumberType;
/**
@@ -127,15 +126,13 @@ public enum DataType {
* @return smallest data type for the given range of values.
*/
public static DataType forRange(final NumberRange<?> range, final boolean asInteger) {
- ArgumentChecks.ensureNonNull("range", range);
- final byte nt = Numbers.getEnumConstant(range.getElementType());
- if (!asInteger) {
- if (nt >= Numbers.DOUBLE) return DOUBLE;
- if (nt >= Numbers.FRACTION) return FLOAT;
+ final NumberType nt = NumberType.forNumberClass(range.getElementType());
+ if (!asInteger && nt.isFractional()) {
+ return nt.isNarrowerThan(NumberType.DOUBLE) ? FLOAT : DOUBLE;
}
final double min = range.getMinDouble();
final double max = range.getMaxDouble();
- if (nt < Numbers.BYTE || nt > Numbers.FLOAT || nt == Numbers.LONG) {
+ if (!nt.isReal() || nt.ordinal() >= NumberType.LONG.ordinal()) {
/*
* Value type is long, double, BigInteger, BigDecimal or unknown type.
* If conversions to 32 bits integers would lost integer digits, or if
@@ -183,13 +180,13 @@ public enum DataType {
* @throws RasterFormatException if the given type is not a recognized.
*/
public static DataType forPrimitiveType(final Class<?> type, final boolean unsigned) {
- switch (Numbers.getEnumConstant(type)) {
- case Numbers.BYTE: return unsigned ? UBYTE : BYTE;
- case Numbers.SHORT: return unsigned ? USHORT : SHORT;
- case Numbers.INTEGER: return unsigned ? UINT : INT;
- case Numbers.LONG: return LONG;
- case Numbers.FLOAT: return FLOAT;
- case Numbers.DOUBLE: return DOUBLE;
+ switch (NumberType.forNumberClass(type)) {
+ case BYTE: return unsigned ? UBYTE : BYTE;
+ case SHORT: return unsigned ? USHORT : SHORT;
+ case INTEGER: return unsigned ? UINT : INT;
+ case LONG: return LONG;
+ case FLOAT: return FLOAT;
+ case DOUBLE: return DOUBLE;
}
throw new RasterFormatException("Unknown data type " + type.getSimpleName());
}
diff --git a/optional/src/org.apache.sis.gui/main/org/apache/sis/gui/coverage/CellFormat.java b/optional/src/org.apache.sis.gui/main/org/apache/sis/gui/coverage/CellFormat.java
index 8259fc5d69..bc7a3aaa38 100644
--- a/optional/src/org.apache.sis.gui/main/org/apache/sis/gui/coverage/CellFormat.java
+++ b/optional/src/org.apache.sis.gui/main/org/apache/sis/gui/coverage/CellFormat.java
@@ -29,7 +29,7 @@ import javafx.scene.control.Tooltip;
import javafx.util.Duration;
import org.apache.sis.image.PlanarImage;
import org.apache.sis.math.DecimalFunctions;
-import org.apache.sis.util.Numbers;
+import org.apache.sis.math.NumberType;
import org.apache.sis.util.Workaround;
import org.apache.sis.gui.internal.Styles;
import org.apache.sis.gui.internal.RecentChoices;
@@ -311,7 +311,7 @@ final class CellFormat extends SimpleStringProperty {
private static OptionalInt getFractionDigits(final RenderedImage image, final int band) {
final Object property = image.getProperty(PlanarImage.SAMPLE_RESOLUTIONS_KEY);
if (property != null) {
- if (Numbers.isNumber(property.getClass().getComponentType()) && band < Array.getLength(property)) {
+ if (NumberType.isReal(property.getClass().getComponentType()) && band < Array.getLength(property)) {
final double resolution = Math.abs(((Number) Array.get(property, band)).doubleValue());
if (resolution > 0 && resolution <= Double.MAX_VALUE) { // Non-zero, non-NaN and finite.
return OptionalInt.of(DecimalFunctions.fractionDigitsForDelta(resolution, false));