kotlin icon indicating copy to clipboard operation
kotlin copied to clipboard

Improve `kotlin.uuid.Uuid` hashcode

Open FelixDes opened this issue 1 year ago • 4 comments
trafficstars

Hi, dear maintainers,

I've found an issue with the new multiplatform implementation of kotlin.uuid.Uuid. Its hashCode method can be rewritten with utilizing Long.hashCode() for better readability.

FelixDes avatar Oct 03 '24 18:10 FelixDes

The math underlying this change:

x = mostSignificantBits ^ leastSignificantBits Original code was:

int( x ) ^ int( x >> 32 )

With my change it is:

int( x ^ (x >>> 32) ) <=> int( x ) ^ int( x >>> 32 )

>>> and >> are equal in this case because the difference is in the left most bit which is truncated by int casting

FelixDes avatar Oct 03 '24 18:10 FelixDes

cc @qurbonzoda

fzhinkin avatar Oct 07 '24 17:10 fzhinkin

The two implementations are indeed equivalent according to Long.hashCode() documentation: https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/lang/Long.html#hashCode() I am not sure about the improved readability, it depends on whether the reader is familiar with how Long.hashCode() is implemented.

qurbonzoda avatar Oct 09 '24 13:10 qurbonzoda

The readability is straightforward -- instead "hey, is it something tailored by UUID? Is it handrolled? Is it robust for hashmaps?" there is immediate "Ok, this is how the language hashes longs"

qwwdfsad avatar Oct 09 '24 13:10 qwwdfsad

I've merged your commit into master manually: https://github.com/JetBrains/kotlin/commit/1fe504564ecacdbbb5b231be34355dca557f1840

Thanks for the contribution!

qurbonzoda avatar Oct 17 '24 09:10 qurbonzoda