FIX encode target for scoring when using early stopping in HistGradientBoostinClassifier (#14710)

<|original_code|>
        with scorers.
        """
        subsample_size = 10000
        if X_binned_train.shape[0] > subsample_size:
            indices = np.arange(X_binned_train.shape[0])
            stratify = y_train if is_classifier(self) else None
            indices = resample(indices, n_samples=subsample_size,
                               replace=False, random_state=seed,
                               stratify=stratify)
            X_binned_small_train = X_binned_train[indices]
            y_small_train = y_train[indices]
            X_binned_small_train = np.ascontiguousarray(X_binned_small_train)
            return X_binned_small_train, y_small_train
        else:
            return X_binned_train, y_train

    def _check_early_stopping_scorer(self, X_binned_small_train, y_small_train,
                                     X_binned_val, y_val):
        """Check if fitting should be early-stopped based on scorer.

        Scores are computed on validation data or on training data.
        """
        self.train_score_.append(
            self.scorer_(self, X_binned_small_train, y_small_train)
        )

        if self._use_validation_data:
            self.validation_score_.append(
                self.scorer_(self, X_binned_val, y_val)
            )
            return self._should_stop(self.validation_score_)
        else:
            return self._should_stop(self.train_score_)

    def _check_early_stopping_loss(self,
                                   raw_predictions,
                                   y_train,
                                   raw_predictions_val,
                                   y_val):
        """Check if fitting should be early-stopped based on loss.

        Scores are computed on validation data or on training data.
        """

        self.train_score_.append(
            -self.loss_(y_train, raw_predictions)
        )

        if self._use_validation_data:
            self.validation_score_.append(
                -self.loss_(y_val, raw_predictions_val)
<|edits_diff|>
--- sklearn/ensemble/_hist_gradient_boosting/gradient_boosting.py
+++ sklearn/ensemble/_hist_gradient_boosting/gradient_boosting.py
@@ -20,6 +20,8 @@

         Scores are computed on validation data or on training data.
         """
+        if is_classifier(self):
+            y_small_train = self.classes_[y_small_train.astype(int)]
         self.train_score_.append(
             self.scorer_(self, X_binned_small_train, y_small_train)
         )
<|current_version|>
        with scorers.
        """
        subsample_size = 10000
        if X_binned_train.shape[0] > subsample_size:
            indices = np.arange(X_binned_train.shape[0])
            stratify = y_train if is_classifier(self) else None
            indices = resample(indices, n_samples=subsample_size,
                               replace=False, random_state=seed,
                               stratify=stratify)
            X_binned_small_train = X_binned_train[indices]
            y_small_train = y_train[indices]
            X_binned_small_train = np.ascontiguousarray(X_binned_small_train)
            return X_binned_small_train, y_small_train
        else:
            return X_binned_train, y_train

    def _check_early_stopping_scorer(self, X_binned_small_train, y_small_train,
                                     X_binned_val, y_val):
        """Check if fitting should be early-stopped based on scorer.

        Scores are computed on validation data or on training data.
        """
        if is_classifier(self):
            y_small_train = self.classes_[y_small_train.astype(int)]
        self.train_score_.append(
            self.scorer_(self, X_binned_small_train, y_small_train)
        )

        if self._use_validation_data:
            self.validation_score_.append(
                self.scorer_(self, X_binned_val, y_val)
            )
            return self._should_stop(self.validation_score_)
        else:
            return self._should_stop(self.train_score_)

    def _check_early_stopping_loss(self,
                                   raw_predictions,
                                   y_train,
                                   raw_predictions_val,
                                   y_val):
        """Check if fitting should be early-stopped based on loss.

        Scores are computed on validation data or on training data.
        """

        self.train_score_.append(
            -self.loss_(y_train, raw_predictions)
        )

        if self._use_validation_data:
            self.validation_score_.append(
                -self.loss_(y_val, raw_predictions_val)
<|next_version|>
        with scorers.
        """
        subsample_size = 10000
        if X_binned_train.shape[0] > subsample_size:
            indices = np.arange(X_binned_train.shape[0])
            stratify = y_train if is_classifier(self) else None
            indices = resample(indices, n_samples=subsample_size,
                               replace=False, random_state=seed,
                               stratify=stratify)
            X_binned_small_train = X_binned_train[indices]
            y_small_train = y_train[indices]
            X_binned_small_train = np.ascontiguousarray(X_binned_small_train)
            return X_binned_small_train, y_small_train
        else:
            return X_binned_train, y_train

    def _check_early_stopping_scorer(self, X_binned_small_train, y_small_train,
                                     X_binned_val, y_val):
        """Check if fitting should be early-stopped based on scorer.

        Scores are computed on validation data or on training data.
        """
        if is_classifier(self):
            y_small_train = self.classes_[y_small_train.astype(int)]
        self.train_score_.append(
            self.scorer_(self, X_binned_small_train, y_small_train)
        )

        if self._use_validation_data:
            if is_classifier(self):
                y_val = self.classes_[y_val.astype(int)]
            self.validation_score_.append(
                self.scorer_(self, X_binned_val, y_val)
            )
            return self._should_stop(self.validation_score_)
        else:
            return self._should_stop(self.train_score_)

    def _check_early_stopping_loss(self,
                                   raw_predictions,
                                   y_train,
                                   raw_predictions_val,
                                   y_val):
        """Check if fitting should be early-stopped based on loss.

        Scores are computed on validation data or on training data.
        """

        self.train_score_.append(
            -self.loss_(y_train, raw_predictions)
        )

        if self._use_validation_data:
            self.validation_score_.append(
                -self.loss_(y_val, raw_predictions_val)


Address a few more Error Prone warnings.

<|original_code|>
  static Dispatcher legacyAsync() {
    return new LegacyAsyncDispatcher();
  }

  /**
   * Returns a dispatcher that dispatches events to subscribers immediately as they're posted
   * without using an intermediate queue to change the dispatch order. This is effectively a
   * depth-first dispatch order, vs. breadth-first when using a queue.
   */
  static Dispatcher immediate() {
    return ImmediateDispatcher.INSTANCE;
  }

  /** Dispatches the given {@code event} to the given {@code subscribers}. */
  abstract void dispatch(Object event, Iterator<Subscriber> subscribers);

  /** Implementation of a {@link #perThreadDispatchQueue()} dispatcher. */
  private static final class PerThreadQueuedDispatcher extends Dispatcher {

    // This dispatcher matches the original dispatch behavior of EventBus.

    /** Per-thread queue of events to dispatch. */
    private final ThreadLocal<Queue<Event>> queue =
        new ThreadLocal<Queue<Event>>() {
          @Override
          protected Queue<Event> initialValue() {
            return Queues.newArrayDeque();
          }
        };

    /** Per-thread dispatch state, used to avoid reentrant event dispatching. */
    private final ThreadLocal<Boolean> dispatching =
        new ThreadLocal<Boolean>() {
          @Override
          protected Boolean initialValue() {
            return false;
          }
        };

    @Override
    void dispatch(Object event, Iterator<Subscriber> subscribers) {
      checkNotNull(event);
      checkNotNull(subscribers);
      // requireNonNull accommodates Android's @RecentlyNullable annotation on ThreadLocal.get
      Queue<Event> queueForThread = requireNonNull(queue.get());
      queueForThread.offer(new Event(event, subscribers));

      if (!dispatching.get()) {
        dispatching.set(true);
        try {
          Event nextEvent;
          while ((nextEvent = queueForThread.poll()) != null) {
            while (nextEvent.subscribers.hasNext()) {
              nextEvent.subscribers.next().dispatchEvent(nextEvent.event);
            }
<|edits_diff|>
--- android/guava/src/com/google/common/eventbus/Dispatcher.java
+++ android/guava/src/com/google/common/eventbus/Dispatcher.java
@@ -20,6 +20,7 @@
     // This dispatcher matches the original dispatch behavior of EventBus.

     /** Per-thread queue of events to dispatch. */
+    @SuppressWarnings("ThreadLocalUsage") // Each Dispatcher needs its own state.
     private final ThreadLocal<Queue<Event>> queue =
         new ThreadLocal<Queue<Event>>() {
           @Override
<|current_version|>
  static Dispatcher legacyAsync() {
    return new LegacyAsyncDispatcher();
  }

  /**
   * Returns a dispatcher that dispatches events to subscribers immediately as they're posted
   * without using an intermediate queue to change the dispatch order. This is effectively a
   * depth-first dispatch order, vs. breadth-first when using a queue.
   */
  static Dispatcher immediate() {
    return ImmediateDispatcher.INSTANCE;
  }

  /** Dispatches the given {@code event} to the given {@code subscribers}. */
  abstract void dispatch(Object event, Iterator<Subscriber> subscribers);

  /** Implementation of a {@link #perThreadDispatchQueue()} dispatcher. */
  private static final class PerThreadQueuedDispatcher extends Dispatcher {

    // This dispatcher matches the original dispatch behavior of EventBus.

    /** Per-thread queue of events to dispatch. */
    @SuppressWarnings("ThreadLocalUsage") // Each Dispatcher needs its own state.
    private final ThreadLocal<Queue<Event>> queue =
        new ThreadLocal<Queue<Event>>() {
          @Override
          protected Queue<Event> initialValue() {
            return Queues.newArrayDeque();
          }
        };

    /** Per-thread dispatch state, used to avoid reentrant event dispatching. */
    private final ThreadLocal<Boolean> dispatching =
        new ThreadLocal<Boolean>() {
          @Override
          protected Boolean initialValue() {
            return false;
          }
        };

    @Override
    void dispatch(Object event, Iterator<Subscriber> subscribers) {
      checkNotNull(event);
      checkNotNull(subscribers);
      // requireNonNull accommodates Android's @RecentlyNullable annotation on ThreadLocal.get
      Queue<Event> queueForThread = requireNonNull(queue.get());
      queueForThread.offer(new Event(event, subscribers));

      if (!dispatching.get()) {
        dispatching.set(true);
        try {
          Event nextEvent;
          while ((nextEvent = queueForThread.poll()) != null) {
            while (nextEvent.subscribers.hasNext()) {
              nextEvent.subscribers.next().dispatchEvent(nextEvent.event);
            }
<|next_version|>
  static Dispatcher legacyAsync() {
    return new LegacyAsyncDispatcher();
  }

  /**
   * Returns a dispatcher that dispatches events to subscribers immediately as they're posted
   * without using an intermediate queue to change the dispatch order. This is effectively a
   * depth-first dispatch order, vs. breadth-first when using a queue.
   */
  static Dispatcher immediate() {
    return ImmediateDispatcher.INSTANCE;
  }

  /** Dispatches the given {@code event} to the given {@code subscribers}. */
  abstract void dispatch(Object event, Iterator<Subscriber> subscribers);

  /** Implementation of a {@link #perThreadDispatchQueue()} dispatcher. */
  private static final class PerThreadQueuedDispatcher extends Dispatcher {

    // This dispatcher matches the original dispatch behavior of EventBus.

    /** Per-thread queue of events to dispatch. */
    @SuppressWarnings("ThreadLocalUsage") // Each Dispatcher needs its own state.
    private final ThreadLocal<Queue<Event>> queue =
        new ThreadLocal<Queue<Event>>() {
          @Override
          protected Queue<Event> initialValue() {
            return Queues.newArrayDeque();
          }
        };

    /** Per-thread dispatch state, used to avoid reentrant event dispatching. */
    @SuppressWarnings("ThreadLocalUsage") // Each Dispatcher needs its own state.
    private final ThreadLocal<Boolean> dispatching =
        new ThreadLocal<Boolean>() {
          @Override
          protected Boolean initialValue() {
            return false;
          }
        };

    @Override
    void dispatch(Object event, Iterator<Subscriber> subscribers) {
      checkNotNull(event);
      checkNotNull(subscribers);
      // requireNonNull accommodates Android's @RecentlyNullable annotation on ThreadLocal.get
      Queue<Event> queueForThread = requireNonNull(queue.get());
      queueForThread.offer(new Event(event, subscribers));

      if (!dispatching.get()) {
        dispatching.set(true);
        try {
          Event nextEvent;
          while ((nextEvent = queueForThread.poll()) != null) {
            while (nextEvent.subscribers.hasNext()) {
              nextEvent.subscribers.next().dispatchEvent(nextEvent.event);
            }


Override `Predicate.test` wherever we override `Predicate.apply`.

<|original_code|>
            IllegalArgumentException.class,
            () -> {
              BloomFilter<String> unused =
                  BloomFilter.create(HashTestUtils.BAD_FUNNEL, Integer.MAX_VALUE, Double.MIN_VALUE);
            });
    assertThat(expected)
        .hasMessageThat()
        .isEqualTo("Could not create BloomFilter of 3327428144502 bits");
  }

  @AndroidIncompatible // OutOfMemoryError
  public void testLargeNumberOfInsertions() {
    // We use horrible FPPs here to keep Java from OOM'ing
    BloomFilter<String> unused =
        BloomFilter.create(Funnels.unencodedCharsFunnel(), Integer.MAX_VALUE / 2, 0.30);
    unused = BloomFilter.create(Funnels.unencodedCharsFunnel(), 45L * Integer.MAX_VALUE, 0.99);
  }

  @SuppressWarnings({"deprecation", "InlineMeInliner"}) // test of a deprecated method
  private static void checkSanity(BloomFilter<Object> bf) {
    assertFalse(bf.mightContain(new Object()));
    assertFalse(bf.apply(new Object()));
    for (int i = 0; i < 100; i++) {
      Object o = new Object();
      bf.put(o);
      assertTrue(bf.mightContain(o));
      assertTrue(bf.apply(o));
    }
  }

  public void testCopy() {
    BloomFilter<String> original = BloomFilter.create(Funnels.unencodedCharsFunnel(), 100);
    BloomFilter<String> copy = original.copy();
    assertNotSame(original, copy);
    assertEquals(original, copy);
  }

  public void testExpectedFpp() {
    BloomFilter<Object> bf = BloomFilter.create(HashTestUtils.BAD_FUNNEL, 10, 0.03);
    double fpp = bf.expectedFpp();
    assertThat(fpp).isEqualTo(0.0);
    // usually completed in less than 200 iterations
    while (fpp != 1.0) {
      boolean changed = bf.put(new Object());
      double newFpp = bf.expectedFpp();
      // if changed, the new fpp is strictly higher, otherwise it is the same
      assertTrue(changed ? newFpp > fpp : newFpp == fpp);
      fpp = newFpp;
    }
  }

<|edits_diff|>
--- guava-tests/test/com/google/common/hash/BloomFilterTest.java
+++ guava-tests/test/com/google/common/hash/BloomFilterTest.java
@@ -20,6 +20,7 @@
   private static void checkSanity(BloomFilter<Object> bf) {
     assertFalse(bf.mightContain(new Object()));
     assertFalse(bf.apply(new Object()));
+    assertFalse(bf.test(new Object()));
     for (int i = 0; i < 100; i++) {
       Object o = new Object();
       bf.put(o);
<|current_version|>
            IllegalArgumentException.class,
            () -> {
              BloomFilter<String> unused =
                  BloomFilter.create(HashTestUtils.BAD_FUNNEL, Integer.MAX_VALUE, Double.MIN_VALUE);
            });
    assertThat(expected)
        .hasMessageThat()
        .isEqualTo("Could not create BloomFilter of 3327428144502 bits");
  }

  @AndroidIncompatible // OutOfMemoryError
  public void testLargeNumberOfInsertions() {
    // We use horrible FPPs here to keep Java from OOM'ing
    BloomFilter<String> unused =
        BloomFilter.create(Funnels.unencodedCharsFunnel(), Integer.MAX_VALUE / 2, 0.30);
    unused = BloomFilter.create(Funnels.unencodedCharsFunnel(), 45L * Integer.MAX_VALUE, 0.99);
  }

  @SuppressWarnings({"deprecation", "InlineMeInliner"}) // test of a deprecated method
  private static void checkSanity(BloomFilter<Object> bf) {
    assertFalse(bf.mightContain(new Object()));
    assertFalse(bf.apply(new Object()));
    assertFalse(bf.test(new Object()));
    for (int i = 0; i < 100; i++) {
      Object o = new Object();
      bf.put(o);
      assertTrue(bf.mightContain(o));
      assertTrue(bf.apply(o));
    }
  }

  public void testCopy() {
    BloomFilter<String> original = BloomFilter.create(Funnels.unencodedCharsFunnel(), 100);
    BloomFilter<String> copy = original.copy();
    assertNotSame(original, copy);
    assertEquals(original, copy);
  }

  public void testExpectedFpp() {
    BloomFilter<Object> bf = BloomFilter.create(HashTestUtils.BAD_FUNNEL, 10, 0.03);
    double fpp = bf.expectedFpp();
    assertThat(fpp).isEqualTo(0.0);
    // usually completed in less than 200 iterations
    while (fpp != 1.0) {
      boolean changed = bf.put(new Object());
      double newFpp = bf.expectedFpp();
      // if changed, the new fpp is strictly higher, otherwise it is the same
      assertTrue(changed ? newFpp > fpp : newFpp == fpp);
      fpp = newFpp;
    }
  }

<|next_version|>
            IllegalArgumentException.class,
            () -> {
              BloomFilter<String> unused =
                  BloomFilter.create(HashTestUtils.BAD_FUNNEL, Integer.MAX_VALUE, Double.MIN_VALUE);
            });
    assertThat(expected)
        .hasMessageThat()
        .isEqualTo("Could not create BloomFilter of 3327428144502 bits");
  }

  @AndroidIncompatible // OutOfMemoryError
  public void testLargeNumberOfInsertions() {
    // We use horrible FPPs here to keep Java from OOM'ing
    BloomFilter<String> unused =
        BloomFilter.create(Funnels.unencodedCharsFunnel(), Integer.MAX_VALUE / 2, 0.30);
    unused = BloomFilter.create(Funnels.unencodedCharsFunnel(), 45L * Integer.MAX_VALUE, 0.99);
  }

  @SuppressWarnings({"deprecation", "InlineMeInliner"}) // test of a deprecated method
  private static void checkSanity(BloomFilter<Object> bf) {
    assertFalse(bf.mightContain(new Object()));
    assertFalse(bf.apply(new Object()));
    assertFalse(bf.test(new Object()));
    for (int i = 0; i < 100; i++) {
      Object o = new Object();
      bf.put(o);
      assertTrue(bf.mightContain(o));
      assertTrue(bf.apply(o));
      assertTrue(bf.test(o));
    }
  }

  public void testCopy() {
    BloomFilter<String> original = BloomFilter.create(Funnels.unencodedCharsFunnel(), 100);
    BloomFilter<String> copy = original.copy();
    assertNotSame(original, copy);
    assertEquals(original, copy);
  }

  public void testExpectedFpp() {
    BloomFilter<Object> bf = BloomFilter.create(HashTestUtils.BAD_FUNNEL, 10, 0.03);
    double fpp = bf.expectedFpp();
    assertThat(fpp).isEqualTo(0.0);
    // usually completed in less than 200 iterations
    while (fpp != 1.0) {
      boolean changed = bf.put(new Object());
      double newFpp = bf.expectedFpp();
      // if changed, the new fpp is strictly higher, otherwise it is the same
      assertTrue(changed ? newFpp > fpp : newFpp == fpp);
      fpp = newFpp;
    }
  }


Standardize annotations on `serialVersionUID` fields.

<|original_code|>
/*
 * Written by Doug Lea with assistance from members of JCP JSR-166
 * Expert Group and released to the public domain, as explained at
 * http://creativecommons.org/publicdomain/zero/1.0/
 */

/*
 * Source:
 * http://gee.cs.oswego.edu/cgi-bin/viewcvs.cgi/jsr166/src/jsr166e/LongAdder.java?revision=1.17
 */

package com.google.common.hash;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.concurrent.atomic.AtomicLong;

/**
 * One or more variables that together maintain an initially zero {@code long} sum. When updates
 * (method {@link #add}) are contended across threads, the set of variables may grow dynamically to
 * reduce contention. Method {@link #sum} (or, equivalently, {@link #longValue}) returns the current
 * total combined across the variables maintaining the sum.
 *
 *
This class is usually preferable to {@link AtomicLong} when multiple threads update a common
 * sum that is used for purposes such as collecting statistics, not for fine-grained synchronization
 * control. Under low update contention, the two classes have similar characteristics. But under
 * high contention, expected throughput of this class is significantly higher, at the expense of
 * higher space consumption.
 *
 *
This class extends {@link Number}, but does not define methods such as {@code
 * equals}, {@code hashCode} and {@code compareTo} because instances are expected to be mutated, and
 * so are not useful as collection keys.
 *
 *
jsr166e note: This class is targeted to be placed in java.util.concurrent.atomic.
 *
 * @since 1.8
 * @author Doug Lea
 */
final class LongAdder extends Striped64 implements Serializable, LongAddable {
  private static final long serialVersionUID = 7249069246863182397L;

  /** Version of plus for use in retryUpdate */
  @Override
  final long fn(long v, long x) {
    return v + x;
  }

  /** Creates a new adder with initial sum of zero. */
  public LongAdder() {}

  /**
   * Adds the given value.
   *
   * @param x the value to add
   */
  @Override
  public void add(long x) {
    Cell[] as;
    long b, v;
    int[] hc;
    Cell a;
    int n;
    if ((as = cells) != null || !casBase(b = base, b + x)) {
<|edits_diff|>
--- android/guava/src/com/google/common/hash/LongAdder.java
+++ android/guava/src/com/google/common/hash/LongAdder.java
@@ -11,6 +11,8 @@

 package com.google.common.hash;

+import com.google.common.annotations.GwtIncompatible;
+import com.google.common.annotations.J2ktIncompatible;
 import java.io.IOException;
 import java.io.ObjectInputStream;
 import java.io.ObjectOutputStream;
<|current_version|>
/*
 * Written by Doug Lea with assistance from members of JCP JSR-166
 * Expert Group and released to the public domain, as explained at
 * http://creativecommons.org/publicdomain/zero/1.0/
 */

/*
 * Source:
 * http://gee.cs.oswego.edu/cgi-bin/viewcvs.cgi/jsr166/src/jsr166e/LongAdder.java?revision=1.17
 */

package com.google.common.hash;

import com.google.common.annotations.GwtIncompatible;
import com.google.common.annotations.J2ktIncompatible;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.concurrent.atomic.AtomicLong;

/**
 * One or more variables that together maintain an initially zero {@code long} sum. When updates
 * (method {@link #add}) are contended across threads, the set of variables may grow dynamically to
 * reduce contention. Method {@link #sum} (or, equivalently, {@link #longValue}) returns the current
 * total combined across the variables maintaining the sum.
 *
 *
This class is usually preferable to {@link AtomicLong} when multiple threads update a common
 * sum that is used for purposes such as collecting statistics, not for fine-grained synchronization
 * control. Under low update contention, the two classes have similar characteristics. But under
 * high contention, expected throughput of this class is significantly higher, at the expense of
 * higher space consumption.
 *
 *
This class extends {@link Number}, but does not define methods such as {@code
 * equals}, {@code hashCode} and {@code compareTo} because instances are expected to be mutated, and
 * so are not useful as collection keys.
 *
 *
jsr166e note: This class is targeted to be placed in java.util.concurrent.atomic.
 *
 * @since 1.8
 * @author Doug Lea
 */
final class LongAdder extends Striped64 implements Serializable, LongAddable {
  private static final long serialVersionUID = 7249069246863182397L;

  /** Version of plus for use in retryUpdate */
  @Override
  final long fn(long v, long x) {
    return v + x;
  }

  /** Creates a new adder with initial sum of zero. */
  public LongAdder() {}

  /**
   * Adds the given value.
   *
   * @param x the value to add
   */
  @Override
  public void add(long x) {
    Cell[] as;
    long b, v;
    int[] hc;
    Cell a;
    int n;
    if ((as = cells) != null || !casBase(b = base, b + x)) {
<|next_version|>
/*
 * Written by Doug Lea with assistance from members of JCP JSR-166
 * Expert Group and released to the public domain, as explained at
 * http://creativecommons.org/publicdomain/zero/1.0/
 */

/*
 * Source:
 * http://gee.cs.oswego.edu/cgi-bin/viewcvs.cgi/jsr166/src/jsr166e/LongAdder.java?revision=1.17
 */

package com.google.common.hash;

import com.google.common.annotations.GwtIncompatible;
import com.google.common.annotations.J2ktIncompatible;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.concurrent.atomic.AtomicLong;

/**
 * One or more variables that together maintain an initially zero {@code long} sum. When updates
 * (method {@link #add}) are contended across threads, the set of variables may grow dynamically to
 * reduce contention. Method {@link #sum} (or, equivalently, {@link #longValue}) returns the current
 * total combined across the variables maintaining the sum.
 *
 *
This class is usually preferable to {@link AtomicLong} when multiple threads update a common
 * sum that is used for purposes such as collecting statistics, not for fine-grained synchronization
 * control. Under low update contention, the two classes have similar characteristics. But under
 * high contention, expected throughput of this class is significantly higher, at the expense of
 * higher space consumption.
 *
 *
This class extends {@link Number}, but does not define methods such as {@code
 * equals}, {@code hashCode} and {@code compareTo} because instances are expected to be mutated, and
 * so are not useful as collection keys.
 *
 *
jsr166e note: This class is targeted to be placed in java.util.concurrent.atomic.
 *
 * @since 1.8
 * @author Doug Lea
 */
final class LongAdder extends Striped64 implements Serializable, LongAddable {
  @GwtIncompatible @J2ktIncompatible
  private static final long serialVersionUID = 7249069246863182397L;

  /** Version of plus for use in retryUpdate */
  @Override
  final long fn(long v, long x) {
    return v + x;
  }

  /** Creates a new adder with initial sum of zero. */
  public LongAdder() {}

  /**
   * Adds the given value.
   *
   * @param x the value to add
   */
  @Override
  public void add(long x) {
    Cell[] as;
    long b, v;
    int[] hc;
    Cell a;
    int n;
    if ((as = cells) != null || !casBase(b = base, b + x)) {


Add `@CanIgnoreReturnValue`, or suppress where we shouldn't.

<|original_code|>
/*
 * Copyright (C) 2011 The Guava Authors
 *
 * 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 com.google.common.collect;

import com.google.caliper.Benchmark;
import org.jspecify.annotations.NullUnmarked;

/**
 * Benchmarking interners.
 *
 * @author Dimitris Andreou
 */
@NullUnmarked
public class InternersBenchmark {
  @Benchmark
  int weakInterner(int reps) {
    Interner<String> interner = Interners.newWeakInterner();
    for (int i = 0; i < reps; i++) {
      String unused = interner.intern(Double.toHexString(Math.random()));
    }
    return reps;
  }

  @Benchmark
  int strongInterner(int reps) {
    Interner<String> interner = Interners.newStrongInterner();
    for (int i = 0; i < reps; i++) {
      String unused = interner.intern(Double.toHexString(Math.random()));
    }
    return reps;
  }

  @Benchmark
  int stringIntern(int reps) {
    for (int i = 0; i < reps; i++) {
      String unused = Double.toHexString(Math.random()).intern();
    }
    return reps;
  }
}

<|edits_diff|>
--- android/guava-tests/benchmark/com/google/common/collect/InternersBenchmark.java
+++ android/guava-tests/benchmark/com/google/common/collect/InternersBenchmark.java
@@ -17,6 +17,7 @@
 package com.google.common.collect;

 import com.google.caliper.Benchmark;
+import com.google.errorprone.annotations.CanIgnoreReturnValue;
 import org.jspecify.annotations.NullUnmarked;

 /**
@@ -26,6 +27,7 @@
  */
 @NullUnmarked
 public class InternersBenchmark {
+  @CanIgnoreReturnValue
   @Benchmark
   int weakInterner(int reps) {
     Interner<String> interner = Interners.newWeakInterner();
@@ -35,6 +37,7 @@
     return reps;
   }

+  @CanIgnoreReturnValue
   @Benchmark
   int strongInterner(int reps) {
     Interner<String> interner = Interners.newStrongInterner();
<|current_version|>
/*
 * Copyright (C) 2011 The Guava Authors
 *
 * 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 com.google.common.collect;

import com.google.caliper.Benchmark;
import com.google.errorprone.annotations.CanIgnoreReturnValue;
import org.jspecify.annotations.NullUnmarked;

/**
 * Benchmarking interners.
 *
 * @author Dimitris Andreou
 */
@NullUnmarked
public class InternersBenchmark {
  @CanIgnoreReturnValue
  @Benchmark
  int weakInterner(int reps) {
    Interner<String> interner = Interners.newWeakInterner();
    for (int i = 0; i < reps; i++) {
      String unused = interner.intern(Double.toHexString(Math.random()));
    }
    return reps;
  }

  @CanIgnoreReturnValue
  @Benchmark
  int strongInterner(int reps) {
    Interner<String> interner = Interners.newStrongInterner();
    for (int i = 0; i < reps; i++) {
      String unused = interner.intern(Double.toHexString(Math.random()));
    }
    return reps;
  }

  @Benchmark
  int stringIntern(int reps) {
    for (int i = 0; i < reps; i++) {
      String unused = Double.toHexString(Math.random()).intern();
    }
    return reps;
  }
}

<|next_version|>
/*
 * Copyright (C) 2011 The Guava Authors
 *
 * 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 com.google.common.collect;

import com.google.caliper.Benchmark;
import com.google.errorprone.annotations.CanIgnoreReturnValue;
import org.jspecify.annotations.NullUnmarked;

/**
 * Benchmarking interners.
 *
 * @author Dimitris Andreou
 */
@NullUnmarked
public class InternersBenchmark {
  @CanIgnoreReturnValue
  @Benchmark
  int weakInterner(int reps) {
    Interner<String> interner = Interners.newWeakInterner();
    for (int i = 0; i < reps; i++) {
      String unused = interner.intern(Double.toHexString(Math.random()));
    }
    return reps;
  }

  @CanIgnoreReturnValue
  @Benchmark
  int strongInterner(int reps) {
    Interner<String> interner = Interners.newStrongInterner();
    for (int i = 0; i < reps; i++) {
      String unused = interner.intern(Double.toHexString(Math.random()));
    }
    return reps;
  }

  @CanIgnoreReturnValue
  @Benchmark
  int stringIntern(int reps) {
    for (int i = 0; i < reps; i++) {
      String unused = Double.toHexString(Math.random()).intern();
    }
    return reps;
  }
}


Apply or suppress suggestions to use `@InlineMe`.

<|original_code|>
 * 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 com.google.common.graph;

import static com.google.common.base.Preconditions.checkNotNull;
import static java.util.Objects.requireNonNull;

import com.google.common.annotations.Beta;
import com.google.common.base.Function;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Maps;
import com.google.errorprone.annotations.CanIgnoreReturnValue;
import com.google.errorprone.annotations.Immutable;

/**
 * A {@link ValueGraph} whose elements and structural relationships will never change. Instances of
 * this class may be obtained with {@link #copyOf(ValueGraph)}.
 *
 *
See the Guava User's Guide's discussion
 * of the {@code Immutable*} types for more information on the properties and guarantees
 * provided by this class.
 *
 * @author James Sexton
 * @author Jens Nyman
 * @param <N> Node parameter type
 * @param <V> Value parameter type
 * @since 20.0
 */
@Beta
@Immutable(containerOf = {"N", "V"})
@SuppressWarnings("Immutable") // Extends StandardValueGraph but uses ImmutableMaps.
public final class ImmutableValueGraph<N, V> extends StandardValueGraph<N, V> {

  private ImmutableValueGraph(ValueGraph<N, V> graph) {
    super(ValueGraphBuilder.from(graph), getNodeConnections(graph), graph.edges().size());
  }

  /** Returns an immutable copy of {@code graph}. */
  public static <N, V> ImmutableValueGraph<N, V> copyOf(ValueGraph<N, V> graph) {
    return (graph instanceof ImmutableValueGraph)
        ? (ImmutableValueGraph<N, V>) graph
        : new ImmutableValueGraph<N, V>(graph);
  }

  /**
   * Simply returns its argument.
   *
   * @deprecated no need to use this
   */
  @Deprecated
  public static <N, V> ImmutableValueGraph<N, V> copyOf(ImmutableValueGraph<N, V> graph) {
    return checkNotNull(graph);
  }

  @Override
  public ElementOrder<N> incidentEdgeOrder() {
    return ElementOrder.stable();
  }

  @Override
  public ImmutableGraph<N> asGraph() {
    return new ImmutableGraph<>(this); // safe because the view is effectively immutable
  }

  private static <N, V> ImmutableMap<N, GraphConnections<N, V>> getNodeConnections(
      ValueGraph<N, V> graph) {
    // ImmutableMap.Builder maintains the order of the elements as inserted, so the map will have
    // whatever ordering the graph's nodes do, so ImmutableSortedMap is unnecessary even if the
    // input nodes are sorted.
    ImmutableMap.Builder<N, GraphConnections<N, V>> nodeConnections = ImmutableMap.builder();
    for (N node : graph.nodes()) {
      nodeConnections.put(node, connectionsOf(graph, node));
    }
<|edits_diff|>
--- guava/src/com/google/common/graph/ImmutableValueGraph.java
+++ guava/src/com/google/common/graph/ImmutableValueGraph.java
@@ -20,6 +20,7 @@
 import com.google.common.collect.Maps;
 import com.google.errorprone.annotations.CanIgnoreReturnValue;
 import com.google.errorprone.annotations.Immutable;
+import com.google.errorprone.annotations.InlineMe;

 /**
  * A {@link ValueGraph} whose elements and structural relationships will never change. Instances of
<|current_version|>
 * 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 com.google.common.graph;

import static com.google.common.base.Preconditions.checkNotNull;
import static java.util.Objects.requireNonNull;

import com.google.common.annotations.Beta;
import com.google.common.base.Function;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Maps;
import com.google.errorprone.annotations.CanIgnoreReturnValue;
import com.google.errorprone.annotations.Immutable;
import com.google.errorprone.annotations.InlineMe;

/**
 * A {@link ValueGraph} whose elements and structural relationships will never change. Instances of
 * this class may be obtained with {@link #copyOf(ValueGraph)}.
 *
 *
See the Guava User's Guide's discussion
 * of the {@code Immutable*} types for more information on the properties and guarantees
 * provided by this class.
 *
 * @author James Sexton
 * @author Jens Nyman
 * @param <N> Node parameter type
 * @param <V> Value parameter type
 * @since 20.0
 */
@Beta
@Immutable(containerOf = {"N", "V"})
@SuppressWarnings("Immutable") // Extends StandardValueGraph but uses ImmutableMaps.
public final class ImmutableValueGraph<N, V> extends StandardValueGraph<N, V> {

  private ImmutableValueGraph(ValueGraph<N, V> graph) {
    super(ValueGraphBuilder.from(graph), getNodeConnections(graph), graph.edges().size());
  }

  /** Returns an immutable copy of {@code graph}. */
  public static <N, V> ImmutableValueGraph<N, V> copyOf(ValueGraph<N, V> graph) {
    return (graph instanceof ImmutableValueGraph)
        ? (ImmutableValueGraph<N, V>) graph
        : new ImmutableValueGraph<N, V>(graph);
  }

  /**
   * Simply returns its argument.
   *
   * @deprecated no need to use this
   */
  @Deprecated
  public static <N, V> ImmutableValueGraph<N, V> copyOf(ImmutableValueGraph<N, V> graph) {
    return checkNotNull(graph);
  }

  @Override
  public ElementOrder<N> incidentEdgeOrder() {
    return ElementOrder.stable();
  }

  @Override
  public ImmutableGraph<N> asGraph() {
    return new ImmutableGraph<>(this); // safe because the view is effectively immutable
  }

  private static <N, V> ImmutableMap<N, GraphConnections<N, V>> getNodeConnections(
      ValueGraph<N, V> graph) {
    // ImmutableMap.Builder maintains the order of the elements as inserted, so the map will have
    // whatever ordering the graph's nodes do, so ImmutableSortedMap is unnecessary even if the
    // input nodes are sorted.
    ImmutableMap.Builder<N, GraphConnections<N, V>> nodeConnections = ImmutableMap.builder();
    for (N node : graph.nodes()) {
      nodeConnections.put(node, connectionsOf(graph, node));
    }
<|next_version|>
 * 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 com.google.common.graph;

import static com.google.common.base.Preconditions.checkNotNull;
import static java.util.Objects.requireNonNull;

import com.google.common.annotations.Beta;
import com.google.common.base.Function;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Maps;
import com.google.errorprone.annotations.CanIgnoreReturnValue;
import com.google.errorprone.annotations.Immutable;
import com.google.errorprone.annotations.InlineMe;

/**
 * A {@link ValueGraph} whose elements and structural relationships will never change. Instances of
 * this class may be obtained with {@link #copyOf(ValueGraph)}.
 *
 *
See the Guava User's Guide's discussion
 * of the {@code Immutable*} types for more information on the properties and guarantees
 * provided by this class.
 *
 * @author James Sexton
 * @author Jens Nyman
 * @param <N> Node parameter type
 * @param <V> Value parameter type
 * @since 20.0
 */
@Beta
@Immutable(containerOf = {"N", "V"})
@SuppressWarnings("Immutable") // Extends StandardValueGraph but uses ImmutableMaps.
public final class ImmutableValueGraph<N, V> extends StandardValueGraph<N, V> {

  private ImmutableValueGraph(ValueGraph<N, V> graph) {
    super(ValueGraphBuilder.from(graph), getNodeConnections(graph), graph.edges().size());
  }

  /** Returns an immutable copy of {@code graph}. */
  public static <N, V> ImmutableValueGraph<N, V> copyOf(ValueGraph<N, V> graph) {
    return (graph instanceof ImmutableValueGraph)
        ? (ImmutableValueGraph<N, V>) graph
        : new ImmutableValueGraph<N, V>(graph);
  }

  /**
   * Simply returns its argument.
   *
   * @deprecated no need to use this
   */
  @InlineMe(
      replacement = "checkNotNull(graph)",
      staticImports = "com.google.common.base.Preconditions.checkNotNull")
  @Deprecated
  public static <N, V> ImmutableValueGraph<N, V> copyOf(ImmutableValueGraph<N, V> graph) {
    return checkNotNull(graph);
  }

  @Override
  public ElementOrder<N> incidentEdgeOrder() {
    return ElementOrder.stable();
  }

  @Override
  public ImmutableGraph<N> asGraph() {
    return new ImmutableGraph<>(this); // safe because the view is effectively immutable
  }

  private static <N, V> ImmutableMap<N, GraphConnections<N, V>> getNodeConnections(
      ValueGraph<N, V> graph) {
    // ImmutableMap.Builder maintains the order of the elements as inserted, so the map will have
    // whatever ordering the graph's nodes do, so ImmutableSortedMap is unnecessary even if the
    // input nodes are sorted.
    ImmutableMap.Builder<N, GraphConnections<N, V>> nodeConnections = ImmutableMap.builder();
    for (N node : graph.nodes()) {
      nodeConnections.put(node, connectionsOf(graph, node));
    }


Avoid calling methods whose return type changed in Java 9 -- even from tests.

<|original_code|>
import com.google.common.annotations.GwtIncompatible;
import java.nio.Buffer;

/**
 * Wrappers around {@link Buffer} methods that are covariantly overridden in Java 9+. See
 * https://github.com/google/guava/issues/3990
 */
@GwtIncompatible
@ElementTypesAreNonnullByDefault
final class Java8Compatibility {
  static void clear(Buffer b) {
    b.clear();
  }

  static void flip(Buffer b) {
    b.flip();
  }

  static void limit(Buffer b, int limit) {
    b.limit(limit);
  }

  static void position(Buffer b, int position) {
    b.position(position);
  }

  private Java8Compatibility() {}
}

<|edits_diff|>
--- guava/src/com/google/common/io/Java8Compatibility.java
+++ guava/src/com/google/common/io/Java8Compatibility.java
@@ -20,6 +20,10 @@
     b.limit(limit);
   }

+  static void mark(Buffer b) {
+    b.mark();
+  }
+
   static void position(Buffer b, int position) {
     b.position(position);
   }
<|current_version|>
import com.google.common.annotations.GwtIncompatible;
import java.nio.Buffer;

/**
 * Wrappers around {@link Buffer} methods that are covariantly overridden in Java 9+. See
 * https://github.com/google/guava/issues/3990
 */
@GwtIncompatible
@ElementTypesAreNonnullByDefault
final class Java8Compatibility {
  static void clear(Buffer b) {
    b.clear();
  }

  static void flip(Buffer b) {
    b.flip();
  }

  static void limit(Buffer b, int limit) {
    b.limit(limit);
  }

  static void mark(Buffer b) {
    b.mark();
  }

  static void position(Buffer b, int position) {
    b.position(position);
  }

  private Java8Compatibility() {}
}

<|next_version|>
import com.google.common.annotations.GwtIncompatible;
import java.nio.Buffer;

/**
 * Wrappers around {@link Buffer} methods that are covariantly overridden in Java 9+. See
 * https://github.com/google/guava/issues/3990
 */
@GwtIncompatible
@ElementTypesAreNonnullByDefault
final class Java8Compatibility {
  static void clear(Buffer b) {
    b.clear();
  }

  static void flip(Buffer b) {
    b.flip();
  }

  static void limit(Buffer b, int limit) {
    b.limit(limit);
  }

  static void mark(Buffer b) {
    b.mark();
  }

  static void position(Buffer b, int position) {
    b.position(position);
  }

  static void reset(Buffer b) {
    b.reset();
  }

  private Java8Compatibility() {}
}


Copy the `setUp` and `tearDown` from the parent builder to derived test suites.

<|original_code|>
        MapSizeTester.class,
        MapToStringTester.class);
  }

  @Override
  protected List<TestSuite> createDerivedSuites(
      FeatureSpecificTestSuiteBuilder<
              ?, ? extends OneSizeTestContainerGenerator<Map<K, V>, Entry<K, V>>>
          parentBuilder) {
    // TODO: Once invariant support is added, supply invariants to each of the
    // derived suites, to check that mutations to the derived collections are
    // reflected in the underlying map.

    List<TestSuite> derivedSuites = super.createDerivedSuites(parentBuilder);

    if (parentBuilder.getFeatures().contains(CollectionFeature.SERIALIZABLE)) {
      derivedSuites.add(
          MapTestSuiteBuilder.using(
                  new ReserializedMapGenerator<K, V>(parentBuilder.getSubjectGenerator()))
              .withFeatures(computeReserializedMapFeatures(parentBuilder.getFeatures()))
              .named(parentBuilder.getName() + " reserialized")
              .suppressing(parentBuilder.getSuppressedTests())
              .createTestSuite());
    }

    derivedSuites.add(
        createDerivedEntrySetSuite(
                new MapEntrySetGenerator<K, V>(parentBuilder.getSubjectGenerator()))
            .withFeatures(computeEntrySetFeatures(parentBuilder.getFeatures()))
            .named(parentBuilder.getName() + " entrySet")
            .suppressing(parentBuilder.getSuppressedTests())
            .createTestSuite());

    derivedSuites.add(
        createDerivedKeySetSuite(keySetGenerator(parentBuilder.getSubjectGenerator()))
            .withFeatures(computeKeySetFeatures(parentBuilder.getFeatures()))
            .named(parentBuilder.getName() + " keys")
            .suppressing(parentBuilder.getSuppressedTests())
            .createTestSuite());

    derivedSuites.add(
        createDerivedValueCollectionSuite(
                new MapValueCollectionGenerator<K, V>(parentBuilder.getSubjectGenerator()))
            .named(parentBuilder.getName() + " values")
            .withFeatures(computeValuesCollectionFeatures(parentBuilder.getFeatures()))
            .suppressing(parentBuilder.getSuppressedTests())
            .createTestSuite());

    return derivedSuites;
  }

  protected SetTestSuiteBuilder<Entry<K, V>> createDerivedEntrySetSuite(
      TestSetGenerator<Entry<K, V>> entrySetGenerator) {
    return SetTestSuiteBuilder.using(entrySetGenerator);
  }

  protected SetTestSuiteBuilder<K> createDerivedKeySetSuite(TestSetGenerator<K> keySetGenerator) {
    return SetTestSuiteBuilder.using(keySetGenerator);
  }

  protected CollectionTestSuiteBuilder<V> createDerivedValueCollectionSuite(
      TestCollectionGenerator<V> valueCollectionGenerator) {
    return CollectionTestSuiteBuilder.using(valueCollectionGenerator);
  }

  private static Set<Feature<?>> computeReserializedMapFeatures(Set<Feature<?>> mapFeatures) {
    Set<Feature<?>> derivedFeatures = Helpers.copyToSet(mapFeatures);
    derivedFeatures.remove(CollectionFeature.SERIALIZABLE);
    derivedFeatures.remove(CollectionFeature.SERIALIZABLE_INCLUDING_VIEWS);
    return derivedFeatures;
<|edits_diff|>
--- android/guava-testlib/src/com/google/common/collect/testing/MapTestSuiteBuilder.java
+++ android/guava-testlib/src/com/google/common/collect/testing/MapTestSuiteBuilder.java
@@ -20,6 +20,8 @@
               .withFeatures(computeReserializedMapFeatures(parentBuilder.getFeatures()))
               .named(parentBuilder.getName() + " reserialized")
               .suppressing(parentBuilder.getSuppressedTests())
+              .withSetUp(parentBuilder.getSetUp())
+              .withTearDown(parentBuilder.getTearDown())
               .createTestSuite());
     }

@@ -29,6 +31,8 @@
             .withFeatures(computeEntrySetFeatures(parentBuilder.getFeatures()))
             .named(parentBuilder.getName() + " entrySet")
             .suppressing(parentBuilder.getSuppressedTests())
+            .withSetUp(parentBuilder.getSetUp())
+            .withTearDown(parentBuilder.getTearDown())
             .createTestSuite());

     derivedSuites.add(
@@ -36,6 +40,8 @@
             .withFeatures(computeKeySetFeatures(parentBuilder.getFeatures()))
             .named(parentBuilder.getName() + " keys")
             .suppressing(parentBuilder.getSuppressedTests())
+            .withSetUp(parentBuilder.getSetUp())
+            .withTearDown(parentBuilder.getTearDown())
             .createTestSuite());

     derivedSuites.add(
<|current_version|>
        MapSizeTester.class,
        MapToStringTester.class);
  }

  @Override
  protected List<TestSuite> createDerivedSuites(
      FeatureSpecificTestSuiteBuilder<
              ?, ? extends OneSizeTestContainerGenerator<Map<K, V>, Entry<K, V>>>
          parentBuilder) {
    // TODO: Once invariant support is added, supply invariants to each of the
    // derived suites, to check that mutations to the derived collections are
    // reflected in the underlying map.

    List<TestSuite> derivedSuites = super.createDerivedSuites(parentBuilder);

    if (parentBuilder.getFeatures().contains(CollectionFeature.SERIALIZABLE)) {
      derivedSuites.add(
          MapTestSuiteBuilder.using(
                  new ReserializedMapGenerator<K, V>(parentBuilder.getSubjectGenerator()))
              .withFeatures(computeReserializedMapFeatures(parentBuilder.getFeatures()))
              .named(parentBuilder.getName() + " reserialized")
              .suppressing(parentBuilder.getSuppressedTests())
              .withSetUp(parentBuilder.getSetUp())
              .withTearDown(parentBuilder.getTearDown())
              .createTestSuite());
    }

    derivedSuites.add(
        createDerivedEntrySetSuite(
                new MapEntrySetGenerator<K, V>(parentBuilder.getSubjectGenerator()))
            .withFeatures(computeEntrySetFeatures(parentBuilder.getFeatures()))
            .named(parentBuilder.getName() + " entrySet")
            .suppressing(parentBuilder.getSuppressedTests())
            .withSetUp(parentBuilder.getSetUp())
            .withTearDown(parentBuilder.getTearDown())
            .createTestSuite());

    derivedSuites.add(
        createDerivedKeySetSuite(keySetGenerator(parentBuilder.getSubjectGenerator()))
            .withFeatures(computeKeySetFeatures(parentBuilder.getFeatures()))
            .named(parentBuilder.getName() + " keys")
            .suppressing(parentBuilder.getSuppressedTests())
            .withSetUp(parentBuilder.getSetUp())
            .withTearDown(parentBuilder.getTearDown())
            .createTestSuite());

    derivedSuites.add(
        createDerivedValueCollectionSuite(
                new MapValueCollectionGenerator<K, V>(parentBuilder.getSubjectGenerator()))
            .named(parentBuilder.getName() + " values")
            .withFeatures(computeValuesCollectionFeatures(parentBuilder.getFeatures()))
            .suppressing(parentBuilder.getSuppressedTests())
            .createTestSuite());

    return derivedSuites;
  }

  protected SetTestSuiteBuilder<Entry<K, V>> createDerivedEntrySetSuite(
      TestSetGenerator<Entry<K, V>> entrySetGenerator) {
    return SetTestSuiteBuilder.using(entrySetGenerator);
  }

  protected SetTestSuiteBuilder<K> createDerivedKeySetSuite(TestSetGenerator<K> keySetGenerator) {
    return SetTestSuiteBuilder.using(keySetGenerator);
  }

  protected CollectionTestSuiteBuilder<V> createDerivedValueCollectionSuite(
      TestCollectionGenerator<V> valueCollectionGenerator) {
    return CollectionTestSuiteBuilder.using(valueCollectionGenerator);
  }

  private static Set<Feature<?>> computeReserializedMapFeatures(Set<Feature<?>> mapFeatures) {
    Set<Feature<?>> derivedFeatures = Helpers.copyToSet(mapFeatures);
    derivedFeatures.remove(CollectionFeature.SERIALIZABLE);
    derivedFeatures.remove(CollectionFeature.SERIALIZABLE_INCLUDING_VIEWS);
    return derivedFeatures;
<|next_version|>
        MapSizeTester.class,
        MapToStringTester.class);
  }

  @Override
  protected List<TestSuite> createDerivedSuites(
      FeatureSpecificTestSuiteBuilder<
              ?, ? extends OneSizeTestContainerGenerator<Map<K, V>, Entry<K, V>>>
          parentBuilder) {
    // TODO: Once invariant support is added, supply invariants to each of the
    // derived suites, to check that mutations to the derived collections are
    // reflected in the underlying map.

    List<TestSuite> derivedSuites = super.createDerivedSuites(parentBuilder);

    if (parentBuilder.getFeatures().contains(CollectionFeature.SERIALIZABLE)) {
      derivedSuites.add(
          MapTestSuiteBuilder.using(
                  new ReserializedMapGenerator<K, V>(parentBuilder.getSubjectGenerator()))
              .withFeatures(computeReserializedMapFeatures(parentBuilder.getFeatures()))
              .named(parentBuilder.getName() + " reserialized")
              .suppressing(parentBuilder.getSuppressedTests())
              .withSetUp(parentBuilder.getSetUp())
              .withTearDown(parentBuilder.getTearDown())
              .createTestSuite());
    }

    derivedSuites.add(
        createDerivedEntrySetSuite(
                new MapEntrySetGenerator<K, V>(parentBuilder.getSubjectGenerator()))
            .withFeatures(computeEntrySetFeatures(parentBuilder.getFeatures()))
            .named(parentBuilder.getName() + " entrySet")
            .suppressing(parentBuilder.getSuppressedTests())
            .withSetUp(parentBuilder.getSetUp())
            .withTearDown(parentBuilder.getTearDown())
            .createTestSuite());

    derivedSuites.add(
        createDerivedKeySetSuite(keySetGenerator(parentBuilder.getSubjectGenerator()))
            .withFeatures(computeKeySetFeatures(parentBuilder.getFeatures()))
            .named(parentBuilder.getName() + " keys")
            .suppressing(parentBuilder.getSuppressedTests())
            .withSetUp(parentBuilder.getSetUp())
            .withTearDown(parentBuilder.getTearDown())
            .createTestSuite());

    derivedSuites.add(
        createDerivedValueCollectionSuite(
                new MapValueCollectionGenerator<K, V>(parentBuilder.getSubjectGenerator()))
            .named(parentBuilder.getName() + " values")
            .withFeatures(computeValuesCollectionFeatures(parentBuilder.getFeatures()))
            .suppressing(parentBuilder.getSuppressedTests())
            .withSetUp(parentBuilder.getSetUp())
            .withTearDown(parentBuilder.getTearDown())
            .createTestSuite());

    return derivedSuites;
  }

  protected SetTestSuiteBuilder<Entry<K, V>> createDerivedEntrySetSuite(
      TestSetGenerator<Entry<K, V>> entrySetGenerator) {
    return SetTestSuiteBuilder.using(entrySetGenerator);
  }

  protected SetTestSuiteBuilder<K> createDerivedKeySetSuite(TestSetGenerator<K> keySetGenerator) {
    return SetTestSuiteBuilder.using(keySetGenerator);
  }

  protected CollectionTestSuiteBuilder<V> createDerivedValueCollectionSuite(
      TestCollectionGenerator<V> valueCollectionGenerator) {
    return CollectionTestSuiteBuilder.using(valueCollectionGenerator);
  }

  private static Set<Feature<?>> computeReserializedMapFeatures(Set<Feature<?>> mapFeatures) {
    Set<Feature<?>> derivedFeatures = Helpers.copyToSet(mapFeatures);
    derivedFeatures.remove(CollectionFeature.SERIALIZABLE);
    derivedFeatures.remove(CollectionFeature.SERIALIZABLE_INCLUDING_VIEWS);
    return derivedFeatures;


Use ConcurrentHashMap.newKeySet() in Sets.newConcurrentHashSet()

<|original_code|>
 * Copyright (C) 2008 The Guava Authors
 *
 * 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 com.google.common.collect;

import com.google.common.annotations.GwtCompatible;
import java.lang.reflect.Array;
import java.util.Arrays;
import java.util.Map;
import java.util.Set;

/**
 * Methods factored out so that they can be emulated differently in GWT.
 *
 * @author Hayward Chan
 */
@GwtCompatible(emulated = true)
final class Platform {
  private static final java.util.logging.Logger logger =
      java.util.logging.Logger.getLogger(Platform.class.getName());

  /** Returns the platform preferred implementation of a map based on a hash table. */
  static <K, V> Map<K, V> newHashMapWithExpectedSize(int expectedSize) {
    return Maps.newHashMapWithExpectedSize(expectedSize);
  }

  /**
   * Returns the platform preferred implementation of an insertion ordered map based on a hash
   * table.
   */
  static <K, V> Map<K, V> newLinkedHashMapWithExpectedSize(int expectedSize) {
    return Maps.newLinkedHashMapWithExpectedSize(expectedSize);
  }

  /** Returns the platform preferred implementation of a set based on a hash table. */
  static <E> Set<E> newHashSetWithExpectedSize(int expectedSize) {
    return Sets.newHashSetWithExpectedSize(expectedSize);
  }

  /**
   * Returns the platform preferred implementation of an insertion ordered set based on a hash
   * table.
   */
  static <E> Set<E> newLinkedHashSetWithExpectedSize(int expectedSize) {
    return Sets.newLinkedHashSetWithExpectedSize(expectedSize);
  }

  /**
   * Returns the platform preferred map implementation that preserves insertion order when used only
   * for insertions.
   */
  static <K, V> Map<K, V> preservesInsertionOrderOnPutsMap() {
    return Maps.newLinkedHashMap();
  }

  /**
   * Returns the platform preferred set implementation that preserves insertion order when used only
   * for insertions.
   */
  static <E> Set<E> preservesInsertionOrderOnAddsSet() {
    return Sets.newLinkedHashSet();
<|edits_diff|>
--- guava/src/com/google/common/collect/Platform.java
+++ guava/src/com/google/common/collect/Platform.java
@@ -20,6 +20,7 @@
 import java.util.Arrays;
 import java.util.Map;
 import java.util.Set;
+import java.util.concurrent.ConcurrentHashMap;

 /**
  * Methods factored out so that they can be emulated differently in GWT.
<|current_version|>
 * Copyright (C) 2008 The Guava Authors
 *
 * 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 com.google.common.collect;

import com.google.common.annotations.GwtCompatible;
import java.lang.reflect.Array;
import java.util.Arrays;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;

/**
 * Methods factored out so that they can be emulated differently in GWT.
 *
 * @author Hayward Chan
 */
@GwtCompatible(emulated = true)
final class Platform {
  private static final java.util.logging.Logger logger =
      java.util.logging.Logger.getLogger(Platform.class.getName());

  /** Returns the platform preferred implementation of a map based on a hash table. */
  static <K, V> Map<K, V> newHashMapWithExpectedSize(int expectedSize) {
    return Maps.newHashMapWithExpectedSize(expectedSize);
  }

  /**
   * Returns the platform preferred implementation of an insertion ordered map based on a hash
   * table.
   */
  static <K, V> Map<K, V> newLinkedHashMapWithExpectedSize(int expectedSize) {
    return Maps.newLinkedHashMapWithExpectedSize(expectedSize);
  }

  /** Returns the platform preferred implementation of a set based on a hash table. */
  static <E> Set<E> newHashSetWithExpectedSize(int expectedSize) {
    return Sets.newHashSetWithExpectedSize(expectedSize);
  }

  /**
   * Returns the platform preferred implementation of an insertion ordered set based on a hash
   * table.
   */
  static <E> Set<E> newLinkedHashSetWithExpectedSize(int expectedSize) {
    return Sets.newLinkedHashSetWithExpectedSize(expectedSize);
  }

  /**
   * Returns the platform preferred map implementation that preserves insertion order when used only
   * for insertions.
   */
  static <K, V> Map<K, V> preservesInsertionOrderOnPutsMap() {
    return Maps.newLinkedHashMap();
  }

  /**
   * Returns the platform preferred set implementation that preserves insertion order when used only
   * for insertions.
   */
  static <E> Set<E> preservesInsertionOrderOnAddsSet() {
    return Sets.newLinkedHashSet();
<|next_version|>
 * Copyright (C) 2008 The Guava Authors
 *
 * 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 com.google.common.collect;

import com.google.common.annotations.GwtCompatible;
import java.lang.reflect.Array;
import java.util.Arrays;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;

/**
 * Methods factored out so that they can be emulated differently in GWT.
 *
 * @author Hayward Chan
 */
@GwtCompatible(emulated = true)
final class Platform {
  private static final java.util.logging.Logger logger =
      java.util.logging.Logger.getLogger(Platform.class.getName());

  /** Returns the platform preferred implementation of a map based on a hash table. */
  static <K, V> Map<K, V> newHashMapWithExpectedSize(int expectedSize) {
    return Maps.newHashMapWithExpectedSize(expectedSize);
  }

  /**
   * Returns the platform preferred implementation of an insertion ordered map based on a hash
   * table.
   */
  static <K, V> Map<K, V> newLinkedHashMapWithExpectedSize(int expectedSize) {
    return Maps.newLinkedHashMapWithExpectedSize(expectedSize);
  }

  /** Returns the platform preferred implementation of a set based on a hash table. */
  static <E> Set<E> newHashSetWithExpectedSize(int expectedSize) {
    return Sets.newHashSetWithExpectedSize(expectedSize);
  }

  /** Returns the platform preferred implementation of a thread-safe hash set. */
  static <E> Set<E> newConcurrentHashSet() {
    return ConcurrentHashMap.newKeySet();
  }

  /**
   * Returns the platform preferred implementation of an insertion ordered set based on a hash
   * table.
   */
  static <E> Set<E> newLinkedHashSetWithExpectedSize(int expectedSize) {
    return Sets.newLinkedHashSetWithExpectedSize(expectedSize);
  }

  /**
   * Returns the platform preferred map implementation that preserves insertion order when used only
   * for insertions.
   */
  static <K, V> Map<K, V> preservesInsertionOrderOnPutsMap() {
    return Maps.newLinkedHashMap();
  }

  /**
   * Returns the platform preferred set implementation that preserves insertion order when used only
   * for insertions.
   */
  static <E> Set<E> preservesInsertionOrderOnAddsSet() {
    return Sets.newLinkedHashSet();


Rename 'ConfigurableX' to 'StandardX' for Network, which better captures what these implementations represent.

<|original_code|>
    // Since the reference node is defined to be 'source' for directed graphs,
    // we can assume this edge lives in the set of outgoing edges.
    return checkNotNull(outEdgeMap.get(edge));
  }

  @Override
  public N removeInEdge(E edge, boolean isSelfLoop) {
    if (isSelfLoop) {
      checkNonNegative(--selfLoopCount);
    }
    N previousNode = inEdgeMap.remove(edge);
    return checkNotNull(previousNode);
  }

  @Override
  public N removeOutEdge(E edge) {
    N previousNode = outEdgeMap.remove(edge);
    return checkNotNull(previousNode);
  }

  @Override
  public void addInEdge(E edge, N node, boolean isSelfLoop) {
    if (isSelfLoop) {
      checkPositive(++selfLoopCount);
    }
    N previousNode = inEdgeMap.put(edge, node);
    checkState(previousNode == null);
  }

  @Override
  public void addOutEdge(E edge, N node) {
    N previousNode = outEdgeMap.put(edge, node);
    checkState(previousNode == null);
  }
}

<|edits_diff|>
--- android/guava/src/com/google/common/graph/AbstractDirectedNetworkConnections.java
+++ android/guava/src/com/google/common/graph/AbstractDirectedNetworkConnections.java
@@ -20,6 +20,9 @@

   @Override
   public void addInEdge(E edge, N node, boolean isSelfLoop) {
+    checkNotNull(edge);
+    checkNotNull(node);
+
     if (isSelfLoop) {
       checkPositive(++selfLoopCount);
     }
<|current_version|>
    // Since the reference node is defined to be 'source' for directed graphs,
    // we can assume this edge lives in the set of outgoing edges.
    return checkNotNull(outEdgeMap.get(edge));
  }

  @Override
  public N removeInEdge(E edge, boolean isSelfLoop) {
    if (isSelfLoop) {
      checkNonNegative(--selfLoopCount);
    }
    N previousNode = inEdgeMap.remove(edge);
    return checkNotNull(previousNode);
  }

  @Override
  public N removeOutEdge(E edge) {
    N previousNode = outEdgeMap.remove(edge);
    return checkNotNull(previousNode);
  }

  @Override
  public void addInEdge(E edge, N node, boolean isSelfLoop) {
    checkNotNull(edge);
    checkNotNull(node);

    if (isSelfLoop) {
      checkPositive(++selfLoopCount);
    }
    N previousNode = inEdgeMap.put(edge, node);
    checkState(previousNode == null);
  }

  @Override
  public void addOutEdge(E edge, N node) {
    N previousNode = outEdgeMap.put(edge, node);
    checkState(previousNode == null);
  }
}

<|next_version|>
    // Since the reference node is defined to be 'source' for directed graphs,
    // we can assume this edge lives in the set of outgoing edges.
    return checkNotNull(outEdgeMap.get(edge));
  }

  @Override
  public N removeInEdge(E edge, boolean isSelfLoop) {
    if (isSelfLoop) {
      checkNonNegative(--selfLoopCount);
    }
    N previousNode = inEdgeMap.remove(edge);
    return checkNotNull(previousNode);
  }

  @Override
  public N removeOutEdge(E edge) {
    N previousNode = outEdgeMap.remove(edge);
    return checkNotNull(previousNode);
  }

  @Override
  public void addInEdge(E edge, N node, boolean isSelfLoop) {
    checkNotNull(edge);
    checkNotNull(node);

    if (isSelfLoop) {
      checkPositive(++selfLoopCount);
    }
    N previousNode = inEdgeMap.put(edge, node);
    checkState(previousNode == null);
  }

  @Override
  public void addOutEdge(E edge, N node) {
    checkNotNull(edge);
    checkNotNull(node);

    N previousNode = outEdgeMap.put(edge, node);
    checkState(previousNode == null);
  }
}


Add support for scope IDs to InetAddresses.isInetAddress().

  /**
   * Returns an {@link Inet4Address}, given a byte array representation of the IPv4 address.
   *
   * @param bytes byte array representing an IPv4 address (should be of length 4)
   * @return {@link Inet4Address} corresponding to the supplied byte array
   * @throws IllegalArgumentException if a valid {@link Inet4Address} can not be created
   */
  private static Inet4Address getInet4Address(byte[] bytes) {
    checkArgument(
        bytes.length == 4,
        "Byte array has invalid length for an IPv4 address: %s != 4.",
        bytes.length);

    // Given a 4-byte array, this cast should always succeed.
    return (Inet4Address) bytesToInetAddress(bytes);
  }

  /**
   * Returns the {@link InetAddress} having the given string representation.
   *
   * <p>This deliberately avoids all nameservice lookups (e.g. no DNS).
   *
   * @param ipString {@code String} containing an IPv4 or IPv6 string literal, e.g. {@code
   *     "192.168.0.1"} or {@code "2001:db8::1"}
   * @return {@link InetAddress} representing the argument
   * @throws IllegalArgumentException if the argument is not a valid IP string literal
   */
  public static InetAddress forString(String ipString) {
    byte[] addr = ipStringToBytes(ipString);

    // The argument was malformed, i.e. not an IP string literal.
    if (addr == null) {
      throw formatIllegalArgumentException("'%s' is not an IP string literal.", ipString);
    }

    return bytesToInetAddress(addr);
  }

  /**
   * Returns {@code true} if the supplied string is a valid IP string literal, {@code false}
   * otherwise.
   *
   * @param ipString {@code String} to evaluated as an IP string literal
   * @return {@code true} if the argument is a valid IP string literal
   */
  public static boolean isInetAddress(String ipString) {
    return ipStringToBytes(ipString) != null;
  }

  @NullableDecl
  private static byte[] ipStringToBytes(String ipString) {
    // Make a first pass to categorize the characters in this string.
    boolean hasColon = false;
    boolean hasDot = false;
    for (int i = 0; i < ipString.length(); i++) {
      char c = ipString.charAt(i);
      if (c == '.') {
        hasDot = true;
      } else if (c == ':') {
        if (hasDot) {
          return null; // Colons must not appear after dots.
        }
        hasColon = true;
      } else if (Character.digit(c, 16) == -1) {
        return null; // Everything else must be a decimal or hex digit.
      }
    }

    // Now decide which address family to parse.
    if (hasColon) {
      if (hasDot) {
        ipString = convertDottedQuadToHex(ipString);
        if (ipString == null) {
          return null;
        }
      }
      return textToNumericFormatV6(ipString);
    } else if (hasDot) {
      return textToNumericFormatV4(ipString);
    }
    return null;
  }

  @NullableDecl
  private static byte[] textToNumericFormatV4(String ipString) {
    byte[] bytes = new byte[IPV4_PART_COUNT];
    int i = 0;
    try {
      for (String octet : IPV4_SPLITTER.split(ipString)) {
        bytes[i++] = parseOctet(octet);
      }
    } catch (NumberFormatException ex) {
      return null;
    }

    return i == IPV4_PART_COUNT ? bytes : null;
  }

  @NullableDecl

<|original_code|>
  /**
   * Returns an {@link Inet4Address}, given a byte array representation of the IPv4 address.
   *
   * @param bytes byte array representing an IPv4 address (should be of length 4)
   * @return {@link Inet4Address} corresponding to the supplied byte array
   * @throws IllegalArgumentException if a valid {@link Inet4Address} can not be created
   */
  private static Inet4Address getInet4Address(byte[] bytes) {
    checkArgument(
        bytes.length == 4,
        "Byte array has invalid length for an IPv4 address: %s != 4.",
        bytes.length);

    // Given a 4-byte array, this cast should always succeed.
    return (Inet4Address) bytesToInetAddress(bytes);
  }

  /**
   * Returns the {@link InetAddress} having the given string representation.
   *
   *
This deliberately avoids all nameservice lookups (e.g. no DNS).
   *
   * @param ipString {@code String} containing an IPv4 or IPv6 string literal, e.g. {@code
   *     "192.168.0.1"} or {@code "2001:db8::1"}
   * @return {@link InetAddress} representing the argument
   * @throws IllegalArgumentException if the argument is not a valid IP string literal
   */
  public static InetAddress forString(String ipString) {
    byte[] addr = ipStringToBytes(ipString);

    // The argument was malformed, i.e. not an IP string literal.
    if (addr == null) {
      throw formatIllegalArgumentException("'%s' is not an IP string literal.", ipString);
    }

    return bytesToInetAddress(addr);
  }

  /**
   * Returns {@code true} if the supplied string is a valid IP string literal, {@code false}
   * otherwise.
   *
   * @param ipString {@code String} to evaluated as an IP string literal
   * @return {@code true} if the argument is a valid IP string literal
   */
  public static boolean isInetAddress(String ipString) {
    return ipStringToBytes(ipString) != null;
  }

  @NullableDecl
  private static byte[] ipStringToBytes(String ipString) {
    // Make a first pass to categorize the characters in this string.
    boolean hasColon = false;
    boolean hasDot = false;
    for (int i = 0; i < ipString.length(); i++) {
      char c = ipString.charAt(i);
      if (c == '.') {
        hasDot = true;
      } else if (c == ':') {
        if (hasDot) {
          return null; // Colons must not appear after dots.
        }
        hasColon = true;
      } else if (Character.digit(c, 16) == -1) {
        return null; // Everything else must be a decimal or hex digit.
      }
    }

    // Now decide which address family to parse.
    if (hasColon) {
      if (hasDot) {
        ipString = convertDottedQuadToHex(ipString);
        if (ipString == null) {
          return null;
        }
      }
      return textToNumericFormatV6(ipString);
    } else if (hasDot) {
      return textToNumericFormatV4(ipString);
    }
    return null;
  }

  @NullableDecl
  private static byte[] textToNumericFormatV4(String ipString) {
    byte[] bytes = new byte[IPV4_PART_COUNT];
    int i = 0;
    try {
      for (String octet : IPV4_SPLITTER.split(ipString)) {
        bytes[i++] = parseOctet(octet);
      }
    } catch (NumberFormatException ex) {
      return null;
    }

    return i == IPV4_PART_COUNT ? bytes : null;
  }

  @NullableDecl
<|edits_diff|>
--- android/guava/src/com/google/common/net/InetAddresses.java
+++ android/guava/src/com/google/common/net/InetAddresses.java
@@ -19,6 +19,8 @@
    * Returns the {@link InetAddress} having the given string representation.
    *
    *
This deliberately avoids all nameservice lookups (e.g. no DNS).
+   *
+   *
Anything after a {@code %} in an IPv6 address is ignored (assumed to be a Scope ID).
    *
    * @param ipString {@code String} containing an IPv4 or IPv6 string literal, e.g. {@code
    *     "192.168.0.1"} or {@code "2001:db8::1"}
@@ -47,11 +49,13 @@
     return ipStringToBytes(ipString) != null;
   }

+  /** Returns {@code null} if unable to parse into a {@code byte[]}. */
   @NullableDecl
   private static byte[] ipStringToBytes(String ipString) {
     // Make a first pass to categorize the characters in this string.
     boolean hasColon = false;
     boolean hasDot = false;
+    int percentIndex = -1;
     for (int i = 0; i < ipString.length(); i++) {
       char c = ipString.charAt(i);
       if (c == '.') {
@@ -61,6 +65,9 @@
           return null; // Colons must not appear after dots.
         }
         hasColon = true;
+      } else if (c == '%') {
+        percentIndex = i;
+        break; // everything after a '%' is ignored (it's a Scope ID): http://superuser.com/a/99753
       } else if (Character.digit(c, 16) == -1) {
         return null; // Everything else must be a decimal or hex digit.
       }
<|current_version|>
  /**
   * Returns an {@link Inet4Address}, given a byte array representation of the IPv4 address.
   *
   * @param bytes byte array representing an IPv4 address (should be of length 4)
   * @return {@link Inet4Address} corresponding to the supplied byte array
   * @throws IllegalArgumentException if a valid {@link Inet4Address} can not be created
   */
  private static Inet4Address getInet4Address(byte[] bytes) {
    checkArgument(
        bytes.length == 4,
        "Byte array has invalid length for an IPv4 address: %s != 4.",
        bytes.length);

    // Given a 4-byte array, this cast should always succeed.
    return (Inet4Address) bytesToInetAddress(bytes);
  }

  /**
   * Returns the {@link InetAddress} having the given string representation.
   *
   *
This deliberately avoids all nameservice lookups (e.g. no DNS).
   *
   *
Anything after a {@code %} in an IPv6 address is ignored (assumed to be a Scope ID).
   *
   * @param ipString {@code String} containing an IPv4 or IPv6 string literal, e.g. {@code
   *     "192.168.0.1"} or {@code "2001:db8::1"}
   * @return {@link InetAddress} representing the argument
   * @throws IllegalArgumentException if the argument is not a valid IP string literal
   */
  public static InetAddress forString(String ipString) {
    byte[] addr = ipStringToBytes(ipString);

    // The argument was malformed, i.e. not an IP string literal.
    if (addr == null) {
      throw formatIllegalArgumentException("'%s' is not an IP string literal.", ipString);
    }

    return bytesToInetAddress(addr);
  }

  /**
   * Returns {@code true} if the supplied string is a valid IP string literal, {@code false}
   * otherwise.
   *
   * @param ipString {@code String} to evaluated as an IP string literal
   * @return {@code true} if the argument is a valid IP string literal
   */
  public static boolean isInetAddress(String ipString) {
    return ipStringToBytes(ipString) != null;
  }

  /** Returns {@code null} if unable to parse into a {@code byte[]}. */
  @NullableDecl
  private static byte[] ipStringToBytes(String ipString) {
    // Make a first pass to categorize the characters in this string.
    boolean hasColon = false;
    boolean hasDot = false;
    int percentIndex = -1;
    for (int i = 0; i < ipString.length(); i++) {
      char c = ipString.charAt(i);
      if (c == '.') {
        hasDot = true;
      } else if (c == ':') {
        if (hasDot) {
          return null; // Colons must not appear after dots.
        }
        hasColon = true;
      } else if (c == '%') {
        percentIndex = i;
        break; // everything after a '%' is ignored (it's a Scope ID): http://superuser.com/a/99753
      } else if (Character.digit(c, 16) == -1) {
        return null; // Everything else must be a decimal or hex digit.
      }
    }

    // Now decide which address family to parse.
    if (hasColon) {
      if (hasDot) {
        ipString = convertDottedQuadToHex(ipString);
        if (ipString == null) {
          return null;
        }
      }
      return textToNumericFormatV6(ipString);
    } else if (hasDot) {
      return textToNumericFormatV4(ipString);
    }
    return null;
  }

  @NullableDecl
  private static byte[] textToNumericFormatV4(String ipString) {
    byte[] bytes = new byte[IPV4_PART_COUNT];
    int i = 0;
    try {
      for (String octet : IPV4_SPLITTER.split(ipString)) {
        bytes[i++] = parseOctet(octet);
      }
    } catch (NumberFormatException ex) {
      return null;
    }

    return i == IPV4_PART_COUNT ? bytes : null;
  }

  @NullableDecl
<|next_version|>
  /**
   * Returns an {@link Inet4Address}, given a byte array representation of the IPv4 address.
   *
   * @param bytes byte array representing an IPv4 address (should be of length 4)
   * @return {@link Inet4Address} corresponding to the supplied byte array
   * @throws IllegalArgumentException if a valid {@link Inet4Address} can not be created
   */
  private static Inet4Address getInet4Address(byte[] bytes) {
    checkArgument(
        bytes.length == 4,
        "Byte array has invalid length for an IPv4 address: %s != 4.",
        bytes.length);

    // Given a 4-byte array, this cast should always succeed.
    return (Inet4Address) bytesToInetAddress(bytes);
  }

  /**
   * Returns the {@link InetAddress} having the given string representation.
   *
   *
This deliberately avoids all nameservice lookups (e.g. no DNS).
   *
   *
Anything after a {@code %} in an IPv6 address is ignored (assumed to be a Scope ID).
   *
   * @param ipString {@code String} containing an IPv4 or IPv6 string literal, e.g. {@code
   *     "192.168.0.1"} or {@code "2001:db8::1"}
   * @return {@link InetAddress} representing the argument
   * @throws IllegalArgumentException if the argument is not a valid IP string literal
   */
  public static InetAddress forString(String ipString) {
    byte[] addr = ipStringToBytes(ipString);

    // The argument was malformed, i.e. not an IP string literal.
    if (addr == null) {
      throw formatIllegalArgumentException("'%s' is not an IP string literal.", ipString);
    }

    return bytesToInetAddress(addr);
  }

  /**
   * Returns {@code true} if the supplied string is a valid IP string literal, {@code false}
   * otherwise.
   *
   * @param ipString {@code String} to evaluated as an IP string literal
   * @return {@code true} if the argument is a valid IP string literal
   */
  public static boolean isInetAddress(String ipString) {
    return ipStringToBytes(ipString) != null;
  }

  /** Returns {@code null} if unable to parse into a {@code byte[]}. */
  @NullableDecl
  private static byte[] ipStringToBytes(String ipString) {
    // Make a first pass to categorize the characters in this string.
    boolean hasColon = false;
    boolean hasDot = false;
    int percentIndex = -1;
    for (int i = 0; i < ipString.length(); i++) {
      char c = ipString.charAt(i);
      if (c == '.') {
        hasDot = true;
      } else if (c == ':') {
        if (hasDot) {
          return null; // Colons must not appear after dots.
        }
        hasColon = true;
      } else if (c == '%') {
        percentIndex = i;
        break; // everything after a '%' is ignored (it's a Scope ID): http://superuser.com/a/99753
      } else if (Character.digit(c, 16) == -1) {
        return null; // Everything else must be a decimal or hex digit.
      }
    }

    // Now decide which address family to parse.
    if (hasColon) {
      if (hasDot) {
        ipString = convertDottedQuadToHex(ipString);
        if (ipString == null) {
          return null;
        }
      }
      if (percentIndex != -1) {
        ipString = ipString.substring(0, percentIndex);
      }
      return textToNumericFormatV6(ipString);
    } else if (hasDot) {
      return textToNumericFormatV4(ipString);
    }
    return null;
  }

  @NullableDecl
  private static byte[] textToNumericFormatV4(String ipString) {
    byte[] bytes = new byte[IPV4_PART_COUNT];
    int i = 0;
    try {
      for (String octet : IPV4_SPLITTER.split(ipString)) {
        bytes[i++] = parseOctet(octet);
      }
    } catch (NumberFormatException ex) {
      return null;
    }

    return i == IPV4_PART_COUNT ? bytes : null;
  }

  @NullableDecl


Fix MpscLinkedQueue GC issues (#7799)

<|original_code|>
     *

     * IMPLEMENTATION NOTES:

     * Poll is allowed from a SINGLE thread.

     * Poll reads the next node from the consumerNode and:
     *

     *
If it is null, the queue is assumed empty (though it might not be).
     *
If it is not null set it as the consumer node and return it's now evacuated value.
     *

     * This means the consumerNode.value is always null, which is also the starting point for the queue. Because null
     * values are not allowed to be offered this is the only node with it's value set to null at any one time.
     *
     * @see java.util.Queue#poll()
     */
    @Nullable
    @Override
    public T poll() {
        LinkedQueueNode<T> currConsumerNode = lpConsumerNode(); // don't load twice, it's alright
        LinkedQueueNode<T> nextNode = currConsumerNode.lvNext();
        if (nextNode != null) {
            // we have to null out the value because we are going to hang on to the node
            final T nextValue = nextNode.getAndNullValue();
            spConsumerNode(nextNode);
            return nextValue;
        }
        else if (currConsumerNode != lvProducerNode()) {
            // spin, we are no longer wait free
            while ((nextNode = currConsumerNode.lvNext()) == null) { } // NOPMD
            // got the next node...

            // we have to null out the value because we are going to hang on to the node
            final T nextValue = nextNode.getAndNullValue();
            spConsumerNode(nextNode);
            return nextValue;
        }
        return null;
    }

    @Override
    public boolean offer(T v1, T v2) {
        offer(v1);
        offer(v2);
        return true;
    }

    @Override
    public void clear() {
        while (poll() != null && !isEmpty()) { } // NOPMD
    }
    LinkedQueueNode<T> lvProducerNode() {
        return producerNode.get();
    }
    LinkedQueueNode<T> xchgProducerNode(LinkedQueueNode<T> node) {
        return producerNode.getAndSet(node);
    }
    LinkedQueueNode<T> lvConsumerNode() {
        return consumerNode.get();
<|edits_diff|>
--- src/main/java/io/reactivex/rxjava3/internal/queue/MpscLinkedQueue.java
+++ src/main/java/io/reactivex/rxjava3/internal/queue/MpscLinkedQueue.java
@@ -20,6 +20,8 @@
             // we have to null out the value because we are going to hang on to the node
             final T nextValue = nextNode.getAndNullValue();
             spConsumerNode(nextNode);
+            // unlink previous consumer to help gc
+            currConsumerNode.soNext(null);
             return nextValue;
         }
         else if (currConsumerNode != lvProducerNode()) {
<|current_version|>
     *

     * IMPLEMENTATION NOTES:

     * Poll is allowed from a SINGLE thread.

     * Poll reads the next node from the consumerNode and:
     *

     *
If it is null, the queue is assumed empty (though it might not be).
     *
If it is not null set it as the consumer node and return it's now evacuated value.
     *

     * This means the consumerNode.value is always null, which is also the starting point for the queue. Because null
     * values are not allowed to be offered this is the only node with it's value set to null at any one time.
     *
     * @see java.util.Queue#poll()
     */
    @Nullable
    @Override
    public T poll() {
        LinkedQueueNode<T> currConsumerNode = lpConsumerNode(); // don't load twice, it's alright
        LinkedQueueNode<T> nextNode = currConsumerNode.lvNext();
        if (nextNode != null) {
            // we have to null out the value because we are going to hang on to the node
            final T nextValue = nextNode.getAndNullValue();
            spConsumerNode(nextNode);
            // unlink previous consumer to help gc
            currConsumerNode.soNext(null);
            return nextValue;
        }
        else if (currConsumerNode != lvProducerNode()) {
            // spin, we are no longer wait free
            while ((nextNode = currConsumerNode.lvNext()) == null) { } // NOPMD
            // got the next node...

            // we have to null out the value because we are going to hang on to the node
            final T nextValue = nextNode.getAndNullValue();
            spConsumerNode(nextNode);
            return nextValue;
        }
        return null;
    }

    @Override
    public boolean offer(T v1, T v2) {
        offer(v1);
        offer(v2);
        return true;
    }

    @Override
    public void clear() {
        while (poll() != null && !isEmpty()) { } // NOPMD
    }
    LinkedQueueNode<T> lvProducerNode() {
        return producerNode.get();
    }
    LinkedQueueNode<T> xchgProducerNode(LinkedQueueNode<T> node) {
        return producerNode.getAndSet(node);
    }
    LinkedQueueNode<T> lvConsumerNode() {
        return consumerNode.get();
<|next_version|>
     *

     * IMPLEMENTATION NOTES:

     * Poll is allowed from a SINGLE thread.

     * Poll reads the next node from the consumerNode and:
     *

     *
If it is null, the queue is assumed empty (though it might not be).
     *
If it is not null set it as the consumer node and return it's now evacuated value.
     *

     * This means the consumerNode.value is always null, which is also the starting point for the queue. Because null
     * values are not allowed to be offered this is the only node with it's value set to null at any one time.
     *
     * @see java.util.Queue#poll()
     */
    @Nullable
    @Override
    public T poll() {
        LinkedQueueNode<T> currConsumerNode = lpConsumerNode(); // don't load twice, it's alright
        LinkedQueueNode<T> nextNode = currConsumerNode.lvNext();
        if (nextNode != null) {
            // we have to null out the value because we are going to hang on to the node
            final T nextValue = nextNode.getAndNullValue();
            spConsumerNode(nextNode);
            // unlink previous consumer to help gc
            currConsumerNode.soNext(null);
            return nextValue;
        }
        else if (currConsumerNode != lvProducerNode()) {
            // spin, we are no longer wait free
            while ((nextNode = currConsumerNode.lvNext()) == null) { } // NOPMD
            // got the next node...

            // we have to null out the value because we are going to hang on to the node
            final T nextValue = nextNode.getAndNullValue();
            spConsumerNode(nextNode);
            // unlink previous consumer to help gc
            currConsumerNode.soNext(null);
            return nextValue;
        }
        return null;
    }

    @Override
    public boolean offer(T v1, T v2) {
        offer(v1);
        offer(v2);
        return true;
    }

    @Override
    public void clear() {
        while (poll() != null && !isEmpty()) { } // NOPMD
    }
    LinkedQueueNode<T> lvProducerNode() {
        return producerNode.get();
    }
    LinkedQueueNode<T> xchgProducerNode(LinkedQueueNode<T> node) {
        return producerNode.getAndSet(node);
    }
    LinkedQueueNode<T> lvConsumerNode() {
        return consumerNode.get();


Suppress UndeliverableException handling in tests (#6987) (#6996)

<|original_code|>
/**
 * Copyright (c) 2016-present, RxJava Contributors.
 *
 * 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.reactivex.rxjava3.core;

import java.util.concurrent.TimeUnit;

import org.junit.*;
import org.junit.rules.Timeout;

public abstract class RxJavaTest {
    @Rule
    public Timeout globalTimeout = new Timeout(5, TimeUnit.MINUTES);

    /**
     * Announce creates a log print preventing Travis CI from killing the build.
     */
    @Test
    @Ignore
    public final void announce() {
    }
}

<|edits_diff|>
--- src/test/java/io/reactivex/rxjava3/core/RxJavaTest.java
+++ src/test/java/io/reactivex/rxjava3/core/RxJavaTest.java
@@ -20,6 +20,8 @@
 import org.junit.*;
 import org.junit.rules.Timeout;

+import io.reactivex.rxjava3.testsupport.SuppressUndeliverableRule;
+
 public abstract class RxJavaTest {
     @Rule
     public Timeout globalTimeout = new Timeout(5, TimeUnit.MINUTES);
<|current_version|>
/**
 * Copyright (c) 2016-present, RxJava Contributors.
 *
 * 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.reactivex.rxjava3.core;

import java.util.concurrent.TimeUnit;

import org.junit.*;
import org.junit.rules.Timeout;

import io.reactivex.rxjava3.testsupport.SuppressUndeliverableRule;

public abstract class RxJavaTest {
    @Rule
    public Timeout globalTimeout = new Timeout(5, TimeUnit.MINUTES);

    /**
     * Announce creates a log print preventing Travis CI from killing the build.
     */
    @Test
    @Ignore
    public final void announce() {
    }
}

<|next_version|>
/**
 * Copyright (c) 2016-present, RxJava Contributors.
 *
 * 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.reactivex.rxjava3.core;

import java.util.concurrent.TimeUnit;

import org.junit.*;
import org.junit.rules.Timeout;

import io.reactivex.rxjava3.testsupport.SuppressUndeliverableRule;

public abstract class RxJavaTest {
    @Rule
    public Timeout globalTimeout = new Timeout(5, TimeUnit.MINUTES);
    @Rule
    public final SuppressUndeliverableRule suppressUndeliverableRule = new SuppressUndeliverableRule();

    /**
     * Announce creates a log print preventing Travis CI from killing the build.
     */
    @Test
    @Ignore
    public final void announce() {
    }
}


<|original_code|>
/**
 * Copyright (c) 2016-present, RxJava Contributors.
 *
 * 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.reactivex.rxjava3.internal.operators.observable;

import static org.junit.Assert.*;

import org.junit.Test;

import io.reactivex.rxjava3.core.*;
import io.reactivex.rxjava3.exceptions.TestException;

public class ObservableLiftTest extends RxJavaTest {

    @Test
    public void callbackCrash() {
        try {
            Observable.just(1)
            .lift(new ObservableOperator<Object, Integer>() {
                @Override
                public Observer<? super Integer> apply(Observer<? super Object> o) throws Exception {
                    throw new TestException();
                }
            })
            .test();
            fail("Should have thrown");
        } catch (NullPointerException ex) {
            assertTrue(ex.toString(), ex.getCause() instanceof TestException);
        }
    }
}

<|edits_diff|>
--- src/test/java/io/reactivex/rxjava3/internal/operators/observable/ObservableLiftTest.java
+++ src/test/java/io/reactivex/rxjava3/internal/operators/observable/ObservableLiftTest.java
@@ -19,6 +19,7 @@

 import io.reactivex.rxjava3.core.*;
 import io.reactivex.rxjava3.exceptions.TestException;
+import io.reactivex.rxjava3.testsupport.SuppressUndeliverable;

 public class ObservableLiftTest extends RxJavaTest {

<|current_version|>
/**
 * Copyright (c) 2016-present, RxJava Contributors.
 *
 * 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.reactivex.rxjava3.internal.operators.observable;

import static org.junit.Assert.*;

import org.junit.Test;

import io.reactivex.rxjava3.core.*;
import io.reactivex.rxjava3.exceptions.TestException;
import io.reactivex.rxjava3.testsupport.SuppressUndeliverable;

public class ObservableLiftTest extends RxJavaTest {

    @Test
    public void callbackCrash() {
        try {
            Observable.just(1)
            .lift(new ObservableOperator<Object, Integer>() {
                @Override
                public Observer<? super Integer> apply(Observer<? super Object> o) throws Exception {
                    throw new TestException();
                }
            })
            .test();
            fail("Should have thrown");
        } catch (NullPointerException ex) {
            assertTrue(ex.toString(), ex.getCause() instanceof TestException);
        }
    }
}

<|next_version|>
/**
 * Copyright (c) 2016-present, RxJava Contributors.
 *
 * 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.reactivex.rxjava3.internal.operators.observable;

import static org.junit.Assert.*;

import org.junit.Test;

import io.reactivex.rxjava3.core.*;
import io.reactivex.rxjava3.exceptions.TestException;
import io.reactivex.rxjava3.testsupport.SuppressUndeliverable;

public class ObservableLiftTest extends RxJavaTest {

    @Test
    @SuppressUndeliverable
    public void callbackCrash() {
        try {
            Observable.just(1)
            .lift(new ObservableOperator<Object, Integer>() {
                @Override
                public Observer<? super Integer> apply(Observer<? super Object> o) throws Exception {
                    throw new TestException();
                }
            })
            .test();
            fail("Should have thrown");
        } catch (NullPointerException ex) {
            assertTrue(ex.toString(), ex.getCause() instanceof TestException);
        }
    }
}