Skip to content

Use Double and Long hashCode functions#3046

Open
lllincoln wants to merge 1 commit into
google:mainfrom
lllincoln:main
Open

Use Double and Long hashCode functions#3046
lllincoln wants to merge 1 commit into
google:mainfrom
lllincoln:main

Conversation

@lllincoln

Copy link
Copy Markdown

Purpose

JsonPrimitive.hashCode currently contains a comment and the hashCode bitwise computation itself. This can be simplified using the hashCode functions that JDK 1.8+ provides through Long and Double. This PR aims to improve the readability of the function by using those Long and Double hashCode functions.

Description

Java 1.8 introduced Double.hashCode and Long.hashCode.

Double.hashCode:

/**
 * Returns a hash code for a {@code double} value; compatible with
 * {@code Double.hashCode()}.
 *
 * @param value the value to hash
 * @return a hash code value for a {@code double} value.
 * @since 1.8
 */
public static int hashCode(double value) {
    long bits = doubleToLongBits(value);
    return (int)(bits ^ (bits >>> 32));
}

Long.hashCode:

/**
 * Returns a hash code for a {@code long} value; compatible with
 * {@code Long.hashCode()}.
 *
 * @param value the value to hash
 * @return a hash code value for a {@code long} value.
 * @since 1.8
 */
public static int hashCode(long value) {
    return (int)(value ^ (value >>> 32));
}

Currently, GSON performs the same operations by essentially inlining these functions. By using the JDK provided hashCode functions and not inlining them, this PR improves the readability of the JsonPrimitive.hashCode function. Thanks for considering!

Checklist

  • New code follows the Google Java Style Guide
    This is automatically checked by mvn verify, but can also be checked on its own using mvn spotless:check.
    Style violations can be fixed using mvn spotless:apply; this can be done in a separate commit to verify that it did not cause undesired changes.
  • mvn clean verify javadoc:jar passes without errors

@Marcono1234

Copy link
Copy Markdown
Contributor

Thanks!

The "check-android-compatibility" CI workflow currently fails because those methods were only added in Android API level 24 (Double#hashCode(double), Long#hashCode(long)), but Gson's minimum supported API level is 23 (the README is outdated, saying still 21):

gson/pom.xml

Lines 526 to 528 in c9f3fd5

<!-- Google's internal use currently requires API Level 23 without desugaring. -->
<groupId>net.sf.androidscents.signature</groupId>
<artifactId>android-api-level-23</artifactId>

@eamonnmcmanus, would it make sense to raise the minimum API level to 24? There are a few other TODOs in the code which could be addressed then as well (in subsequent PRs).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants