Skip to content

Commit

Permalink
Enable NarrowCalculation error-prone check
Browse files Browse the repository at this point in the history
This mostly matches IntelliJ's `integer multiplication implicitly cast
to long` inspection. While places changed do not look like bugs, so can
be viewed as false positives, this helps avoid IDE warnings and thus
makes spotting problems easier.
  • Loading branch information
findepi committed Aug 8, 2023
1 parent 30114bd commit a327d63
Show file tree
Hide file tree
Showing 34 changed files with 60 additions and 59 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -2133,9 +2133,9 @@ private static Time parseTimeWithTimeZone(String value)
fractionValue = Long.parseLong(fraction);
}

long epochMilli = (hour * 3600 + minute * 60 + second) * MILLISECONDS_PER_SECOND + rescale(fractionValue, precision, 3);
long epochMilli = (hour * 3600L + minute * 60L + second) * MILLISECONDS_PER_SECOND + rescale(fractionValue, precision, 3);

epochMilli -= calculateOffsetMinutes(offsetSign, offsetHour, offsetMinute) * MILLISECONDS_PER_MINUTE;
epochMilli -= calculateOffsetMinutes(offsetSign, offsetHour, offsetMinute) * (long) MILLISECONDS_PER_MINUTE;

return new Time(epochMilli);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -337,7 +337,7 @@ private boolean addPages(HttpPageBufferClient client, List<Slice> pages)

successfulRequests++;
// AVG_n = AVG_(n-1) * (n-1)/n + VALUE_n / n
averageBytesPerRequest = (long) (1.0 * averageBytesPerRequest * (successfulRequests - 1) / successfulRequests + responseSize / successfulRequests);
averageBytesPerRequest = (long) (1.0 * averageBytesPerRequest * (successfulRequests - 1) / successfulRequests + (double) responseSize / successfulRequests);
}

return true;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -101,7 +101,7 @@ public DriverWindowInfo build()
long totalRowsCount = indexInfos.stream()
.mapToLong(IndexInfo::getTotalRowsCount)
.sum();
double averageIndexPositions = totalRowsCount / indexInfos.size();
double averageIndexPositions = (double) totalRowsCount / indexInfos.size();
double squaredDifferencesPositionsOfIndex = indexInfos.stream()
.mapToDouble(index -> Math.pow(index.getTotalRowsCount() - averageIndexPositions, 2))
.sum();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -93,7 +93,7 @@ private static long computeEpochMillis(ConnectorSession session, ZoneId zoneId,
{
long milliFraction = rescale(picoFraction, TimeType.MAX_PRECISION, 3);
long epochMillis = multiplyExact(epochSeconds, MILLISECONDS_PER_SECOND) + milliFraction;
epochMillis -= zoneId.getRules().getOffset(session.getStart()).getTotalSeconds() * MILLISECONDS_PER_SECOND;
epochMillis -= zoneId.getRules().getOffset(session.getStart()).getTotalSeconds() * (long) MILLISECONDS_PER_SECOND;
return epochMillis;
}
}
4 changes: 2 additions & 2 deletions core/trino-main/src/main/java/io/trino/type/DateTimes.java
Original file line number Diff line number Diff line change
Expand Up @@ -634,7 +634,7 @@ public static LongTimestamp longTimestamp(long precision, Instant start)
checkArgument(precision > MAX_SHORT_PRECISION && precision <= TimestampType.MAX_PRECISION, "Precision is out of range");
return new LongTimestamp(
start.getEpochSecond() * MICROSECONDS_PER_SECOND + start.getLong(MICRO_OF_SECOND),
(int) round((start.getNano() % PICOSECONDS_PER_NANOSECOND) * PICOSECONDS_PER_NANOSECOND, (int) (TimestampType.MAX_PRECISION - precision)));
(int) round((start.getNano() % PICOSECONDS_PER_NANOSECOND) * (long) PICOSECONDS_PER_NANOSECOND, (int) (TimestampType.MAX_PRECISION - precision)));
}

public static LongTimestamp longTimestamp(long epochSecond, long fractionInPicos)
Expand All @@ -649,7 +649,7 @@ public static LongTimestampWithTimeZone longTimestampWithTimeZone(long precision
checkArgument(precision <= TimestampWithTimeZoneType.MAX_PRECISION, "Precision is out of range");

long epochMilli = start.toEpochMilli();
int picosOfMilli = (int) round((start.getNano() % NANOSECONDS_PER_MILLISECOND) * PICOSECONDS_PER_NANOSECOND, (int) (TimestampWithTimeZoneType.MAX_PRECISION - precision));
int picosOfMilli = (int) round((start.getNano() % NANOSECONDS_PER_MILLISECOND) * (long) PICOSECONDS_PER_NANOSECOND, (int) (TimestampWithTimeZoneType.MAX_PRECISION - precision));
if (picosOfMilli == PICOSECONDS_PER_MILLISECOND) {
epochMilli++;
picosOfMilli = 0;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -69,7 +69,7 @@ public void testNewBlockBuilderLike()
arrayBlockBuilder.buildEntry(elementBuilder -> {
ArrayBlockBuilder nestedArrayBuilder = (ArrayBlockBuilder) elementBuilder;
nestedArrayBuilder.buildEntry(valueBuilder -> BIGINT.writeLong(valueBuilder, value));
nestedArrayBuilder.buildEntry(valueBuilder -> BIGINT.writeLong(valueBuilder, value * 2));
nestedArrayBuilder.buildEntry(valueBuilder -> BIGINT.writeLong(valueBuilder, value * 2L));
});
pageBuilder.declarePosition();
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@ public class TestArbitraryDistributionSplitAssigner
{
private static final int FUZZ_TESTING_INVOCATION_COUNT = 100;

private static final int STANDARD_SPLIT_SIZE_IN_BYTES = 1;
private static final long STANDARD_SPLIT_SIZE_IN_BYTES = 1;

private static final PlanNodeId PARTITIONED_1 = new PlanNodeId("partitioned-1");
private static final PlanNodeId PARTITIONED_2 = new PlanNodeId("partitioned-2");
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ protected Block[] getSequenceBlocks(int start, int length)
{
BlockBuilder blockBuilder = INTERVAL_DAY_TIME.createBlockBuilder(null, length);
for (int i = start; i < start + length; i++) {
INTERVAL_DAY_TIME.writeLong(blockBuilder, i * 250);
INTERVAL_DAY_TIME.writeLong(blockBuilder, i * 250L);
}
return new Block[] {blockBuilder.build()};
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ protected Block[] getSequenceBlocks(int start, int length)
{
BlockBuilder blockBuilder = INTERVAL_DAY_TIME.createBlockBuilder(null, length);
for (int i = start; i < start + length; i++) {
INTERVAL_DAY_TIME.writeLong(blockBuilder, i * 1000);
INTERVAL_DAY_TIME.writeLong(blockBuilder, i * 1000L);
}
return new Block[] {blockBuilder.build()};
}
Expand All @@ -45,7 +45,7 @@ protected SqlIntervalDayTime getExpectedValue(int start, int length)

long sum = 0;
for (int i = start; i < start + length; i++) {
sum += i * 1000;
sum += i * 1000L;
}
return new SqlIntervalDayTime(sum);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -117,8 +117,8 @@ public void testDifferentPositions()
assertTrue(output.getBlock(0) instanceof DictionaryBlock);
assertEquals(output.getPositionCount(), entries / 2);
for (int i = 0; i < entries / 2; i++) {
assertEquals(output.getBlock(0).getLong(i, 0), i * 2);
assertEquals(output.getBlock(1).getLong(i, 0), i * 2);
assertEquals(output.getBlock(0).getLong(i, 0), i * 2L);
assertEquals(output.getBlock(1).getLong(i, 0), i * 2L);
}
lookupJoinPageBuilder.reset();

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -118,8 +118,8 @@ public void testDifferentPositions()
assertTrue(output.getBlock(0) instanceof DictionaryBlock);
assertEquals(output.getPositionCount(), entries / 2);
for (int i = 0; i < entries / 2; i++) {
assertEquals(output.getBlock(0).getLong(i, 0), i * 2);
assertEquals(output.getBlock(1).getLong(i, 0), i * 2);
assertEquals(output.getBlock(0).getLong(i, 0), i * 2L);
assertEquals(output.getBlock(1).getLong(i, 0), i * 2L);
}
lookupJoinPageBuilder.reset();

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -159,8 +159,8 @@ public class TestHttpRemoteTask
private static final Duration FAIL_TIMEOUT = new Duration(20, SECONDS);
private static final TaskManagerConfig TASK_MANAGER_CONFIG = new TaskManagerConfig()
// Shorten status refresh wait and info update interval so that we can have a shorter test timeout
.setStatusRefreshMaxWait(new Duration(IDLE_TIMEOUT.roundTo(MILLISECONDS) / 100, MILLISECONDS))
.setInfoUpdateInterval(new Duration(IDLE_TIMEOUT.roundTo(MILLISECONDS) / 10, MILLISECONDS));
.setStatusRefreshMaxWait(new Duration(IDLE_TIMEOUT.roundTo(MILLISECONDS) / 100.0, MILLISECONDS))
.setInfoUpdateInterval(new Duration(IDLE_TIMEOUT.roundTo(MILLISECONDS) / 10.0, MILLISECONDS));

private static final boolean TRACE_HTTP = false;

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -156,7 +156,7 @@ private void testSpiller(List<Type> types, Spiller spiller, List<Page>... spills
assertEquals(spillerStats.getTotalSpilledBytes() - spilledBytesBefore, spilledBytes);
// At this point, the buffers should still be accounted for in the memory context, because
// the spiller (FileSingleStreamSpiller) doesn't release its memory reservation until it's closed.
assertEquals(memoryContext.getBytes(), spills.length * FileSingleStreamSpiller.BUFFER_SIZE);
assertEquals(memoryContext.getBytes(), (long) spills.length * FileSingleStreamSpiller.BUFFER_SIZE);

List<Iterator<Page>> actualSpills = spiller.getSpills();
assertEquals(actualSpills.size(), spills.length);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -78,7 +78,7 @@ public void testBasicOps(long nullKey1, long nullKey2)
count++;
assertTrue(map.replace(key1, key2, count - 1, count));
assertFalse(map.isEmpty());
assertEquals(map.size(), values.size() * values.size());
assertEquals(map.size(), (long) values.size() * values.size());
}
}

Expand Down Expand Up @@ -145,7 +145,7 @@ public boolean equals(long a1, long a2, long b1, long b2)
count++;
assertTrue(map.replace(key1, key2, count - 1, count));
assertFalse(map.isEmpty());
assertEquals(map.size(), values.size() * values.size());
assertEquals(map.size(), (long) values.size() * values.size());
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -77,13 +77,13 @@ public String toString()
int lastLineBytes = bytes.length % 32;

// 4 full words with 3 word separators and one line break per full line of output
long totalSize = fullLineCount * ((4 * OUTPUT_CHARS_PER_FULL_WORD) + (3 * WORD_SEPARATOR.length()) + 1);
long totalSize = (long) fullLineCount * ((4 * OUTPUT_CHARS_PER_FULL_WORD) + (3 * WORD_SEPARATOR.length()) + 1);
if (lastLineBytes == 0) {
totalSize--; // no final line separator
}
else {
int lastLineWords = lastLineBytes / 8;
totalSize += (lastLineWords * (OUTPUT_CHARS_PER_FULL_WORD + WORD_SEPARATOR.length()));
totalSize += (long) lastLineWords * (OUTPUT_CHARS_PER_FULL_WORD + WORD_SEPARATOR.length());
// whole words and separators on last line
if (lastLineWords * 8 == lastLineBytes) {
totalSize -= WORD_SEPARATOR.length(); // last line ends on a word boundary, no separator
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -94,7 +94,7 @@ private static void assertNotificationsRecursive(int depth, Block lazyBlock, Lis
assertEquals(actualNotifications, expectedNotifications);

if (loadedBlock instanceof ArrayBlock) {
long expectedSize = (Integer.BYTES + Byte.BYTES) * loadedBlock.getPositionCount();
long expectedSize = (long) (Integer.BYTES + Byte.BYTES) * loadedBlock.getPositionCount();
assertEquals(loadedBlock.getSizeInBytes(), expectedSize);

Block elementsBlock = loadedBlock.getChildren().get(0);
Expand All @@ -107,7 +107,7 @@ private static void assertNotificationsRecursive(int depth, Block lazyBlock, Lis
return;
}
if (loadedBlock instanceof RowBlock) {
long expectedSize = (Integer.BYTES + Byte.BYTES) * loadedBlock.getPositionCount();
long expectedSize = (long) (Integer.BYTES + Byte.BYTES) * loadedBlock.getPositionCount();
assertEquals(loadedBlock.getSizeInBytes(), expectedSize);

for (Block fieldBlock : loadedBlock.getChildren()) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -239,7 +239,7 @@ public void init()
{
ranges = new ArrayList<>();

int factor = 0;
long factor = 0;
for (int i = 0; i < 10_000; i++) {
long from = ThreadLocalRandom.current().nextLong(100) + factor * 100;
long to = ThreadLocalRandom.current().nextLong(100) + (factor + 1) * 100;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@ public void testRetainedSizeWithOverlappingBlocks()
long expectedSize = instanceSize(BlockBigArray.class)
+ referenceCountMap.sizeOf()
+ (new ObjectBigArray<>()).sizeOf()
+ block.getRetainedSizeInBytes() + (arraySize - 1) * instanceSize(block.getClass());
+ block.getRetainedSizeInBytes() + (arraySize - 1L) * instanceSize(block.getClass());
assertThat(blockBigArray.sizeOf()).isEqualTo(expectedSize);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -233,7 +233,7 @@ public void testInputFile()

// read int at a time
for (int intPosition = 0; intPosition < 4 * MEGABYTE; intPosition++) {
assertThat(inputStream.getPosition()).isEqualTo(intPosition * 4);
assertThat(inputStream.getPosition()).isEqualTo(intPosition * 4L);

int size = inputStream.readNBytes(bytes, 0, bytes.length);
assertThat(size).isEqualTo(4);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -88,7 +88,7 @@ public long next()
readValues();
}
if (repeat) {
result = literals[0] + (used++) * delta;
result = literals[0] + (used++) * (long) delta;
}
else {
result = literals[used++];
Expand All @@ -111,7 +111,7 @@ public void next(long[] values, int items)
int chunkSize = min(numLiterals - used, items);
if (repeat) {
for (int i = 0; i < chunkSize; i++) {
values[offset + i] = literals[0] + ((used + i) * delta);
values[offset + i] = literals[0] + ((used + i) * (long) delta);
}
}
else {
Expand All @@ -138,7 +138,7 @@ public void next(int[] values, int items)
int chunkSize = min(numLiterals - used, items);
if (repeat) {
for (int i = 0; i < chunkSize; i++) {
long literal = literals[0] + ((used + i) * delta);
long literal = literals[0] + ((used + i) * (long) delta);
int value = (int) literal;
if (literal != value) {
throw new OrcCorruptionException(input.getOrcDataSourceId(), "Decoded value out of range for a 32bit number");
Expand Down Expand Up @@ -177,7 +177,7 @@ public void next(short[] values, int items)
int chunkSize = min(numLiterals - used, items);
if (repeat) {
for (int i = 0; i < chunkSize; i++) {
long literal = literals[0] + ((used + i) * delta);
long literal = literals[0] + ((used + i) * (long) delta);
short value = (short) literal;
if (literal != value) {
throw new OrcCorruptionException(input.getOrcDataSourceId(), "Decoded value out of range for a 16bit number");
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -197,7 +197,7 @@ public StreamDataOutput getStreamDataOutput(OrcColumnId columnId)
@Override
public long getBufferedBytes()
{
return buffer.estimateOutputDataSize() + (Long.BYTES * size);
return buffer.estimateOutputDataSize() + (Long.BYTES * (long) size);
}

@Override
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -756,7 +756,7 @@ public StreamDataOutput getStreamDataOutput(OrcColumnId columnId)
@Override
public long getBufferedBytes()
{
return buffer.estimateOutputDataSize() + (Long.BYTES * numLiterals);
return buffer.estimateOutputDataSize() + (Long.BYTES * (long) numLiterals);
}

@Override
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -153,7 +153,7 @@ public void testSingleDictionaryColumnMemoryLimit()
// construct a simulator that will hit the dictionary (low) memory limit by estimating the number of rows at the memory limit, and then setting large limits around this value
int stripeMaxBytes = megabytes(100);
int dictionaryMaxMemoryBytesLow = dictionaryMaxMemoryBytes - (int) DICTIONARY_MEMORY_MAX_RANGE.toBytes();
int expectedMaxRowCount = (int) (dictionaryMaxMemoryBytesLow / bytesPerEntry / uniquePercentage);
int expectedMaxRowCount = (int) (1.0 * dictionaryMaxMemoryBytesLow / bytesPerEntry / uniquePercentage);
DataSimulator simulator = new DataSimulator(0, stripeMaxBytes, expectedMaxRowCount * 2, dictionaryMaxMemoryBytes, 0, column);

for (int loop = 0; loop < 3; loop++) {
Expand Down Expand Up @@ -191,7 +191,7 @@ public void testDirectConversionOnDictionaryFull()

// construct a simulator that will flip the column to direct and then hit the bytes limit
int stripeMaxBytes = megabytes(100);
int expectedRowCountAtFlip = (int) (dictionaryMaxMemoryBytes / bytesPerEntry / uniquePercentage);
int expectedRowCountAtFlip = (int) (1.0 * dictionaryMaxMemoryBytes / bytesPerEntry / uniquePercentage);
int expectedMaxRowCountAtFull = stripeMaxBytes / bytesPerEntry;
DataSimulator simulator = new DataSimulator(stripeMaxBytes / 2, stripeMaxBytes, expectedMaxRowCountAtFull * 2, dictionaryMaxMemoryBytes, 0, column);

Expand Down Expand Up @@ -239,7 +239,7 @@ public void testNotDirectConversionOnDictionaryFull()
// construct a simulator that will be full because of dictionary memory limit;
// the column cannot not be converted to direct encoding because of stripe size limit
int stripeMaxBytes = megabytes(100);
int expectedMaxRowCount = (int) (dictionaryMaxMemoryBytes / bytesPerEntry / uniquePercentage);
int expectedMaxRowCount = (int) (1.0 * dictionaryMaxMemoryBytes / bytesPerEntry / uniquePercentage);
DataSimulator simulator = new DataSimulator(stripeMaxBytes / 2, stripeMaxBytes, expectedMaxRowCount * 2, dictionaryMaxMemoryBytes, 0, column);

for (int loop = 0; loop < 3; loop++) {
Expand Down Expand Up @@ -573,7 +573,7 @@ public long getBufferedBytes()
}
int dictionaryEntries = getDictionaryEntries();
int bytesPerValue = estimateIndexBytesPerValue(dictionaryEntries);
return (dictionaryEntries * bytesPerEntry) + (getNonNullValueCount() * bytesPerValue);
return ((long) dictionaryEntries * bytesPerEntry) + (getNonNullValueCount() * bytesPerValue);
}

@Override
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -168,7 +168,7 @@ public void testOrcHiveBloomFilterSerde()
@Test
public void testBloomFilterPredicateValuesExisting()
{
BloomFilter bloomFilter = new BloomFilter(TEST_VALUES.size() * 10, 0.01);
BloomFilter bloomFilter = new BloomFilter(TEST_VALUES.size() * 10L, 0.01);

for (Map.Entry<Object, Type> testValue : TEST_VALUES.entrySet()) {
Object o = testValue.getKey();
Expand Down Expand Up @@ -212,7 +212,7 @@ else if (o instanceof Double) {
@Test
public void testBloomFilterPredicateValuesNonExisting()
{
BloomFilter bloomFilter = new BloomFilter(TEST_VALUES.size() * 10, 0.01);
BloomFilter bloomFilter = new BloomFilter(TEST_VALUES.size() * 10L, 0.01);

for (Map.Entry<Object, Type> testValue : TEST_VALUES.entrySet()) {
boolean matched = checkInBloomFilter(bloomFilter, testValue.getKey(), testValue.getValue());
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -224,7 +224,7 @@ public void testBatchSizesForVariableWidth()
rowCountsInCurrentRowGroup += page.getPositionCount();

Block block = page.getBlock(0);
if (MAX_BATCH_SIZE * currentStringBytes <= READER_OPTIONS.getMaxBlockSize().toBytes()) {
if (MAX_BATCH_SIZE * (long) currentStringBytes <= READER_OPTIONS.getMaxBlockSize().toBytes()) {
// Either we are bounded by 1024 rows per batch, or it is the last batch in the row group
// For the first 3 row groups, the strings are of length 300, 600, and 900 respectively
// So the loaded data is bounded by MAX_BATCH_SIZE
Expand Down Expand Up @@ -374,7 +374,7 @@ private static void assertCurrentBatch(Page page, int rowIndex, int batchSize)
{
Block block = page.getBlock(0);
for (int i = 0; i < batchSize; i++) {
assertEquals(BIGINT.getLong(block, i), (rowIndex + i) * 3);
assertEquals(BIGINT.getLong(block, i), (rowIndex + i) * 3L);
}
}

Expand Down
Loading

0 comments on commit a327d63

Please sign in to comment.