/*
 * Licensed 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 io.trino.operator;

import io.trino.spi.Page;

import static com.google.common.base.Preconditions.checkState;

public interface HashGenerator
{
    long hashPosition(int position, Page page);

    default int getPartition(int partitionCount, int position, Page page)
    {
        long rawHash = hashPosition(position, page);

        // clear the sign bit
        rawHash &= 0x7fff_ffff_ffff_ffffL;

        int partition = (int) (rawHash % partitionCount);

        checkState(partition >= 0 && partition < partitionCount);
        return partition;
    }
}

@@ -614,72 +614,8 @@
 e;%0A%0A
-import static com.google.common.base.Preconditions.checkState;%0A%0A
 publ
@@ -821,25 +821,24 @@
 ion, page);%0A
-%0A
         // c
@@ -840,178 +840,236 @@
  // 
-clear the sign bit%0A        rawHash &= 0x7fff_ffff_ffff_ffffL;%0A%0A        int partition = (int) (rawHash %25 partitionCount);%0A%0A        checkState(partition %3E= 0 && partition %3C
+This function reduces the 64 bit rawHash to %5B0, partitionCount) uniformly. It first reduces the rawHash to 32 bit%0A        // integer x then normalize it to x / 2%5E32 * partitionCount to reduce the range of x from %5B0, 2%5E32) to %5B0,
  par
@@ -1080,17 +1080,16 @@
 onCount)
-;
 %0A       
@@ -1096,25 +1096,96 @@
  return 
-partition
+(int) ((Integer.toUnsignedLong(Long.hashCode(rawHash)) * partitionCount) %3E%3E%3E 32)
 ;%0A    %7D%0A

Improve HashGenerator.getPartition performance